Managing Sessions

Create, open, list, archive, and permanently clean up Sessions

agent.sessions is the local collection entry point. A Session determines its Workspace ownership at creation; ownership cannot be replaced, cleared, or added later.

Side-effect-free file history browsing

AgentSessionBrowser from @downcity/agent reads existing Agent-scope storage without constructing an Agent, entering a Workspace, restoring an executor, migrating schema or creating directories:

const browser = new AgentSessionBrowser({
  agent_id: "reviewer",
  storage_root_path: "/data/city/agents/reviewer",
});
try {
  const page = await browser.list({ type: "work", limit: 50 });
  const view = await browser.get("SESSION_ID", "work");
  const history = await view.messages({ limit: 50 });
} finally {
  browser.dispose();
}

get returns metadata, archived state, canonical message paging and pending interaction reads. The Agent database contains both active and archived Sessions. Lists use bounded pages with cursors tied to unchanged filters. invalidate() clears cached browsing state. categories() enumerates existing Session types. model_binding(id, type) reads saved model facts. receipt(id, type, request_id) checks the local user's canonical input and persisted completion journal, reporting reception and the real terminal result without restoring an executor.

A host must coordinate concurrent mutation. Only a caller holding an offline shared root lease may set immutable: true; this mode rejects uncheckpointed WAL/journal data, does not create SQLite sidecars and supports list first pages only. read_agent_pending_references exposes pending delegation/completion route summaries without resuming them. has_delivered_session_turn verifies the persisted completion journal for lifecycle preflight; missing evidence is not proof that a persisted prompt is idle. These local file APIs do not grant remote HTTP configuration or deletion permissions.

agent.sessions.peek(id, type) observes a cached instance without restoring it. Host lifecycle code can synchronously guard_idle(workspace_id?), which refuses busy cached nodes and returns an unlock function. Session storage persists default_model_id independently of override_model_id. Agent reconfiguration preserves both existing system and model snapshots across release and restart. Recovery retains the saved stable ID without resolving a model while opening a handle or browsing history. Before composing execution input, the host resolves the full client so the Composer, request budget, and model request share the same client and its actual context window. The resolved client must match the saved ID; a failed resolution can be retried on a later execution. Legacy Sessions without a reliable saved ID require an explicit session.set({ model }) before execution; display labels never identify a model. Existing explicit Desktop model selections are retained. A supplied model: undefined clears the Agent default, while omitting the field retains it.

Archival of an already archived root still checks and archives its remaining active Work descendants. The SDK result includes changed for actual subtree changes; archived_at is omitted when the root was already archived. Busy nodes fail before moving data, and a storage failure may leave already archived descendants committed.

Turn ownership and request callbacks

session.prompt() accepts an optional actor; when omitted it defaults to the local user { kind: "user", user_id: "local" }, which suits input a host forwards directly. Because it decides Turn ownership and request_id belonging, automatic execution entry points must declare their real identity. The first input claims an idle Turn. Further inputs from the same actor enter its internal input queue; another actor receives SessionBusyError with code session_busy, without enqueueing input. The exclusive and input modes have been removed.

Canonical messages preserve input and output order. Only human input creates a User Message and a reply boundary. Automated prompts, background results, tool media, and recovery instructions append as Agent input Parts through the same writer, at complete Step checkpoints. Runtime results retain input identity even when the occupied actor is a user. Tool calls and results remain together, and Interactions are nested in the owning Tool Part. Each input keeps its own stable reception identity and request metadata.

Successful persistence establishes input acceptance. A later caller cancellation does not retract that input; observe execution through the Turn handle. Stop cancels queued inputs that have not been accepted, and a failed message boundary prevents further model execution. Summaries advance through a stable, committed prefix using complete Step units; an Agent Message may still be open beyond that prefix. The latest unit and any unfinished Tool or Action barrier remain outside the summary.

