<!-- source: https://cli.dreamlake.ai/dev/typescript-api @ 0.134.0 99837ab -->

# TypeScript API

The [Memo presence and attachment API map](/dev/note-collaboration-api.md) lists
matching TypeScript operations, JSON receipts, and recovery behavior.

`@dreamlake/dreamlake-cli/api` exports a typed client over the HTTP routes the
CLI commands and the built-in agent's server-side plugins call. Permissions,
revisions, pagination and error codes are those of the server; the server remains the authority for those decisions.

```ts
import { createClient, ApiError } from '@dreamlake/dreamlake-cli/api';

const dl = createClient({ remote: 'https://api.dreamlake.ai', token: process.env.DREAMLAKE_API_KEY! });
const sessions = dl.sessions('marvin');

// Discovery
const { sessions: mine } = await sessions.list({ sort: 'recent', pageSize: 20 });
const waiting = mine.filter(s => s.runState === 'waiting');

// Control (needs `dl sessions serve` on one of your machines)
const { command } = await sessions.commands.create('send', { sessionId: waiting[0].id, text: 'rebase on main' });
const receipt = await sessions.commands.wait(command.id, 120);
if (receipt.status !== 'completed') console.log(receipt.status, receipt.error);

// Notes: a conditional append refuses (412 stale) if the note changed since it was read
try { await dl.notes('fortyfive').append(noteId, '## Status\n…'); }
catch (e) { if (e instanceof ApiError && e.status === 412) { /* re-read and retry deliberately */ } }

// Skills: one file of the pinned bundle, with the revision it came from
const page = await dl.skills.read({ skill: 'dreamlake-memos', path: 'actions/read.md' });
console.log(page.tag, page.commit, page.sha256, page.content.length);

// The built-in agent as a stream of events
for await (const event of dl.agent.chat({ message: 'What did Yanbing run this week?' })) {
  if (event.type === 'delta') process.stdout.write(event.text);
  if (event.type === 'tool') console.error(event.name, event.status, event.receiptId);
}
```

| Surface | Operation | HTTP |
| --- | --- | --- |
| `sessions(ns).list / available / get / conversation / resources` | discovery | `GET /namespaces/:ns/terminal-sessions…`, `GET /terminal-sessions/available` |
| `sessions(ns).rename / archive` | metadata | `PATCH …/:id/name`, `PATCH …/:id/archive` |
| `sessions(ns).commands.create / wait / get / list / cancel / broadcast` | control plane | `/namespaces/:ns/session-commands…` |
| `sessions(ns).runners.register / claim / deregister`, `commands.renew / finish` | runner protocol | `/namespaces/:ns/session-runners…` |
| `notes(ns).search / body / sections / write / append / addSection` | memos | `/namespaces/:ns/notes…` |
| `agent.chat / conversations / restore / toolCallsPage` | built-in agent | `/agent/chat`, `/agent/sessions…` |
| `skills.list / skill / read / file` | skills registry | `GET /skills`, `GET /skills/:skill`, `GET /skills/:skill/files/*` |

Pass `agent: { conversationId, turnId, toolCallId }` to `createClient` to
attribute calls to an agent conversation; the server records it as
provenance, never as authority.

## Canonical Memo API (0.105.0)

Use `client.memos`, `memosApi`, and `Memo*` types for collaborative documents.
The implementation lives in Memo modules, including the CLI command implementation.
The existing `client.notes`, `notesApi`, and `Note*` exports remain aliases during
the phased rollout; both spellings use the same transport and editing engine.

```ts
import {createClient, type MemoSnapshot} from '@dreamlake/dreamlake-cli/api';

const client = createClient({remote: serverUrl, token: apiToken});
const memo = client.memos('team/6ae3f318608512b4ba34860c');
const snapshot: MemoSnapshot = await memo.read();
await memo.append({text: '\nReviewed.', at: snapshot, mode: 'merge'});
```

This release preserves existing server routes and response fields. Database
collection names and RTC wire changes are separate coordinated rollout steps.
New references use ordinary links; saved `:note` directives remain readable.
No `:memo` directive is introduced.

## Revision-aware Memos and recovery observations

The unreleased source API adds `notes(ns).source(id, at)`,
`edit(id, baseRevision, edits)`, `patch`, `find`, `versions` and `version`.
Edits use Unicode codepoint positions in the pinned original revision;
page snapshot and project text search offsets are UTF-16 instead. Check
revision/hash and pagination metadata before composing an edit.

