@deepseek-ai/dsh-api-session-controller 0.1.3-alpha.2 → 0.1.5-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +2 -2
- package/README.md +12 -2
- package/README.zh.md +12 -2
- package/lib/client.js +246 -30
- package/lib/index.js +107 -29
- package/lib/typert.host.js +71 -55
- package/lib/typert.remote-client.js +34 -34
- package/lib/types/agent.js +6 -8
- package/lib/types/client/session-wire-event.d.ts +11 -0
- package/lib/types/client/session-wire-event.js +43 -0
- package/lib/types/client/transport.js +6 -0
- package/lib/types/commands.d.ts +1 -1
- package/lib/types/commands.js +14 -4
- package/lib/types/control.d.ts +0 -1
- package/lib/types/control.js +19 -22
- package/lib/types/index.js +2 -0
- package/lib/types/media-references.d.ts +16 -0
- package/lib/types/media-references.js +77 -0
- package/lib/types/types.d.ts +15 -7
- package/package.json +71 -64
package/README.i18n.yaml
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
|
3
3
|
# after editing either side, bring the other along and re-record with:
|
|
4
4
|
# pnpm run verify-translation-pairing --write packages/api/session-controller/README.md
|
|
5
|
-
README.md:
|
|
6
|
-
README.zh.md:
|
|
5
|
+
README.md: ef6ffb35636f9f1a87c3b30832f68540d5dcd0ea
|
|
6
|
+
README.zh.md: 97949e01379446e6171debb9fb1250e8088413f8
|
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@ English | [中文](README.zh.md)
|
|
|
13
13
|
## Table of Contents
|
|
14
14
|
|
|
15
15
|
- [Use this package](#use-this-package)
|
|
16
|
+
- [Session media references](#session-media-references)
|
|
16
17
|
- [Configuration](#configuration)
|
|
17
18
|
- [Model Experience](#model-experience)
|
|
18
19
|
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
|
@@ -25,12 +26,20 @@ English | [中文](README.zh.md)
|
|
|
25
26
|
|
|
26
27
|
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.
|
|
27
28
|
|
|
28
|
-
|
|
29
|
+
The Client journal validates exact V3 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 provenance, 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.
|
|
29
30
|
|
|
30
|
-
|
|
31
|
+
Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. 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, attachment, 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. Queue mutation and cancellation require live state; 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`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. 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 subagent ownership fence 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 when present or the recorded preset's standing scope when cold, so listing never starts an Agent.
|
|
32
|
+
|
|
33
|
+
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 50-message page, and `loadThrough(seq)` — the turn-jump loader — loops 200-message 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 publishes one named settlement delta that retires the attempt's transient rows and adds the durable entry while 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 queue, jobs, and projection state instead of treating transient values as durable events. For each inbox change, the Host publishes the projection frame first and derives the queue replacement from that same validated post-fold value, so listener registration order cannot produce a stale queue frame.Client Agent contexts provide the identity used by the independent [`fileUpload`](../../client/file-upload/README.md) service; Session objects expose lifecycle, prompt, queue, and history operations rather than file transfer.
|
|
31
34
|
|
|
32
35
|
The Session object also carries local submission echoes: `session.beginSubmission` inserts one into `SessionSnapshot.pendingSubmissions` synchronously, before the caller serializes and prompts, so a conversation UI can show the message on the submit click's own frame. 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 while serialization is in flight. The prompt's `requestId` is the correlation identity: the Host echoes it as the durable user source's `rpcId`, and queue occurrences project it as `SessionQueuedItem.rpcId`. An echo retires one animation frame after its durable event or queue occurrence is observed, immediately when its identified prompt fails or is abandoned, and as failed on disposal. Each retirement fires `onRetire` exactly once; an observed retirement includes the ordered durable attachment references so the composer can release successful cards while preserving failed drafts. Echoes are Client memory only; reload and reconnect rebuild the conversation from durable events alone.
|
|
33
36
|
|
|
37
|
+
|
|
38
|
+
<a id="session-media-references"></a>
|
|
39
|
+
## Session media references
|
|
40
|
+
|
|
41
|
+
`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 20 MiB); exceeding this limit returns 413. Responses contain the complete file, ignore Range, and carry `private, no-store`, `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.
|
|
42
|
+
|
|
34
43
|
-----
|
|
35
44
|
|
|
36
45
|
<a id="configuration"></a>
|
|
@@ -57,6 +66,7 @@ No direct effect; model requests remain owned by the Agent and LLM packages.
|
|
|
57
66
|
|
|
58
67
|
<a id="known-limitations-and-deferred-work"></a>
|
|
59
68
|
|
|
69
|
+
- The image byte cap does not validate decoded dimensions or pixel count.
|
|
60
70
|
- Control baselines represent process-local state and therefore cannot reconstruct jobs after a Host restart.
|
|
61
71
|
- A failed follow resumption remains visible to the caller instead of retrying indefinitely.
|
|
62
72
|
- The raw browser upload is one streaming HTTP request without resumable offsets; a retry sends the file again from byte zero.
|
package/README.zh.md
CHANGED
|
@@ -13,6 +13,7 @@ kind: "package-reference"
|
|
|
13
13
|
## 目录
|
|
14
14
|
|
|
15
15
|
- [使用本包](#use-this-package)
|
|
16
|
+
- [会话媒体引用](#session-media-references)
|
|
16
17
|
- [配置](#configuration)
|
|
17
18
|
- [模型体验](#model-experience)
|
|
18
19
|
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
|
@@ -25,12 +26,20 @@ kind: "package-reference"
|
|
|
25
26
|
|
|
26
27
|
历史页与 follow opening snapshot 为每个持久 Session event 携带一条 `{ type: 'event', event: SessionWireEvent }` record。Client 把每条已接受 record 保留为一个持久 `SessionEventLikeEntry`;Assistant token 边界保留在 `assistant/message` 或 `assistant/attempt` 的紧凑 stream 内。工具参数、结果内容、失败信息和 `tool/result.data.meta` 原样通过;controller 不解析 Tool definition、不运行 presenter,也不附加 UI 数据。
|
|
27
28
|
|
|
28
|
-
|
|
29
|
+
Client journal 在发布 follow snapshot、live entry 或历史页之前验证精确的 V3 event envelope。它复用浏览器安全的 Session validator,检查必需的 surface marker、精确的 replacement endpoint、更早且唯一的 source seq、内嵌 Assistant 来源、request header 可选字段的省略规则以及 tool error 一致性。无效 record 直接失败,不删除字段或归一化;范围成员与来源存在性仍由 Host 的持久日志检查。
|
|
29
30
|
|
|
30
|
-
|
|
31
|
+
每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。queue 变更与取消要求 live 状态;模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。prompt 会在解析 Agent 或追加 Session event 前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent,否则使用所记录 preset 的常驻 scope,因此列表查询绝不会启动 Agent。
|
|
32
|
+
|
|
33
|
+
Client adapter 提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend`、`append` 与 `settle-assistant` 变更,并通过 tail page 修复重连或 seq 缺口。向后分页有两个动词:`loadOlder()` 拉一页 50 条 message,而 `loadThrough(seq)`——轮次跳转加载器——按 200 条 message 一页循环拉取直到窗口覆盖目标 seq,重复调用会下调共享目标,遇到无进展的页即停止,忙碌状态复用同一个 `loadingOlder` 快照位。Web adapter 显式选择接收无 cursor 的 Assistant frame:每个 opening 携带活跃 attempt 的 `startedAfterSeq`、`nextIndex` 与紧凑 stream,每个 stream member 都成为排在持久 cursor 之间的 Client-only `assistant/live-chunk` 条目。Host 会随该 baseline 捕获 follower 本地到达序号,并抑制该 cut 及之前的 buffered frame;replacement Agent 可以从 revision 一重新开始。活跃 opening 之后到达的持久 `assistant/message` 或 `assistant/attempt` 只有在其 seq 晚于 `startedAfterSeq` 且 Turn 与 Step 匹配时才会保持暂存;匹配的 end type、seq 与 index 会发布一个具名 settlement delta,删除该 attempt 的瞬态 row、加入持久条目,并保留同一步骤中更早的 retry。已知 attempt 的 revision、密集 index 或 settlement 缺口会重新打开 follow;若 controller 错过 start,则忽略 unknown-attempt frame,并正常发布其持久 settlement。Abandoned end 会发布不含持久条目的 settlement delta,使瞬态 row 立即退出。持久缺口修复 page 不携带 Assistant baseline,因此 held notification 会重新打开 follow 一次,以取得配对的 page 与 baseline。每条历史 record 只覆盖自身的 event seq。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 queue、jobs 和 projection 状态,而不会把瞬态值当作 durable event。每次 inbox 变更时,Host 会先发布 projection frame,再从同一份已校验的折叠后值派生 queue replacement,因此监听器注册顺序不会产生陈旧的 queue frame。Client Agent context 提供独立 [`fileUpload`](../../client/file-upload/README.zh.md) 服务使用的身份;Session 对象提供生命周期、prompt、queue 与历史操作,不提供文件传输。
|
|
31
34
|
|
|
32
35
|
Session 对象还承载本地提交回显:`session.beginSubmission` 在调用方序列化与 prompt 之前,同步把一条回显写入 `SessionSnapshot.pendingSubmissions`,会话 UI 因此能在点击提交的当帧显示消息。回显按顺序存放图片预览与持久文件引用。Session 根据当前运行状态与请求的投递模式推导其 `transcript`、`queued` 或 `steering` 位置,并在序列化期间保留该位置。prompt 的 `requestId` 是关联标识:Host 把它回显为 durable user source 的 `rpcId`,queue occurrence 也把它投影为 `SessionQueuedItem.rpcId`。回显在观察到其 durable event 或 queue occurrence 后延迟一个动画帧退休,带标识的 prompt 失败或被放弃时立即退休,销毁时按 failed 退休。每次退休恰好触发一次 `onRetire`;observed 退休还会携带有序的持久附件引用,让 composer 释放成功卡片并保留失败草稿。回显只存在于 Client 内存;刷新与重连只从 durable event 重建会话。
|
|
33
36
|
|
|
37
|
+
|
|
38
|
+
<a id="session-media-references"></a>
|
|
39
|
+
## 会话媒体引用
|
|
40
|
+
|
|
41
|
+
当 `connection`、`fs` 与 `attachments` 均被组合时,`SessionMediaReferences` 在鉴权 `connection.fetch` 通道上挂载 `GET|HEAD /api/file?path=<绝对路径>`。它通过 `ctx.fs` 读取普通文件,包括已注册工作区之外的临时路径与远程提供方中的文件。目录包含关系与 MIME 类别均不限制访问;`mime-types` 提供响应类型,未知扩展名使用 `application/octet-stream`。GET 复用 `readBytes` 执行读取前及读取中的字节限制;HEAD 只读取元数据。所有文件均使用 `ctx.attachments.imageLimits.maxImageBytes`(通常为 20 MiB);超过此上限返回 413。响应包含完整文件,忽略 Range,并携带 `private, no-store`、`nosniff` 与 sandbox CSP,使直接打开的 HTML/SVG 无法以 API 源身份执行脚本。客户端重写位于 `ui-chat`(`AssistantMarkdown`);音视频文件响应已可用,Markdown 音视频播放器节点仍是独立工作。
|
|
42
|
+
|
|
34
43
|
-----
|
|
35
44
|
|
|
36
45
|
<a id="configuration"></a>
|
|
@@ -57,6 +66,7 @@ Session 对象还承载本地提交回显:`session.beginSubmission` 在调用
|
|
|
57
66
|
|
|
58
67
|
<a id="known-limitations-and-deferred-work"></a>
|
|
59
68
|
|
|
69
|
+
- 图片字节上限不校验解码后的尺寸或像素数。
|
|
60
70
|
- Control baseline 表示进程本地状态,因此 Host 重启后无法重建 jobs。
|
|
61
71
|
- follow 恢复失败会对调用方可见,而不会无限重试。
|
|
62
72
|
- 浏览器原始字节上传使用一次不带断点续传偏移的流式 HTTP 请求;重试会从第一个字节重新传输整个文件。
|
package/lib/client.js
CHANGED
|
@@ -62,6 +62,249 @@ window.__ModuleLoader__.load({
|
|
|
62
62
|
return record.event.seq;
|
|
63
63
|
}
|
|
64
64
|
//#endregion
|
|
65
|
+
//#region ../../util/brand/lib/index.js
|
|
66
|
+
/**
|
|
67
|
+
* Apply a compile-time number brand without changing the value.
|
|
68
|
+
* @param value - number admitted by the domain that owns the target brand.
|
|
69
|
+
* @returns the same number with the requested compile-time brand.
|
|
70
|
+
*/
|
|
71
|
+
function brandNumber(value) {
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region ../../core/session/lib/types/types.js
|
|
76
|
+
/**
|
|
77
|
+
* Admit a numeric value as an existing Session event position.
|
|
78
|
+
* @param value - non-negative safe integer admitted by the owning log operation.
|
|
79
|
+
* @returns the same number with the Session-sequence brand.
|
|
80
|
+
*/
|
|
81
|
+
function SessionSeq(value) {
|
|
82
|
+
if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`);
|
|
83
|
+
return brandNumber(value);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Admit a numeric value as a Session log offset.
|
|
87
|
+
* @param value - non-negative safe integer used as a gap or prefix length.
|
|
88
|
+
* @returns the same number with the Session-log-offset brand.
|
|
89
|
+
*/
|
|
90
|
+
function SessionLogOffset(value) {
|
|
91
|
+
if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(value)}`);
|
|
92
|
+
return brandNumber(value);
|
|
93
|
+
}
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region ../../core/session/lib/types/known-event-types.js
|
|
96
|
+
/**
|
|
97
|
+
* GENERATED by `scripts/gen-persistence-catalog.ts` — do not edit by hand; run
|
|
98
|
+
* `pnpm run gen-persistence-catalog` to regenerate (verified fresh by
|
|
99
|
+
* `pnpm run verify-persistence-catalog`, part of `doc-sync`).
|
|
100
|
+
* @module @deepseek-ai/dsh-session/known-event-types
|
|
101
|
+
*/
|
|
102
|
+
/**
|
|
103
|
+
* Every `SessionEventMap` member declared in this repository — the event
|
|
104
|
+
* vocabulary this build understands. The persistence read path refuses to
|
|
105
|
+
* interpret a log containing a type outside this set unless the event
|
|
106
|
+
* carries the envelope's `ignorable` marker (see `SessionEvent.ignorable`
|
|
107
|
+
* in `./types.ts`): such a log was likely written by a newer harness, and
|
|
108
|
+
* silently skipping a required event would reconstruct a wrong session.
|
|
109
|
+
* Downstream (out-of-repo) plugin events are outside this list by
|
|
110
|
+
* construction. The persisted `SessionEvent.ignorable` marker is the
|
|
111
|
+
* compatibility mechanism; event-name registration was rejected because
|
|
112
|
+
* it does not classify omission safety and would make reads
|
|
113
|
+
* composition-dependent. The rationale is in
|
|
114
|
+
* `.agents/notes/implemented/architecture/2026-08-30-retain-ignorable-external-session-events.md`.
|
|
115
|
+
*/
|
|
116
|
+
const KNOWN_SESSION_EVENT_TYPES = new Set([
|
|
117
|
+
"agent-preset/selected",
|
|
118
|
+
"agent/inbox/spliced",
|
|
119
|
+
"approval/asked",
|
|
120
|
+
"approval/decided",
|
|
121
|
+
"approval/policy",
|
|
122
|
+
"assistant/attempt",
|
|
123
|
+
"assistant/message",
|
|
124
|
+
"command/done",
|
|
125
|
+
"command/run",
|
|
126
|
+
"compaction/end",
|
|
127
|
+
"compaction/prune",
|
|
128
|
+
"compaction/start",
|
|
129
|
+
"compaction/summary",
|
|
130
|
+
"feedback/message-delete",
|
|
131
|
+
"feedback/message-put",
|
|
132
|
+
"feedback/record",
|
|
133
|
+
"goal/change",
|
|
134
|
+
"hook/invoked",
|
|
135
|
+
"hook/result",
|
|
136
|
+
"llm/retry",
|
|
137
|
+
"llm/retry-started",
|
|
138
|
+
"model/selection",
|
|
139
|
+
"permission/preset",
|
|
140
|
+
"plan/mode",
|
|
141
|
+
"request/context",
|
|
142
|
+
"request/header",
|
|
143
|
+
"sandbox/mode",
|
|
144
|
+
"schedule/change",
|
|
145
|
+
"session-log-deepseek/delivery-accepted",
|
|
146
|
+
"session/end-seed",
|
|
147
|
+
"session/title",
|
|
148
|
+
"session/title-llm-request",
|
|
149
|
+
"step/end",
|
|
150
|
+
"step/start",
|
|
151
|
+
"subagent/descriptor",
|
|
152
|
+
"subagent/model-selection-policy",
|
|
153
|
+
"system/message",
|
|
154
|
+
"team/member",
|
|
155
|
+
"team/message/delivered",
|
|
156
|
+
"team/message/queued",
|
|
157
|
+
"team/task",
|
|
158
|
+
"todo/write",
|
|
159
|
+
"tool-workflow/agent-end",
|
|
160
|
+
"tool-workflow/agent-start",
|
|
161
|
+
"tool-workflow/run-end",
|
|
162
|
+
"tool-workflow/run-start",
|
|
163
|
+
"tool/call",
|
|
164
|
+
"tool/ptc-dispatch",
|
|
165
|
+
"tool/ptc-dispatch-start",
|
|
166
|
+
"tool/result",
|
|
167
|
+
"turn/end",
|
|
168
|
+
"turn/start",
|
|
169
|
+
"user/message",
|
|
170
|
+
"web/deepseek-search-llm-request"
|
|
171
|
+
]);
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region ../../core/session/lib/types/surface.js
|
|
174
|
+
/** Runtime counterpart of the message-producing event union. */
|
|
175
|
+
const SURFACE_EVENT_TYPES = new Set([
|
|
176
|
+
"system/message",
|
|
177
|
+
"user/message",
|
|
178
|
+
"assistant/message",
|
|
179
|
+
"tool/result"
|
|
180
|
+
]);
|
|
181
|
+
/**
|
|
182
|
+
* Whether an event type can join the model-visible surface.
|
|
183
|
+
* @param type - event type to test.
|
|
184
|
+
* @returns true for one of the four message-producing event types.
|
|
185
|
+
*/
|
|
186
|
+
function isSurfaceEligibleType(type) {
|
|
187
|
+
return SURFACE_EVENT_TYPES.has(type);
|
|
188
|
+
}
|
|
189
|
+
/** Whether a payload field is a JSON object rather than an array or scalar. */
|
|
190
|
+
function isRecord(value) {
|
|
191
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Reject noncanonical request-header fields and contradictory tool failure metadata.
|
|
195
|
+
* This does not validate complete event payloads or embedded provider streams.
|
|
196
|
+
* @param event - event whose locally related payload fields are inspected.
|
|
197
|
+
* @param subject - event location to include in validation errors.
|
|
198
|
+
* @throws when request data/header is not an object, optional header fields are empty, or tool failure metadata contradicts its message.
|
|
199
|
+
*/
|
|
200
|
+
function validateSessionEventData(event, subject) {
|
|
201
|
+
const data = event.data;
|
|
202
|
+
if (event.type === "request/header") {
|
|
203
|
+
if (!isRecord(data)) throw new Error(`${subject} data must be an object`);
|
|
204
|
+
const header = data["header"];
|
|
205
|
+
if (!isRecord(header)) throw new Error(`${subject} header must be an object`);
|
|
206
|
+
if (Object.hasOwn(header, "system")) throw new Error(`${subject} must omit header.system; use system/message`);
|
|
207
|
+
if (Array.isArray(header["tools"]) && header["tools"].length === 0) throw new Error(`${subject} must omit empty tools`);
|
|
208
|
+
const defaults = header["adapterDefaults"];
|
|
209
|
+
if (isRecord(defaults) && Object.keys(defaults).length === 0) throw new Error(`${subject} must omit empty adapterDefaults`);
|
|
210
|
+
} else if (event.type === "tool/result") {
|
|
211
|
+
if (!isRecord(data)) throw new Error(`${subject} data must be an object`);
|
|
212
|
+
if (data["error"] === void 0) return;
|
|
213
|
+
const message = data["message"];
|
|
214
|
+
const content = isRecord(message) ? message["content"] : void 0;
|
|
215
|
+
const block = Array.isArray(content) ? content[0] : void 0;
|
|
216
|
+
if (!isRecord(block) || block["isError"] !== true) throw new Error(`${subject} error requires message content[0].isError === true`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** Whether a runtime value is a non-negative safe event sequence. */
|
|
220
|
+
function isEventSeq(value) {
|
|
221
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0);
|
|
222
|
+
}
|
|
223
|
+
/** Whether a runtime value is the exact positional-replacement shape. */
|
|
224
|
+
function isReplaceOp(value) {
|
|
225
|
+
const op = value;
|
|
226
|
+
return Object.keys(op).length === 3 && Object.hasOwn(op, "op") && Object.hasOwn(op, "startSeq") && Object.hasOwn(op, "endSeq") && op["op"] === "replace" && isEventSeq(op["startSeq"]) && isEventSeq(op["endSeq"]);
|
|
227
|
+
}
|
|
228
|
+
/** Validate event-local surface eligibility and return its operation. */
|
|
229
|
+
function surfaceOpOf(event) {
|
|
230
|
+
const raw = event;
|
|
231
|
+
if (!isSurfaceEligibleType(event.type)) {
|
|
232
|
+
if (!KNOWN_SESSION_EVENT_TYPES.has(event.type) && event.ignorable === true) return;
|
|
233
|
+
if (raw.surfaceOp !== void 0) throw new Error(`session event "${event.type}" is not surface-eligible and cannot carry surfaceOp`);
|
|
234
|
+
if (raw.sourceEventSeqs !== void 0) throw new Error(`session event "${event.type}" is not surface-eligible and cannot carry sourceEventSeqs`);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const op = raw.surfaceOp;
|
|
238
|
+
if (op === void 0) throw new Error(`session event "${event.type}" is surface-eligible and requires a surfaceOp marker`);
|
|
239
|
+
if (op === "append") return op;
|
|
240
|
+
if (op === null || typeof op !== "object" || Array.isArray(op)) throw new Error(`session event "${event.type}" carries an invalid surfaceOp`);
|
|
241
|
+
if (!isReplaceOp(op)) throw new Error(`session event "${event.type}" carries an invalid replace surfaceOp`);
|
|
242
|
+
return op;
|
|
243
|
+
}
|
|
244
|
+
/** Validate cited source-event seqs against prior log entries and the replacement range. */
|
|
245
|
+
function assertProvenance(event, shadowedSeqs) {
|
|
246
|
+
const raw = event.sourceEventSeqs;
|
|
247
|
+
if (event.type === "assistant/message" && raw !== void 0) throw new Error("assistant/message embeds its source stream and cannot carry sourceEventSeqs");
|
|
248
|
+
const sources = /* @__PURE__ */ new Set();
|
|
249
|
+
if (raw !== void 0) {
|
|
250
|
+
if (!Array.isArray(raw)) throw new Error(`sourceEventSeqs on event at seq ${event.seq} must be an array when present`);
|
|
251
|
+
if (raw.length === 0) throw new Error("sourceEventSeqs must not be empty");
|
|
252
|
+
let nonEarlierSource;
|
|
253
|
+
for (const source of raw) {
|
|
254
|
+
if (!isEventSeq(source)) throw new Error(`session event "${event.type}" sourceEventSeqs must densely contain non-negative safe integers`);
|
|
255
|
+
sources.add(source);
|
|
256
|
+
if (nonEarlierSource === void 0 && source >= event.seq) nonEarlierSource = source;
|
|
257
|
+
}
|
|
258
|
+
if (sources.size !== raw.length) throw new Error("sourceEventSeqs must not contain duplicates");
|
|
259
|
+
if (nonEarlierSource !== void 0) throw new Error(`sourceEventSeqs must reference earlier events: ${nonEarlierSource} >= current seq ${event.seq}`);
|
|
260
|
+
}
|
|
261
|
+
const missing = shadowedSeqs.filter((seq) => !sources.has(seq));
|
|
262
|
+
if (missing.length > 0) throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(", ")}`);
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Validate one event's surface metadata without checking membership in a log or surface.
|
|
266
|
+
* @param event - event whose marker and source sequence values are inspected.
|
|
267
|
+
* Unknown ignorable records retain opaque metadata and never change the surface.
|
|
268
|
+
* @returns the validated operation, or undefined for a log-only or unknown ignorable event.
|
|
269
|
+
* @throws when metadata violates event-local eligibility, marker, or source-sequence rules.
|
|
270
|
+
*/
|
|
271
|
+
function validateSurfaceMetadata(event) {
|
|
272
|
+
const op = surfaceOpOf(event);
|
|
273
|
+
if (op !== void 0 && op !== "append" && (op.startSeq >= event.seq || op.endSeq >= event.seq)) throw new Error(`surface replace at seq ${event.seq}: startSeq and endSeq must reference earlier events`);
|
|
274
|
+
if (op !== void 0) assertProvenance(event, []);
|
|
275
|
+
return op;
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region lib/types/client/session-wire-event.js
|
|
279
|
+
/** Event-local acceptance for raw Session journal responses; payloads remain owner-defined JSON. */
|
|
280
|
+
/**
|
|
281
|
+
* Reject non-current event envelopes without stripping or normalizing wire fields.
|
|
282
|
+
* Range membership and source existence require the durable log and remain Host-owned.
|
|
283
|
+
* @param value - one event received in a follow frame or history page.
|
|
284
|
+
* @returns nothing after narrowing the accepted event envelope.
|
|
285
|
+
* @throws when the envelope or current event-local metadata is invalid.
|
|
286
|
+
*/
|
|
287
|
+
function assertSessionWireEvent(value) {
|
|
288
|
+
const subject = "session wire event";
|
|
289
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${subject} must be an object`);
|
|
290
|
+
const event = value;
|
|
291
|
+
for (const key of Object.keys(event)) switch (key) {
|
|
292
|
+
case "type":
|
|
293
|
+
case "seq":
|
|
294
|
+
case "time":
|
|
295
|
+
case "data":
|
|
296
|
+
case "ignorable":
|
|
297
|
+
case "surfaceOp":
|
|
298
|
+
case "sourceEventSeqs": break;
|
|
299
|
+
default: throw new Error(`${subject} has unexpected field ${key}`);
|
|
300
|
+
}
|
|
301
|
+
const seq = event["seq"];
|
|
302
|
+
if (typeof event["type"] !== "string" || typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 0 || Object.is(seq, -0) || typeof event["time"] !== "number" || !Number.isSafeInteger(event["time"]) || !Object.hasOwn(event, "data") || event["data"] === void 0 || Object.hasOwn(event, "ignorable") && event["ignorable"] !== true) throw new Error(`${subject} has an invalid envelope`);
|
|
303
|
+
const current = event;
|
|
304
|
+
validateSurfaceMetadata(current);
|
|
305
|
+
validateSessionEventData(current, subject);
|
|
306
|
+
}
|
|
307
|
+
//#endregion
|
|
65
308
|
//#region lib/types/types.js
|
|
66
309
|
/** Browser-safe request, result, and lifecycle vocabulary for the Session Remote service. */
|
|
67
310
|
/** Maximum number of Sessions returned by one search. */
|
|
@@ -145,6 +388,7 @@ window.__ModuleLoader__.load({
|
|
|
145
388
|
...request.maxMessages === void 0 ? {} : { maxMessages: request.maxMessages }
|
|
146
389
|
}, signal)) {
|
|
147
390
|
if (frame.type === "snapshot") {
|
|
391
|
+
for (const record of frame.records) assertSessionWireEvent(record.event);
|
|
148
392
|
if (frame.assistantStream === void 0) throw new RemoteError("gateway/internal", "session assistant stream omitted its opted-in opening baseline", {});
|
|
149
393
|
assistantRevision = frame.assistantStream.revision;
|
|
150
394
|
yield {
|
|
@@ -169,6 +413,7 @@ window.__ModuleLoader__.load({
|
|
|
169
413
|
};
|
|
170
414
|
continue;
|
|
171
415
|
}
|
|
416
|
+
assertSessionWireEvent(frame.event);
|
|
172
417
|
yield {
|
|
173
418
|
type: "entry",
|
|
174
419
|
entry: frame
|
|
@@ -183,6 +428,7 @@ window.__ModuleLoader__.load({
|
|
|
183
428
|
...request
|
|
184
429
|
}, signal);
|
|
185
430
|
if (!result.ok) throw result.error;
|
|
431
|
+
for (const record of result.value.records) assertSessionWireEvent(record.event);
|
|
186
432
|
return result.value;
|
|
187
433
|
}
|
|
188
434
|
/** @inheritdoc */
|
|
@@ -191,36 +437,6 @@ window.__ModuleLoader__.load({
|
|
|
191
437
|
}
|
|
192
438
|
};
|
|
193
439
|
//#endregion
|
|
194
|
-
//#region ../../util/brand/lib/index.js
|
|
195
|
-
/**
|
|
196
|
-
* Apply a compile-time number brand without changing the value.
|
|
197
|
-
* @param value - number admitted by the domain that owns the target brand.
|
|
198
|
-
* @returns the same number with the requested compile-time brand.
|
|
199
|
-
*/
|
|
200
|
-
function brandNumber(value) {
|
|
201
|
-
return value;
|
|
202
|
-
}
|
|
203
|
-
//#endregion
|
|
204
|
-
//#region ../../core/session/lib/types/types.js
|
|
205
|
-
/**
|
|
206
|
-
* Admit a numeric value as an existing Session event position.
|
|
207
|
-
* @param value - non-negative safe integer admitted by the owning log operation.
|
|
208
|
-
* @returns the same number with the Session-sequence brand.
|
|
209
|
-
*/
|
|
210
|
-
function SessionSeq(value) {
|
|
211
|
-
if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`);
|
|
212
|
-
return brandNumber(value);
|
|
213
|
-
}
|
|
214
|
-
/**
|
|
215
|
-
* Admit a numeric value as a Session log offset.
|
|
216
|
-
* @param value - non-negative safe integer used as a gap or prefix length.
|
|
217
|
-
* @returns the same number with the Session-log-offset brand.
|
|
218
|
-
*/
|
|
219
|
-
function SessionLogOffset(value) {
|
|
220
|
-
if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) throw new TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(value)}`);
|
|
221
|
-
return brandNumber(value);
|
|
222
|
-
}
|
|
223
|
-
//#endregion
|
|
224
440
|
//#region ../../util/workspace-path/lib/index.js
|
|
225
441
|
/**
|
|
226
442
|
* Read the final non-empty segment of a Workspace path for display.
|