Files
deepseek-harness/packages/api/session-controller
Xu HanxiangandDeepSeek Harness da7f9b4c5a feat(liveshare): open the viewer capabilities a share can serve (#8304)
* feat(liveshare): open reader capabilities the share can serve

(cherry picked from commit 3c893b488900fff776a21eebee4eb2d95b878764)

* feat(liveshare): let a reader run the session's slash commands

(cherry picked from commit ae02bcc0f819e55ebf066de7581d4d89994930a4)

* fix(liveshare): allow a reader to list the workspace file references

(cherry picked from commit fffaa864b9d790a0aab30da639d5ef50ff8f303c)

* fix(liveshare): bind the job endpoints to their session resource

(cherry picked from commit 357d1f6efe5b161a4ce1b616e66599c4e75a6ab1)

* chore: refresh the Cordis surface catalog

(cherry picked from commit 88f88b225f0fcff0a5a88f09b0f555749dd62756)

* test(job-controller): read the Session resources the Remote methods declare

The job roster, the follow stream, and a kill each declare the request's
Session as the resource they touch, and an unowned job's follow names none.
Read those declarations off the mounted Controller and pin what they answer.

(cherry picked from commit fa3f92427a6bd56ad2a949dc74315505cb75533b)

* feat(liveshare): offer a shareable core component to viewers

The terminal controller reaches the catalog from a core profile bundle, which
the catalog excludes so no application plumbing is offered. Mark such a
component shareable: PluginMetadata gains the mark, and the host names the
packages that carry it, so a marked core component enters the catalog and
every other core component stays out.

The terminal namespace leaves the exclusion list for the same reason, and
the marked component carries the title its dialog row shows.

(cherry picked from commit b0e9e390719aab519fd82cf39c85c60e4f77b588)

* fix(liveshare): classify the terminal methods as owner-selected

The nine terminal methods leave owner-only for plugin-offered: the owner picks
them in the share dialog, no reader role grants one, and a share that names
none still refuses every terminal call.

(cherry picked from commit 718c1b45a1b01320cbe9be46ece9deca37225fe2)

* docs(liveshare): state that terminals open per method

Terminals are no longer unconditionally owner-only: the share dialog offers
the terminal controller's methods and opens none until the owner picks them.

(cherry picked from commit 505c1193571b16431731f69bd5ca1b59a1059a13)

* test(liveshare): cover a viewer reaching the Session's terminals

The end-to-end case mounts a real terminal controller beside the share host:
the catalog offers it as a shareable core component, a share that selects
nothing refuses every terminal call, and a selected terminal/create through
the reader's own Peer binds the shell to the Session its agentId names.

(cherry picked from commit 25955a936dc5b58ebfd8e1d24f495d62d59f7b70)

* fix(workspace-files): confine non-owner reads to the session workspace

A non-owner Peer now reads and watches files only inside the connected Session workspace. stat, read, readBytes (including baseFile) and changes resolve the target canonically and refuse an outside one with workspace-file/outside-workspace before reporting its kind. Owner and trusted in-process callers keep the filesystem read authority.

(cherry picked from commit 7ae855e12ba6c5bc99c7ae75d65d984661f3bbb5)

* refactor(workspace-files): name the file access confinement

Replace the contain boolean with a named FileConfinement carried by the service, and move the outside-workspace refusal into one helper shared by file reads and watches. No Remote interface or behavior changes.

(cherry picked from commit 1c4dbd68220df7c559f84cf2782f9626c5b2ef4b)

* refactor(workspace-files): name the path mode PathScope

Replace the FileConfinement/confinement vocabulary with PathScope, and rename its module and test. The values and behavior are unchanged.

# Conflicts:
#	packages/api/workspace-files/src/index.ts
#	packages/api/workspace-files/tsconfig.host.json

(cherry picked from commit 5d3f7b31dc6a1dbcf44c5fdd59295402bf40cf76)

* refactor(workspace-files): accept several workspace roots in the path check

The confinement helper and change feed now take several resolved roots; the current scope still supplies one. WorkspaceFileScope.workspaceRoot remains the primary root, so a future multi-workspace Session can add optional roots without changing endpoint signatures, path arguments, or the client address.

(cherry picked from commit 73fd59be92c421c378b7fe5606d8d7c5806b13cb)

* fix(workspace-files): keep the multi-root watch check covered

Pass the primary watch root separately and iterate the roots list, so the feed keeps full coverage for the multi-root preparation. Add braces to the multi-root test arrow for the lint rule.

(cherry picked from commit 1286aac6a6d93e693dbb33f2feaa71e6252424e0)

* test(workspace-files): assert a refusal never reports the target kind

The outside-workspace failure carries only the path, so a share reader learns
nothing about what it was refused. stat, read, readBytes, list, and a relative
escape are each asserted not to carry a kind.

(cherry picked from commit a9495de0ff63a1aac325d1cb62b8111c188ae8a5)

* test(workspace-files): keep the search caps in the shared harness config

Rebasing over the search endpoint left configOf() without the search limits
the master harness passed inline, so every search call reached the subprocess
provider with an undefined graceMs. configOf and peer() now take Caps and
supply the suite defaults.

(cherry picked from commit 70cecb9b352ce5c1e17482429b1539483e101d60)

* docs(workspace-files): describe the read confinement against the search-era structure

The master README added the search section and rewrote the file-read checks
without a workspace-containment check. Those paragraphs now state which
caller the check applies to, the change feed mentions the non-owner watch,
and the source map lists path-scope.ts. Bilingual hashes re-recorded with
verify-translation-pairing --write.

(cherry picked from commit e61fdabaf2fb9b0c0bc507ef5ceea0f213f70683)

* fix(liveshare): keep workspaceFiles/search in the reader session-read role

The classification table is the single source for POLICY_DECIDED_ACTIONS, so
the new search endpoint must also appear in the read role's actions.

(cherry picked from commit 665093b07cfee87be105fdc71a7d58fe25974788)

* docs(catalog): regenerate the client and config catalogs

Removing the viewer share-path tab drops its client slot entry, and the workspace file import shifts the Config source line.

(cherry picked from commit 7bb9295a18b011971b4338171a60d16ff82eebd1)

* docs(catalog): regenerate the config catalog source line

(cherry picked from commit 2d98a59afc8aa6e2a9ac268d4446bcd8cd5eeb26)

* fix(liveshare): let share readers preview workspace files

The served page keeps the shipped Sidebar and now reads the shared Session
workspace through workspaceFiles: stat, read, readBytes, list and changes join
the Session read role, while the file service confines every non-owner read to
that workspace root. The viewer tab type that answered each file address with
"a share hands over paths, not contents" is removed, so the shipped document
preview opens the file.

Refs #7901

(cherry picked from 5e0ceac3faa)(partial: liveshare files only)

* fix(ui-jobs): offer the stop control only with job/kill access

(cherry picked from commit 804956ece9c09b2fac6180cd78da7aa7393ae0de)

* fix(ui-chat): attribute a reader's steering row while it is pending

Chat declared the message-source seat on the user node registration, so an
admitted steering row rendered the shared bubble without asking for it and
a Host-pending steering occurrence carried no source to ask with. Move the
seat to the flow: it renders user rows, admitted steering rows, and pending
steering occurrences, and hands the same renderer to each.

Liveshare's selector now elects a share-viewer source of either kind, so a
reader's interjection states its author from the moment it is sent.

(cherry picked from c802aef8392)(partial: liveshare client files only)

* docs(liveshare): state when a reader's interjection shows its author

A local submission echo carries no source, so the author line appears once the
Host records the input in the Inbox, not when the reader sends it.

(cherry picked from 42001b1294d)(partial: liveshare client files only)

* docs(liveshare): describe the seat source arriving as row props

(cherry picked from commit 466e25328c5c42c792bfb30bba05ff790259bf99)

* fix(liveshare): refuse /permission to share readers

The commands executor runs a command handler inside the owner Host with no
reader-specific narrowing, so a reader line such as
`/permission danger-full-access` left the shared Session unconfined with no
approval. The read role's condition now parses the `commands/execute` line
and refuses the owner-only command names, starting with `/permission`, with
the new `command-owner-only` reason the viewer page classifies. Every other
command keeps following visibility.

* feat(permission-presets): add the permissionPresets/set Remote

The `/permission` command switches a Session's sandbox mode and approval
policy inside the owner Host's own handler, which gives a share reader that
reaches `commands/execute` no endpoint decision to meet. The switch now has
a Remote face: `permissionPresets/set` names the Session it writes as its
`session` resource, so the Gateway decides who may call it before any preset
is resolved or any knob changes.

The request carries the Session id and the preset name only. An unknown
preset and a Session this process does not hold live both refuse with
`gateway/bad-request` before writing. The call reports the selection the
Session reads back after the switch.

The command reaches the same switch, keeping its ordering and its `success`
and `error` text. Because a Remote parameter cannot carry an Agent, the
command supplies the approval write itself so its model-visible policy
notice still follows the switch.

Co-Authored-By: DeepSeek Harness <[email protected]>

* fix(liveshare): classify permissionPresets/set owner-only

The new preset endpoint writes the source Session's sandbox mode and approval
policy, so no share reader role may reach it at any tier. The viewer endpoint
classification records it as owner-only, and the viewer access policy spec
proves a reader is refused on the shared Session, on its own forks, and on a
Session outside the share, and that no reader grant carries the action.

The owner-only command whitelist stays as the second defense: the commands
handler runs inside the owner Host, so a reader line must not depend on that
handler continuing to route through the endpoint.

Co-Authored-By: DeepSeek Harness <[email protected]>

* test(liveshare): keep every permission preset endpoint owner-only

The classification table's completeness gate proves a new generated endpoint
has a row, but not that the row keeps a reader out. This case reads the table
and fails when any `permissionPresets/*` endpoint is classified as anything
other than owner-only, so an endpoint added there without its class checked
turns the suite red instead of widening a reader's reach.

Co-Authored-By: DeepSeek Harness <[email protected]>

* docs(catalog): regenerate for the preset set Remote

The new `permissionPresets/set` Remote adds its signature and its request type
to the generated service and type catalogs, maps the request type to the
permission presets subsystem page, and shifts the permission preset config
source line. The permission presets subsystem pages describe the write path
and its Remote face on both sides.

Co-Authored-By: DeepSeek Harness <[email protected]>

* test: construct SessionId values and keep the approval notice lock

The rebased specs called SessionId as a value while importing it as a
type, so every case threw ReferenceError. Construct the ids the way the
packages already do, and keep the /permission case that locks the single
model-visible approval notice.

* test(liveshare): load the terminal controller without a built artifact

The spec resolved a generated typert artifact at module load, so a clean
checkout failed before any case ran.

* docs(liveshare): state the reader limits the review asked about

Marks the answer path's dependence on timed asks, records that @ mentions
list every host session, and explains which commands stay owner-only.

* feat(liveshare): let a viewer manage the goal of a visible Session

The goal is Session data, not the workspace sandbox, so the same visibility
rule that already covers goals/get and goals/edit applies to create, pause,
resume, complete and clear. The /goal command reaches the same service, so
the endpoint and the command now agree.

# Conflicts:
#	packages/experimental/liveshare/README.i18n.yaml

* fix(liveshare): keep the terminal component titles

The shareable mark's localized titles were spread onto the metadata record, which
put `en` and `zh` at the top level instead of in the `titles` field the catalog
reads. A core bundle without display metadata therefore offered the terminal
with no product name at all.

* fix(workspace-files): decide the path scope before stat

A non-owner read probed the path with `lstat` before it checked containment, so
reading an absent path outside the workspace answered `not-found` while an
existing one answered `outside-workspace`. That let a share reader probe whether
any path on the owner's machine exists.

Every confined read now resolves and confines its target first: `read`, `stat`,
`readBytes` (including a path relative to a base file) and `list`. The final
`lstat` still reports the component's own kind, and the owner keeps the
filesystem's authority, including its previous answer for an absent path.

* docs(liveshare): drop the queue-verb mention

`session/updateQueue` is not in the viewer Session read role, and viewer queue
management is not part of this change. The role's rationale now names the
reach it actually carries, and the workspace file actions no longer leak
whether a path outside the workspace exists.

* test(liveshare): describe the terminal suite's actual coverage

* chore: regenerate the catalogs the viewer capability change moves

session-reference, user-questions and the permission presets all feed the
Cordis, persistence and doc-graph generators, so their artifacts were stale.

* fix(liveshare): keep the command refusal copy paired and cover the file paths

The English notice read "/permission on", which the locale gate tokenised
together while the translations kept the command alone. The workspace-file
and preset paths the coverage lane flagged now have cases of their own.

* test(workspace-files): accept either refusal code for a UNC base

Windows resolves an unreachable UNC host through the local backend's ancestor
walk, which reports an IO failure instead of the not-found POSIX reads. Both
refuse the read; the code belongs to that backend, not to the path-scope
decision this case covers.

* refactor(liveshare): leave the command surface to its own change

Running a slash command is a separate decision from what a reader may read:
the executor wraps several capabilities in one opaque call, so the endpoint
that admits it is not the place to decide them. This change keeps the reader
capabilities and the preset endpoint, and returns the command wiring when the
command surface itself is reshaped.

* refactor(liveshare): leave the workspace file preview and terminal grant out

Reading a Session's data and reaching into the owner's workspace or shell are
different promises: the first follows visibility, the second changes what the
owner's machine does. This change keeps the reader capabilities that describe
Session data and returns the other two for their own discussion.

* refactor(jobs): let the session resolver name the job endpoints' Session

The session resource resolver already reads a top-level sessionId, so the
explicit readers restated what it derives. Removing them keeps one rule for
how a Session resource is named.

* test(liveshare): drop the workspace preview stubs the strip left behind

The viewer shell no longer opens workspace files, so the fixture route and
the assertion about it no longer describe anything.

* fix(jobs): bind the job endpoints to the Session they name

The session resolver reads a top-level sessionId, but these methods take a
request object and no lookup parameter, so the request fell through to the
global resource and a reader was refused. The explicit readers state the
Session the Gateway must authorise.

* refactor(jobs): let the session resolver name the job endpoints' Session

The session controller's resolver already reads the sessionId of the first
object argument, so an explicit reader on these methods restated a rule the
Gateway already applies. The tests now install the session controller and
assert the resource the production composition produces.

* refactor(session-controller): take the resolve input as one argument

An exported function cannot destructure its parameters, because the JSDoc
gate names them one by one.

* docs(liveshare): describe the capabilities this change actually opens

The workspace file preview, the terminal grant and the command surface
moved out of this change, so the package reference and the PR description
now state what remains.

* docs(persistence): refresh the catalog after the preset JSDoc edit

The permission-presets module doc grew a line, so the recorded source
line for its persisted event moved from 60 to 61.

---------

Co-authored-by: DeepSeek Harness <[email protected]>
2026-11-14 15:41:52 +00:00
..
2026-11-13 13:11:59 +08:00

description, kind
description kind
Host and Client session control: create, resume, prompt, follow history, and project live session state. package-reference

Session Controller

English | 中文

Desktop analytics follows the product collection policy, including its launch-time switch. Web usage is excluded.

Summary

@deepseek-ai/dsh-api-session-controller owns the Host ctx.sessionController service and the generated Client session, skills, and fileReferences Remote namespaces. It serves Session lifecycle and history, the Host-generation model catalog, human background-job kill, workspace-path opening, user-invocable skill discovery, and Agent-scoped file references. Use it through API Gateway when a Client needs operations addressed by a Session.

Table of Contents


Use this package

Prompt retries use the request identity in the first committed inbox insertion, including after the message is claimed or removed. Admission checks again after asynchronous attachment preparation, so concurrent retries accept one input. Acceptance acknowledges insertion, not execution or completion.

The controller reads a Session's recorded preset through the optional agentPresets.presetForSession(session) service method. A null result means no preset was recorded; an absent service means preset identity is unavailable to the controller.

History pages and follow opening snapshots carry one { type: 'event', event: SessionWireEvent } record per durable Session event. The Client retains each accepted record as one durable SessionEventLikeEntry; Assistant token boundaries remain inside the compact stream on assistant/message or assistant/attempt. Tool arguments, result content, failures, and tool/result.data.meta pass through unchanged; the controller does not resolve a Tool definition, run a presenter, or attach UI data.

The Client journal validates current Session event envelopes before publishing follow snapshots, live entries, or history pages. It reuses the browser-safe Session validators for required surface markers, exact replacement endpoints, earlier unique source seqs, embedded Assistant provider metadata, request-header omissions, and tool-error consistency. Invalid records fail without field stripping or normalization; range membership and source existence remain durable-log checks on the Host.

Each endpoint states its activation policy. For a cold Session, list reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. An attached Session is summarized from its in-memory log. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; canOpenWorkspacePath() reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected fileUploads Host service and resolves every same-Agent receipt before sending the complete ordered content list through ctx.attachments. A receipt names a staged file or a staged image, and an image receipt subjects the prompt to the same image-input check as an encoded image. Prompt retries whose requestId is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and the subagent ownership fence determined by origin: 'subagent' to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use workspaceDesktop() for the serving Host name and file-manager behavior. openWorkspacePath({ path, action: "reveal" }) delegates file-manager navigation to the native adapter; omitting action opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. session.projections normally reads an exact baseline, including current-format cold logs, and returns kind: sequenced. Only a read requiring migration returns kind: migration-required hints without asOfSeq; missing keys remain absent. It returns null for a missing Session. Fork callers may set allowMigration: false to receive session/migration-required instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through projectionsBySession; domains select their own keys. Session-list summaries carry agentAvailable, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values.

Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in dsh-api-remote-access grants a role listing the action (Peer principals Agent Note). The controller injects remoteAccess and registers a default resolver for the session resource kind through typert.resources. It reads a named sessionId parameter, otherwise the first object argument's sessionId or address; unrelated string parameters name no Session. An object containing both sessionId and address is invalid, even when they name the same Session. session/events, the deprecated session/page, session/observeEvent, and session/follow use this resolver to read address.sessionId for an ordinary Session address and address.childSessionId for a subagent address; whether access to the parent Session covers its children is the policy's rule. session/projections, session/observeProjections, session/state, session/observeState, and session/wait read the Session resource from request.sessionId, so each call and subscription names only the Sessions it may read. session/list, session/search, and session/control read no resource, so their calls touch the global resource and need a global role; for a non-owner caller, session/list returns only the rows, session/search only the hits, and session/control only the baseline projections and projection frames, whose Session ctx.remoteAccess.allows() admits for the same action, so that action also belongs to a session role; owner results are unfiltered. session/prompt builds the durable user-rpc message source in its Remote method and records principal only for a non-owner caller, read through principalOf(this.ctx.invocation); a source without principal belongs to the owner.

events reads one chronological page from a durable cut and returns its records, hasMore, and an inclusive cursor; omitting throughSeq selects the observed log end, and the compatible page method carries the same read with a deprecated entry point. events, observeEvent, and follow take an Address; projection and state operations take a Session ID. Page reads and Follow openings validate the supplied Address. Pure observeEvent and observeProjections subscriptions neither acquire an Observation nor establish existence: their ready frame carries no snapshot cursor.

List rows carry formatStatus when available, so Clients can identify migration-required Sessions without requesting their projections.

Host list generation yields between complete rows only when its configured work slice is exhausted; cheap remaining work returns without a forced yield. Request cancellation is checked per row and after each yield and rejects without partial results. Each row is synchronous; the list does not promise one cross-Session snapshot. A Session already queued as cold remains a cached row if it attaches during a yield: Client in-flight mutation replay corrects its availability, and sequenced projections supersede cached hints. An attached Session's summary reads its blankness and last-prompt recency through the sessionListMetadata projection handle, and its projection hints carry every summary key computed through snapshot. The first summary of an attached Session computes these projections over its whole in-memory log, and later summaries advance them incrementally; this computation runs inside one synchronous row, so listWorkSliceMs cannot split it.

Client list rows and resident Sessions use the current sessionListMetadata projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank.

session.create returns a Session for a new conversation, and its response names the Session actually used. A named sessionId is reused while it is blank (no turn has started), belongs to the requested directory, is an unarchived member of the requested Workspace, and is not written by another owner; a live Session is reused in place, and a persisted one is resumed while retaining its writer lock. The reused Session runs the requested agentPreset, or the configured default when the request names none: its recorded preset is not resolved, and a change is logged as agent-preset/selected before the Agent is published. A named Session that has started, fails the Workspace placement, or is written by another owner stays unchanged, and a new Session is created instead. A sessionId with no stored Session becomes the new Session's identity. A named Session in another directory fails with session/conflict, and one owned by subagent routing with session/agent-busy; both checks precede preset resolution. Creations naming one identity run in arrival order, including their preset resolution, and each response reports the preset its own request left the Session running. session.list includes persisted blanks using cached metadata, without opening cold log bodies.

Client list refreshes retain unchanged row objects and reuse the items array when order and values match. Each row's retainedBy contains positive local reference-source counts; Host metadata refreshes cannot overwrite them. Cache membership checks use a per-refresh ID set, so reconciliation grows linearly with the current list and retained cache sizes. Host summary updates replace running and Agent availability; local create/fork responses only fill missing metadata on existing rows. Removed ordinary Sessions retain projection stores only when their catalogs contain children.

Background-job rows and observation streams belong to dsh-api-job-controller; the control stream carries projections only.

Projection reads retain loading and failure state independently of their values. Reconnect cancels reads from the previous connection and reloads previously requested projections; live membership updates arrive through the control stream. Parent availability comes from Host summaries and remains unknown until a summary or a successful list baseline establishes it. Address lookup resolves projected children without selecting them or creating scopes.

Accepted prompts and observed running keep their Client display conversion across list refresh, reconnect, and Session-object replacement. The Manager retains these observations by Session id; they do not establish durable history. Drafts, projection stores, and sidebar display rules retain their existing behavior. The blank rollback decision defines retention and late-response handling.

The Client adapter exposes SessionEventStream, a Gateway RemoteJournalStream bound to one ordinary or direct-subagent address. It opens follow before the initial page, publishes only contiguous replace, prepend, append, and settle-assistant changes, and repairs reconnect or sequence gaps through a tail page. Backwards paging has two verbs: loadOlder() pulls one Turn-aligned page, and loadThrough(seq) — the turn-jump loader — loops Turn-aligned pages until the window covers the target seq, lowering a shared target on repeated calls, stopping on a page that makes no progress, and reporting busy through the same loadingOlder snapshot bit. The Web adapter explicitly opts into cursorless Assistant frames: each opening carries the active attempt's startedAfterSeq, nextIndex, and compact stream, and every stream member becomes a Client-only assistant/live-chunk entry ordered between durable cursors. The Host captures a follower-local arrival ordinal with that baseline and suppresses buffered frames at or before the cut; a replacement Agent may restart frame revision at one. A durable assistant/message or assistant/attempt arriving after an active opening stays staged only when its seq follows startedAfterSeq and its Turn and Step match; the matching end type, seq, and index releases the durable entry. A successful message retains its transient rows until the owning step/end, so pending tool identities remain available for dispatch. Failed or interrupted settlements retire their rows immediately; earlier same-step retries remain visible. Revision, dense-index, or settlement gaps for a known attempt reopen follow, while a controller that missed the start ignores unknown-attempt frames and publishes their durable settlement normally. An abandoned end publishes a settlement delta without a durable entry so its transient rows retire immediately. A durable gap-repair page has no Assistant baseline, so its held notification reopens follow once for a paired page and baseline. Every history record covers exactly its event seq. A business, persistence, or unresolved continuity failure terminates the stream, while only physical carrier loss selects automatic resumption. SessionControlStream is a Gateway RemoteSnapshotStream; every generation opens with a complete process-local baseline, so reconnect replaces projection state instead of treating transient values as durable events. At each ready Host generation, a synchronous Client subscription clears retained projection values and watermarks before refreshing queries and restarting the control stream, including Sessions absent from the control baseline. The first control stream waits for generation readiness, so its opening values cannot precede invalidation. Outstanding list responses from the previous generation cannot republish those values. Within a generation, a delayed control baseline cannot overwrite or clear newer sequenced values, whether they arrived through a live Session's list block, a history page, or a frame; a cached list block, viewed from the projection cache for a cold Session, yields to the connected Session's baseline whatever watermark it carries. The durable inbox projection carries both pending lists through the same cold-read and reconnect path as other projections. Client Agent contexts provide the identity used by the independent fileUpload service; Session objects expose lifecycle, prompt, queue, and history operations rather than file transfer.

The Session object also carries local submission echoes: session.beginSubmission registers one before the caller serializes and prompts, and Session publishes it in SessionSnapshot.pendingSubmissions once the Host has accepted the prompt, as the prompt receipt or an inbox row carrying the request id shows, whichever arrives first. A conversation UI therefore shows the message from acceptance until its durable entry renders, and Chat and QueueDock exclude the matching Inbox row from the moment it arrives. The blank-to-engaging transition happens at the same acceptance. The echo stores ordered image previews and durable file references. Session derives its transcript, queued, or steering placement from the current running state and requested delivery mode, then retains that placement until the display handoff. The prompt's requestId is the correlation identity: the Host echoes it as the durable user source's rpcId, including pending messages in the inbox projection. Queued echoes retire one animation frame after queue acceptance; Chat echoes follow the admission rule below. Identified failures and abandonment retire unadmitted echoes immediately. Disposal preserves observed admission and fails other unsettled submissions. Acceptance fires onAccept once, in the same update that publishes the echo, so the sender can settle its composer together with the echo. Each retirement fires onRetire exactly once; an observed retirement includes the ordered durable attachment references so the sender can release or hand over the sent attachments. Echoes are Client memory only; reload and reconnect rebuild the conversation from durable events alone.

During uninterrupted following, transcript and steering echoes stay in Chat through Inbox acceptance and claim until their durable messages arrive. After a local Chat message is admitted, its identity remains until the Inbox watermark reaches its next-turn or next-step claim seq: Chat already renders the durable Node, while Chat and QueueDock exclude matching stale Inbox rows. Other queued messages remain visible. A replacement follow baseline withdraws receipt-confirmed echoes as observed, using their accepted attachment references; unconfirmed submissions remain pending. Host data then supplies the pending or admitted rows. Reconnecting between claim and admission can briefly omit that bubble; withdrawal confirms acceptance, not execution or failure.

The user-invocable skills/list metadata includes the winning provider’s optional instruction-file path. The composer can preview that file without loading every skill body or activating a cold Agent.

Fork copies the exact inclusive event prefix selected by atSeq, including a cut inside an open turn, into an independent Session without parentSession. Client placeholders likewise omit parentSessionId; list indentation applies only to subagent-origin rows, including when historical ordinary forks retain a parent id. Workspace attachment and optional title increments use the source selected for the operation; an increment skips numbers that other Host-listed titles already use. The child records its inherited marker before synthetic fork results and closing events. Omitting atSeq selects the latest completed turn and its standalone tail, stopping before the next turn or queued input; a nonexistent event is rejected. The chat action selects a completed turn.

A resume blocked by an existing write handle returns session/writer-held with the Session id; other resume failures retain gateway/internal.

loadThrough(seq) retains older pages privately until its shared target is covered or loading ends, then publishes the successful pages as one ordered prepend. Live events remain visible while history loads. A later page failure retains the successful prefix; replacing the history window discards buffered pages from the replaced window. Ordinary loadOlder() prepares and consumes one Host-selected page; { deferConsumption: true } retains that page until consumeOlder() publishes it synchronously. A retained page blocks another ordinary request without blocking live events. historyLoadStatus distinguishes idle, loading, pendingConsumption, and error; loadingOlder is derived from loading, including Turn jumps. Failures and pages without progress permit explicit retry rather than claiming exhaustion. historyWasPartial remembers an incomplete visible window for the Client Session lifetime, including reconnects, without persisting presentation state.

The Client's initial follow, reconnect openings, and loadOlder() request at least 50 append-origin user/message and assistant/message events and cross at least two turn/start events, including the partial Turn at the loaded window's beginning. The Host stops at the first Turn start satisfying both minima, or at 500 counted messages or history exhaustion, whichever comes first. Steering does not add a Turn boundary. Intervening events accompany the page without counting toward the message budget. The optional turnWindow on page and follow requests supplies these minima under maxMessages. loadThrough() uses the same rules with a 200-message minimum per page; the 500-message cap does not limit the whole jump. Requests without turnWindow retain message-aligned paging.

Queue edits replace pending content with non-empty text only.

session.attachment receives { sessionId, attachment: ImageAttachmentRef } and passes the complete reference to AttachmentStore.readImage(), without reading or traversing Session history. The Client supplies the message's reference through session.readAttachment(ref). Connection authentication and Gateway permission checks still apply; sessionId selects the Session resource for the endpoint's permission check. After authorization, the handler does not check whether that Session exists and does not return session/not-found merely because it is absent. An authorized caller may read any image in the same store, including an image referenced only by another Session or by no Session. The response preserves the supplied reference after verifying its ID, media type, byte length, width, and height against the stored bytes. Optional name and originalDimensions pass through as caller-supplied display information and are not verified against the file. Missing or invalid objects return a terminal attachment failure. The Client's historical-image cache retains one result and browser URL per Session and attachment ID.

The controller composes ArchivedSessionGate through ctx.plugin: it loads once the Agent registry, Session store, and Workspace registry exist and unwinds with the controller. Its agent/pre-step listener rejects a step proposed for an archived Session or for a subagent descendant of one — read through available Session headers, never a fork — so a late waking delivery ends its turn as blocked without a model request; unarchiving lifts the gate for the whole lineage. The Subagent runtime separately checks retained creation ancestors, covering managed descendants whose intermediate creators are offline. The work an archived Session still runs is reported and stopped by its owners through the Workspace registry's archive admission (seam): the running turn by the Agent registry, owned jobs by the job registry seam, subagent descendants by the Subagent runtime, reminders by the Schedule plugin; this controller reports nothing itself.

Client references

sessions.retain(target, { source, signal? }) immediately acquires one exact Client generation and starts its shared initial history opening. The target is a known Session id or a durable direct-parent subagent address; the Host validates an explicit address when history opens. The returned reference supports idempotent release() and Symbol.dispose; its ready Promise follows the shared Session.open() result and resolves to the exact binding when that attempt settles, including when a Remote failure is represented by openState: 'error'. It rejects when Session.open() rejects, its waiter is cancelled, or the reference is released early. Cancelling one waiter does not cancel another owner's opening. sessions.using(target, options, operation) waits for that settlement, holds its reference until the callback settles, and propagates rejected readiness and callback failures.

References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. binding(id) and scope(id) only borrow an existing generation. retainInfo(id) observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. See Client Session references for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability.

Session media references

SessionMediaReferences mounts GET|HEAD /api/file?path=<absolute path> on the authenticated connection.fetch channel when connection, fs, and attachments are composed. It reads ordinary files through ctx.fs, including temporary paths outside registered workspaces and files in remote providers. Neither directory containment nor MIME categories restrict access; mime-types supplies the response type, with application/octet-stream for unknown extensions. GET reuses readBytes for preflight and ongoing byte limits; HEAD reads metadata only. All files use ctx.attachments.imageLimits.maxImageBytes (normally 50 MiB); exceeding this limit returns 413. A request whose v parameter differs from the file's current ctx.fs version, including a request without one, receives a private, no-store 302 to the same route with only path and the current v; the versioned response is private, max-age=31536000, immutable, so browsers reuse cached bytes until the file changes, and private file contents may enter the browser disk cache. Responses contain the complete file, ignore Range, and carry nosniff, and a sandbox CSP so directly opened HTML/SVG cannot execute with the API origin. The Client rewrite lives in ui-chat (AssistantMarkdown); audio/video responses are available, while Markdown audio/video player nodes remain separate work.

GUI model selection requires the exact provider/model pair in the available catalog; unavailable choices reject with session/model-unavailable. Prompt admission retains the saved route without a catalog availability gate, so request execution reports missing credentials or unavailable models. initializeDefaultModel() saves the first available account model after login when no other provider has a configured API key; credential checks use configured references independently of model availability. A provider with no available models rejects initialization with session/provider-models-unavailable. Availability never substitutes another model or rewrites a Session selection.

A successful selectModel response acknowledges the recorded Session selection without waiting for the default profile setting to save. The loop registers its projection; a change applies to the next step while a prepared step retains its captured choice. Default saves run in the background in submission order; a failure logs a warning and leaves the Session selection intact. A Session with no recorded selection or request reads the last successfully saved default through live AgentOptions accessors. An explicit choice is recorded even when it equals that default. Omitting reasoning effort clears the explicit effort and lets each request use the adapter default.


Configuration

Field Default Meaning
nativeOpen platform-detected Whether Session workspace paths can be handed to a native desktop opener
listWorkSliceMs 16 Positive integral list-work time slice in milliseconds; checks occur between complete rows

The generated configuration catalog is the exhaustive source for accepted fields and their JSDoc.


Blockquotes travel as ordinary prompt text without quote metadata. Local submission echoes and durable messages use the same text rendering rules; queue edits replace content while retaining prompt correlation.

An empty prompt.content array requests a new turn only for an eligible failed, idle ordinary Session in queue mode. Pending human input prevents admission; non-waking injected context is retained. conversationContinuation supplies the shared six-code manual policy, independently of provider retry configuration. The input follows ordinary inbox and Loop admission and records an empty user/message with source.kind: 'retry'; its input identity and caller metadata support deduplication and recovery. Whitespace-only text parts remain invalid.

Model Experience

None, as invoked Agent commands own any model-visible effect.

KV Cache effect

No direct effect; model requests remain owned by the Agent and LLM packages.

Known Limitations and Deferred Work

  • A single summary, the query provider's own enumeration, final sorting, and response serialization can exceed the list work-slice target; it is not a hard Host latency bound.
  • The image byte cap does not validate decoded dimensions or pixel count.
  • A failed follow resumption remains visible to the caller instead of retrying indefinitely.
  • The raw browser upload is one streaming HTTP request without resumable offsets; a retry sends the file again from byte zero.
  • Fork title increments compare candidates with the Client list before the Host normalizes them: concurrent forks of one source, or a title the Host truncates at its byte limit, can still produce duplicate titles.
  • File-reference completion uses the shared Agent lookup and can resume a cold Session; the skills/list catalog is the non-activating alternative for skill metadata.
  • Accepted/running display memory lives only in Client memory and is lost on page reload.
  • That memory is not shared between tabs: one tab can show a converted row while another still shows New Session for the same Session.

Dev Note

Working context for maintainers — click to expand

None.