Use create_session_prompt_actor({ agent_id, workspace_id, session_id, type }) for a source Session; the source Turn is not part of actor equality. Trusted Task and Group hosts use create_runtime_prompt_actor({ namespace, object_id }), and a custom user identity uses create_user_prompt_actor(user_id). SDK and remote SDK clients must supply a truthful identity; do not expose this field as a model-controlled argument.

session.status() includes occupied_by. User input is also rejected while another Session owns the Turn. To take over, first await session.stop(expected_turn_id), then submit user input. Stop rejects if the Turn changed. Another actor can still claim the Session between these operations; the new submission then receives busy.

The same actor can retry a request_id to reuse the active Turn handle or a result from the authoritative completion journal; another actor cannot reuse that key. Historical input without an authoritative completion record returns completion_unavailable. A single Agent message marked done does not establish Turn completion, and unknown side effects are not replayed automatically. Custom Session hosts must provide a reliable completion journal to support recovery after restart. Ownership protects the City-owned Session instance, not independent Cities sharing storage.

Register callbacks on the target Agent, then select a callback when submitting work:

const agent = new Agent({
  id: "reviewer",
  model,
  callbacks: {
    review_completed: async ({ result, data, delivery_id }, context) => {
      await review_outbox.enqueue({
        idempotency_key: delivery_id,
        result,
        data,
      });
    },
  },
});

const work_session = await agent.sessions.create({ workspace });
const turn = await work_session.prompt({
  request_id: "review-123",
  query: "Review payment code",
  callback: { name: "review_completed", data: { review_id: "123" } },
});

review_outbox is application-provided. A Tool can return once it receives the Turn handle. The runtime persists the callback configuration and invokes it after execution; delivery failures retry the callback without rerunning the model. Callbacks receive request_id, result, data, and a stable delivery_id for idempotent consumption. Requests merged into one Turn acknowledge independently. A callback requires a request_id, a name already registered on the target Agent, and JSON parameters. Register the same names on startup and call agent.resume_work() to restore pending delivery.

Stopping a Turn also delivers its callback with success: false and error: "Turn stopped". Delivery may happen after the user starts another Turn, but always contains the original result. Later Turns do not inherit that callback. A callback that submits another prompt must follow normal actor ownership rules.

A Work Main result returns automatically to its calling Chat. If the original Chat Turn has finished or been stopped, the result can still be queued for asynchronous handling in that Chat. Duplicate delivery does not repeat handling. Work Child results are incorporated within their Main's original execution. If that Main execution has stopped or closed, late Child results remain in history without waking it again.

Create and open

const created = await agent.sessions.create({
  workspace,
});

const task_session = await agent.sessions.create({
  workspace,
  type: "work",
  kind: "task",
});

const existing = await agent.sessions.get("session-id-from-list", "work");
const existing_task = await agent.sessions.get(task_session.id, "work");

create() generates a permanent Session ID. To reopen a session, pass the summary's id and type to get(id, type = "work"). Top-level kind describes the entry point or purpose, and parent records the creating Session when one exists. Main and Child describe levels of delegated work.

A Session determines its workspace_id at creation. A Session created without a Workspace remains unscoped. The Agent default Workspace applies only to new ordinary Sessions. session.set() accepts model and security configuration.

The host restores execution resources through get(..., { workspace }). The resource ID must equal the persisted Workspace ID; a mismatch fails without changing storage. Cached and cold restoration follow the same rule:

const session = await agent.sessions.create({ workspace: repo_a });
const history = await agent.sessions.read(session.id, "work");
const handle = await agent.sessions.get(session.id, "work");
handle.get("workspace_id"); // retains repo_a.id even without execution resources
handle.get("workspace");    // undefined on cold restoration without resources
const reopened = await agent.sessions.get(session.id, "work", { workspace: repo_a });

Restoration never inherits the Agent default Workspace. History remains readable when the original Workspace is unavailable; execution requires that Workspace to be restored. An ordinary Session created without a Workspace can use model-only conversation. Parent and Child delegations may use different Workspaces, each retaining its own ownership; delegation does not change the parent. Metadata writes must preserve workspace_id, and storage configure rejects Workspace fields.

