* feat(session-query): import DeepSeek chat exports as Sessions Add @deepseek-ai/dsh-deepseek-chat-import: the browser uploads a deepseek_data-*.zip export, the Host buffers it in memory (bounded by maxUploadBytes, default 512 MiB), linearizes each conversation tree to its newest leaf, keeps the most recent maxSessions conversations, and stores one Session per conversation in the chosen Workspace with original titles and times. Reasoning, answers, web search/open fragments, and exported images map to native events and attachments; withdrawn, failed, and templated replies end their turn with an error and stay out of model context. Also add the sidebar.session.action slot beside New session, publish the New-session Workspace menu as the reusable workspace.picker Factory (with a directory-flow hole both directory pickers fill), and add an upload icon. * refactor(experimental): ship DeepSeek chat import as an optional bundle Move @deepseek-ai/dsh-deepseek-chat-import from packages/session-query to packages/experimental under its unprefixed name (recorded in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS). The Web composition no longer mounts it: the package now declares dsh.bundle.patch with its own deepseek-chat-import row, an icon, and localized display metadata, and joins OPTIONAL_BUNDLES, MORE_BUNDLES, and EXPERIMENTAL_BUNDLES, so the Plugins page offers it switched off under More with the Experimental badge. The dsh installation carries it as an optional-bundle dependency. Also fix the test typings that failed the aggregate build:check (branded SessionId keys, the generic renderFactorySlot stub, an ArrayBuffer-backed Request body), the lines oxlint rejected, and regenerate the config catalog, module graph, and dsh-doc package list. * docs(experimental): document DeepSeek chat import as an optional bundle Rewrite the DeepSeek chat export import Agent Note for the current design, add its English counterpart and pairing record: browser upload to an owner-only exact route, in-memory unzip bounded by maxUploadBytes, one import at a time, a Workspace chosen through workspace.picker, the closed failure reasons, and delivery as an experimental optional bundle. Record the rejected host-path input, Workspace file listing, and disk staging alternatives. Add the package README pair in the package-bundle layout (enabling from the Plugins page, Config fields, results, failures, implementation, Model Experience, limitations), list the package in the experimental group tables, and re-record the ui-sidebar README pair whose sidebar.session.action paragraph changed on both sides without a new record. * fix(experimental): import DeepSeek chat exports one conversation at a time Address the review of the DeepSeek chat import route and importer: - Decompress with fflate's asynchronous unzip, one entry per request, and refuse any entry whose declared uncompressed size exceeds the new maxEntryBytes (default 256 MiB) before inflating it. A first pass keeps only each conversation's entry, id, title, and last-message time; a second pass imports the selected conversations oldest first, one at a time, yielding to the event loop between them. - Fill the Session limit with the next older conversation when a selected one fails; omittedByLimit counts only conversations never attempted. - Check that the Workspace still exists before each write; a Session stored but not attached is reported in skipped with its id. - Stream the route answer as NDJSON progress lines and one outcome line; the dialog shows a progress bar and "Importing n/K". - The service owns the single import slot and an AbortController per request; unloading cancels the running import and waits for it to stop. - Buffer the upload once, sized from content-length; drop the unreachable 405 branch. - limits() refuses non-owner callers. - Normalize titles with normalizeSessionTitle (new maxTitleBytes, default 80); fixed error codes for unfinished replies with DEEPSEEK_EXPORT_UNFINISHED_REPLY for unknown statuses; an empty user message becomes "[empty message]"; a question whose reply was withdrawn by content filtering is left out together with the reply. - The plugin entry exports only the Service class, error classes, and types. - The dialog shows thrown errors, refreshes the Session list after every attempt without turning a success into a failure, and chooses singular or plural summary lines. * docs(experimental): document and test the per-conversation chat import Move the DeepSeek chat export import Agent Note to implemented/feature with the Decision/Consequences skeleton and describe the shipped design: two passes over the in-memory archive, the maxEntryBytes and maxTitleBytes limits, NDJSON progress, the service-owned import slot and unload cancellation, owner-only limits(), filling the limit, the per-conversation validation guarantee, attach failures without a persistence delete, the [empty message] placeholder, dropped content-filtered rounds, fixed error codes, and branch selection that ignores current_message_id. Update the package README pair to match, rewrite the unit tests for the new importer, route, archive, and client behavior (including a declared-size zip bomb, a misdeclared entry, buffer sizing, owner-only limits, and unloading during a paused import through the real Loader composition) at 100% per-file coverage, classify normalizeSessionTitle as a peer-required Host export, record the Session exports the importer already uses in the dependency policy spec, fix the lines oxlint rejected, and regenerate the config catalog and module graph. * fix(experimental): give imported Sessions a protected empty system head An imported seed had no system/message, so a resumed Agent appended its system prompt after the imported history. The released Session format accepts a system/message only as surface node 0 or after such a head, and the JSONL reader checks this on every read, so a continued imported Session failed to open again with SessionPersistenceCorruptionError. The first imported turn now writes an empty system/message as surface node 0. It derives no model message and renders no prompt card; on resume the Agent replaces it with the real prompt. The resume test asserts the single replacement, one system message in the model request, and a successful read of the stored log after the turn. * test(web): record a DeepSeek chat import snapshot Add the keyless Web snapshot case snapshots/web/deepseek-chat-import with its driver apps/web/tests/deepseek-chat-import.e2e.ts. The driver enables the optional bundle in the scaffold profile, uploads a synthetic export through the owner route (two conversations: a branch, reasoning, a web_search/web_fetch pair, a content-filtered round, and an incomplete reply), opens the imported Session in the browser, and continues it with one recorded model turn. The persisted log shows the empty system head replaced by the real prompt and replays without a key. Register the driver in the Host program and out of the Web Client program, and point the package README pair and the Agent Note at the case. * fix(experimental): classify the chat import service in the doc gates The chat import service surfaces in the Cordis catalog, the capability-seam graph, and the plugin manager inventory, but none of the three gates knew about it: doc graphs threw on the missing role classification, the catalog gate rejected the unclassified `DeepseekChatImportLimits` and the service without a subsystems page, and the Web inventory expectation predated the bundle. Map `ctx.deepseekChatImport` to persistence.md and classify the limits type and service role, then regenerate the catalog and graph docs. The two Web replay fixtures were recorded before the bundle was listed, so regenerate them against the current catalog and plugin inventory. * fix(experimental): upload chat imports through the page transport carrier A page whose Host runs in another execution context has no HTTP server: the preview answers the archive POST with 405. Send the export through the pre-boot `__DSH_TRANSPORT__.fetch` carrier when a shell installed one, and keep XMLHttpRequest on served pages so the browser still reports upload progress. * test(experimental): cover the chat import upload carrier path Cover the page-transport branch of the export upload, which the previous commit left untested: the carrier request, a streamed NDJSON answer, an answer without a body, non-200/JSON/result failures, and cancellation before and during the request. Both upload paths now share one answer collector, so the XHR path keeps its behavior with fewer branches. Resolve the generated `./remote` contribution through a stand-in when this package has no built `lib/`, as the LiveShare suite does: on a clean checkout Vite transforms the client entry before `vi.mock` can answer that import, which failed the jsdom assembly suite in CI. Record the Chinese capability-seams row and the pair after the generated English row, so the bilingual pairing gate passes. * feat(experimental): import the 2026-11-12 DeepSeek chat export structure The 2026-11-12 exporter keeps `export_format_version: 3` while adding `current_message_id`, `stage_id`, tool statuses, plaintext `READ_LINK` fields, and exported `TOOL_FIND.pattern`. Read the added fields as optional so a structurally older archive still imports. - Select the branch ending at `current_message_id`, falling back to the greatest message id when the field is absent, null, or unknown. - Split steps at a `stage_id` change; fragments without one keep the reasoning-or-text-after-a-tool-call rule. - Replay a `FAILED` search as an error result, skip `WIP`, and treat a missing `status` as `FINISHED`. - Write placeholder lines for opened pages without an address, links, image searches, partial file reads, tips, and page finds instead of dropping them; keep `CONTENT_RISK` dropped. - Cover the new fields with a synthetic archive test, update the Web snapshot driver to the new structure, and refresh its fixture. * docs(experimental): record the 2026-11-12 chat import structure Update the package README pair and the Agent Note pair for the branch rule (`current_message_id` with the greatest-id fallback), the new fragment mappings, the `TOOL_FIND` pattern, the `stage_id` step rule, and the limitation that only the 2026-11-12 structure is supported. Re-record both translation-pairing records. * fix(experimental): reject duplicate and misdeclared archive entries A ZIP may list several entries under one name, and read() selects by name, so duplicates decompressed every match at once and bypassed maxEntryBytes. Reject a directory with duplicate names while opening the archive. A ZIP_STORED entry is copied by its compressed size, not by originalSize, so a stored entry could declare 16 bytes and deliver a megabyte. Require the declared and stored sizes to agree and bound both by maxEntryBytes before anything is copied. * fix(experimental): validate the chat import answer lines parseLine cast decoded JSON to the line union, so a null or any other valid JSON threw when the reader read line.type. In the XHR path that throw happened inside onload/onprogress, leaving the upload promise unsettled and the dialog on "importing". Validate the decoded value against the union with typed guards: an object of a known type with that type's fields. An invalid line now fails the answer as "the server answered with invalid JSON". Covered on both the XHR and carrier paths. * fix(experimental): keep call-less chat import steps open and bracket tips A stage_id change split a step even when it held only placeholder text, so a placeholder-only step became an assistant message without a call and the resumed history carried two adjacent assistant messages, which the live agent loop never produces. Split only when the open step already holds a tool call; otherwise update its stage. A TIP is a website notice attributed to the assistant, so write it as the bracketed placeholder [tip: ...] like the other non-model records. * fix(experimental): report the import limit the Host applied The pre-check limit (maxUploadBytes) was attached to every Host failure, and failureText printed only that limit, so a manifest over maxEntryBytes was reported as "the file is too large: the limit is 512MB". Attach the pre-check limit only to the browser's own too-large outcome and show the Host's message when it reports too-large, which names the real limit. * fix(client): fade the imported sidebar action in with the rail The rail-in fade targeted .newSessionRow > *, whose slot entry is the renderer's display: contents anchor: it has no box, so the imported button appeared without fading next to New session. Hit the anchor's child too and assert the selector keeps the rail-in animation. * docs(experimental): describe the chat import upload carrier A page whose Host runs in another execution context, such as the static Cloudflare Pages preview, supplies __DSH_TRANSPORT__.fetch and carries the archive over it with no byte progress, straight to the reading and importing phases; a served page uses XMLHttpRequest. Record that in the README and the Agent Note, and list the missing upload percentage under Known Limitations. Also record the bracketed [tip: ...] placeholder, the stage-split rule that keeps call-less steps merged, the within-step block order, and why dsh-client-file-upload is not reused. Re-record both i18n pairs. * fix(client): fade only the slot entry with the rail The rail-in rule reached every child below the row's slot anchor, which also matched the label mask and shortcut inside the New session button: the button ran the animation twice, so its icon was clipped and then slid in from the edge. Target the renderer's `data-slot` anchor child, which is the registered session action alone, and assert that no rule under the row reaches into the button. * feat(experimental): stream the chat import from the export index `chat_session_index.json` now selects the conversations: the newest `maxSessions` by its `updated_at` (ties by `inserted_at`, then id) are imported, and a missing or unreadable index fails with the new `missing-index` reason instead of falling back to a scan. The selected conversations are handled in one streaming pass over the archive. Each conversation is parsed, converted, and written as it arrives; one that waits for its images is held until they stream past or the archive ends, and images that never arrive stay placeholders. No conversation the index does not select is inflated, and a failure pulls the next older indexed conversation by name. The pass reports a stored entry whose declared size differs from the bytes it holds as damage, not as an oversized entry, and reports actual bytes above `maxEntryBytes` as oversized. * refactor(client): wrap the New-session row with the session-action slot Make `sidebar.session.action` an HOC layer instead of a list: the shell passes the New-session Tooltip and button as `children` and an occupant returns them together with its own controls. No wrapper element is added, the per-entry anchors are gone, and an occupant that adds nothing (or may not act) returns `children` unchanged. The rail-in fade now targets the outlet anchor's children, because the renderer's `display: contents` anchor has no box of its own; the style spec asserts the rule matches both buttons and nothing inside them. * fix(experimental): read chat-import images by name Resolve each selected conversation's images by name through the archive's targeted read instead of holding the conversation until its image entries stream past. Archive entry order no longer decides whether an image is attached, and an image rejected for size or corruption reports its own reason. A replacement conversation now runs image planning and reads inside its per-conversation failure handling, so an invalid candidate is skipped instead of aborting the import. * docs(experimental): record chat-import residual risks Document the synchronous inflation that outlives the entry size bound, duplicate local file headers, partial writes after a mid-pass archive failure, by-name read truncation, and attachments stored for withdrawn rounds. Explain the session-action HOC layering and the children obligation in the Agent Note, and align both language pairs. * docs(experimental): give the chat import a plugin detail page The Plugins page renders `meta.detail` rather than the README, so the package now ships `docs/DETAIL.md` and `docs/DETAIL.zh.md` beside Chinese and English preview images of the import dialog. Every locale names its detail document, and `docs` joins the published files. * fix(experimental): store chat-import images in one archive pass Pass 1 stores every image entry of a conversation the index chooses, before any conversation is parsed, and records the reference or the reason it stayed a placeholder. Pass 2 converts and writes each chosen conversation from those references, so the main path no longer re-parses the central directory once per image. A replacement conversation is still read by name once, and its images come from one further image pass. Correct the convertWithStoredImages JSDoc and the Known Limitations entry: the images-first order makes validate-before-store impossible, so images of a withdrawn round, a dropped branch, or a conversation that fails conversion or Session.create seed validation stay stored without a referencing event. Neither SessionPersistence nor the attachment store offers a removal. Settle the browser answer on the first invalid NDJSON line in both the XHR and page-carrier paths, cancel the rest of the stream, and prevent a later outcome from replacing the failure. * fix(experimental): drop image searches and address-less opens from the chat import The website shows neither of these in a reply, so the import no longer writes a line for them: - `TOOL_IMAGE_SEARCH` replays as nothing. The searched image is not in the export and the reply's reasoning already states what the model took from the results, so the `[image search: n results]` line carried no information a reader could act on. - A `TOOL_OPEN` without an address is the all-null record the exporter writes beside the real page opens of a stage, carrying only `stage_id` and `group_id`; it names no page and replaces the line `[opened page: the export recorded no address]` with nothing. A constructed archive with a pictured question, an image search, two opened pages, and the all-null record now imports to the image, the two fetch cards, the reasoning, and the answer. * feat(experimental): show imported files as cards instead of placeholder text The website shows none of these records as reply text, so the import now matches it: - A non-image file, and an image the archive cannot store, become a synthetic file card: the standard card renders its icon, name, and exported size, and no bytes exist behind the reference. - A `READ_LINK` record becomes one Markdown link line per linked page. - A `TOOL_FIND`, `PARTIAL_FILE_READ`, `TIP`, or `TOOL_IMAGE_SEARCH` record leaves no trace in the reply. - A user message without any content keeps one empty text block instead of `[empty message]`. `file_size` is optional in the export schema so an archive without it still imports. * fix(session-query): keep the session-log export when an attachment is gone A reference whose stored object was deleted failed the whole ZIP download. Each attachment is now read inside the entry that needs it: a missing object is recorded in `attachments-missing.txt` with its archive path and reason, while every other read failure still fails the export. A file's first chunk is pulled before its entry is yielded, so an absent object no longer breaks the download halfway through. * fix(experimental): take attachment brands and error codes from their owners The import package now builds the synthetic file reference with `brandString<AttachmentId>` from dsh-brand instead of importing the attachment package's runtime helper, so dsh-attachment stays type-only and dsh-brand becomes its one runtime dependency. The log export matches the missing-object code on the error instead of importing the class, which keeps that class its owner's peer. The recorded web snapshot follows the new link line. * fix(session-query): release an abandoned attachment stream and accept invalid references A consumer that stops early left the open file iterator to the garbage collector: the entry's stream is now closed by the entry owner too, so a cancelled download releases it. A reference the backend rejects as invalid joins a missing object as a reported skip rather than failing the download. The chat import documents that an empty question's text block is dropped by DeepSeek request serialization, so that Turn's question stays out of the model context. * docs(experimental): drop a duplicated clause from the import note * fix(session-query): close abandoned attachment streams without masking failures Closing one stream must not keep the others open or replace the failure in flight: the streams live in a set that removes each entry as it closes, and the drain settles every close. The chat import converts a pictured conversation once, resolving its references first, and states both possible model handles for a synthetic card.
28 KiB
会话持久化
English | 中文
事件日志的持久性 seam。session.md 描述了内存中的 Session:仅追加的 SessionEvent 日志即为真源。本页描述如何使该日志持久化:抽象的 SessionPersistence 服务、它的提供方模型与随产品交付的 JSONL 后端、flush 检查点、崩溃恢复,以及随日志一同存储的元数据头。日志承载的事件词汇在生成的持久化日志事件目录中逐项列举。
该 seam 是一个能力 seam:一个抽象服务(dsh-session-persistence,ctx.sessionPersistence)在现有 SessionEvent 上暴露 create/open/stat/list——没有平行的持久化事件类型——其中 create 与 open 返回逐会话的 SessionHandle(read/append/flush/close),它承载全部日志访问与单写者所有权。仓库随产品交付 dsh-session-persistence-jsonl 作为其 provider;仓库外 provider 可以实现同一服务约定。见基于句柄的持久化 Agent Note与 session-persistence reference。
SessionHandle——通向已存储会话的一条打开通道
每一次日志读写都经由句柄流动,绝不经由按 id 寻址的服务方法:句柄是跨进程写租约把守的唯一入口。读取会返回调用方独占的外层 slice,以及由生产者建立的 event value 别名状态。一种句柄类型同时服务两种访问——在 read 句柄上执行修改是运行时的 SessionReadOnlyError,而非类型层面的拆分——而进程内单写者所有权使得在已有活跃持有者时第二次 open(id, 'write') 以 SessionAlreadyOwnedError 拒绝。
/** One persistence event slice returned by {@link SessionHandle.read}. */
interface SessionHandleReadResult {
/**
* Whether event values are exclusively owned or shared only after deep
* freezing. Slicing preserves the producer's state even when no events remain.
*/
readonly eventState: SessionSeedEventState
/** Event values in a caller-owned outer array. */
readonly events: readonly SessionEvent[]
}
/**
* One open channel onto a stored session. A handle is single-owner state, not
* a shared service: `read` never backtracks below what this handle already
* observed, a `write` handle reads its own successful appends, and `close()`
* is the one teardown (idempotent, uncancellable; `Symbol.asyncDispose`
* delegates to it). Every operation on a closed handle rejects with
* `SessionHandleClosedError`.
*
* Freshness across handles: once an `append` or `flush` resolves on a write
* handle, every read STARTED afterwards on the same backend instance — on any
* handle, or through `stat`/`list` — observes at least that prefix.
* Reads concurrent with a mutation carry no ordering promise beyond the valid
* contiguous prefix.
*/
interface SessionHandle extends AsyncDisposable {
/** The stored session this handle addresses. */
readonly id: SessionId
/** The immutable stored header, fixed at `create`/`open`. */
readonly header: SessionHeader
/**
* Exact fork-inherited prefix length stored with the log; `0` when
* `header.isSeeded` is false. Storage metadata paired with the header for
* every body read, never part of the replayable event log.
*/
readonly inheritedEventCount: SessionLogOffset
/** Whether this handle may mutate the log. */
readonly access: SessionAccess
/**
* Read a slice of the valid contiguous logical log. The slice is a legal log
* prefix segment: a torn physical tail is never returned, and repeated reads
* on this handle never observe an older state than a prior read.
* @param offset - first logical event seq to include; defaults to `0`.
* @param length - maximum number of events to return; defaults to the rest
* of the log. An offset at or past the end returns an empty list.
* @param options - optional cancellation.
* @returns the caller-owned outer slice plus the ownership state of its event values.
*/
read(offset?: number, length?: number, options?: SessionHandleReadOptions): Promise<SessionHandleReadResult>
/**
* Append a contiguous batch continuing the current logical end. The first
* event's `seq` MUST equal the stored next-seq; committed events are never
* rewritten. Persistence is best-effort: on resolution the batch is
* accepted, ordered, and visible to reads on this backend instance, but
* only a resolved {@link flush} promises it survives a crash — a backend
* may buffer or batch physical writes behind append. Rejects with
* `SessionReadOnlyError` on a read handle and `SessionOwnershipLostError`
* when write ownership is gone.
* @param events - the contiguous batch, in seq order.
* @param options - optional cancellation observed before the write starts.
*/
append(events: readonly SessionEvent[], options?: SessionHandleAppendOptions): Promise<void>
/**
* The durability barrier — the one operation that promises storage: on
* resolution every acknowledged append is durable and the session is
* materialized for other processes; an empty created session becomes
* durably listable here. Callers that must survive a crash flush; a backend
* whose `append` already persists on resolution treats this as
* materialize-if-needed. Rejects with `SessionReadOnlyError` on a read
* handle.
* @param options - optional cancellation observed before the barrier starts.
*/
flush(options?: SessionHandleFlushOptions): Promise<void>
/**
* Release the handle: a read handle frees local resources; a write handle
* completes pending durability and releases write ownership. Idempotent,
* asynchronous, and deliberately not cancellable.
*/
close(): Promise<void>
}
已创建的会话自 create 完成之刻起即可在本进程内被观察到,而后端可以把物理实体化(纯粹的优化)推迟到第一次 append 或 flush;其他进程只能看到已实体化的会话,一个在崩溃前从未实体化的会话等于从未存在。
flush 检查点
session/event 是一个同步通知;挂载的后端按会话 id 把它路由进活跃写句柄的有界 write-behind 窗口,而不阻塞生产方(后端一次性安装这些监听器,因为持久化已保证每个 id 只有一个活跃写句柄)。第一个待处理事件会开启固定的内部批处理窗口,后续事件会加入但不会重置其截止时间。窗口到期后会通过该会话的写句柄启动一次持久化 append;该次写入期间接纳的事件会获得自己的截止时间,并形成后续批次。session/flush 会取消等待并排空至完全停稳,因此循环仍将其用作在领取下一个普通轮次之前的顺序与错误观察检查点。后台写入被拒绝时会按序保留对应事件、暂停自动路径,并通过 logger 报告;下一次显式 flush 会重试,并向其调用方响亮地拒绝。session/disposed 会执行同样的最终排空并关闭句柄,而 close() 本身会经由仍然打开的存储排空已路由的缓冲,因此后端 teardown 的关闭清扫不丢任何数据。该窗口只限制有意的批处理等待,不限制事件循环调度或后端完成持久化的延迟。
崩溃恢复保留被中断的轮次
一个在轮次中途崩溃的日志以打开的 turn/start 而无 turn/end 结束。持久化不会截断或修复它:在长周期任务中,单个轮次可能非常庞大(许多步骤、大量工具输出),而这些事件在崩溃前已被持久追加。它返回物理上有效的连续日志;只有撕裂物理尾部——属于一次从未完成的 append——中不完整的碎片会被丢弃:从中恢复的完整记录(JSONL 后端会部分解码撕裂的 Zstandard 帧)由写路径在句柄的第一次新 append 之前持久重写。修复是读方的职责:resume(agent-loop)通过其写句柄读取已存储的日志,计算 interruptedTurnClosers——缺失的工具错误、任何未闭合的 step/end,以及一个合成的 turn/end { reason: { kind: 'interrupted' } }——并在发布 Session 之前把它们作为普通批次通过同一句柄追加。interrupted 是唯一一个不由循环发出的 TurnEndReason(见 session.md)。
因此修复只在写所有权之下写入:活跃会话的写句柄由其生命周期所有者持有,故并发的 open(id, 'write') 会以 SessionAlreadyOwnedError 拒绝,而不是让修复与活跃轮次竞速。只读观察方(session-query)仅在内存中用同样的闭合事件配平被中断的冷日志,不回写任何内容。
只读观察即 open(id, 'read'):句柄提供经过验证的连续前缀切片,绝不返回撕裂尾部,且同一句柄上的重复读取绝不会观察到比先前读取更旧的状态。持久化侧不存在已准备 Session 缓存:session-query 拥有自己的冷读缓存,按 stat().revision 变更令牌为每个 id 缓存一个已配平的冷 Session,仅在令牌变化时重新读取。该生命周期由基于句柄的持久化 Agent Note定义;已归档的 Session 准备阶段记录记载了发布边界 SessionPreparation 最初的决策。
SessionLocation——每一 Session 的产物元数据
SessionLocation 用于诊断与导出的观察元数据;日志访问仍走会话句柄的 read。已物化的持久化快照携带选中产物路径,SessionFormatUnsupportedError 也能指出本构建拒绝解读的原始日志。JSONL 提供其项目/会话目录内 transcript(文本记录)的绝对路径;没有逐会话工件的后端则不提供。
/**
* A backend-resolved, per-Session local artifact path used by observational
* snapshots and refusal diagnostics. It names a backend target for the Session
* and does not authorize reads; log access still goes through a session
* handle's `read`. It is not persisted Session content.
*/
interface SessionLocation {
/** Backend-specific artifact kind, for example `jsonl`. */
readonly kind: string
/** Absolute path to this session's backend-owned artifact. */
readonly path: string
}
SessionHeader:日志旁的元数据
每个会话的元数据与事件日志分开存储:header 携带格式版本、cwd 与 isSeeded 谱系 bit,含正文的存储值则在其旁边单独携带精确 inherited cut。二者都不进入 SessionEventMap,也不会到达 deriveMessages()。logical header 通过 session.header 附加,Session 则以 inheritedEventCount 暴露其 cut。
源码:packages/core/session/src/types.ts
/**
* Immutable validated storage metadata, kept outside the conversation event log.
*/
interface SessionHeader {
/**
* Current logical format version, stamped from {@link SESSION_FORMAT_VERSION}.
* Historical physical headers are translated before entering this interface.
*/
readonly version: typeof SESSION_FORMAT_VERSION
/** The session's id (mirrors the {@link Session}'s id). */
readonly id: SessionId
/** Non-negative safe-integer Unix epoch milliseconds when the session was created. */
readonly createdAt: number
/** Absolute working directory the session was created in (if any). */
readonly cwd?: string
/**
* Direct creator of a subagent Session. Ordinary forks omit this field;
* historical ordinary forks may retain their source id here. Presence alone
* does not classify a Session as a subagent; use `origin` for that distinction.
*/
readonly parentSession?: SessionId
/**
* Whether this Session contains a fork-inherited event prefix. The exact prefix
* length is Session state rather than ordinary header metadata.
*/
readonly isSeeded: boolean
/**
* Coarse product classification for a session created as a subagent child.
* This is presentation metadata, not proof that the child is continuable.
*/
readonly origin?: 'subagent'
/**
* Delegation depth: absent (zero) for a top-level session, parent depth + 1
* for a subagent child. Persisted so a recursion budget survives restart and
* resume — a runtime-only depth would reset a resumed child to top-level.
*/
readonly delegationDepth?: number
/**
* Id of the agent preset this session's agent was composed from, when the
* deployment composes per session. Durable because the preset decides the
* session's tools and prompt: a resume that restored a different composition
* would replay history the model can no longer act on.
*/
readonly agentPreset?: string
}
格式拒绝:本构建无法可靠读取的日志
后端用 SessionFormatUnsupportedError 拒绝无法可靠解读的日志,它与 SessionPersistenceCorruptionError 区分,因为数据没有损坏。stat 与 list 会对最高规范 generation 分类,并在不读取或改变正文的前提下转换受支持的历史 header。历史 open 会共享每个 Session 唯一的一次 migration preparation,再返回当前逻辑值,并保持每个源路径、字节与 inode 不变。JSONL provider 直接从该内存结果返回读句柄而不发布;写 open 则在持有单写者 claim 与文件 lease 时复用 preparation、排他发布最终 current generation,随后才返回可写句柄。即使仍有较旧的可读 generation,最高的未来 generation 仍会导致拒绝。当前格式恢复会保留已安装扩展和带 ignorable: true 的未知事件;历史 v0/v1/v2 迁移则会拒绝未知类型,即使它带有 ignorable 标记。后端为每个会话保留独立文件时,消息附上选定的原始日志路径。仓库外后端必须在自己的物理格式入口提供等价的仅当前句柄值与方向感知拒绝。已发布格式迁移决策负责迁移链与不可变发布规则。
CreateSessionOptions:seed 与元数据
通过 store 创建 Session 时会接收 seed(初始回放或 fork 历史)、可选的精确 inheritedEventCount 与 meta(store 整合进 SessionHeader 的存储层字段)。store 填充 version/id 并为 createdAt 提供默认值;调用方可以提供已校验的绝对 cwd、parentSession 谱系、isSeeded 谱系标记、可选的粗粒度 origin、delegationDepth、用于组装该 agent(智能体)的 agentPreset 以及已有的 createdAt。seeded 创建必须显式提供与 inherited prefix 完全相等的 seed 和精确 cut;constructor 会先在该 cut 追加 child-owned tagged end-seed marker,setup 再添加 child-owned event。origin: 'subagent' 让产品导航能够隐藏重复的 child 行;它不证明描述符有效,也不证明 child 可以恢复。
/**
* Options for creating a {@link Session} via the store. `seed` replays/forks
* an existing event log; `meta` carries the caller-supplied storage fields the
* store folds into a {@link SessionHeader}.
*/
interface CreateSessionOptions {
/** Initial replay or fork history supplied at construction. */
readonly seed?: readonly SessionEvent[]
/**
* Exact fork-inherited prefix length when `meta.isSeeded` is true. The
* constructor appends the child-owned tagged marker at the cut unless
* the seed already includes it followed by child-owned fork closers.
*/
readonly inheritedEventCount?: SessionLogOffset
/**
* Storage metadata read once before publication. `isSeeded` marks fork
* lineage; supplying replay history alone does not make it inherited.
*/
readonly meta?: {
readonly cwd?: string
readonly parentSession?: SessionId
readonly createdAt?: number
readonly isSeeded?: boolean
readonly origin?: 'subagent'
readonly delegationDepth?: number
readonly agentPreset?: string
}
}
因此,回放/fork 的调用方式为 ctx.agents.create({ sessionId, seed, meta })——fork 还会随 meta.isSeeded: true 提供 inheritedEventCount,且只有经 agent-loop 发布的会话才会持久化,且循环会在发布之前通过新会话的写句柄存储 seed;将一个持久化会话恢复为活跃 agent 的调用方式为 ctx.agents.resume({ resumeSessionId })。
准备与恢复所有权
SessionStore.prepare() 接收普通创建选项,或通过 RestoredSessionOptions 接收可直接接管的 seed。它的 eventState 表明 event value 是独占对象,还是只有深度冻结后的共享对象;生产者负责建立该状态,slice 不会根据结果长度推断其他状态。恢复流程会校验并直接接管这些值,不再复制或冻结。SessionPreparation 随后持有该精确的未发布 Session,直至发布或回滚;dispose 是同步且幂等的。agent-loop 的 resume 通过该会话的写句柄读取这份结果,并在准备之前追加独占的 interruptedTurnClosers。
/**
* Aliasing state of an adoptable Session seed. `shared-frozen` permits deeply
* frozen aliases plus independently owned unfrozen values in the same seed.
*/
type SessionSeedEventState = 'detached' | 'shared-frozen'
/**
* Adoptable storage values transferred to {@link SessionStore.prepare}
* without another copy or freeze pass.
*/
interface RestoredSessionOptions {
/** Events that are independently owned or already deeply frozen. */
readonly seed: SessionEvent[]
/** Independently owned storage metadata to validate and freeze in place. */
readonly meta: SessionHeader
/** Exact number of fork-inherited leading events decoded from storage. */
readonly inheritedEventCount: SessionLogOffset
/** Aliasing state carried from the operation that produced the seed. */
readonly eventState: SessionSeedEventState
}
/** Inputs accepted while constructing an unpublished Session. */
type PrepareSessionOptions =
| (CreateSessionOptions & { readonly eventState?: undefined })
| RestoredSessionOptions
/** Options for a preparation whose provider retains unpublished state. */
interface SessionPreparationOptions {
/** Release provider-owned state when the Session was not published. */
readonly release?: () => void
}
/**
* One exact unpublished Session and the provider state that keeps it usable.
* Disposal is synchronous and idempotent. Providers decide whether release
* returns the Session to a cache or discards it; publication may consume that
* state before disposal, making the callback a no-op.
*/
declare class SessionPreparation implements Disposable {
/** The exact Session to use for setup and publication. */
readonly session: Session;
/**
* Wrap an unpublished Session in one preparation lifetime.
* @param session - exact unpublished Session.
* @param options - optional provider release behavior.
* @returns a preparation disposed after publication or rollback.
*/
static create(session: Session, options?: SessionPreparationOptions): SessionPreparation;
/** Release provider state once when this preparation leaves its caller. */
[Symbol.dispose](): void;
}
轻量源修订号
派生读取模型的消费方会在加载完整事件日志之前比较一个低开销的不透明修订号。该修订号是来自 stat/list 的逐后端实例变更令牌:修订号相等可视为日志未变;不相等则不作任何承诺,且写所有权的变动绝不会改变修订号。session-query 以它为键管理冷读缓存;该令牌在 open、read 或 resume 中不起任何作用。
/**
* Backend-owned token that identifies both one storage source and one revision
* of a persisted session log.
*/
type SessionPersistenceRevision = Branded<'SessionPersistenceRevision'>
/**
* Lightweight stored-session observation returned by {@link SessionPersistence.stat}
* and {@link SessionPersistence.list} without reading the full event log.
*/
interface SessionPersistenceSnapshot {
/** Detached metadata for one stored session. */
readonly header: SessionHeader
/** Header-only format classification; absent without versioned artifact metadata. */
readonly formatStatus?: 'current' | 'migration-required'
/** Opaque change token; see {@link SessionPersistence.stat}. */
readonly revision: SessionPersistenceRevision
/** Logical event count, when the backend can provide it cheaply from metadata; otherwise absent. */
readonly eventCount?: number
/** Physical artifact byte size, when the backend can provide it cheaply (JSONL); otherwise absent. */
readonly sizeBytes?: number
/**
* Backend-resolved location of the selected materialized per-Session
* artifact, for diagnostics and export. Absent when the backend has no
* materialized per-Session file, including an unmaterialized pending Session.
*/
readonly location?: SessionLocation
}
可选的 eventCount/sizeBytes 字段仍是供明确需要它们的 consumer 使用的低成本 backend observation。Session 列表不借助这两个字段打开冷日志,只读取 header 与经过 identity 校验的 projection cache hint,因此 cache 或 Session format 升级不会把启动变成 body scan。
后端
随产品交付的 provider 实现抽象 SessionPersistence 约定(create/open/stat/list,逐会话 SessionHandle 承载 read/append/flush/close,全程可选支持取消),并通过共享的持久化契约套件:
- dsh-session-persistence-jsonl——逐会话仅追加的逻辑 JSONL 日志,默认存储为带 checksum 的连续 Zstandard frame,也可配置为原始行;具备崩溃安全的原子实体化、逐批
fsync的 append,以及在第一次新 append 之前截断撕裂尾部。stat/list携带sizeBytes与尽力而为的、由fs.stat派生的修订号。
Cordis API
Generated from source by scripts/gen-cordis-catalog.ts (verified fresh by pnpm run verify-cordis-catalog in doc-sync; regenerate with pnpm run gen-cordis-catalog) — the language sides differ only in locale-specific paired document paths. Signature blocks use a ts cordis-catalog fence and keep the original source JSDoc; dispatch modes are defined in the primer, and the framework-inherited ctx API lives in cordis-api/inherited.md.
ctx.deepseekChatImport — DeepseekChatImportService
Serves the owner-only export upload route and the limits the browser checks first.
/**
* Report the limits the browser checks before uploading. Only the owner may
* import, so every other principal is refused.
* @param signal - Client cancellation or Remote withdrawal.
* @returns the largest accepted archive size.
* @throws {RemoteError} `deepseekChatImport/owner-only` for a caller that is not the owner.
*/
@Remote limits(signal: AbortSignal): DeepseekChatImportLimits
Source: packages/experimental/deepseek-chat-import/src/index.ts
ctx.sessionPersistence — SessionPersistence (abstract seam)
Durable append-only session storage addressed through per-session handles.
Storage semantics shared by every backend: events are contiguous from seq 0 and never rewritten; a torn physical tail is never returned to a reader and is truncated by the write path before its first append; reads validate current-format records only and refuse unknown vocabulary fail-closed. append persists best-effort; flush — per handle or service-wide — is the durability barrier.
Visibility: a created session is observable through stat/list/open in this process from the moment create resolves, even while a backend defers physical materialization (a pure optimization); other processes see the session only once it materializes, and a session that never materialized before a crash never existed. SessionHandle.flush forces materialization.
Freshness: once an append or flush resolves, reads started afterwards on this backend instance observe at least that prefix.
/**
* Create a new stored session and take its write ownership.
* @param header - the immutable header (id, version, cwd, lineage) to store.
* @param options - optional cancellation.
* @returns a `write` handle owned by the caller; close it to release ownership.
* @throws {SessionAlreadyExistsError} when the id already exists.
*/
abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise<SessionHandle>
/**
* Open an existing stored session.
*
* `read` never takes ownership and works while another handle (or process)
* holds write ownership. `write` atomically claims single-writer ownership;
* an existing active owner rejects.
* @param id - the stored session to open.
* @param access - `read` or `write`.
* @param options - optional cancellation.
* @returns the open handle.
* @throws {SessionPersistenceNotFoundError} when the session does not exist.
* @throws {SessionAlreadyOwnedError} for `write` when ownership is taken.
*/
abstract open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle>
/**
* Flush every active write handle owned by this service instance in one
* durability barrier: each handle's routed live events drain durably and
* its session materializes, exactly as that handle's own
* `SessionHandle.flush` would. Read handles buffer nothing and are
* untouched. A handle closed concurrently counts as flushed — close itself
* drains durably.
* @returns resolution once every write handle active at the call has flushed.
* @throws {AggregateError} naming each session whose flush failed; the
* remaining handles still flush.
*/
abstract flush(): Promise<void>
/**
* Observe one stored session without reading its event log or taking
* ownership.
*
* The snapshot's `revision` is an opaque change token comparable only
* against revisions from the same service instance and session id: equal
* revisions may be treated as an unchanged log; unequal revisions promise
* nothing. Write-ownership churn does not change a revision. It exists for
* derived read-model caches keyed off `stat`/`list`; it plays no part in
* open, read, or resume.
* @param id - the stored session to observe.
* @param options - optional cancellation.
* @returns the snapshot, or `undefined` when the session does not exist.
*/
abstract stat(id: SessionId, options?: SessionPersistenceStatOptions): Promise<SessionPersistenceSnapshot | undefined>
/**
* List every stored session visible to this process, in no promised order.
* @param options - optional cancellation.
* @returns one snapshot per stored session.
*/
abstract list(options?: SessionPersistenceListOptions): Promise<readonly SessionPersistenceSnapshot[]>
Types: SessionId