`agent.chat` accepts typed `page.content` observations (resource path,
SHA-256, text, structure and selection), which grant no permissions.
`agent.searchProject(projectId, query, { content: true, cursor })` returns
bounded results with `partial`, `skipped` and `nextCursor`.
`agent.browserActions(conversationId)` returns retained browser ACKs.

Runner clients can append late evidence with
`sessions(ns).commands.reconcile(commandId, runnerId, observation)`.
This preserves the original terminal status and never replays effects.
Only the owner and assigned runner may report such observations.

## API contract and full command inventory (unreleased)

The [complete CLI/API inventory](/dev/api-coverage.md) is generated from the
executable command tree, rather than a manually selected set of commands.
It includes every executable command, the exported operation(s) that implement
its service protocol, and a reason for each local-only exclusion. Run
`pnpm check:api` after changing command registration or exported APIs.

`createApi(transport)` supplies the TypeScript service adapters. Existing CLI
implementations remain in their original modules. Public API entries re-export
existing pure helpers or add explicit-credential/request adapters; existing CLI
commands are not rewritten to call the new API. See the [per-file rollback
review](/dev/api-change-audit.md) for every reverted relocation and retained change.

Jobs/Infra `.create` and `createClient` use supplied credentials and fetch;
legacy CLI `.connect` methods retain their existing login resolution. Memo
source spans, HTML/outline, upload execution, library planners and layout reuse
the original modules without moving them. Command registration, login selection,
confirmation, presentation and local processes remain CLI responsibilities.
Backend plugins and UI keep independent thin implementations over the same
permission-checked service contract. There is no separate SDK package or
vendored artifact. Contract tests compare requests, refusals and revisions.

| API | Capabilities |
| --- | --- |
| `profile`, `organizations`, `teams`, `graphql` | Identity, membership, roles, organization and team operations |
| `projects(ns)`, `nodes`, `tasks(ns, project)` | Resource discovery, grant-management preflight, attachments, bindrs/datasets, file reads, task events/links and revision-aware edits |
| `notes(ns)` | Metadata, v2 source and pinned history, patch/replace/insert/remove/full replacement, HTML/outline/search/events, legacy section operations, sharing and files/publication recovery |
| `connections(ns)`, `sources(ns)` | OAuth operations, revision/idempotency-aware settings, external layers, browsing/read/upload grants, deletion operations/retries and sharing |
| `artifacts(ns)`, `scenes(ns)`, `libraries(ns)` | Catalog/version protocols, explicit storage credentials/authorizations, metadata/sharing, library manifests and shared add/remove planners |
| `pipelines(ns)`, `workflows(ns)`, `runnables(ns)`, `registeredRuns`, `runConfigs(ns)` | Definitions/versions, binary workspace upload, workflow specs/runs, pinned registered execution and result/log receipts |
| `runs(ns)`, `providers(ns)`, `hosts(ns)`, `queues(ns)`, `jobs(ns)` | Configured launch-server protocols, enrollment, observations/power, owner-managed connection grants, delegated terminals, remote execution, queues and job tracking |
| `platform(ns)`, `infra`, `ownership(ns)` | Provider/storage/queue declarations, Slurm/experiment binding, repository snapshots, infrastructure backend/state/locks and ownership transfer/recovery |
| `vault(scope)`, `serviceAccounts(ns)`, `machine` | Explicit scoped secret/key/KMS/OTP/binding/password-rotation protocols, machine identities and grants |
| `sessions(ns)`, `terminal(ns)`, `agent` | Session discovery/context/lineage, commands/lifecycle/messages, native session records, runners/fencing/reconciliation and agent receipts/events |
| `browser`, `openResources`, `pages` | Page snapshots/selection/locations, bounded literal search, parameterized macro driver, permission-checked open-resource search and page generation/edit SSE |
| `skills` | The server's pinned dreamlake-skills bundle: the catalog with its version, one skill's manifest, body and file index, one whole file verified against its sha256, and conditional file reads |