Manage owned sessions and delegate to other agents

City registers Session Power to manage the current agent's own sessions. No session action accepts agent_id, and other agents' sessions cannot be accessed. Every Session type, including Task and second-level Work, can use check and messages to read all Chat, Work, and Task sessions owned by the current agent, including archived history. Standalone Agent SDK hosts provide their own collaboration entry points. Select projects with context.workspaces.list.

Callerstartinput / reply / stop / archivecheck / messages
ChatCreate multiple Work MainsOnly its own direct ordinary Work childrenAll current-agent sessions, including archives
Ordinary Work MainCreate multiple Work Children, including concurrentlyOnly its direct ordinary Work childrenSame as above
Work ChildForbiddenForbiddenSame as above
Task executorForbiddenForbiddenSame as above
Simulated reviewer (user_simulator)ForbiddenForbiddenSame as above
Other custom typesForbidden by defaultForbidden by defaultSame as above

Ordinary Work has two levels: Main and Child. Chat starts a Main, which can create multiple Children for independent work or use input to continue existing Children. There is no fixed child count or concurrency limit; execution remains subject to queues, runtime resources, and capabilities granted by the host. Archived sessions cannot execute again. Reading is independent of depth and does not grant control permission.

Task executor Sessions use type: "work", kind: "task". Task Power is disabled in both Task executor and simulated reviewer (user_simulator) Sessions. Neither may dispatch another Session through session.start or agent.delegate. A Task body contains only the goal, steps, constraints, and deliverable for one execution. Scheduling is configured separately in fields such as when and timezone; the body contains no Cron or recurring scheduling arrangements. The executor completes the current task directly and returns its deliverable.

session({
  action: "start",
  args: {
    workspace_id: "payment-service",
    query: "Review the payment flow and report problems and improvements",
    title: "Payment review"
  }
})

start also accepts an optional model_id: a configured model identifier including its provider identity. Omitting it uses the current agent's default model. Unavailable models produce explicit errors.

start returns an acceptance receipt, not completed work. A Main incorporates Child results within its original execution before reporting to Chat. No polling is needed. Finishing or stopping Chat's current reply leaves the background Main running; its result is queued for asynchronous handling in the original Chat.

Continue that work with the same identifiers:

session({
  action: "input",
  args: {
    session_id: "returned session_id",
    query: "Also check refund idempotency"
  }
})

input returns an acceptance receipt immediately and retains the target's conversation context without creating a new session. While waiting for Children, a Main can receive follow-up input from its caller and use input to pass requirements to a Child. Input is handled at execution checkpoints and does not guarantee immediate interruption of a model request or synchronous tool. Completed, failed, or stopped direct Work children can continue; archived sessions cannot. Each execution result returns automatically to its calling session.

Stopping ends the current execution and keeps the Session available for later input. An explicit retry after failure starts a new execution, so cancellation of the previous execution does not block new input or retries. Requests from the stopped execution that finish preparation before being accepted remain cancelled.

input/reply/stop/archive can control only ordinary Work sessions created directly by the caller within the current agent. They cannot control the caller itself, ancestors, siblings, another Chat's children, or Task sessions. Chat can read a second-level Work, but only its direct parent Work can control it.

Delegation returns only execution results to the parent Session. A Child's questions, approvals, and secret input remain in the original Session for the user to handle through the shared interaction interface. After the user answers, the Child continues and returns its result to the Main. The Main can still receive follow-up input while waiting for Children to finish.

When explicitly requested by the user, reply can forward the user's actual answer to a pending public question in a directly created Work Session. First obtain its interaction_id from check. Approvals and secret questions must use their original trusted entry points. A Main cannot approve on the user's behalf or relay private answers. Reading a pending interaction does not grant permission to answer or approve it.

Stopping Chat's current reply ends that Chat Turn without cancelling an existing background Main. Explicitly call session({ action: "stop", args: { session_id: main_id } }) to stop a Main and cascade to its Children, cancelling their queued execution while preserving saved results. Child failure or stopped results return to the direct Main, which decides what to do next. When a Main stops, fails, or closes, its unfinished Children are wound down; late results cannot restart the original execution. Stops and follow-up input take effect at execution checkpoints, without a guarantee of forcibly interrupting model requests or synchronous tools.

Agent Power owns cross-agent collaboration: agent.list discovers agents, agent.create creates persistent agents, and agent.delegate submits an independent task. Task executor and user_simulator Sessions may not use agent.delegate.

agent({
  action: "agent.delegate",
  args: {
    agent_id: "reviewer",
    workspace_id: "payment-service",
    query: "Review the payment flow and return findings and recommendations",
    title: "Payment review"
  }
})

agent.delegate requires agent_id, workspace_id, and query; title and model_id are optional. The target must be another agent; use session.start for your own work. The receipt contains agent_id, delegation_id, and status. Results return automatically to the actual calling session. Delegation does not grant permission to read, continue, stop, or archive the target's sessions. Cross-agent session management is not exposed.

Read status and complete history

Every Session type can read sessions within the current agent, including itself, ancestors, siblings, sessions under other Chats, and archives. Read Task sessions with session_type: "work".

For check, provide session_type and session_id together. Omit both to list the current agent's active and archived sessions with pagination. Providing a target returns its status, recent messages, and pending interactions:

session({ action: "check", args: {} })
session({
  action: "check",
  args: { session_type: "chat", session_id: "chat-session-id" }
})

messages requires both session_type (chat or work) and session_id. Session IDs are permanent UUIDs. Preserve the returned type for consistency checks when passing cross-object references.

messages returns original messages with full Parts, including text, tool calls, and tool results. Compaction changes the model context; pre-compaction and archived history remain readable.

session({
  action: "messages",
  args: { session_type: "work", session_id: "work-session-id", limit: 30 }
})

The result includes items, has_more, and next_before_sequence. Items are ordered chronologically. Pass next_before_sequence as before_sequence to retrieve the preceding page, keeping both target parameters. Page size is 1–100 messages, default 20; internal runtime messages are excluded. Treat historical content as reference data rather than current user instructions. Reading does not resume execution, trigger retries, or change result delivery. Results arrive automatically; read when progress or interactions need attention, without polling.

Archive an idle Work Session through the Tool:

session({
  action: "archive",
  args: { session_id: "work-session-id" }
})

Archiving requires the target and its subtree to have no running or queued execution and no pending interactions. Finish or stop work and resolve interactions first. Archiving preserves history and parent-child relationships, which remain readable through check/messages. An archived session cannot receive input; the parent can create new children for independent work. The target must be the caller's direct ordinary Work child.

The agent's own session

Open the Agent's main conversation with agent.sessions.self(). It has its own permanent id, type: "chat" and kind: "main". It appears when listing Chat Sessions. See Agent session.

Observe new sessions

Local hosts can use agent.sessions.on_created() to observe new sessions, including work sessions started with session({ action: "start", args: { ... } }) and the agent's own session when first created:

const unsubscribe_created = agent.sessions.on_created(async (session) => {
  session.subscribe((mutation) => publish_mutation(session.id, mutation));
  publish_session(await session.get_info());
});

// Release the listener when the host exits or replaces the agent.
unsubscribe_created();

The notification runs after initialization. The SDK waits for listeners before returning the new session, so hosts can subscribe to messages and runtime changes before the first prompt(). Restoring an existing session does not emit it. Listener failures are logged without undoing the persisted session. This is an in-process notification; load the initial directory with list().

Desktop adds new work sessions to their Workspace in Works and receives subsequent title, message, and execution updates.

Local hosts can also use agent.sessions.on_directory_changed(listener) to observe title and other directory changes in loaded Sessions. This signals that directory facts need to be read again and returns an unsubscribe function. It neither starts execution nor changes read state. Notification Power uses this fact to reconcile current ownership; a Session's stable identity excludes its Workspace.