Host connection grants are owner-only: `hosts(ns).accessGrants(hostId)`,
`grantAccess(hostId, { enrollmentId, grantee })` and
`revokeAccess(hostId, grantId)` return `HostAccessGrantList`,
`HostAccessGrantResult` and `HostAccessRevokeResult`. CLI 0.132.0+:
`allAccessGrants(hostId)` returns person and team grants as
`HostAccessGrantsAll` and throws `HostTeamGrantsUnsupportedError` when the
server lacks team grants; `grantAccess(hostId, { enrollmentId, team })` takes a
team slug instead of `grantee` (exactly one) and returns
`HostTeamAccessGrantResult`; revoke receipts may add
`stillAuthorizedConnections`. A grant shares the
enrollment's Unix account; a revoke receipt with `unconfirmedConnections > 0`
means some connections end only by `unconfirmedUntil`, and repeating the revoke
retries closing them. Hosts reached through a grant carry
`access: HostSharedAccess` (`kind: "grant"`) in `list` and `status`; its
grant entries may name `via: "team"` and the `team`. `projects(ns).attach` and
`detach` accept `ProjectAttachmentType`, including `host`, which is placement
only and confers no host access. See
[Share connection access](/host-enrollment.md#share-connection-access).

The broad catalog APIs retain server-owned extensible JSON fields. Stable
contracts such as sessions, commands, Memo source/patch/search/files, page
snapshots, macro outcomes and storage adapters have named types. A JSON response
must be narrowed before reading fields outside a documented stable contract;
TypeScript types do not replace server validation or ACLs.

### Explicit execution and storage adapters

Artifact `publish` and workflow `publishSpec` take a `VersionedContentStore`.
It obtains a real next version and writes bytes using the broker's scoped
credentials. Version-read failure stops before writing; write or registration
failure returns `PublicationError` with the stage, version and whether content
may exist. No write is replayed automatically. The CLI retains its DreamDB and
filesystem adapters. Scene packaging/compose, library file preparation and
presigned transfers likewise require explicit bytes/IO; Python engines,
SSH/TTY, Terraform, runner daemons and updater/install behavior are not hidden
inside an HTTP API.

`openResources.find(descriptors, { query, offset, limit, ifResourcesRevision })`
rechecks each Memo through its global permission-checked detail route before
searching its actual owner namespace. File descriptors can carry an explicit
`projectId` for the granted file-read API. Results include locations, revisions,
pagination, skipped reasons and `partial`; an unsupported renderer is never
reported as a successful empty search. Pass the returned `resourcesRevision`
on subsequent pages to refuse a changed descriptor list.

### Repository boundary

Install the CLI's existing `@dreamlake/dreamlake-cli/api` export for external
TypeScript callers. Backend plugins and browser code retain independent thin
implementations/types; they do not install the CLI or a generated SDK tarball.
The service API contract is the compatibility boundary. Local opt-in contract
checks can compare these independent implementations without introducing a
production dependency between repositories.

## Skills

`dl.skills` is the TypeScript leg of one operation shared with
`dl skill read` and the built-in agent's `dreamlake_skills_read`
([Reading a skill](/skills.md#reading-a-skill)). It needs no namespace: the
registry serves the one bundle the server's `skills.lock` pins, read-only, to
any logged-in principal.

| Operation | Returns | HTTP |
| --- | --- | --- |
| `skills.list()` | `{ version: { tag, commit }, skills: [{ name, description, requires, tools, files }], renamed }` | `GET /skills` |
| `skills.skill(name)` | `{ version, name, renamedFrom?, manifest, body, files: [{ path, bytes, sha256, text }] }` | `GET /skills/:skill` |
| `skills.read({ skill, path? })` | `{ tag, commit, skill, renamedFrom?, path, sha256, content, files, filesTotal, filesTruncated }` — the agent tool's fields minus paging; the whole file, hashed against the index, and the whole index (`filesTruncated` is always `false`) | `GET /skills/:skill`, then `GET /skills/:skill/files/*` unless `path` is `SKILL.md` |
| `skills.file({ skill, path, ifNoneMatch? })` | `{ status: 200 \| 304, tag, commit, path, sha256, content }`; `content` is `null` on 304 | `GET /skills/:skill/files/*` (`If-None-Match`; the ETag is the content sha256) |

Refusals are `SkillsError`, an `ApiError` whose `code` is one of
`skills_unavailable` (503), `skills_lock_mismatch` (503), `skill_not_found`
(404), `skill_file_not_found` (404), `skill_path_invalid` (400) and
`skill_file_binary` (415); `SKILLS_ERROR_CODES` maps each to its status. A bad
name or path is refused before any request; a missing or binary file is refused
from the index without a second request. Content that does not hash to its ETag
or to the index, or a bundle whose commit changed between the two requests, is
an ordinary `Error` rather than a result. `SKILL_READ_FIELDS`,
`SKILL_READ_OPTIONAL_FIELDS` and `SKILL_READ_PAGING_FIELDS` name the shared,
the optional (`renamedFrom`) and the agent-only paging fields (`start`, `end`,
`total`, `next`, `complete`).

## Archive lifecycle

The [archive guide](/notes/archival.md#typescript) documents `notes(ns).archive`,
`unarchive`, `includeArchived` list/search filters, `nodes.archive` and
`nodes.unarchive`. Saved edits restore archived ancestor folders on the server;
clients do not need to traverse or clear the path themselves.

## Infrastructure registration moves

`dl.platform(namespace).infrastructure.move(stackId, "preview", input)` and
`move(stackId, "commit", preview.request)` use the same reviewed move routes as
[`dl infra move`](/infrastructure.md#move-an-existing-stack-registration).
The exported `InfrastructureStackMovePreviewInput` and
`InfrastructureStackMoveRequest` types describe destination namespace/Project,
optional name/path, source identity, state version/digest and idempotency pins.

For a cross-project move, omitting `destinationPath` preserves the stack's
relative path. The server then includes that path and `expectedSourcePath` in its
review; send the complete returned request unchanged. An explicit path selects a
new destination placement. Never reconstruct a request from only the destination
or obtain a new operation key to retry an unknown outcome. HTTP failures propagate
as `ApiError` without mutation retries. This changes registration placement and
access scope; it does not run Terraform or move cloud resources. The separate
`infrastructure.transfer.*` API remains capability-gated and never falls back to
`move` when unavailable.

## Bindrs and resource identifiers

The identifier and Bindr contract fixes described in this section are available in
`@dreamlake/dreamlake-cli` 0.107.2 and later.

Path identifiers are literal: `projects('@alice').delete('@review')` targets the
project named `@review` in namespace `alice`. Only namespace inputs interpret a
leading `@` as shorthand; resource names and IDs retain it.

`dl.projects(namespace).bindrs(project)` lists and creates in the project.
`list()` returns `{ bindrs }`; `create({ name, parent?, member?: { nodeId } })`
returns `{ bindr }`, preserving the server envelope previously returned at runtime
(the old generic `Resource` return type was inaccurate). Read, update, delete,
and membership methods accept stable Bindr IDs or the previous exact name arguments. Both resolve through the selected
project list, with exact IDs taking precedence and ambiguous names refused before
any write. A canonical item-route failure is returned without retrying by name.
These methods preserve name-based callers while
replacing obsolete project/name HTTP routes. Legacy `create({ name, members })`
is also supported: the first node is seeded during creation, and remaining nodes
are tagged sequentially. A later failure leaves the created Bindr and earlier
tags intact; `BindrMembersError` includes the Bindr ID and confirmed node IDs.

`get(id, query?)` returns
`{ bindr, members, page, pageSize, total, totalPages }`; `summary(id)` and
`update(id, changes)` return `{ bindr }`.

`addMember(id, nodeId)` and `removeMember(id, nodeId)` tag a node, not a resource
ID. `addMembers(id, nodeIds)` and `removeMembers(id, nodeIds)` compose sequential
single-node requests and return `{ completedNodeIds, memberCount }`. They are not
atomic: `BindrMembersError` exposes `bindrId`, `completedNodeIds`, `failedNodeId`,
and `cause`. Inspect membership before retrying a failed request whose server
outcome is unknown. `resources(project, 'bindrs')` uses the same contract.

## Folder and Bindr visibility

```ts
const folder = await client.nodes.visibility.get(folderId);
await client.nodes.visibility.set(folderId, "unlisted", folder.updatedAt);

const bindr = await client.bindrVisibility.get(bindrId);
await client.bindrVisibility.set(bindrId, "unlisted", bindr.updatedAt);
```

These direct-ID operations work without discovering the item in a public Project
listing. Visibility is `private`, `unlisted` or `public`; a null Bindr visibility
means inherited behavior. Ordinary folder reads additionally return
`explicitVisibility` (null for inherited) and the effective `visibility`.

Project-scoped `projects(namespace).bindrs(project).create` accepts `visibility`.
Its `update` accepts `visibility` with the required `expectedUpdatedAt` from a
fresh summary. The server requires Project ADMIN. Helpers validate inputs before
sending a write and verify its acknowledgment. An uncertain result must be
reconciled by reading current metadata; helpers do not repeat writes.