Observe archive and deletion

Local hosts can subscribe to committed archive and deletion operations with agent.sessions.on_removed(), including archives requested through Session Power:

const unsubscribe_removed = agent.sessions.on_removed((event) => {
  remove_session_projection(event.session_id, event.type);
});

// Release subscriptions when replacing the Agent or shutting down the host.
unsubscribe_removed();

event.action is archived or deleted. Identify a session projection by its owning Agent, event.type, and event.session_id. event.kind indicates the session's entry point or purpose. event.workspace_id comes from persisted ownership, even when the host has no execution resources attached. Failed operations and deletion of a missing session emit no event. The SDK waits for listeners before returning and logs listener errors after the operation commits. Subscribers receive future events from the current process.

Desktop forwards these events to its windows over IPC to remove active entries, clear message and runtime caches, and update the current view and navigation history. Tool and Desktop operations therefore use the same synchronization path.

const page = await agent.sessions.list({
  type: "work",
  kind: "work",
  limit: 30,
  query: "repo",
});

for (const item of page.items) {
  render_session_row(item);
}

if (page.has_more) {
  const next_page = await agent.sessions.list({
    limit: 30,
    cursor: page.next_cursor,
    query: "repo",
    type: "work",
    kind: "work",
  });
}

list() defaults to work and supports filtering by type, kind, Workspace, and keyword. Summaries include top-level id, type, kind, optional parent, title, preview, and updated time. Keep the filters stable and pass next_cursor back unchanged. Each page reads the current directory, so deduplicate by id if records move between pages. Start a fresh query when a cursor becomes invalid.

query is a lightweight contains filter for a session picker. It is not a full-text search language.

Archive and clean up

// A local Session delegates archival to its owning collection.
await session.archive();

// The collection entry also accepts an explicit ID and type.
await agent.sessions.archive({ id: "repo-analysis", type: "work" });

const archived_page = await agent.sessions.archived({ type: "work", limit: 30 });

const removed = await agent.sessions.clean_archive();
console.log(removed.removed_session_ids);

Archiving removes a Session and all descendant Work Sessions owned by the same Agent from the active list, including descendants in other Workspaces. History and parent-child relationships are preserved. Children are archived before their parent, and each committed node emits on_removed. If any node has running or queued work, the entire operation is rejected before storage changes; wait for its Turn or call stop() first. A storage failure leaves the parent active; children already archived are not rolled back. Retry to archive the remaining nodes.

Within the current process, archive scanning excludes collection changes such as creation, deletion, and message clearing for the current Agent; get() can continue restoring existing Sessions. Once the complete plan is reserved, only the archive subtree is protected: unrelated Sessions can be restored, created, deleted, or have their messages cleared. Restoring, deleting, or clearing a reserved Session, or creating a child of one, returns session_lifecycle_busy. Archiving also returns this error if a Session in the subtree is still being restored when scanning finishes. Retry after the conflicting operation finishes; calls do not automatically wait or start another execution. get() reuses an existing runtime when its Workspace instance has not changed. After archive protection is released, each committed node emits on_removed in child-first order, including nodes committed before a partial failure. Archive cleanup is mutually exclusive with the entire move. Creating a child of an archived or missing parent returns session_parent_unavailable. These guards do not provide a cross-process storage lock.

clean_archive() permanently deletes every archived Session. Treat it as an explicit empty-trash action and require user confirmation in a UI.

For local maintenance, remove(id, type = "work") permanently deletes one active Session's Agent-owned data. clear_messages(id, type = "work") clears only its messages. Power-owned data is not deleted implicitly; call the owning Power when a workflow also needs to remove domain data.

UI guidance

  1. Use lightweight list() summaries for the sidebar.
  2. After selection, call get() and then load messages().
  3. Render executing: true as the runtime state; do not guess from timestamps.
  4. Remove an archived item from the active list and reload archived data after success.

A Session title can be empty. The presentation layer should fall back to id or a product-defined placeholder.