From 5c27df5ed711cf2f491498b47c949da9f6eacd5c Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 04:00:40 +0800 Subject: [PATCH 01/31] fix(subagent): preserve actionable ACP failure facts --- ...ess-subagent-minimal-diagnostics.i18n.yaml | 6 + ...of-process-subagent-minimal-diagnostics.md | 73 +++ ...process-subagent-minimal-diagnostics.zh.md | 73 +++ ...ubagent-acp-diagnostic.cordis.snapshot.yml | 41 ++ .../subagent-acp-diagnostic.cordis.yml | 31 + examples/acp-agent/tests/acp.snapshot.ts | 18 + .../fixtures/subagent/subagent-acp/cordis.yml | 13 +- .../subagent-acp-diagnostic/input.json | 7 + .../replay.override.json | 42 ++ .../subagent-acp-diagnostic/session.jsonl | 48 ++ .../stdout.expected.jsonl | 4 + .../tool-schemas.expected.json | 548 ++++++++++++++++++ .../subagent/subagent-acp/README.i18n.yaml | 4 +- packages/subagent/subagent-acp/README.md | 33 +- packages/subagent/subagent-acp/README.zh.md | 33 +- packages/subagent/subagent-acp/src/index.ts | 15 +- packages/subagent/subagent-acp/src/run.ts | 334 +++++++++-- .../tests/loader-composition.e2e.ts | 55 +- .../subagent-acp/tests/mock-acp-server.ts | 35 +- .../subagent-acp/tests/subagent-acp.spec.ts | 388 ++++++++++++- .../subagent/subagent/src/out-of-process.ts | 17 +- .../subagent/subagent/src/run-settlement.ts | 10 +- .../subagent/tests/run-settlement.spec.ts | 69 +++ 23 files changed, 1776 insertions(+), 121 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md create mode 100644 .agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md create mode 100644 examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml create mode 100644 examples/acp-agent/subagent-acp-diagnostic.cordis.yml create mode 100644 examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/input.json create mode 100644 examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/replay.override.json create mode 100644 examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl create mode 100644 examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/stdout.expected.jsonl create mode 100644 examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/tool-schemas.expected.json diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml new file mode 100644 index 0000000000..486a768623 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md +2026-08-21-out-of-process-subagent-minimal-diagnostics.md: 38cf32dc3de3fe157f73e1546a827df9b3622fa6 +2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md: 386f85e6b5665c8006e10a0ed0aa49845b6ffed0 diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md new file mode 100644 index 0000000000..38cf32dc3d --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md @@ -0,0 +1,73 @@ +# Agent Note: Out-of-process subagents expose minimal actionable diagnostics + +Status: implemented + +English | [中文](2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md) + +## Problem + +An ACP child can stop because it reached a remote limit, denied a required permission, lost its protocol transport, or exited as a process. The shared result historically reduced these outcomes to a stop reason such as `error`, while startup and cleanup rejection messages could expose the original exception. A parent could not choose between narrowing the task, adjusting permission policy, or repairing the child deployment without Host logs. + +Copying exceptions, stderr, task content, tool input, paths, environment values, credentials, or protocol payloads into `SubagentResult.diagnostic` would make untrusted child text model-visible. Reusing a complete product-specific error union would also duplicate independently versioned authorities in the provider-neutral [subagent seam](2026-06-21-subagent-capability-seam.md). + +## Decision + +Each out-of-process provider owns a small mapping from facts it already receives at its protocol and process lifecycle points to fixed safe display text. The ACP provider implements that rule from its closed stop reasons, current operation, closed tool kind, configured permission policy, selected permission outcome, and the managed subprocess exit code or signal. Consumers continue to use the existing optional `SubagentResult.diagnostic`; they do not parse its punctuation or provider-private category names. + +### Safe failure text + +The first line has this fixed field order: + +```text +Subagent failure (provider: ; stage: ; category: ; stop reason: ; exit code: ; signal: ) +``` + +Unavailable optional fields are omitted. The complete result is limited to 4096 UTF-8 bytes by the shared settlement boundary. Successful results and local cancellation carry no failure diagnostic. Partial assistant output remains in `SubagentResult.output` and is presented separately. + +When an ACP permission request contributes to a non-completed result, a second fixed line records `policy`, the closed ACP tool `request` kind, and `decision`. Tool titles, raw input, locations, option names, and metadata are excluded. A diagnostic-bearing remote `aborted` result keeps its public stop reason; the one-shot Job adapter treats it as failed, while diagnostic-free local cancellation remains killed. + +### ACP facts + +| Stage | Owned operation | Safe categories and facts | +| --- | --- | --- | +| `initialize` | Parent workspace resolution, spawn, and ACP initialize | `configuration`, `transport`, `process-start`, or `process-exit` | +| `new-session` | ACP `session/new` and returned session-id validation | `protocol`, `transport`, or `process-exit` | +| `prompt` | ACP prompt request, remote stop reason, and permission callback | `remote-limit`, `remote-refusal`, `permission`, `transport`, or `unknown` | +| `process` | Managed child exits before a prompt terminal response | `process-exit` plus independently observed exit code and signal | +| `teardown` | EOF quiescence and managed process-tree termination | Fixed teardown facts; the original cleanup failure remains internal | + +`max_turn_requests` remains the shared `error` stop reason and adds `remote-limit`. An unknown stop reason remains `error` and becomes the fixed `unknown` category without copying the value. `max_tokens`, `refusal`, and `cancelled` keep their existing shared stop reasons; they add a diagnostic only when a permission decision must be explained. + +### Ownership and lifecycle + +| Fact or resource | Owner | Consumer behavior | +| --- | --- | --- | +| ACP stop reason and tool kind | ACP server and SDK | The provider maps only closed values and uses fixed unknown fallbacks | +| Current failure stage and latest permission decision | One ACP run | Derived at the failure point and discarded with the run; concurrent runs share no diagnostic state | +| Exit code and signal | `dsh-subprocess` handle | Displayed only after the managed outcome is observed; stderr is never parsed | +| Diagnostic bytes and presentation | `dsh-subagent`, foreground tool, and Job runtime | The same bounded text stays separate from assistant output in foreground and one-shot background modes | +| Raw failure | Child runtime, Error cause chain, and Host logger | Available for Host diagnosis only, never copied into the parent model result | + +Startup publishes no run until initialize and new-session succeed. A startup failure rolls the private child back to quiescence before rejecting with safe facts. A published run settles its result without rejection, and `dispose()` independently reports a safe teardown failure while still using the backend's existing whole-tree cleanup ladder. + +## Verification + +ACP package tests drive a real stdio protocol child and pin every stop-reason mapping, remote-limit and unknown fallbacks, permission allow/deny facts, configuration, initialize, new-session, prompt, process, and teardown stages, startup rollback, successful-result and local-cancellation omission, partial output, concurrent-run isolation, Host-only raw errors, process quiescence, and the shared multibyte diagnostic limit. A Loader composition proves the real configured provider reaches the model-visible foreground result. The keyless ACP snapshot pins the same diagnostic and permission fact in foreground error output and one-shot background `job_output` detail. + +## Alternatives considered + +**Return raw exceptions, stderr, or protocol payloads.** These values can contain task content, tool input, paths, environment values, credentials, and upstream prose. Fixed allowlisted facts preserve the actionable distinction without expanding the model-visible trust boundary. + +**Add a shared structured error enum.** ACP and other process-backed providers own different lifecycle points and closed termination vocabularies. A shared enum would invent false equivalence and force unrelated consumers to track provider releases. + +**Parse exception messages or stderr into categories.** Free-form text is neither stable nor safe. Only closed protocol values, typed errors, current call sites, and managed process outcomes qualify as diagnostic inputs. + +**Change existing stop reasons.** The stop reason remains the provider-neutral terminal result. The optional diagnostic explains why a non-completed result needs a different next action without adding new public result states. + +**Add retries, recovery state, or interactive approval.** Diagnostics report a failure; they do not own remediation. Retry policy, session recovery, and human interaction require separate user contracts and lifecycle owners. + +## Consequences + +The parent can distinguish an ACP remote limit, permission involvement, protocol or transport failure, deployment/process failure, and teardown failure without receiving child-controlled text. Startup and cleanup errors use the same safe facts as published results, while Host observation retains the original cause. + +The diagnostic remains display text rather than a public protocol. Consumers may present it but must not branch on its format. This decision adds no retry policy, recovery controller, shared provider-error enum, stderr classifier, authentication taxonomy, session persistence, progress stream, or new ACP capability. diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md new file mode 100644 index 0000000000..386f85e6b5 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md @@ -0,0 +1,73 @@ +# Agent Note: 进程外 subagent 公开最小可行动诊断 + +Status: implemented + +[English](2026-08-21-out-of-process-subagent-minimal-diagnostics.md) | 中文 + +## Problem + +ACP 子进程可能因为达到远端限制、拒绝必需权限、失去协议传输或进程退出而停止。共享结果以往只把这些结果压成 `error` 等结束原因,而启动和清理拒绝的消息还可能暴露原始异常。父 agent 若不读取 Host 日志,就无法决定应缩小任务、调整权限策略还是修复子运行时部署。 + +若把异常、stderr、任务内容、工具输入、路径、环境值、凭证或协议 payload 复制进 `SubagentResult.diagnostic`,不受信任的子进程文本就会变成模型可见内容。若复用完整的产品专属错误联合,又会在提供方无关的 [subagent seam](2026-06-21-subagent-capability-seam.zh.md) 中复制彼此独立版本化的权威。 + +## Decision + +每个进程外提供方分别拥有一份小型映射,把其协议与进程生命周期位置已经收到的事实转换成固定安全展示文本。ACP 提供方使用闭集结束原因、当前操作、闭集工具种类、已配置权限策略、选中的权限结果,以及受管子进程退出码或信号来实现该规则。消费方继续使用现有可选 `SubagentResult.diagnostic`,且不解析其标点或提供方私有 category 名称。 + +### 安全失败文本 + +首行采用以下固定字段顺序: + +```text +Subagent failure (provider: ; stage: ; category: ; stop reason: ; exit code: ; signal: ) +``` + +不可用的可选字段会被省略。共享结算边界会把完整结果限制在 4096 个 UTF-8 字节以内。成功结果和本地取消不携带失败诊断。部分 assistant 输出继续保留在 `SubagentResult.output` 中,并与诊断分开呈现。 + +当 ACP 权限请求参与非完成结果时,第二个固定行会记录 `policy`、ACP 闭集工具 `request` 种类和 `decision`。工具标题、raw input、位置、选项名称与 metadata 均被排除。带诊断的远端 `aborted` 结果仍保持公共结束原因;一次性 Job adapter 会把它判为 failed,而不带诊断的本地取消仍是 killed。 + +### ACP 事实 + +| Stage | 归属操作 | 安全 category 与事实 | +| --- | --- | --- | +| `initialize` | 父工作区解析、spawn 与 ACP initialize | `configuration`、`transport`、`process-start` 或 `process-exit` | +| `new-session` | ACP `session/new` 与返回 session id 校验 | `protocol`、`transport` 或 `process-exit` | +| `prompt` | ACP prompt 请求、远端结束原因与权限回调 | `remote-limit`、`remote-refusal`、`permission`、`transport` 或 `unknown` | +| `process` | 受管子进程先于 prompt 终态响应退出 | `process-exit`,以及分别观测到的退出码与信号 | +| `teardown` | EOF 停稳与受管进程树终止 | 固定 teardown 事实;原始清理失败仍留在内部 | + +`max_turn_requests` 继续映射到共享 `error`,并附加 `remote-limit`。未知结束原因继续映射到 `error`,category 固定为 `unknown`,不会复制原值。`max_tokens`、`refusal` 与 `cancelled` 保持既有共享结束原因;只有需要解释权限决定时才会附加诊断。 + +### 所有权与生命周期 + +| 事实或资源 | Owner | 消费方行为 | +| --- | --- | --- | +| ACP 结束原因与工具种类 | ACP server 与 SDK | 提供方只映射闭集值,并对闭集外值使用固定 unknown 回退 | +| 当前失败 stage 与最新权限决定 | 单次 ACP 运行 | 只在失败点派生,并随运行丢弃;并发运行不共享诊断状态 | +| 退出码与信号 | `dsh-subprocess` 句柄 | 仅在观测到受管结果后展示;绝不解析 stderr | +| 诊断字节与呈现 | `dsh-subagent`、前台工具与 Job 运行时 | 前台和一次性后台模式都把同一份有界文本与 assistant 输出分开 | +| 原始失败 | 子运行时、Error cause 链与 Host logger | 只供 Host 排障,绝不复制进父模型结果 | + +启动只有在 initialize 与 new-session 成功后才发布运行。启动失败会先把私有子进程回滚到完全停稳,再以安全事实拒绝。已发布运行的结果不会拒绝,而 `dispose()` 会独立报告安全 teardown 失败,并继续使用后端既有的整棵进程树清理阶梯。 + +## Verification + +ACP 包测试通过真实 stdio 协议子进程固定全部结束原因映射、远端限制与 unknown 回退、权限 allow/deny 事实、configuration、initialize、new-session、prompt、process 与 teardown stage、启动回滚、成功结果与本地取消省略、部分输出、并发运行隔离、仅 Host 可见的原始错误、进程完全停稳,以及共享多字节诊断限制。Loader 组合证明真实配置的提供方会到达模型可见前台结果。无密钥 ACP snapshot 会在前台错误输出与一次性后台 `job_output` detail 中固定同一份诊断与权限事实。 + +## Alternatives considered + +**返回原始异常、stderr 或协议 payload。** 这些值可能包含任务内容、工具输入、路径、环境值、凭证和上游文本。固定白名单事实能够保留可行动差异,而不扩大模型可见信任边界。 + +**增加共享结构化错误 enum。** ACP 与其他进程外提供方拥有不同生命周期位置和闭集终止词汇。共享 enum 会制造虚假的统一,并迫使无关消费方跟随提供方版本。 + +**解析异常消息或 stderr 来分类。** 自由文本既不稳定也不安全。只有闭集协议值、typed 错误、当前调用位置与受管进程结果可以成为诊断输入。 + +**修改既有结束原因。** 结束原因继续表示提供方无关的终态结果。可选诊断说明非完成结果为何要求不同的下一步,而不增加新的公共结果状态。 + +**增加重试、恢复状态或交互审批。** 诊断只负责报告失败,不拥有修复动作。重试策略、会话恢复与人工交互需要独立用户约定和生命周期责任方。 + +## Consequences + +父 agent 可以区分 ACP 远端限制、权限参与、协议或传输失败、部署/进程失败与 teardown 失败,同时不会接收子进程控制的文本。启动和清理错误与已发布结果使用同一套安全事实,而 Host 观测仍保留原始 cause。 + +诊断仍是展示文本,不是公共协议。消费方可以呈现它,但不得按格式分支。本决策不增加重试策略、恢复控制器、共享提供方错误 enum、stderr 分类器、认证分类、会话持久化、进度流或新的 ACP 能力。 diff --git a/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml b/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml new file mode 100644 index 0000000000..2019b2337a --- /dev/null +++ b/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml @@ -0,0 +1,41 @@ +# Keyless twin of subagent-acp-diagnostic.cordis.yml: keep the real ACP child +# process/provider/tool and replace only the external parent model adapter. +- id: base + name: '@deepseek-ai/cordis-plugin-include' + config: + path: ./cordis.yml + patches: + - id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek' + disabled: true + - insert: + - id: llm-replay + name: '@deepseek-ai/dsh-llm-replay' + config: + providers: + - id: deepseek-official + name: DeepSeek + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + - id: subagent-acp-diagnostic + name: '@deepseek-ai/dsh-subagent-acp' + config: + providerName: acp-diagnostic + command: !!js process.execPath + args: + - !!js process.env.DSH_TEST_MOCK_ACP_SERVER + permission: reject + env: + MOCK_TEXT: partial ACP assistant text + MOCK_STOP: max_turn_requests + MOCK_PERMISSION: '1' + MOCK_PERMISSION_IGNORE_DECISION: '1' + MOCK_TOOL_KIND: execute + - id: tool-subagent-acp-diagnostic + name: '@deepseek-ai/dsh-tool-subagent' + config: + provider: acp-diagnostic + toolName: subagent_acp + backgroundMode: one-shot + maxDepth: provider-managed diff --git a/examples/acp-agent/subagent-acp-diagnostic.cordis.yml b/examples/acp-agent/subagent-acp-diagnostic.cordis.yml new file mode 100644 index 0000000000..e09c00e048 --- /dev/null +++ b/examples/acp-agent/subagent-acp-diagnostic.cordis.yml @@ -0,0 +1,31 @@ +# Add the real ACP provider behind a one-shot delegation tool. The snapshot +# scenario supplies the absolute protocol fixture path through +# DSH_TEST_MOCK_ACP_SERVER; the child returns a remote limit after a denied +# execute permission and streams partial assistant output first. +- id: base + name: '@deepseek-ai/cordis-plugin-include' + config: + path: ./cordis.yml + patches: + - insert: + - id: subagent-acp-diagnostic + name: '@deepseek-ai/dsh-subagent-acp' + config: + providerName: acp-diagnostic + command: !!js process.execPath + args: + - !!js process.env.DSH_TEST_MOCK_ACP_SERVER + permission: reject + env: + MOCK_TEXT: partial ACP assistant text + MOCK_STOP: max_turn_requests + MOCK_PERMISSION: '1' + MOCK_PERMISSION_IGNORE_DECISION: '1' + MOCK_TOOL_KIND: execute + - id: tool-subagent-acp-diagnostic + name: '@deepseek-ai/dsh-tool-subagent' + config: + provider: acp-diagnostic + toolName: subagent_acp + backgroundMode: one-shot + maxDepth: provider-managed diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index bedd75c311..16e6108ffb 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -84,6 +84,13 @@ const PRODUCT_SUBAGENT_BOTH_CONFIG = fileURLToPath(new URL('../product-subagent- const PRODUCT_SUBAGENT_RESULT_DIAGNOSTIC_CONFIG = fileURLToPath( new URL('../subagent-result-diagnostic.cordis.yml', import.meta.url), ) +const SUBAGENT_ACP_DIAGNOSTIC_CONFIG = fileURLToPath( + new URL('../subagent-acp-diagnostic.cordis.yml', import.meta.url), +) +const SUBAGENT_ACP_MOCK_SERVER = fileURLToPath(new URL( + '../../../packages/subagent/subagent-acp/tests/mock-acp-server.ts', + import.meta.url, +)) const FS_DIFF_BOUND_CONFIG = fileURLToPath(new URL('./fs-diff-bound.cordis.yml', import.meta.url)) const SNAPSHOTS_DIR = join(dirname(fileURLToPath(import.meta.url)), 'snapshots') const PACKED_CHUNKS_SOURCE = 'hook-cc-pretool-deny' @@ -192,6 +199,17 @@ const SCENARIOS: Scenario[] = [ systemPromptSource: 'product-subagent-codex', configPath: PRODUCT_SUBAGENT_RESULT_DIAGNOSTIC_CONFIG, }, + { + name: 'subagent-acp-diagnostic', + hasModelTurn: true, + recorded: false, + overridden: true, + pinsHeader: true, + headerClass: 'subagent-acp-diagnostic', + systemPromptSource: 'product-subagent-codex', + configPath: SUBAGENT_ACP_DIAGNOSTIC_CONFIG, + env: { DSH_TEST_MOCK_ACP_SERVER: SUBAGENT_ACP_MOCK_SERVER }, + }, { name: 'session-title-after-turn', hasModelTurn: true, diff --git a/examples/acp-agent/tests/fixtures/subagent/subagent-acp/cordis.yml b/examples/acp-agent/tests/fixtures/subagent/subagent-acp/cordis.yml index 6575f1b145..ecc275f0a3 100644 --- a/examples/acp-agent/tests/fixtures/subagent/subagent-acp/cordis.yml +++ b/examples/acp-agent/tests/fixtures/subagent/subagent-acp/cordis.yml @@ -1,9 +1,9 @@ # Test-only composition: the ACP subagent backend on the real Loader/app path. -# The scripted model delegates once; the scripted mock ACP child (MOCK_ECHO_CWD) -# echoes its process cwd and announced session cwd, so parent-session cwd -# inheritance is asserted keylessly end to end. `cwd` is deliberately omitted — -# the inheritance branch under test. The child command path is machine-absolute, -# so the driving e2e supplies it via DSH_TEST_MOCK_ACP_SERVER. +# The scripted model delegates once. The driving e2e selects either the cwd +# echo or a remote-limit diagnostic through DSH_TEST_ACP_MODE. `cwd` is +# deliberately omitted so both paths exercise parent-session inheritance. The +# child command path is machine-absolute and arrives through +# DSH_TEST_MOCK_ACP_SERVER. - id: mock-llm name: './mock-delegating-llm.ts' @@ -22,8 +22,7 @@ args: - !!js process.env.DSH_TEST_MOCK_ACP_SERVER permission: reject - env: - MOCK_ECHO_CWD: '1' + env: !!js "process.env.DSH_TEST_ACP_MODE === 'diagnostic' ? { MOCK_TEXT: 'partial loader answer', MOCK_STOP: 'max_turn_requests' } : { MOCK_ECHO_CWD: '1' }" - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' diff --git a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/input.json b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/input.json new file mode 100644 index 0000000000..5633fd5d35 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/input.json @@ -0,0 +1,7 @@ +{ + "steps": [ + { "op": "initialize" }, + { "op": "newSession" }, + { "op": "prompt", "text": "Observe the ACP diagnostic twice with subagent_acp. First call it in the foreground. Then call it in the background and collect subagent-1 with job_output using wait true. After both failures, reply with exactly PARENT_OBSERVED_ACP_DIAGNOSTIC. Do not call any other tools." } + ] +} diff --git a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/replay.override.json b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/replay.override.json new file mode 100644 index 0000000000..302125db53 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/replay.override.json @@ -0,0 +1,42 @@ +[ + { + "kind": "chunks", + "chunks": [ + { "type": "block-start", "index": 0, "blockType": "tool-call" }, + { "type": "tool-call-delta", "index": 0, "id": "call_acp_foreground", "name": "subagent_acp", "argumentsDelta": "{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}" }, + { "type": "block-end", "index": 0, "block": { "type": "tool-call", "id": "call_acp_foreground", "name": "subagent_acp", "arguments": "{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}" } }, + { "type": "usage", "usage": { "inputTokens": 10, "outputTokens": 5 } }, + { "type": "finish", "reason": { "kind": "tool-calls" } } + ] + }, + { + "kind": "chunks", + "chunks": [ + { "type": "block-start", "index": 0, "blockType": "tool-call" }, + { "type": "tool-call-delta", "index": 0, "id": "call_acp_background", "name": "subagent_acp", "argumentsDelta": "{\"description\":\"Observe ACP background failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":true}" }, + { "type": "block-end", "index": 0, "block": { "type": "tool-call", "id": "call_acp_background", "name": "subagent_acp", "arguments": "{\"description\":\"Observe ACP background failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":true}" } }, + { "type": "usage", "usage": { "inputTokens": 10, "outputTokens": 5 } }, + { "type": "finish", "reason": { "kind": "tool-calls" } } + ] + }, + { + "kind": "chunks", + "chunks": [ + { "type": "block-start", "index": 0, "blockType": "tool-call" }, + { "type": "tool-call-delta", "index": 0, "id": "call_acp_output", "name": "job_output", "argumentsDelta": "{\"job_id\":\"subagent-1\",\"wait\":true}" }, + { "type": "block-end", "index": 0, "block": { "type": "tool-call", "id": "call_acp_output", "name": "job_output", "arguments": "{\"job_id\":\"subagent-1\",\"wait\":true}" } }, + { "type": "usage", "usage": { "inputTokens": 10, "outputTokens": 5 } }, + { "type": "finish", "reason": { "kind": "tool-calls" } } + ] + }, + { + "kind": "chunks", + "chunks": [ + { "type": "block-start", "index": 0, "blockType": "text" }, + { "type": "text-delta", "index": 0, "text": "PARENT_OBSERVED_ACP_DIAGNOSTIC" }, + { "type": "block-end", "index": 0, "block": { "type": "text", "text": "PARENT_OBSERVED_ACP_DIAGNOSTIC" } }, + { "type": "usage", "usage": { "inputTokens": 10, "outputTokens": 2 } }, + { "type": "finish", "reason": { "kind": "stop" } } + ] + } +] diff --git a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl new file mode 100644 index 0000000000..c5b42a7aa1 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl @@ -0,0 +1,48 @@ +{"type":"session","version":0,"id":"00000000-0000-0000-0000-000000000000","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"agent/inbox/spliced","seq":0,"time":1787254574854,"data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Observe the ACP diagnostic twice with subagent_acp. First call it in the foreground. Then call it in the background and collect subagent-1 with job_output using wait true. After both failures, reply with exactly PARENT_OBSERVED_ACP_DIAGNOSTIC. Do not call any other tools."}],"source":{"kind":"user"},"role":"user","id":"a93f593d-0716-4eb9-9c7d-3f7c77ae796f"}]}} +{"type":"turn/start","seq":1,"time":1787254574854,"data":{"turn":1}} +{"type":"agent/inbox/spliced","seq":2,"time":1787254574855,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","seq":3,"time":1787254574883,"data":{"turn":1,"step":1}} +{"type":"user/message","seq":4,"time":1787254574883,"data":{"content":[{"type":"text","text":"Observe the ACP diagnostic twice with subagent_acp. First call it in the foreground. Then call it in the background and collect subagent-1 with job_output using wait true. After both failures, reply with exactly PARENT_OBSERVED_ACP_DIAGNOSTIC. Do not call any other tools."}],"source":{"kind":"user"},"role":"user","id":"a93f593d-0716-4eb9-9c7d-3f7c77ae796f"},"surfaceOp":"append"} +{"type":"user/message","seq":5,"time":1787254574883,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"b0d1e3fd-067c-4aec-9432-a91c750afbf2"},"surfaceOp":"append"} +{"type":"session/title","seq":6,"time":1787254574883,"data":{"title":"Observe the ACP diagnostic twice","messageSeqs":[4],"source":{"kind":"fallback"}}} +{"type":"request/header","seq":7,"time":1787254574884,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","seq":8,"time":1787254574884,"data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} +{"type":"assistant/chunk","seq":9,"time":1787254574889,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":10,"time":1787254574889,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_acp_foreground","name":"subagent_acp","argumentsDelta":"{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}"}}} +{"type":"assistant/chunk","seq":11,"time":1787254574889,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_acp_foreground","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}"}}}} +{"type":"assistant/chunk","seq":12,"time":1787254574889,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":13,"time":1787254574889,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":14,"time":1787254574889,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_acp_foreground","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"ef8e9ff0-886c-4d55-bbdb-8e878258fb53"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[9,10,11,12,13],"surfaceOp":"append"} +{"type":"tool/call","seq":15,"time":1787254574890,"data":{"turn":1,"step":1,"callId":"call_acp_foreground","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}"}} +{"type":"tool/result","seq":16,"time":1787254574996,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_acp_foreground"},"content":[{"type":"tool-result","toolCallId":"call_acp_foreground","content":[{"type":"text","text":"Error: subagent run failed\nDiagnostic: Subagent failure (provider: ACP; stage: prompt; category: remote-limit; stop reason: max_turn_requests)\nACP unattended decision (policy: reject; request: execute; decision: denied)\nPartial output before the run ended:\npartial ACP assistant text"}],"isError":true}],"role":"user","id":"9a82d328-e8dc-43c6-94c5-cfaf93b64c5d"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"step/end","seq":17,"time":1787254574996,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":18,"time":1787254575002,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":19,"time":1787254575006,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":20,"time":1787254575006,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"call_acp_background","name":"subagent_acp","argumentsDelta":"{\"description\":\"Observe ACP background failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":true}"}}} +{"type":"assistant/chunk","seq":21,"time":1787254575006,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_acp_background","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP background failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":true}"}}}} +{"type":"assistant/chunk","seq":22,"time":1787254575006,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":23,"time":1787254575006,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":24,"time":1787254575006,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_acp_background","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP background failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"ed38f844-a1b6-45d5-9ee9-a3b2fb280b48"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[19,20,21,22,23],"surfaceOp":"append"} +{"type":"tool/call","seq":25,"time":1787254575007,"data":{"turn":1,"step":2,"callId":"call_acp_background","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP background failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":true}"}} +{"type":"tool/result","seq":26,"time":1787254575011,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_acp_background"},"content":[{"type":"tool-result","toolCallId":"call_acp_background","content":[{"type":"text","text":"started background subagent job subagent-1"}],"isError":false}],"role":"user","id":"5f00fc5b-7460-4122-a613-720e1749bdf9"}},"sourceEventSeqs":[25],"surfaceOp":"append"} +{"type":"step/end","seq":27,"time":1787254575011,"data":{"turn":1,"step":2}} +{"type":"step/start","seq":28,"time":1787254575017,"data":{"turn":1,"step":3}} +{"type":"assistant/chunk","seq":29,"time":1787254575021,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":30,"time":1787254575021,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"call_acp_output","name":"job_output","argumentsDelta":"{\"job_id\":\"subagent-1\",\"wait\":true}"}}} +{"type":"assistant/chunk","seq":31,"time":1787254575021,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_acp_output","name":"job_output","arguments":"{\"job_id\":\"subagent-1\",\"wait\":true}"}}}} +{"type":"assistant/chunk","seq":32,"time":1787254575021,"data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":33,"time":1787254575021,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":34,"time":1787254575021,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_acp_output","name":"job_output","arguments":"{\"job_id\":\"subagent-1\",\"wait\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"b20d64f1-7fcf-498d-84ec-afe518983863"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[29,30,31,32,33],"surfaceOp":"append"} +{"type":"tool/call","seq":35,"time":1787254575021,"data":{"turn":1,"step":3,"callId":"call_acp_output","name":"job_output","arguments":"{\"job_id\":\"subagent-1\",\"wait\":true}"}} +{"type":"tool/result","seq":36,"time":1787254575110,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"call_acp_output"},"content":[{"type":"tool-result","toolCallId":"call_acp_output","content":[{"type":"text","text":"(no new output)\n[status: failed, error; diagnostic: Subagent failure (provider: ACP; stage: prompt; category: remote-limit; stop reason: max_turn_requests)\nACP unattended decision (policy: reject; request: execute; decision: denied)]"}],"isError":false}],"role":"user","id":"26ecb040-cc32-474c-9db2-a27ffa7fe9fe"}},"sourceEventSeqs":[35],"surfaceOp":"append"} +{"type":"step/end","seq":37,"time":1787254575110,"data":{"turn":1,"step":3}} +{"type":"step/start","seq":38,"time":1787254575116,"data":{"turn":1,"step":4}} +{"type":"assistant/chunk","seq":39,"time":1787254575121,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} +{"type":"assistant/chunk","seq":40,"time":1787254575121,"data":{"turn":1,"step":4,"chunk":{"type":"text-delta","index":0,"text":"PARENT_OBSERVED_ACP_DIAGNOSTIC"}}} +{"type":"assistant/chunk","seq":41,"time":1787254575121,"data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PARENT_OBSERVED_ACP_DIAGNOSTIC"}}}} +{"type":"assistant/chunk","seq":42,"time":1787254575121,"data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}}} +{"type":"assistant/chunk","seq":43,"time":1787254575121,"data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":44,"time":1787254575121,"data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"text","text":"PARENT_OBSERVED_ACP_DIAGNOSTIC"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"3fdb6493-585b-44c6-9faa-88e954401eeb"},"usage":{"inputTokens":10,"outputTokens":2}},"sourceEventSeqs":[39,40,41,42,43],"surfaceOp":"append"} +{"type":"step/end","seq":45,"time":1787254575121,"data":{"turn":1,"step":4}} +{"type":"turn/end","seq":46,"time":1787254575121,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/stdout.expected.jsonl new file mode 100644 index 0000000000..7ce5b64966 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/stdout.expected.jsonl @@ -0,0 +1,4 @@ +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"PARENT_OBSERVED_ACP_DIAGNOSTIC"}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/tool-schemas.expected.json new file mode 100644 index 0000000000..ec5ad385aa --- /dev/null +++ b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/tool-schemas.expected.json @@ -0,0 +1,548 @@ +{ + "initial": [ + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a job id immediately; read its output with `job_output` and stop it with `job_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." + } + }, + "required": [ + "command", + "description" + ] + } + }, + { + "name": "create_goal", + "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace. Must match exactly." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "interrupt_agent", + "description": "Request cancellation of a background agent's current turn by its agent id. The target may be your direct child or a deeper agent created under you. Only the current turn stops: messages already queued for the agent stay parked until a later send_message, agents it started keep running, and the agent itself stays available for follow-ups. This call returns as soon as the stop request is accepted, so the target may keep running briefly; interrupting an agent that already finished is an accepted no-op.", + "parameters": { + "type": "object", + "properties": { + "agent_id": { + "type": "string", + "description": "The agent id of the running agent to interrupt." + } + }, + "required": [ + "agent_id" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job by job id. Returns immediately; the job settles as killed once its work actually stops.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job. Stream jobs return only output since the previous read; final-output jobs return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the job alive." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your continuable background subagents by durable id and label. Use it to recall which ones you started, not to poll for completion — you are told when one finishes. Status comes from the live registry: running means the agent is working right now, idle means it is loaded but between turns (it may be waiting on agents it started), and ready means it exists only in storage — resumable, not terminal, and not a result waiting to be collected; a `send_message` starts a new turn on the same conversation, and a direct child remains a `send_message` candidate in every status. The snapshot is not a delivery promise — `send_message` performs the authoritative check and may still fail. Children that could not be read are reported as diagnostics instead of being silently dropped. Scope `descendants` walks the whole tree below you in stable pre-order, annotating each entry with its durable direct-parent session id and depth. You may use `send_message` only for depth-1 entries; deeper entries are candidates for `interrupt_agent` only.", + "parameters": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "description": "children (default) lists direct children only; descendants walks the complete tree below you.", + "enum": [ + "children", + "descendants" + ] + } + } + } + }, + { + "name": "ralph", + "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The immutable completion objective for every fresh Ralph round." + }, + "maxRounds": { + "type": "number", + "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to a background subagent by its subagent id, continuing the same conversation. It becomes the subagent's next turn: if it is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. This call returns no answer from the subagent — only confirmation that the message was delivered — so use it to give it more work. A failure means the message was NOT delivered.", + "parameters": { + "type": "object", + "properties": { + "subagent_id": { + "type": "string", + "description": "The subagent id returned when the background subagent was started." + }, + "message": { + "type": "string", + "description": "The message to deliver to the subagent." + } + }, + "required": [ + "subagent_id", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + }, + "run_in_background": { + "type": "boolean", + "description": "Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_acp", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. This call waits for the result by default. Set `run_in_background: true` to return a job id; collect with `job_output` and stop with `job_kill`.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + }, + "run_in_background": { + "type": "boolean", + "description": "Whether to run as a background job and return its id. Defaults to false; collect with job_output or stop with job_kill." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This call waits for the subagent and returns its result.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Mark every todo being actively worked on `in_progress` — several at once when work genuinely runs in parallel (e.g. concurrent subagents or background commands), one for sequential work; while work remains, at least one task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit | pause | resume | complete | blocked", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Concrete blocking condition; required only with action blocked." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return ` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return `)." + }, + "meta": { + "type": "object", + "description": "The workflow identity block (plain JSON — never code).", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [] +} diff --git a/packages/subagent/subagent-acp/README.i18n.yaml b/packages/subagent/subagent-acp/README.i18n.yaml index 4aaf1b7552..6aab671122 100644 --- a/packages/subagent/subagent-acp/README.i18n.yaml +++ b/packages/subagent/subagent-acp/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-acp/README.md -README.md: 3bccddbca021bed1f8bf5766b9575f3bd7441669 -README.zh.md: 7ae89ece0ce4282ad5b9a20142a2ba9b111f6d88 +README.md: e01785a7a8cd5406fa545cc5e97b0a09d4f57fa1 +README.zh.md: 9082ab4d57b4393a07dc2e02cf6ce95ca259ae8d diff --git a/packages/subagent/subagent-acp/README.md b/packages/subagent/subagent-acp/README.md index 3bccddbca0..e01785a7a8 100644 --- a/packages/subagent/subagent-acp/README.md +++ b/packages/subagent/subagent-acp/README.md @@ -6,13 +6,13 @@ The ACP provider runs each subagent in a fresh subprocess and drives it as an Ag ## Start and ownership -`start(request)` resolves the child's working directory, then performs `spawn` → ACP `initialize` → `newSession` before it fulfills. Fulfillment therefore means a remote session is ready and ownership has transferred to the caller. A spawn, initialization, new-session, or pre-publication cancellation failure rejects only after the subprocess has been reaped; a working-directory resolution failure rejects before anything is spawned. +`start(request)` resolves the child's working directory, then performs `spawn` → ACP `initialize` → `newSession` before it fulfills. Fulfillment therefore means a remote session is ready and ownership has transferred to the caller. A spawn, initialization, new-session, or pre-publication cancellation failure rejects only after the subprocess has been reaped; a working-directory resolution failure rejects before anything is spawned. Non-cancellation rejections expose only fixed provider, stage, and category facts in their Error message; the original failure remains on the internal cause chain and in Host diagnostics. The working directory is the configured `cwd` override when set, else the delegating parent session's cwd — never the server process's own cwd, because one server process serves sessions from many workspaces. The parent-derived value must be an absolute path naming a directory the harness can enter (search permission — what a subprocess cwd needs), and the same resolved path becomes both the subprocess cwd and the ACP `session/new` workspace. The returned run id is minted in the parent namespace. The child server's session id remains private to ACP wire calls because ACP guarantees it only within that fresh child process; using it as the parent lifecycle id could collide with another remote run or a local agent. -After publication, the provider sends the prompt and collects streamed `agent_message_chunk` text into `SubagentResult.output`. A prompt/transport failure resolves with `stopReason: 'error'`, or `aborted` when the required request signal or disposal requested cancellation. +After publication, the provider sends the prompt and collects streamed `agent_message_chunk` text into `SubagentResult.output`. A prompt/transport or early-process failure resolves with `stopReason: 'error'` and a safe `SubagentResult.diagnostic`; local cancellation resolves as `aborted` without failure detail. Partial assistant text remains in `output`, separate from the diagnostic. `dispose()` is idempotent. It removes the signal listener, requests ACP cancellation when possible, then runs this backend's own teardown ladder (`disposeAcpChild`) over the seam's verbs: close stdin and wait `disposeEofGraceMs` for cooperative quiescence, then invoke the handle's `terminate()` escalation (SIGTERM, the spawn grace, SIGKILL — Windows force-terminates directly) and await the subprocess owner's whole-tree exit proof. Every run uses a fresh process; process pooling is not implemented. @@ -47,13 +47,26 @@ ACP advertises no start-time capabilities because this process cannot enforce th ## Stop-reason mapping -| ACP | Harness | -|---|---| -| `end_turn` | `completed` | -| `max_tokens` | `max-tokens` | -| `refusal` | `refusal` | -| `cancelled` | `aborted` | -| `max_turn_requests` or unknown | `error` | +| ACP | Harness | Additional diagnostic | +|---|---|---| +| `end_turn` | `completed` | None. | +| `max_tokens` | `max-tokens` | Only a contributing permission decision. | +| `refusal` | `refusal` | Only a contributing permission decision. | +| `cancelled` | `aborted` | Only a contributing permission decision; local cancellation never adds one. | +| `max_turn_requests` | `error` | `remote-limit` with the closed stop reason. | +| unknown | `error` | Fixed `unknown`; the wire value is not copied. | + +## Failure diagnostics + +The first line has a fixed field order: + +```text +Subagent failure (provider: ACP; stage: ; category: ; stop reason: ; exit code: ; signal: ) +``` + +Unavailable optional fields are omitted. The provider derives `initialize`, `new-session`, `prompt`, `process`, or `teardown` at the operation that owns the failure. Categories distinguish configuration, protocol or transport failure, process start/exit, remote limits or refusal, permission-related cancellation, and the fixed unknown fallback. Exit code and signal come only from the managed subprocess outcome; stderr, exception messages, task text, tool input, paths, environment values, credentials, and protocol payloads never enter the diagnostic. The shared result boundary limits the complete text to 4096 UTF-8 bytes. + +When a run requested permission and did not complete, a second fixed line records the configured policy, the ACP closed tool kind, and whether the provider allowed or denied it. Tool titles, raw input, locations, and option text are excluded. Successful results and local cancellation omit both lines. A permission-diagnosed remote `aborted` result remains `aborted`; foreground presentation includes its diagnostic, while the one-shot Job adapter classifies that diagnostic-bearing remote abort as failed instead of conflating it with local cancellation. ## Process boundary @@ -81,7 +94,7 @@ Independent of the parent request cache. Each ACP child can reuse only prefixes #### What the model sees -Through `dsh-tool-subagent`, the parent receives only the child's final streamed assistant text or that consumer's exact stop-reason error, not intermediate messages or tool traffic. A request already cancelled before publication becomes exactly `Error: subagent request was aborted before the ACP child started`; other start failures pass through as `Error: `. +Through `dsh-tool-subagent`, the parent receives only the child's final streamed assistant text or that consumer's exact stop-reason error, not intermediate messages or tool traffic. Non-completed results present the safe diagnostic before separately preserved partial assistant output. A request already cancelled before publication becomes exactly `Error: subagent request was aborted before the ACP child started`; another start failure contains only the fixed `Subagent failure (...)` line. #### Token effect diff --git a/packages/subagent/subagent-acp/README.zh.md b/packages/subagent/subagent-acp/README.zh.md index 7ae89ece0c..9082ab4d57 100644 --- a/packages/subagent/subagent-acp/README.zh.md +++ b/packages/subagent/subagent-acp/README.zh.md @@ -6,13 +6,13 @@ ACP(Agent Client Protocol)提供方会在全新的子进程中运行每个 s ## 启动与所有权 -`start(request)` 先解析子 agent 的工作目录,再依次执行 `spawn` → ACP `initialize` → `newSession`,然后才兑现。因此,兑现表示远程会话已就绪,所有权也已转移给调用方。spawn 失败、初始化失败、新建会话失败或因发布前取消而失败时,只有在子进程已回收后才会拒绝;工作目录解析失败则会在尚未 spawn 任何进程时拒绝。 +`start(request)` 先解析子 agent 的工作目录,再依次执行 `spawn` → ACP `initialize` → `newSession`,然后才兑现。因此,兑现表示远程会话已就绪,所有权也已转移给调用方。spawn 失败、初始化失败、新建会话失败或因发布前取消而失败时,只有在子进程已回收后才会拒绝;工作目录解析失败则会在尚未 spawn 任何进程时拒绝。非取消拒绝的 Error 消息只公开固定的 provider、stage 与 category 事实;原始失败仍保留在内部 cause 链和 Host 诊断中。 工作目录优先使用已配置的 `cwd` 覆盖值,否则使用执行委派的父会话 cwd,绝不使用服务器进程自身的 cwd,因为同一个服务器进程会服务来自多个工作区的会话。从父级取得的值必须是绝对路径,指向 harness 可以进入的目录(具备搜索权限,这是子进程 cwd 的要求);解析后的同一路径同时作为子进程 cwd 和 ACP `session/new` 工作区。 返回的运行 id 在父级命名空间中生成。子服务器的会话 id 只用于 ACP 协议调用,因为 ACP 只保证它在该全新子进程中唯一;若将其用作父级生命周期 id,可能与另一个远程运行或本地 agent 冲突。 -发布后,提供方发送提示词,并把流式 `agent_message_chunk` 文本收集到 `SubagentResult.output`。提示词/传输失败会以 `stopReason: 'error'` 兑现;如果必需的请求信号或 dispose(资源释放)请求了取消,则以 `aborted` 兑现。 +发布后,提供方发送提示词,并把流式 `agent_message_chunk` 文本收集到 `SubagentResult.output`。提示词/传输失败或进程提前退出会以 `stopReason: 'error'` 和安全的 `SubagentResult.diagnostic` 兑现;本地取消以 `aborted` 兑现,且不携带失败细节。部分 assistant 文本继续保留在 `output` 中,与诊断分开。 `dispose()` 是幂等的。它会移除信号监听器,在可行时请求 ACP 取消,然后使用该 seam 定义的操作运行本后端自有的拆卸阶梯(`disposeAcpChild`):先关闭 stdin 并等待 `disposeEofGraceMs` 让子进程协作式完全停稳,再触发句柄的 `terminate()` 升级(SIGTERM、spawn 宽限期、SIGKILL——Windows 直接强制终止),并等待子进程责任方给出整棵进程树的退出证明。每次运行都使用全新进程;尚未实现进程池。 @@ -47,13 +47,26 @@ ACP 不声明任何启动时能力,因为当前进程无法强制执行远程 ## 结束原因映射 -| ACP | Harness | -|---|---| -| `end_turn` | `completed` | -| `max_tokens` | `max-tokens` | -| `refusal` | `refusal` | -| `cancelled` | `aborted` | -| `max_turn_requests` 或未知值 | `error` | +| ACP | Harness | 附加诊断 | +|---|---|---| +| `end_turn` | `completed` | 无。 | +| `max_tokens` | `max-tokens` | 仅记录参与失败的权限决定。 | +| `refusal` | `refusal` | 仅记录参与失败的权限决定。 | +| `cancelled` | `aborted` | 仅记录参与失败的权限决定;本地取消绝不附加。 | +| `max_turn_requests` | `error` | `remote-limit` 与闭集结束原因。 | +| 未知值 | `error` | 固定 `unknown`,不复制 wire 原值。 | + +## 失败诊断 + +首行采用固定字段顺序: + +```text +Subagent failure (provider: ACP; stage: ; category: ; stop reason: ; exit code: ; signal: ) +``` + +不可用的可选字段会被省略。提供方从实际拥有失败的操作派生 `initialize`、`new-session`、`prompt`、`process` 或 `teardown`。category 区分配置、协议或传输失败、进程启动/退出、远端限制或拒绝、权限相关取消以及固定 unknown 回退。退出码与信号只来自受管子进程结果;stderr、异常消息、任务文本、工具输入、路径、环境值、凭证和协议 payload 绝不会进入诊断。共享结果边界会把完整文本限制在 4096 个 UTF-8 字节以内。 + +当运行请求过权限且最终未完成时,第二个固定行会记录已配置策略、ACP 闭集工具种类以及提供方允许还是拒绝。工具标题、raw input、位置与选项文本均被排除。成功结果和本地取消会省略两行。带权限诊断的远端 `aborted` 结果仍保持 `aborted`;前台会呈现该诊断,而一次性 Job adapter 会把这种带诊断的远端取消判为 failed,避免与本地取消混淆。 ## 进程边界 @@ -81,7 +94,7 @@ ACP 不声明任何启动时能力,因为当前进程无法强制执行远程 #### 模型看到的内容 -通过 `dsh-tool-subagent`,父级只接收子 agent 最终的流式 assistant 文本,或该消费方给出的精确结束原因错误;不接收中间消息或工具流量。发布前已经取消的请求会精确变为 `Error: subagent request was aborted before the ACP child started`;其他启动失败按原样传递为 `Error: `。 +通过 `dsh-tool-subagent`,父级只接收子 agent 最终的流式 assistant 文本,或该消费方给出的精确结束原因错误;不接收中间消息或工具流量。非完成结果会先呈现安全诊断,再单独呈现保留的部分 assistant 输出。发布前已经取消的请求会精确变为 `Error: subagent request was aborted before the ACP child started`;其他启动失败只包含固定的 `Subagent failure (...)` 行。 #### Token 影响 diff --git a/packages/subagent/subagent-acp/src/index.ts b/packages/subagent/subagent-acp/src/index.ts index 4b526279ba..7cbe1c79c9 100644 --- a/packages/subagent/subagent-acp/src/index.ts +++ b/packages/subagent/subagent-acp/src/index.ts @@ -18,7 +18,7 @@ import type { SubagentStartRequest, } from '@deepseek-ai/dsh-subagent' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' -import { type AcpRunSpec, DEFAULT_DISPOSE_EOF_GRACE_MS, DEFAULT_DISPOSE_GRACE_MS, type PermissionPolicy, startAcpRun } from './run.ts' +import { acpConfigurationFailure, type AcpRunSpec, DEFAULT_DISPOSE_EOF_GRACE_MS, DEFAULT_DISPOSE_GRACE_MS, type PermissionPolicy, startAcpRun } from './run.ts' export const name = 'subagent-acp' export const inject = ['subagents', 'subprocess'] @@ -151,10 +151,21 @@ class AcpProvider implements SubagentProvider { constructor(readonly name: string, private readonly ctx: Context, private readonly config: ResolvedConfig) {} start(request: ResolvedSubagentStartRequest) { + if (request.signal.aborted) { + throw new Error('subagent request was aborted before the ACP child started') + } + let cwd: string + try { + cwd = resolveCwd(this.config.cwd, request) + } catch (error: unknown) { + const failure = acpConfigurationFailure(error) + this.ctx.logger.warn(`subagent-acp "${this.name}": child start failed: %o`, error) + throw failure + } const spec: AcpRunSpec = { command: this.config.command, args: this.config.args, - cwd: resolveCwd(this.config.cwd, request), + cwd, permission: this.config.permission, env: this.config.env, disposeEofGraceMs: this.config.disposeEofGraceMs, diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index 5ba7bc1718..0ec364d115 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -2,9 +2,6 @@ * Fresh-process ACP subagent client. Drives one child session and owns cancellation and * quiescent disposal. * - * TODO(acp-subagent-replay): add snapshot-tier coverage with a separate replay fixture and - * sessions root inside each child process. Current keyless coverage uses a scripted ACP child; - * with-key coverage drives the real ACP example. * @module @deepseek-ai/dsh-subagent-acp/run */ @@ -21,12 +18,13 @@ import { type RequestPermissionResponse, type SessionNotification, type StopReason, + type ToolKind, } from '@agentclientprotocol/sdk' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' -import { AssistantOutputFold } from '@deepseek-ai/dsh-subagent' +import { AssistantOutputFold, settleRunResult, subprocessRunHandle } from '@deepseek-ai/dsh-subagent' import type { SubagentResult, SubagentRun, SubagentStartRequest, SubagentStopReason } from '@deepseek-ai/dsh-subagent' -import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import type { SubprocessHandle, SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' /** Fixed response to child permission requests: reject by default, or select the first allow option. */ export type PermissionPolicy = 'allow' | 'reject' @@ -75,12 +73,9 @@ export interface AcpRunSpec { */ spawn: (spec: SubprocessSpawnSpec) => SubprocessHandle /** - * Sink for a child-level failure that the run flattened into a stop reason - * (the seam contract forbids `result` rejecting). The driver calls this with - * the original error and the chosen stop reason so the fault is preserved - * rather than silently lost; the provider wires it to `ctx.logger.warn`. - * A throw from the sink itself is contained — it cannot reject `result`. - * Optional — omitted in a unit test that asserts the stop reason directly. + * Host sink for startup, published-run, or teardown failures. Model-visible + * text uses fixed safe facts, while this callback retains the original Error + * when one exists. A throw from the sink itself is contained. */ onError?: (error: Error, stopReason: SubagentStopReason) => void } @@ -91,6 +86,92 @@ export const DEFAULT_DISPOSE_EOF_GRACE_MS = 6_000 /** Default POSIX grace between SIGTERM and SIGKILL on dispose (the `disposeGraceMs` config). */ export const DEFAULT_DISPOSE_GRACE_MS = 3_000 +type AcpFailureStage = 'initialize' | 'new-session' | 'prompt' | 'process' | 'teardown' + +type AcpFailureCategory = + | 'protocol' + | 'configuration' + | 'transport' + | 'process-start' + | 'process-exit' + | 'remote-limit' + | 'remote-refusal' + | 'permission' + | 'unknown' + +interface AcpFailureFacts { + readonly stage: AcpFailureStage + readonly category: AcpFailureCategory + readonly stopReason?: StopReason | 'unknown' + readonly outcome?: SubprocessOutcome | undefined +} + +interface AcpPermissionDecision { + readonly policy: PermissionPolicy + readonly request: ToolKind | 'unknown' + readonly decision: 'allowed' | 'denied' +} + +const ACP_TOOL_KINDS: ReadonlySet = new Set([ + 'read', 'edit', 'delete', 'move', 'search', + 'execute', 'think', 'fetch', 'switch_mode', 'other', +]) + +/** Fixed safe failure text derived only from provider-owned structured facts. */ +function failureDiagnostic(facts: AcpFailureFacts): string { + const fields = [ + 'provider: ACP', + `stage: ${facts.stage}`, + `category: ${facts.category}`, + ] + if (facts.stopReason !== undefined) fields.push(`stop reason: ${facts.stopReason}`) + if (facts.outcome?.exitCode !== null && facts.outcome?.exitCode !== undefined) { + fields.push(`exit code: ${facts.outcome.exitCode}`) + } + if (facts.outcome?.signal !== null && facts.outcome?.signal !== undefined) { + fields.push(`signal: ${facts.outcome.signal}`) + } + return `Subagent failure (${fields.join('; ')})` +} + +/** Fixed permission fact; ACP tool titles and option text never enter it. */ +function permissionDiagnostic(permission: AcpPermissionDecision): string { + return `ACP unattended decision (policy: ${permission.policy}; request: ${permission.request}; decision: ${permission.decision})` +} + +/** Put the operation failure first, followed by the latest contributing permission fact. */ +function diagnosticText(facts: AcpFailureFacts, permission?: AcpPermissionDecision): string { + const failure = failureDiagnostic(facts) + return permission === undefined ? failure : `${failure}\n${permissionDiagnostic(permission)}` +} + +class AcpRunFailure extends Error { + constructor(readonly facts: AcpFailureFacts, cause: unknown) { + super( + `subagent-acp: ${failureDiagnostic(facts)}`, + { cause }, + ) + this.name = 'AcpRunFailure' + } +} + +/** + * Hide a pre-spawn workspace/configuration failure behind fixed safe facts. + * @param cause - original Host failure retained on the Error cause chain. + * @returns an Error whose message contains only the fixed ACP failure line. + */ +export function acpConfigurationFailure(cause: unknown): Error { + return new AcpRunFailure({ stage: 'initialize', category: 'configuration' }, cause) +} + +/** Keep only the closed ACP tool-kind vocabulary; future values use a fixed fallback. */ +function permissionRequestKind(kind: ToolKind | null | undefined): ToolKind | 'unknown' { + const candidate = kind ?? 'unknown' + return ACP_TOOL_KINDS.has(candidate) + ? candidate + : 'unknown' +} + /** Bounded whole-tree exit wait: polls the handle's tree liveness until it exits or `ms` elapses. */ async function treeExitsWithin(child: SubprocessHandle, ms: number): Promise { const controller = new AbortController() @@ -187,10 +268,70 @@ function toError(value: unknown): Error { return value instanceof Error ? value : new Error(String(value)) } +/** Report an original Host failure without letting the observation sink replace it. */ +function reportFailure(spec: AcpRunSpec, error: unknown): void { + try { + spec.onError?.(toError(error), 'error') + } catch { + // Host diagnostic logging cannot replace the child failure. + } +} + +/** Classify an unpublished failure from the active protocol operation and observed process facts. */ +function startupFailure( + error: unknown, + stage: Extract, + child: SubprocessHandle, + outcome: SubprocessOutcome | undefined, +): AcpRunFailure { + if (error instanceof AcpRunFailure) return error + if (child.pid <= 0) { + return new AcpRunFailure({ stage: 'process', category: 'process-start' }, error) + } + return new AcpRunFailure( + outcome === undefined + ? { stage, category: 'transport' } + : { stage, category: 'process-exit', outcome }, + error, + ) +} + +/** Map one remote terminal reason to the optional safe failure line it needs. */ +function terminalFailure( + reason: StopReason, + permission: AcpPermissionDecision | undefined, +): string | undefined { + switch (reason) { + case 'end_turn': + return undefined + case 'max_turn_requests': + return diagnosticText({ + stage: 'prompt', + category: 'remote-limit', + stopReason: 'max_turn_requests', + }, permission) + case 'max_tokens': + return permission === undefined + ? undefined + : diagnosticText({ stage: 'prompt', category: 'remote-limit', stopReason: reason }, permission) + case 'refusal': + return permission === undefined + ? undefined + : diagnosticText({ stage: 'prompt', category: 'remote-refusal', stopReason: reason }, permission) + case 'cancelled': + return permission === undefined + ? undefined + : diagnosticText({ stage: 'prompt', category: 'permission', stopReason: reason }, permission) + default: + return diagnosticText({ stage: 'prompt', category: 'unknown', stopReason: 'unknown' }, permission) + } +} + /** * Start and publish one ACP child after initialization and session creation. - * Child failures resolve through the run result; startup failures reject after - * process reap. Disposal cancels, kills, and reaps the child. + * Child failures resolve through the run result; startup and teardown failures + * reject with fixed safe facts after process reap, retaining original causes + * for Host observation. Disposal cancels, kills, and reaps the child. * @param request - the start request; its signal is the cancellation channel. * @param spec - the resolved spawn spec: command/args/cwd, env, permission * policy, dispose graces, and the optional error sink. @@ -218,17 +359,36 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe throw new Error('subagent-acp: subprocess implementation dropped a piped protocol stream') } /* v8 ignore stop */ + let processOutcome: SubprocessOutcome | undefined + const processDone = child.done.then((outcome) => { + processOutcome = outcome + return outcome + }) + // Spawn-level failure surfaces as `done` rejecting into the startup race; a // clean exit must never win it, so the success arm parks forever. (The ACP // connection observing its streams closing bounds a child that exits // without speaking the protocol.) - const spawnFailed: Promise = child.done.then( + const spawnFailed: Promise = processDone.then( /* v8 ignore next -- the success arm's never-settling executor is intentionally empty. */ () => new Promise(() => {}), (err: unknown) => Promise.reject(toError(err)), ) spawnFailed.catch(() => { /* observed by the startup race; never unhandled */ }) + const observeProcessOutcome = async (): Promise => { + if (processOutcome !== undefined || child.pid <= 0) return processOutcome + try { + const exited = await child.waitForExit( + AbortSignal.timeout(Math.min(spec.disposeGraceMs, 100)), + ) + if (exited) return await processDone + } catch { + // The active protocol failure remains authoritative when exit observation fails. + } + return processOutcome + } + // Startup rollback and the published handle share one process teardown. let processDisposal: Promise | undefined const disposeProcess = (): Promise => (processDisposal ??= disposeAcpChild(child, spec.disposeEofGraceMs)) @@ -238,6 +398,7 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe const fold = new AssistantOutputFold() // Shared mutable state keeps cancellation visible across async closures. const flags = { cancelled: false } + let latestPermission: AcpPermissionDecision | undefined const makeClient = (_agent: AcpAgent): Client => ({ sessionUpdate(params: SessionNotification): Promise { @@ -256,9 +417,19 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe if (spec.permission === 'allow') { const allow = params.options.find(o => o.kind === 'allow_once' || o.kind === 'allow_always') if (allow !== undefined) { + latestPermission = { + policy: 'allow', + request: permissionRequestKind(params.toolCall.kind), + decision: 'allowed', + } return Promise.resolve({ outcome: { outcome: 'selected', optionId: allow.optionId } }) } } + latestPermission = { + policy: spec.permission, + request: permissionRequestKind(params.toolCall.kind), + decision: 'denied', + } return Promise.resolve({ outcome: { outcome: 'cancelled' } }) }, }) @@ -272,6 +443,7 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe ) let sessionId: string | undefined + let startupStage: Extract = 'initialize' // Cancellation settles the result without waiting for a cooperative child. let signalCancelSettled!: () => void const cancelSettled = new Promise((resolve) => { signalCancelSettled = resolve }) @@ -300,9 +472,15 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe // child self-serves in its own process. clientCapabilities: {}, }) + startupStage = 'new-session' const session = await conn.newSession({ cwd: spec.cwd, mcpServers: [] }) const returnedSessionId: unknown = Reflect.get(session, 'sessionId') - if (typeof returnedSessionId !== 'string') throw new Error('ACP child published without a session id') + if (typeof returnedSessionId !== 'string') { + throw new AcpRunFailure( + { stage: 'new-session', category: 'protocol' }, + new Error('ACP child published without a session id'), + ) + } sessionId = returnedSessionId if (flags.cancelled) throw new Error('subagent cancelled before the ACP session started') })(), @@ -311,9 +489,36 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe ]) } catch (error: unknown) { request.signal.removeEventListener('abort', onAbort) - await disposeProcess() - if (flags.cancelled) throw new Error('subagent request was aborted before the ACP child started') - throw toError(error) + const cancelledBeforeCleanup = flags.cancelled + // A child closing its protocol stream can precede whole-tree exit + // observation. Wait briefly for an already-ending process, but do not let a + // still-live transport failure delay rollback by a full teardown grace. + const startupOutcome = await observeProcessOutcome() + const failure = startupFailure(error, startupStage, child, startupOutcome) + if (!cancelledBeforeCleanup) { + reportFailure(spec, error instanceof AcpRunFailure + ? error.cause + : error) + } + try { + await disposeProcess() + } catch (cleanupError: unknown) { + reportFailure(spec, cleanupError) + const cleanupFailure = new AcpRunFailure({ + stage: 'teardown', + category: processOutcome === undefined ? 'unknown' : 'process-exit', + ...(processOutcome === undefined ? {} : { outcome: processOutcome }), + }, cleanupError) + if (cancelledBeforeCleanup) throw cleanupFailure + throw new AggregateError( + [failure, cleanupFailure], + `${failure.message}; ${cleanupFailure.message}`, + ) + } + if (cancelledBeforeCleanup) { + throw new Error('subagent request was aborted before the ACP child started') + } + throw failure } // The startup transaction validates the returned id before it can fulfill. // This assertion carries that cross-closure invariant into TypeScript. @@ -321,48 +526,59 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe if (sessionId === undefined) throw new Error('unreachable: ACP startup fulfilled without a session id') const remoteSessionId = sessionId - const result: Promise = (async (): Promise => { - try { - // Race the remote turn against local cancellation. - const prompt = async (): Promise => { - // The startup phase cannot fulfill without assigning the session id. - const promptResult = await conn.prompt({ sessionId: remoteSessionId, prompt: toAcpPrompt(request.prompt) }) - return { output: collectOutput(), stopReason: acpStopReason(promptResult.stopReason) } - } - return await Promise.race([ - prompt(), - cancelSettled.then((): SubagentResult => ({ output: collectOutput(), stopReason: 'aborted' })), - ]) - } catch (error: unknown) { - // Cover a process rejection already queued when cancellation arrives. - /* v8 ignore next */ - if (flags.cancelled) return { output: collectOutput(), stopReason: 'aborted' } - // Flatten post-publication transport failures while preserving diagnostics. + let diagnostic: string | undefined + const result: Promise = settleRunResult({ + attempt: async (): Promise => { try { - spec.onError?.(toError(error), 'error') - } catch { - // The diagnostic sink cannot reject the run result. + const promptResult = await Promise.race([ + conn.prompt({ sessionId: remoteSessionId, prompt: toAcpPrompt(request.prompt) }), + cancelSettled.then((): never => { throw new Error('subagent cancelled while the ACP prompt was running') }), + ]) + const stopReason = acpStopReason(promptResult.stopReason) + diagnostic = terminalFailure(promptResult.stopReason, latestPermission) + return { + output: collectOutput(), + ...(diagnostic === undefined ? {} : { diagnostic }), + stopReason, + } + } catch (error: unknown) { + if (!flags.cancelled) { + const outcome = await observeProcessOutcome() + const facts = outcome === undefined + ? { stage: 'prompt', category: 'transport' } as const + : { stage: 'process', category: 'process-exit', outcome } as const + diagnostic = diagnosticText(facts, latestPermission) + } + throw error } - return { output: collectOutput(), stopReason: 'error' } - } finally { - request.signal.removeEventListener('abort', onAbort) - } - })() - - let disposal: Promise | undefined - return { - id, - localAgent: undefined, - result, - dispose(): Promise { - if (disposal !== undefined) return disposal - request.signal.removeEventListener('abort', onAbort) - requestCancel() - // The shared platform-aware ladder awaits exit. ACP normally quiesces from - // stdin EOF, including the final flush, so this backend uses a wider EOF - // grace before process termination escalates. - disposal = disposeProcess() - return disposal }, - } + collectOutput, + collectDiagnostic: () => diagnostic, + cancelled: () => flags.cancelled, + onError: spec.onError, + signal: request.signal, + onAbort, + }) + + return subprocessRunHandle({ + id, + result, + signal: request.signal, + onAbort, + requestCancel, + teardown: async () => { + try { + // ACP normally quiesces from stdin EOF, including the final flush, so + // this backend uses a wider EOF grace before process termination. + await disposeProcess() + } catch (error: unknown) { + reportFailure(spec, error) + throw new AcpRunFailure({ + stage: 'teardown', + category: processOutcome === undefined ? 'unknown' : 'process-exit', + ...(processOutcome === undefined ? {} : { outcome: processOutcome }), + }, error) + } + }, + }) } diff --git a/packages/subagent/subagent-acp/tests/loader-composition.e2e.ts b/packages/subagent/subagent-acp/tests/loader-composition.e2e.ts index 30160f0607..ddbfb35a81 100644 --- a/packages/subagent/subagent-acp/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-acp/tests/loader-composition.e2e.ts @@ -7,12 +7,10 @@ import { type SessionEvent } from '@deepseek-ai/dsh-session' import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' /** - * Keyless REAL-composition coverage for parent-session cwd inheritance: a - * test-only cordis.yml boots the headless app through the Loader with the ACP - * backend's `cwd` omitted, a scripted model delegates once, and the scripted - * mock ACP child echoes where it actually ran plus the workspace it was - * announced — both must be the parent session's cwd. Mock-only composition, so - * only this keyless tier applies (the with-key tier lives in subagent-acp.e2e.ts). + * Keyless REAL-composition coverage for the ACP provider through a test-only + * cordis.yml: parent-session cwd inheritance and model-visible failure detail + * both cross the Loader, subprocess, ACP, tool, and persisted-session paths. + * The with-key tier lives in subagent-acp.e2e.ts. */ const driver = fileURLToPath(new URL( @@ -36,6 +34,15 @@ async function jsonlFiles(dir: string): Promise { return paths.flat() } +function toolResultText(events: SessionEvent[]): string { + const results = events.filter(event => event.type === 'tool/result') + expect(results).toHaveLength(1) + return results[0]!.data.message.content[0].content + .filter(block => block.type === 'text') + .map(block => block.text) + .join('') +} + describe('ACP subagent cwd inheritance through a real cordis.yml', () => { it('runs the child in the parent session workspace and announces it as the ACP session cwd', async () => { let events: SessionEvent[] = [] @@ -62,12 +69,34 @@ describe('ACP subagent cwd inheritance through a real cordis.yml', () => { // The tool result carries the child's two-line echo: its real process.cwd() // and the cwd the backend announced in `session/new` — both the parent // session's workspace, never the harness process's launch directory. - const results = events.filter(event => event.type === 'tool/result') - expect(results).toHaveLength(1) - const resultText = results[0]!.data.message.content[0].content - .filter(block => block.type === 'text') - .map(block => block.text) - .join('') - expect(resultText).toBe(`${workspace}\n${workspace}`) + expect(toolResultText(events)).toBe(`${workspace}\n${workspace}`) + }, LOADER_SMOKE_TEST_TIMEOUT_MS) + + it('presents the ACP remote-limit diagnostic separately from partial output', async () => { + let events: SessionEvent[] = [] + const { stderr } = await runLoaderSmoke({ + label: 'acp-subagent diagnostic composition smoke', + tempDirPrefix: 'acp-subagent-diagnostic-e2e-', + binScript: driver, + libBinScript: driver, + configPath, + tsconfigPath: repoTsconfig, + env: { + DSH_TEST_MOCK_ACP_SERVER: mockServer, + DSH_TEST_ACP_MODE: 'diagnostic', + }, + inspect: async (cwd) => { + const logs = await jsonlFiles(join(cwd, '.sessions')) + expect(logs).toHaveLength(1) + const lines = (await readFile(logs[0] as string, 'utf8')).trimEnd().split('\n') + events = lines.slice(1).map(line => JSON.parse(line) as SessionEvent) + }, + }) + expect(stderr).not.toContain('UNHANDLED') + expect(toolResultText(events)).toBe( + 'Error: subagent run failed\n' + + 'Diagnostic: Subagent failure (provider: ACP; stage: prompt; category: remote-limit; stop reason: max_turn_requests)\n' + + 'Partial output before the run ended:\npartial loader answer', + ) }, LOADER_SMOKE_TEST_TIMEOUT_MS) }) diff --git a/packages/subagent/subagent-acp/tests/mock-acp-server.ts b/packages/subagent/subagent-acp/tests/mock-acp-server.ts index de5900906a..b5a0340406 100644 --- a/packages/subagent/subagent-acp/tests/mock-acp-server.ts +++ b/packages/subagent/subagent-acp/tests/mock-acp-server.ts @@ -18,6 +18,15 @@ * `dispose()` must still kill the process. * - `MOCK_PERMISSION` — if `1`, the agent calls `session/request_permission` * before answering, to exercise the client's auto-answer. + * - `MOCK_PERMISSION_IGNORE_DECISION` — if `1`, continue after a denied + * permission so the terminal failure can carry the + * provider's fixed permission fact. + * - `MOCK_CRASH_ON_INITIALIZE` / `MOCK_CRASH_ON_NEW_SESSION` — exit while the + * named unpublished protocol operation is active. + * - `MOCK_CLOSE_PROTOCOL_ON_PROMPT` — close stdout while keeping the process + * alive, producing a prompt-stage transport failure. + * - `MOCK_CRASH_AFTER_CHUNK` — exit after streaming the assistant chunk, so + * the parent preserves partial output with process facts. * - `MOCK_ECHO_CWD` — if `1`, ignore MOCK_TEXT and stream two lines instead: * the agent PROCESS's `process.cwd()` and the `cwd` the * client announced in `session/new` — so a test can assert @@ -68,6 +77,7 @@ import { type PromptRequest, type PromptResponse, type StopReason, + type ToolKind, } from '@agentclientprotocol/sdk' // When MOCK_ECHO_ENV names a variable, stream that variable's value in place @@ -80,11 +90,17 @@ const ECHO_CWD = process.env.MOCK_ECHO_CWD === '1' const STOP = (process.env.MOCK_STOP ?? 'end_turn') as StopReason const HANG = process.env.MOCK_HANG === '1' const WANT_PERMISSION = process.env.MOCK_PERMISSION === '1' +const IGNORE_PERMISSION_DECISION = process.env.MOCK_PERMISSION_IGNORE_DECISION === '1' const NO_ALLOW = process.env.MOCK_NO_ALLOW === '1' const THOUGHT = process.env.MOCK_THOUGHT === '1' +const CRASH_ON_INITIALIZE = process.env.MOCK_CRASH_ON_INITIALIZE === '1' +const CRASH_ON_NEW_SESSION = process.env.MOCK_CRASH_ON_NEW_SESSION === '1' const CRASH_ON_CANCEL = process.env.MOCK_CRASH_ON_CANCEL === '1' const CRASH_ON_PROMPT = process.env.MOCK_CRASH_ON_PROMPT === '1' +const CLOSE_PROTOCOL_ON_PROMPT = process.env.MOCK_CLOSE_PROTOCOL_ON_PROMPT === '1' +const CRASH_AFTER_CHUNK = process.env.MOCK_CRASH_AFTER_CHUNK === '1' const IGNORE_CANCEL = process.env.MOCK_IGNORE_CANCEL === '1' +const TOOL_KIND = process.env.MOCK_TOOL_KIND as ToolKind | undefined const READY_FILE = process.env.MOCK_READY_FILE const FLUSH_ON_EOF = process.env.MOCK_FLUSH_ON_EOF // When MOCK_NEWSESSION_READY/GO are set, newSession touches READY then blocks @@ -102,6 +118,7 @@ function makeAgent(conn: AgentSideConnection): Agent { return { initialize(_params: InitializeRequest): Promise { + if (CRASH_ON_INITIALIZE) process.exit(11) return Promise.resolve({ protocolVersion: PROTOCOL_VERSION, agentCapabilities: { loadSession: false, promptCapabilities: { image: false, audio: false, embeddedContext: false } }, @@ -109,6 +126,7 @@ function makeAgent(conn: AgentSideConnection): Agent { }) }, async newSession(params: NewSessionRequest): Promise { + if (CRASH_ON_NEW_SESSION) process.exit(12) sessionCwd = params.cwd // Optionally signal "newSession reached" and block until released, so a // test can cancel DURING newSession (the early-cancel race window) on a @@ -126,6 +144,11 @@ function makeAgent(conn: AgentSideConnection): Agent { }, async prompt(params: PromptRequest): Promise { if (CRASH_ON_PROMPT) process.exit(1) + if (CLOSE_PROTOCOL_ON_PROMPT) { + process.stdout.end() + setInterval(() => { /* keep the process alive after protocol EOF */ }, 1000) + return new Promise(() => {}) + } if (WANT_PERMISSION) { // Ask the client to approve before answering; honor its decision. Under // MOCK_NO_ALLOW the only options are reject-shaped, so an `allow`-policy @@ -138,10 +161,14 @@ function makeAgent(conn: AgentSideConnection): Agent { ] const decision = await conn.requestPermission({ sessionId: params.sessionId, - toolCall: { toolCallId: 'mock-call', title: 'mock side effect' }, + toolCall: { + toolCallId: 'mock-call', + title: 'mock side effect', + ...(TOOL_KIND === undefined ? {} : { kind: TOOL_KIND }), + }, options, }) - if (decision.outcome.outcome === 'cancelled') { + if (decision.outcome.outcome === 'cancelled' && !IGNORE_PERMISSION_DECISION) { return { stopReason: 'cancelled' } } } @@ -162,6 +189,10 @@ function makeAgent(conn: AgentSideConnection): Agent { content: { type: 'text', text: ECHO_CWD ? `${process.cwd()}\n${sessionCwd ?? ''}` : TEXT }, }, }) + if (CRASH_AFTER_CHUNK) { + await new Promise((resolve) => { setImmediate(resolve) }) + process.exit(17) + } // Signal "prompt is in flight" by touching the readiness file, so a test // can wait on a CONDITION (file exists) rather than an arbitrary timeout // before cancelling — deterministic regardless of subprocess cold-start. diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index c534b8e949..d3454fa10c 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -8,7 +8,7 @@ import { fileURLToPath } from 'node:url' import SubagentRuntime from '@deepseek-ai/dsh-subagent' import type { Agent } from '@deepseek-ai/dsh-agent' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' -import type { SubprocessOutcome } from '@deepseek-ai/dsh-subprocess' +import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess' import * as acp from '../src/index.ts' import { acpStopReason, acpContentText, DEFAULT_DISPOSE_EOF_GRACE_MS, DEFAULT_DISPOSE_GRACE_MS, disposeAcpChild, startAcpRun, toAcpPrompt, type AcpRunSpec } from '../src/run.ts' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' @@ -59,6 +59,14 @@ function text(blocks: { type: string; text?: string }[]): string { return blocks.filter(b => b.type === 'text').map(b => b.text).join('') } +function expectedFailure(fields: string): string { + return `Subagent failure (provider: ACP; ${fields})` +} + +function expectedPermission(policy: 'allow' | 'reject', requestKind: string, decision: 'allowed' | 'denied'): string { + return `ACP unattended decision (policy: ${policy}; request: ${requestKind}; decision: ${decision})` +} + /** * Poll until `file` exists (the mock touches it once its prompt is in flight), * so a cancel test waits on a CONDITION rather than an arbitrary timeout — the @@ -73,6 +81,30 @@ async function waitForFile(file: string, timeoutMs = 5000): Promise { } } +function rejectFinalExitWait(child: SubprocessHandle, message: string): SubprocessHandle { + return { + pid: child.pid, + stdin: child.stdin, + stdout: child.stdout, + stderr: child.stderr, + collected: child.collected, + done: child.done, + terminate: () => { child.terminate() }, + waitForExit: (signal?: AbortSignal) => signal === undefined + ? Promise.reject(new Error(message)) + : Promise.resolve(false), + } +} + +function rejectFinalExitWaitAfterExit(child: SubprocessHandle, message: string): SubprocessHandle { + return { + ...rejectFinalExitWait(child, message), + waitForExit: (signal?: AbortSignal) => signal === undefined + ? child.done.then(() => Promise.reject(new Error(message))) + : Promise.resolve(false), + } +} + describe('acpStopReason', () => { it('maps each ACP stop reason to the harness vocabulary', () => { expect(acpStopReason('end_turn')).toBe('completed') @@ -228,7 +260,7 @@ describe('cwd resolution', () => { await ctx.plugin(acp, { providerName: 'acp', command: 'touch', args: [sentinel], permission: 'reject', env: {} }) const parent = { id: 'parent', session: { header: {} } } as unknown as Agent await expect(ctx.subagents.start('acp', { prompt: [{ type: 'text' as const, text: 'p' }], parent, signal: new AbortController().signal })) - .rejects.toThrow('no working directory') + .rejects.toThrow(`subagent-acp: ${expectedFailure('stage: initialize; category: configuration')}`) // Resolution failed BEFORE the process boundary — nothing was launched. expect(existsSync(sentinel)).toBe(false) } finally { @@ -349,7 +381,7 @@ describe('cwd resolution', () => { const ctx = await setup({}) const parent = { id: 'parent', session: { header: { cwd: 'relative/workspace' } } } as unknown as Agent await expect(ctx.subagents.start('acp', { prompt: [{ type: 'text' as const, text: 'p' }], parent, signal: new AbortController().signal })) - .rejects.toThrow('must be an absolute path') + .rejects.toThrow(`subagent-acp: ${expectedFailure('stage: initialize; category: configuration')}`) }) it('rejects a parent session cwd that names a FILE, not a directory', async () => { @@ -360,7 +392,7 @@ describe('cwd resolution', () => { const ctx = await setup({}) const parent = { id: 'parent', session: { header: { cwd: file } } } as unknown as Agent await expect(ctx.subagents.start('acp', { prompt: [{ type: 'text' as const, text: 'p' }], parent, signal: new AbortController().signal })) - .rejects.toThrow('not an accessible directory') + .rejects.toThrow(`subagent-acp: ${expectedFailure('stage: initialize; category: configuration')}`) } finally { rmSync(tmp, { recursive: true, force: true }) } @@ -376,7 +408,7 @@ describe('cwd resolution', () => { await ctx.plugin(acp, { providerName: 'acp', command: 'touch', args: [sentinel], permission: 'reject', env: {} }) const parent = { id: 'parent', session: { header: { cwd: join(tmp, 'vanished') } } } as unknown as Agent await expect(ctx.subagents.start('acp', { prompt: [{ type: 'text' as const, text: 'p' }], parent, signal: new AbortController().signal })) - .rejects.toThrow('not an accessible directory') + .rejects.toThrow(`subagent-acp: ${expectedFailure('stage: initialize; category: configuration')}`) expect(existsSync(sentinel)).toBe(false) } finally { rmSync(tmp, { recursive: true, force: true }) @@ -391,6 +423,7 @@ describe('dsh-subagent-acp', () => { expect(run.id).not.toBe('acp-child-session') const result = await run.result expect(result.stopReason).toBe('completed') + expect(result.diagnostic).toBeUndefined() expect(text(result.output)).toBe('hello from acp child') const disposal = run.dispose() expect(run.dispose()).toBe(disposal) @@ -408,6 +441,7 @@ describe('dsh-subagent-acp', () => { const run = await ctx.subagents.start('acp', request()) const result = await run.result expect(result.stopReason).toBe('max-tokens') + expect(result.diagnostic).toBeUndefined() await run.dispose() }) @@ -416,6 +450,59 @@ describe('dsh-subagent-acp', () => { const run = await ctx.subagents.start('acp', request()) const result = await run.result expect(result.stopReason).toBe('refusal') + expect(result.diagnostic).toBeUndefined() + await run.dispose() + }) + + it.each([ + ['max_tokens', 'max-tokens', 'remote-limit'], + ['refusal', 'refusal', 'remote-refusal'], + ] as const)('adds a permission fact to %s without changing its stop reason', async (remote, stopReason, category) => { + const ctx = await setup({ + MOCK_PERMISSION: '1', + MOCK_PERMISSION_IGNORE_DECISION: '1', + MOCK_TOOL_KIND: 'read', + MOCK_STOP: remote, + }, 'reject') + const run = await ctx.subagents.start('acp', request()) + const result = await run.result + expect(result.stopReason).toBe(stopReason) + expect(result.diagnostic).toBe( + `${expectedFailure(`stage: prompt; category: ${category}; stop reason: ${remote}`)}\n` + + expectedPermission('reject', 'read', 'denied'), + ) + await run.dispose() + }) + + it('keeps an ordinary remote cancelled stop diagnostic-free', async () => { + const ctx = await setup({ MOCK_STOP: 'cancelled' }) + const run = await ctx.subagents.start('acp', request()) + await expect(run.result).resolves.toEqual({ output: [{ type: 'text', text: 'mock child answer' }], stopReason: 'aborted' }) + await run.dispose() + }) + + it('preserves max_turn_requests as an actionable remote limit', async () => { + const ctx = await setup({ MOCK_TEXT: 'partial', MOCK_STOP: 'max_turn_requests' }) + const run = await ctx.subagents.start('acp', request()) + const result = await run.result + expect(result).toEqual({ + output: [{ type: 'text', text: 'partial' }], + diagnostic: expectedFailure('stage: prompt; category: remote-limit; stop reason: max_turn_requests'), + stopReason: 'error', + }) + await run.dispose() + }) + + it('uses a fixed fallback for an unknown remote stop reason', async () => { + const rawReason = 'private/path/SECRET_TOKEN' + const ctx = await setup({ MOCK_TEXT: 'partial', MOCK_STOP: rawReason }) + const run = await ctx.subagents.start('acp', request()) + const result = await run.result + expect(result.stopReason).toBe('error') + expect(result.diagnostic).toBe( + expectedFailure('stage: prompt; category: unknown; stop reason: unknown'), + ) + expect(result.diagnostic).not.toContain(rawReason) await run.dispose() }) @@ -432,6 +519,7 @@ describe('dsh-subagent-acp', () => { controller.abort('test') const result = await run.result expect(result.stopReason).toBe('aborted') + expect(result.diagnostic).toBeUndefined() await run.dispose() } finally { rmSync(tmp, { recursive: true, force: true }) @@ -459,6 +547,35 @@ describe('dsh-subagent-acp', () => { } }) + it('rejects a pre-aborted request through the registered provider before cwd resolution', async () => { + const ctx = await setup() + const controller = new AbortController() + controller.abort() + const parent = { id: 'parent', session: { header: {} } } as unknown as Agent + await expect(ctx.subagents.start('acp', { + prompt: [{ type: 'text' as const, text: 'p' }], + parent, + signal: controller.signal, + })).rejects.toThrow('subagent request was aborted before the ACP child started') + }) + + it('reports an initialize-stage process exit without copying the transport error', async () => { + const error = await startAcpRun(request(), { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission: 'reject', + env: { MOCK_CRASH_ON_INITIALIZE: '1' }, + disposeEofGraceMs: DEFAULT_DISPOSE_EOF_GRACE_MS, + disposeGraceMs: DEFAULT_DISPOSE_GRACE_MS, + spawn: spawnSubprocess, + }).catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe( + `subagent-acp: ${expectedFailure('stage: initialize; category: process-exit; exit code: 11')}`, + ) + }) + it('reaps a child whose session/new response omits the session id', async () => { const tmp = mkdtempSync(join(tmpdir(), 'acp-malformed-session-')) const flushed = join(tmp, 'flushed') @@ -476,7 +593,9 @@ describe('dsh-subagent-acp', () => { disposeEofGraceMs: 1000, disposeGraceMs: 100, spawn: spawnSubprocess, - })).rejects.toThrow('ACP child published without a session id') + })).rejects.toThrow( + `subagent-acp: ${expectedFailure('stage: new-session; category: protocol')}`, + ) // Startup rejects only after its private child reaches quiescence. The // marker proves rollback closed stdin and allowed the child's EOF flush. expect(existsSync(flushed)).toBe(true) @@ -485,6 +604,71 @@ describe('dsh-subagent-acp', () => { } }) + it('aggregates safe startup and teardown facts when rollback itself fails', async () => { + const rawCleanup = 'rollback leaked /private/path SECRET_TOKEN' + let realChild: SubprocessHandle | undefined + const errors: string[] = [] + const error = await startAcpRun(request(), { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission: 'reject', + env: { MOCK_MISSING_SESSION_ID: '1' }, + disposeEofGraceMs: 10, + disposeGraceMs: 10, + spawn: (spec) => { + realChild = spawnSubprocess(spec) + return rejectFinalExitWaitAfterExit(realChild, rawCleanup) + }, + onError: (failure) => { errors.push(failure.message) }, + }).catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(AggregateError) + expect((error as Error).message).toContain( + `subagent-acp: ${expectedFailure('stage: new-session; category: protocol')}; ` + + 'subagent-acp: Subagent failure (provider: ACP; stage: teardown; category: process-exit;', + ) + expect((error as Error).message).not.toContain(rawCleanup) + expect(errors).toContain('ACP child published without a session id') + expect(errors).toContain(rawCleanup) + await realChild?.done + }) + + it('reports only the safe teardown failure when cancelled startup rollback fails', async () => { + const tmp = mkdtempSync(join(tmpdir(), 'acp-cancelled-rollback-')) + const ready = join(tmp, 'ready') + const go = join(tmp, 'go') + const rawCleanup = 'cancel rollback leaked SECRET_TOKEN' + let realChild: SubprocessHandle | undefined + try { + const controller = new AbortController() + const starting = startAcpRun(request('p', controller.signal), { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission: 'reject', + env: { MOCK_NEWSESSION_READY: ready, MOCK_NEWSESSION_GO: go }, + disposeEofGraceMs: 10, + disposeGraceMs: 10, + spawn: (spec) => { + realChild = spawnSubprocess(spec) + return rejectFinalExitWait(realChild, rawCleanup) + }, + }) + await waitForFile(ready) + controller.abort() + writeFileSync(go, 'go') + const error = await starting.catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe( + `subagent-acp: ${expectedFailure('stage: teardown; category: unknown')}`, + ) + expect((error as Error).message).not.toContain(rawCleanup) + await realChild?.done + } finally { + rmSync(tmp, { recursive: true, force: true }) + } + }) + it('dispose escalates SIGTERM → SIGKILL for a child that traps SIGTERM (bounded quiescence)', async () => { // The child traps SIGTERM and keeps its event loop alive, so a graceful // term alone would hang dispose forever. With a short grace, dispose must @@ -632,6 +816,7 @@ describe('dsh-subagent-acp', () => { controller.abort() const result = await run.result expect(result.stopReason).toBe('aborted') + expect(result.diagnostic).toBeUndefined() await run.dispose() } finally { rmSync(tmp, { recursive: true, force: true }) @@ -639,11 +824,15 @@ describe('dsh-subagent-acp', () => { }) it('auto-rejects a permission prompt by default (child settles cancelled→aborted)', async () => { - const ctx = await setup({ MOCK_TEXT: 'x', MOCK_PERMISSION: '1' }, 'reject') + const ctx = await setup({ MOCK_TEXT: 'x', MOCK_PERMISSION: '1', MOCK_TOOL_KIND: 'execute' }, 'reject') const run = await ctx.subagents.start('acp', request()) const result = await run.result // The child asked permission, the backend rejected, the child returned cancelled. expect(result.stopReason).toBe('aborted') + expect(result.diagnostic).toBe( + `${expectedFailure('stage: prompt; category: permission; stop reason: cancelled')}\n` + + expectedPermission('reject', 'execute', 'denied'), + ) await run.dispose() }) @@ -652,6 +841,7 @@ describe('dsh-subagent-acp', () => { const run = await ctx.subagents.start('acp', request()) const result = await run.result expect(result.stopReason).toBe('completed') + expect(result.diagnostic).toBeUndefined() expect(text(result.output)).toBe('approved answer') await run.dispose() }) @@ -663,6 +853,44 @@ describe('dsh-subagent-acp', () => { const run = await ctx.subagents.start('acp', request()) const result = await run.result expect(result.stopReason).toBe('aborted') + expect(result.diagnostic).toBe( + `${expectedFailure('stage: prompt; category: permission; stop reason: cancelled')}\n` + + expectedPermission('allow', 'unknown', 'denied'), + ) + await run.dispose() + }) + + it('appends a rejected permission fact to a later remote failure', async () => { + const ctx = await setup({ + MOCK_PERMISSION: '1', + MOCK_PERMISSION_IGNORE_DECISION: '1', + MOCK_TOOL_KIND: 'edit', + MOCK_STOP: 'max_turn_requests', + }, 'reject') + const run = await ctx.subagents.start('acp', request()) + const result = await run.result + expect(result.stopReason).toBe('error') + expect(result.diagnostic).toBe( + `${expectedFailure('stage: prompt; category: remote-limit; stop reason: max_turn_requests')}\n` + + expectedPermission('reject', 'edit', 'denied'), + ) + await run.dispose() + }) + + it('appends an allowed permission fact only when the run later fails', async () => { + const ctx = await setup({ + MOCK_PERMISSION: '1', + MOCK_PERMISSION_IGNORE_DECISION: '1', + MOCK_TOOL_KIND: 'execute', + MOCK_STOP: 'max_turn_requests', + }, 'allow') + const run = await ctx.subagents.start('acp', request()) + const result = await run.result + expect(result.stopReason).toBe('error') + expect(result.diagnostic).toBe( + `${expectedFailure('stage: prompt; category: remote-limit; stop reason: max_turn_requests')}\n` + + expectedPermission('allow', 'execute', 'allowed'), + ) await run.dispose() }) @@ -678,11 +906,50 @@ describe('dsh-subagent-acp', () => { await run.dispose() }) + it('classifies a prompt transport failure without copying SDK text', async () => { + const run = await startAcpRun(request('private prompt text'), { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission: 'reject', + env: { MOCK_CLOSE_PROTOCOL_ON_PROMPT: '1' }, + disposeEofGraceMs: 100, + disposeGraceMs: 100, + spawn: spawnSubprocess, + }) + const result = await run.result + expect(result).toEqual({ + output: [], + diagnostic: expectedFailure('stage: prompt; category: transport'), + stopReason: 'error', + }) + expect(result.diagnostic).not.toContain('private prompt text') + await run.dispose() + }) + + it('preserves partial output and structured process facts when the child exits', async () => { + const ctx = await setup({ MOCK_TEXT: 'partial answer', MOCK_CRASH_AFTER_CHUNK: '1' }) + const run = await ctx.subagents.start('acp', request()) + const result = await run.result + expect(result).toEqual({ + output: [{ type: 'text', text: 'partial answer' }], + diagnostic: expectedFailure('stage: process; category: process-exit; exit code: 17'), + stopReason: 'error', + }) + await run.dispose() + }) + it('rejects a spawn failure after provider-owned cleanup', async () => { - await expect(startAcpRun( + const privateCommand = '/nonexistent/private/SECRET_TOKEN/acp-agent' + const error = await startAcpRun( request(), - { command: '/nonexistent/acp-agent-binary', args: [], cwd: process.cwd(), permission: 'reject', env: {}, disposeEofGraceMs: DEFAULT_DISPOSE_EOF_GRACE_MS, disposeGraceMs: DEFAULT_DISPOSE_GRACE_MS, spawn: spawnSubprocess }, - )).rejects.toThrow() + { command: privateCommand, args: [], cwd: process.cwd(), permission: 'reject', env: {}, disposeEofGraceMs: DEFAULT_DISPOSE_EOF_GRACE_MS, disposeGraceMs: DEFAULT_DISPOSE_GRACE_MS, spawn: spawnSubprocess }, + ).catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe( + `subagent-acp: ${expectedFailure('stage: process; category: process-start')}`, + ) + expect((error as Error).message).not.toContain(privateCommand) }) it('plugin-config dispose graces reach the run (SIGKILL escalation through the provider)', async () => { @@ -746,7 +1013,95 @@ describe('dsh-subagent-acp', () => { permission: 'reject', env: {}, }) - await expect(ctx.subagents.start('acp', request())).rejects.toThrow() + await expect(ctx.subagents.start('acp', request())).rejects.toThrow( + `subagent-acp: ${expectedFailure('stage: process; category: process-start')}`, + ) + }) + + it('keeps permission diagnostics isolated across concurrent runs', async () => { + const start = (permission: 'allow' | 'reject', kind: 'edit' | 'execute') => startAcpRun( + request(), + { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission, + env: { + MOCK_PERMISSION: '1', + MOCK_PERMISSION_IGNORE_DECISION: '1', + MOCK_TOOL_KIND: kind, + MOCK_STOP: 'max_turn_requests', + }, + disposeEofGraceMs: DEFAULT_DISPOSE_EOF_GRACE_MS, + disposeGraceMs: DEFAULT_DISPOSE_GRACE_MS, + spawn: spawnSubprocess, + }, + ) + const [allowed, denied] = await Promise.all([ + start('allow', 'execute'), + start('reject', 'edit'), + ]) + const [allowedResult, deniedResult] = await Promise.all([allowed.result, denied.result]) + expect(allowedResult.diagnostic).toContain(expectedPermission('allow', 'execute', 'allowed')) + expect(allowedResult.diagnostic).not.toContain('policy: reject') + expect(deniedResult.diagnostic).toContain(expectedPermission('reject', 'edit', 'denied')) + expect(deniedResult.diagnostic).not.toContain('policy: allow') + await Promise.all([allowed.dispose(), denied.dispose()]) + }) + + it('wraps a teardown rejection with safe facts and keeps the raw cause in Host diagnostics', async () => { + const rawMessage = 'teardown leaked /private/path SECRET_TOKEN' + const errors: string[] = [] + let realChild: SubprocessHandle | undefined + const run = await startAcpRun(request(), { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission: 'reject', + env: { MOCK_HANG: '1', MOCK_IGNORE_CANCEL: '1' }, + disposeEofGraceMs: 10, + disposeGraceMs: 10, + spawn: (spec) => { + const child = spawnSubprocess(spec) + realChild = child + return rejectFinalExitWait(child, rawMessage) + }, + onError: (error) => { errors.push(error.message) }, + }) + const error = await run.dispose().catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe( + `subagent-acp: ${expectedFailure('stage: teardown; category: unknown')}`, + ) + expect((error as Error).message).not.toContain(rawMessage) + expect(errors).toContain(rawMessage) + await realChild?.done + await expect(run.result).resolves.toEqual({ output: [], stopReason: 'aborted' }) + }) + + it('adds an observed process outcome to a teardown failure', async () => { + let realChild: SubprocessHandle | undefined + const run = await startAcpRun(request(), { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission: 'reject', + env: { MOCK_HANG: '1', MOCK_IGNORE_CANCEL: '1' }, + disposeEofGraceMs: 10, + disposeGraceMs: 10, + spawn: (spec) => { + const child = spawnSubprocess(spec) + realChild = child + return rejectFinalExitWaitAfterExit(child, 'post-exit wait failed') + }, + }) + const error = await run.dispose().catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toContain( + 'subagent-acp: Subagent failure (provider: ACP; stage: teardown; category: process-exit;', + ) + expect((error as Error).message).toMatch(/(?:exit code|signal): /) + await realChild?.done }) it('reports a flattened child failure through onError (preserved, not silently lost)', async () => { @@ -771,6 +1126,9 @@ describe('dsh-subagent-acp', () => { ) const result = await run.result expect(result.stopReason).toBe('error') + expect(result.diagnostic).toBe( + expectedFailure('stage: process; category: process-exit; exit code: 1'), + ) expect(errors).toHaveLength(1) expect(errors[0]!.stopReason).toBe('error') expect(errors[0]!.message.length).toBeGreaterThan(0) @@ -784,6 +1142,9 @@ describe('dsh-subagent-acp', () => { const run = await ctx.subagents.start('acp', request()) const result = await run.result expect(result.stopReason).toBe('error') + expect(result.diagnostic).toBe( + expectedFailure('stage: process; category: process-exit; exit code: 1'), + ) expect(warnings).toEqual([ expect.stringContaining('subagent-acp "acp": child run failed (error):'), ]) @@ -810,6 +1171,9 @@ describe('dsh-subagent-acp', () => { ) const result = await run.result expect(result.stopReason).toBe('error') + expect(result.diagnostic).toBe( + expectedFailure('stage: process; category: process-exit; exit code: 1'), + ) await run.dispose() }) @@ -828,6 +1192,7 @@ describe('dsh-subagent-acp', () => { controller.abort('crash it') const result = await run.result expect(result.stopReason).toBe('aborted') + expect(result.diagnostic).toBeUndefined() await run.dispose() } finally { rmSync(tmp, { recursive: true, force: true }) @@ -854,6 +1219,7 @@ describe('dsh-subagent-acp', () => { new Promise((_r, reject) => { setTimeout(() => { reject(new Error('result did not settle on cancel — backend waited on the child')) }, 4000) }), ]) expect(result.stopReason).toBe('aborted') + expect(result.diagnostic).toBeUndefined() await run.dispose() } finally { rmSync(tmp, { recursive: true, force: true }) diff --git a/packages/subagent/subagent/src/out-of-process.ts b/packages/subagent/subagent/src/out-of-process.ts index abb6dd50e7..05e7f66148 100644 --- a/packages/subagent/subagent/src/out-of-process.ts +++ b/packages/subagent/subagent/src/out-of-process.ts @@ -41,6 +41,18 @@ function limitSubagentDiagnostic(diagnostic: string): string { + DIAGNOSTIC_TRUNCATION_SUFFIX } +/** Enforce success omission and the byte limit on a provider-returned result. */ +function normalizeSubagentDiagnostic(result: SubagentResult): SubagentResult { + if (result.stopReason === 'completed') { + const normalized = { ...result } + Reflect.deleteProperty(normalized, 'diagnostic') + return normalized + } + return result.diagnostic === undefined + ? result + : { ...result, diagnostic: limitSubagentDiagnostic(result.diagnostic) } +} + /** * The capability advertisement of an out-of-process backend: NONE. A child in * another process cannot honor parent-enforced start features @@ -176,7 +188,8 @@ export interface RunResultSettlement { * rejects after publication. A normally completed or rejected attempt resolves * as `aborted` when cancellation already settled locally; another rejection is * flattened to `stopReason: 'error'` through the contained diagnostic sink. - * The abort listener is removed on every path. + * Provider-returned diagnostics use the same byte limit, and completed results + * omit them. The abort listener is removed on every path. * @param parts - the attempt, output snapshot, cancellation state, sink, and signal wiring. * @returns the terminal result (never a rejection). */ @@ -185,7 +198,7 @@ export async function settleRunResult(parts: RunResultSettlement): Promise { }) }) + it('treats a diagnostic-bearing remote abort as failed without changing local cancellation', async () => { + await expect(settleRun({ + id: SessionId('child-remote-abort'), + localAgent: undefined, + result: Promise.resolve({ + output: [], + diagnostic: 'ACP permission was denied', + stopReason: 'aborted', + }), + dispose: () => Promise.resolve(), + })).resolves.toEqual({ + status: 'failed', + detail: 'aborted; diagnostic: ACP permission was denied', + }) + }) + it('bounds multibyte diagnostics and marks truncation', async () => { const exact = 'x'.repeat(MAX_SUBAGENT_DIAGNOSTIC_BYTES) const oversized = '权限'.repeat(MAX_SUBAGENT_DIAGNOSTIC_BYTES) @@ -114,4 +130,57 @@ describe('outcome mapping helpers', () => { expect(result.stopReason).toBe('error') expect(result.diagnostic).toBe(limited) }) + + it('applies the same diagnostic rules to provider-returned results', async () => { + const controller = new AbortController() + const oversized = '权限'.repeat(MAX_SUBAGENT_DIAGNOSTIC_BYTES) + const failed = await settleRunResult({ + attempt: () => Promise.resolve({ + output: [], + diagnostic: oversized, + stopReason: 'error', + }), + collectOutput: () => [], + cancelled: () => false, + signal: controller.signal, + onAbort: () => {}, + }) + expect(Buffer.byteLength(failed.diagnostic ?? '', 'utf8')) + .toBeLessThanOrEqual(MAX_SUBAGENT_DIAGNOSTIC_BYTES) + expect(failed.diagnostic).toMatch(/\[diagnostic truncated\]$/) + + const completed = await settleRunResult({ + attempt: () => Promise.resolve({ + output: [], + diagnostic: 'must not survive success', + stopReason: 'completed', + }), + collectOutput: () => [], + cancelled: () => false, + signal: controller.signal, + onAbort: () => {}, + }) + expect(completed).toEqual({ output: [], stopReason: 'completed' }) + + const plainFailure = await settleRunResult({ + attempt: () => Promise.resolve({ output: [], stopReason: 'error' }), + collectOutput: () => [], + cancelled: () => false, + signal: controller.signal, + onAbort: () => {}, + }) + expect(plainFailure).toEqual({ output: [], stopReason: 'error' }) + + const cancelledAfterAttempt = await settleRunResult({ + attempt: () => Promise.resolve({ output: [], stopReason: 'completed' }), + collectOutput: () => [{ type: 'text', text: 'partial' }], + cancelled: () => true, + signal: controller.signal, + onAbort: () => {}, + }) + expect(cancelledAfterAttempt).toEqual({ + output: [{ type: 'text', text: 'partial' }], + stopReason: 'aborted', + }) + }) }) From dfb36080d8a2500794f8693bfcbf8b96db34d545 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 04:41:21 +0800 Subject: [PATCH 02/31] fix(subagent): close ACP diagnostic review gaps --- ...ubagent-acp-diagnostic.cordis.snapshot.yml | 2 -- .../subagent-acp-diagnostic.cordis.yml | 2 -- .../subagent-acp-diagnostic/session.jsonl | 4 +-- packages/subagent/subagent-acp/src/run.ts | 26 ++++++++++++------- .../subagent-acp/tests/mock-acp-server.ts | 6 ++--- .../subagent-acp/tests/subagent-acp.spec.ts | 25 +++++++++++++++++- .../subagent/subagent/src/out-of-process.ts | 11 +++----- .../subagent/tests/run-settlement.spec.ts | 13 ---------- 8 files changed, 48 insertions(+), 41 deletions(-) diff --git a/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml b/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml index 2019b2337a..440ce505a8 100644 --- a/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml +++ b/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml @@ -28,9 +28,7 @@ permission: reject env: MOCK_TEXT: partial ACP assistant text - MOCK_STOP: max_turn_requests MOCK_PERMISSION: '1' - MOCK_PERMISSION_IGNORE_DECISION: '1' MOCK_TOOL_KIND: execute - id: tool-subagent-acp-diagnostic name: '@deepseek-ai/dsh-tool-subagent' diff --git a/examples/acp-agent/subagent-acp-diagnostic.cordis.yml b/examples/acp-agent/subagent-acp-diagnostic.cordis.yml index e09c00e048..5fd7260b6b 100644 --- a/examples/acp-agent/subagent-acp-diagnostic.cordis.yml +++ b/examples/acp-agent/subagent-acp-diagnostic.cordis.yml @@ -18,9 +18,7 @@ permission: reject env: MOCK_TEXT: partial ACP assistant text - MOCK_STOP: max_turn_requests MOCK_PERMISSION: '1' - MOCK_PERMISSION_IGNORE_DECISION: '1' MOCK_TOOL_KIND: execute - id: tool-subagent-acp-diagnostic name: '@deepseek-ai/dsh-tool-subagent' diff --git a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl index c5b42a7aa1..38c400dbcf 100644 --- a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl +++ b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl @@ -15,7 +15,7 @@ {"type":"assistant/chunk","seq":13,"time":1787254574889,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":14,"time":1787254574889,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_acp_foreground","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"ef8e9ff0-886c-4d55-bbdb-8e878258fb53"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[9,10,11,12,13],"surfaceOp":"append"} {"type":"tool/call","seq":15,"time":1787254574890,"data":{"turn":1,"step":1,"callId":"call_acp_foreground","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}"}} -{"type":"tool/result","seq":16,"time":1787254574996,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_acp_foreground"},"content":[{"type":"tool-result","toolCallId":"call_acp_foreground","content":[{"type":"text","text":"Error: subagent run failed\nDiagnostic: Subagent failure (provider: ACP; stage: prompt; category: remote-limit; stop reason: max_turn_requests)\nACP unattended decision (policy: reject; request: execute; decision: denied)\nPartial output before the run ended:\npartial ACP assistant text"}],"isError":true}],"role":"user","id":"9a82d328-e8dc-43c6-94c5-cfaf93b64c5d"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","seq":16,"time":1787254574996,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_acp_foreground"},"content":[{"type":"tool-result","toolCallId":"call_acp_foreground","content":[{"type":"text","text":"Error: subagent run was cancelled\nDiagnostic: Subagent failure (provider: ACP; stage: prompt; category: permission; stop reason: cancelled)\nACP unattended decision (policy: reject; request: execute; decision: denied)"}],"isError":true}],"role":"user","id":"720dc6b6-6788-4f6f-8426-b888ccafc84a"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","seq":17,"time":1787254574996,"data":{"turn":1,"step":1}} {"type":"step/start","seq":18,"time":1787254575002,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":19,"time":1787254575006,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} @@ -35,7 +35,7 @@ {"type":"assistant/chunk","seq":33,"time":1787254575021,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":34,"time":1787254575021,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_acp_output","name":"job_output","arguments":"{\"job_id\":\"subagent-1\",\"wait\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"b20d64f1-7fcf-498d-84ec-afe518983863"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[29,30,31,32,33],"surfaceOp":"append"} {"type":"tool/call","seq":35,"time":1787254575021,"data":{"turn":1,"step":3,"callId":"call_acp_output","name":"job_output","arguments":"{\"job_id\":\"subagent-1\",\"wait\":true}"}} -{"type":"tool/result","seq":36,"time":1787254575110,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"call_acp_output"},"content":[{"type":"tool-result","toolCallId":"call_acp_output","content":[{"type":"text","text":"(no new output)\n[status: failed, error; diagnostic: Subagent failure (provider: ACP; stage: prompt; category: remote-limit; stop reason: max_turn_requests)\nACP unattended decision (policy: reject; request: execute; decision: denied)]"}],"isError":false}],"role":"user","id":"26ecb040-cc32-474c-9db2-a27ffa7fe9fe"}},"sourceEventSeqs":[35],"surfaceOp":"append"} +{"type":"tool/result","seq":36,"time":1787254575110,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"call_acp_output"},"content":[{"type":"tool-result","toolCallId":"call_acp_output","content":[{"type":"text","text":"(no new output)\n[status: failed, aborted; diagnostic: Subagent failure (provider: ACP; stage: prompt; category: permission; stop reason: cancelled)\nACP unattended decision (policy: reject; request: execute; decision: denied)]"}],"isError":false}],"role":"user","id":"372a7fa1-e148-46ba-bc6a-33a3e0963276"}},"sourceEventSeqs":[35],"surfaceOp":"append"} {"type":"step/end","seq":37,"time":1787254575110,"data":{"turn":1,"step":3}} {"type":"step/start","seq":38,"time":1787254575116,"data":{"turn":1,"step":4}} {"type":"assistant/chunk","seq":39,"time":1787254575121,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index 0ec364d115..8a70379107 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -146,7 +146,7 @@ function diagnosticText(facts: AcpFailureFacts, permission?: AcpPermissionDecisi } class AcpRunFailure extends Error { - constructor(readonly facts: AcpFailureFacts, cause: unknown) { + constructor(facts: AcpFailureFacts, cause: unknown) { super( `subagent-acp: ${failureDiagnostic(facts)}`, { cause }, @@ -347,13 +347,19 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe // Keep diagnostics on parent stderr ('inherit'); only ACP output contributes // to the result. The seam's scrub drops ambient credentials and DSH_* names // while spec.env (the child's own key, its deployment facts) merges after it. - const child = spec.spawn({ - argv: [spec.command, ...spec.args], - cwd: spec.cwd, - stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'inherit' }, - graceMs: spec.disposeGraceMs, - env: spec.env, - }) + let child: SubprocessHandle + try { + child = spec.spawn({ + argv: [spec.command, ...spec.args], + cwd: spec.cwd, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'inherit' }, + graceMs: spec.disposeGraceMs, + env: spec.env, + }) + } catch (error: unknown) { + reportFailure(spec, error) + throw new AcpRunFailure({ stage: 'process', category: 'process-start' }, error) + } /* v8 ignore start -- 'pipe' dispositions expose both streams by the seam contract; defensive. */ if (child.stdin === undefined || child.stdout === undefined) { throw new Error('subagent-acp: subprocess implementation dropped a piped protocol stream') @@ -509,7 +515,9 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe category: processOutcome === undefined ? 'unknown' : 'process-exit', ...(processOutcome === undefined ? {} : { outcome: processOutcome }), }, cleanupError) - if (cancelledBeforeCleanup) throw cleanupFailure + if (cancelledBeforeCleanup) { + throw new AggregateError([cleanupFailure], cleanupFailure.message) + } throw new AggregateError( [failure, cleanupFailure], `${failure.message}; ${cleanupFailure.message}`, diff --git a/packages/subagent/subagent-acp/tests/mock-acp-server.ts b/packages/subagent/subagent-acp/tests/mock-acp-server.ts index b5a0340406..90b335054c 100644 --- a/packages/subagent/subagent-acp/tests/mock-acp-server.ts +++ b/packages/subagent/subagent-acp/tests/mock-acp-server.ts @@ -21,8 +21,8 @@ * - `MOCK_PERMISSION_IGNORE_DECISION` — if `1`, continue after a denied * permission so the terminal failure can carry the * provider's fixed permission fact. - * - `MOCK_CRASH_ON_INITIALIZE` / `MOCK_CRASH_ON_NEW_SESSION` — exit while the - * named unpublished protocol operation is active. + * - `MOCK_CRASH_ON_INITIALIZE` — exit while the unpublished initialize + * operation is active. * - `MOCK_CLOSE_PROTOCOL_ON_PROMPT` — close stdout while keeping the process * alive, producing a prompt-stage transport failure. * - `MOCK_CRASH_AFTER_CHUNK` — exit after streaming the assistant chunk, so @@ -94,7 +94,6 @@ const IGNORE_PERMISSION_DECISION = process.env.MOCK_PERMISSION_IGNORE_DECISION = const NO_ALLOW = process.env.MOCK_NO_ALLOW === '1' const THOUGHT = process.env.MOCK_THOUGHT === '1' const CRASH_ON_INITIALIZE = process.env.MOCK_CRASH_ON_INITIALIZE === '1' -const CRASH_ON_NEW_SESSION = process.env.MOCK_CRASH_ON_NEW_SESSION === '1' const CRASH_ON_CANCEL = process.env.MOCK_CRASH_ON_CANCEL === '1' const CRASH_ON_PROMPT = process.env.MOCK_CRASH_ON_PROMPT === '1' const CLOSE_PROTOCOL_ON_PROMPT = process.env.MOCK_CLOSE_PROTOCOL_ON_PROMPT === '1' @@ -126,7 +125,6 @@ function makeAgent(conn: AgentSideConnection): Agent { }) }, async newSession(params: NewSessionRequest): Promise { - if (CRASH_ON_NEW_SESSION) process.exit(12) sessionCwd = params.cwd // Optionally signal "newSession reached" and block until released, so a // test can cancel DURING newSession (the early-cancel race window) on a diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index d3454fa10c..f6ec120ba1 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -658,7 +658,8 @@ describe('dsh-subagent-acp', () => { controller.abort() writeFileSync(go, 'go') const error = await starting.catch((cause: unknown) => cause) - expect(error).toBeInstanceOf(Error) + expect(error).toBeInstanceOf(AggregateError) + expect((error as AggregateError).errors).toHaveLength(1) expect((error as Error).message).toBe( `subagent-acp: ${expectedFailure('stage: teardown; category: unknown')}`, ) @@ -952,6 +953,28 @@ describe('dsh-subagent-acp', () => { expect((error as Error).message).not.toContain(privateCommand) }) + it('sanitizes a synchronous subprocess-provider spawn rejection', async () => { + const rawMessage = 'spawn rejected /private/path SECRET_TOKEN' + const errors: string[] = [] + const error = await startAcpRun(request(), { + command: 'unused', + args: [], + cwd: process.cwd(), + permission: 'reject', + env: {}, + disposeEofGraceMs: DEFAULT_DISPOSE_EOF_GRACE_MS, + disposeGraceMs: DEFAULT_DISPOSE_GRACE_MS, + spawn: () => { throw new Error(rawMessage) }, + onError: (failure) => { errors.push(failure.message) }, + }).catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe( + `subagent-acp: ${expectedFailure('stage: process; category: process-start')}`, + ) + expect((error as Error).message).not.toContain(rawMessage) + expect(errors).toEqual([rawMessage]) + }) + it('plugin-config dispose graces reach the run (SIGKILL escalation through the provider)', async () => { // Same trap scenario as the direct startAcpRun escalation test, but the // graces arrive via the PLUGIN CONFIG through the registered provider — so a diff --git a/packages/subagent/subagent/src/out-of-process.ts b/packages/subagent/subagent/src/out-of-process.ts index 05e7f66148..a71fefc4b7 100644 --- a/packages/subagent/subagent/src/out-of-process.ts +++ b/packages/subagent/subagent/src/out-of-process.ts @@ -41,13 +41,8 @@ function limitSubagentDiagnostic(diagnostic: string): string { + DIAGNOSTIC_TRUNCATION_SUFFIX } -/** Enforce success omission and the byte limit on a provider-returned result. */ +/** Enforce the byte limit on a provider-returned diagnostic. */ function normalizeSubagentDiagnostic(result: SubagentResult): SubagentResult { - if (result.stopReason === 'completed') { - const normalized = { ...result } - Reflect.deleteProperty(normalized, 'diagnostic') - return normalized - } return result.diagnostic === undefined ? result : { ...result, diagnostic: limitSubagentDiagnostic(result.diagnostic) } @@ -188,8 +183,8 @@ export interface RunResultSettlement { * rejects after publication. A normally completed or rejected attempt resolves * as `aborted` when cancellation already settled locally; another rejection is * flattened to `stopReason: 'error'` through the contained diagnostic sink. - * Provider-returned diagnostics use the same byte limit, and completed results - * omit them. The abort listener is removed on every path. + * Provider-returned diagnostics use the same byte limit. The abort listener is + * removed on every path. * @param parts - the attempt, output snapshot, cancellation state, sink, and signal wiring. * @returns the terminal result (never a rejection). */ diff --git a/packages/subagent/subagent/tests/run-settlement.spec.ts b/packages/subagent/subagent/tests/run-settlement.spec.ts index 73ce256f4a..146181d43a 100644 --- a/packages/subagent/subagent/tests/run-settlement.spec.ts +++ b/packages/subagent/subagent/tests/run-settlement.spec.ts @@ -149,19 +149,6 @@ describe('outcome mapping helpers', () => { .toBeLessThanOrEqual(MAX_SUBAGENT_DIAGNOSTIC_BYTES) expect(failed.diagnostic).toMatch(/\[diagnostic truncated\]$/) - const completed = await settleRunResult({ - attempt: () => Promise.resolve({ - output: [], - diagnostic: 'must not survive success', - stopReason: 'completed', - }), - collectOutput: () => [], - cancelled: () => false, - signal: controller.signal, - onAbort: () => {}, - }) - expect(completed).toEqual({ output: [], stopReason: 'completed' }) - const plainFailure = await settleRunResult({ attempt: () => Promise.resolve({ output: [], stopReason: 'error' }), collectOutput: () => [], From d6de6bb0cbaca9b904b2a393ec08a8fda0eb7f93 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 04:52:40 +0800 Subject: [PATCH 03/31] test(subagent): align ACP permission snapshot --- .../acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml | 3 +-- examples/acp-agent/subagent-acp-diagnostic.cordis.yml | 5 ++--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml b/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml index 440ce505a8..53bbe79452 100644 --- a/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml +++ b/examples/acp-agent/subagent-acp-diagnostic.cordis.snapshot.yml @@ -1,5 +1,5 @@ # Keyless twin of subagent-acp-diagnostic.cordis.yml: keep the real ACP child -# process/provider/tool and replace only the external parent model adapter. +# permission-denial path and replace only the external parent model adapter. - id: base name: '@deepseek-ai/cordis-plugin-include' config: @@ -27,7 +27,6 @@ - !!js process.env.DSH_TEST_MOCK_ACP_SERVER permission: reject env: - MOCK_TEXT: partial ACP assistant text MOCK_PERMISSION: '1' MOCK_TOOL_KIND: execute - id: tool-subagent-acp-diagnostic diff --git a/examples/acp-agent/subagent-acp-diagnostic.cordis.yml b/examples/acp-agent/subagent-acp-diagnostic.cordis.yml index 5fd7260b6b..664086c89a 100644 --- a/examples/acp-agent/subagent-acp-diagnostic.cordis.yml +++ b/examples/acp-agent/subagent-acp-diagnostic.cordis.yml @@ -1,7 +1,7 @@ # Add the real ACP provider behind a one-shot delegation tool. The snapshot # scenario supplies the absolute protocol fixture path through -# DSH_TEST_MOCK_ACP_SERVER; the child returns a remote limit after a denied -# execute permission and streams partial assistant output first. +# DSH_TEST_MOCK_ACP_SERVER; the denied execute permission returns `cancelled` +# and exercises diagnostic-bearing remote-abort parity. - id: base name: '@deepseek-ai/cordis-plugin-include' config: @@ -17,7 +17,6 @@ - !!js process.env.DSH_TEST_MOCK_ACP_SERVER permission: reject env: - MOCK_TEXT: partial ACP assistant text MOCK_PERMISSION: '1' MOCK_TOOL_KIND: execute - id: tool-subagent-acp-diagnostic From 5e1494ff171ed5e2c3b730e1dec2b77864d3a9dd Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 05:58:43 +0800 Subject: [PATCH 04/31] refactor(subagent): keep ACP permission diagnostics minimal --- ...ess-subagent-minimal-diagnostics.i18n.yaml | 4 ++-- ...of-process-subagent-minimal-diagnostics.md | 6 +++--- ...process-subagent-minimal-diagnostics.zh.md | 6 +++--- .../subagent-acp-diagnostic/session.jsonl | 4 ++-- .../subagent/subagent-acp/README.i18n.yaml | 4 ++-- packages/subagent/subagent-acp/README.md | 6 +++--- packages/subagent/subagent-acp/README.zh.md | 6 +++--- packages/subagent/subagent-acp/src/run.ts | 10 +-------- .../subagent-acp/tests/subagent-acp.spec.ts | 21 ++++++------------- 9 files changed, 25 insertions(+), 42 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml index 486a768623..93c539f1bb 100644 --- a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md -2026-08-21-out-of-process-subagent-minimal-diagnostics.md: 38cf32dc3de3fe157f73e1546a827df9b3622fa6 -2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md: 386f85e6b5665c8006e10a0ed0aa49845b6ffed0 +2026-08-21-out-of-process-subagent-minimal-diagnostics.md: fa795fc12aafe2d7d7707e97cf8c4ca49103e089 +2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md: 9516e924b7d8d13403cf3944b55efabfd2c80dff diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md index 38cf32dc3d..fa795fc12a 100644 --- a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md @@ -16,7 +16,7 @@ Each out-of-process provider owns a small mapping from facts it already receives ### Safe failure text -The first line has this fixed field order: +Generic error diagnostics have this fixed field order: ```text Subagent failure (provider: ; stage: ; category: ; stop reason: ; exit code: ; signal: ) @@ -24,7 +24,7 @@ Subagent failure (provider: ; stage: ; category: ; st Unavailable optional fields are omitted. The complete result is limited to 4096 UTF-8 bytes by the shared settlement boundary. Successful results and local cancellation carry no failure diagnostic. Partial assistant output remains in `SubagentResult.output` and is presented separately. -When an ACP permission request contributes to a non-completed result, a second fixed line records `policy`, the closed ACP tool `request` kind, and `decision`. Tool titles, raw input, locations, option names, and metadata are excluded. A diagnostic-bearing remote `aborted` result keeps its public stop reason; the one-shot Job adapter treats it as failed, while diagnostic-free local cancellation remains killed. +When an ACP permission request contributes to a non-completed result, a fixed line records `policy`, the closed ACP tool `request` kind, and `decision`. Tool titles, raw input, locations, option names, and metadata are excluded. For `max-tokens`, `refusal`, or remote `aborted`, the public stop reason already carries the terminal fact, so the permission line is the complete diagnostic; generic error paths append it after the failure line. A diagnostic-bearing remote `aborted` result keeps its public stop reason; the one-shot Job adapter treats it as failed, while diagnostic-free local cancellation remains killed. ### ACP facts @@ -32,7 +32,7 @@ When an ACP permission request contributes to a non-completed result, a second f | --- | --- | --- | | `initialize` | Parent workspace resolution, spawn, and ACP initialize | `configuration`, `transport`, `process-start`, or `process-exit` | | `new-session` | ACP `session/new` and returned session-id validation | `protocol`, `transport`, or `process-exit` | -| `prompt` | ACP prompt request, remote stop reason, and permission callback | `remote-limit`, `remote-refusal`, `permission`, `transport`, or `unknown` | +| `prompt` | ACP prompt request, remote stop reason, and permission callback | `remote-limit`, `transport`, `unknown`, or a permission-only diagnostic | | `process` | Managed child exits before a prompt terminal response | `process-exit` plus independently observed exit code and signal | | `teardown` | EOF quiescence and managed process-tree termination | Fixed teardown facts; the original cleanup failure remains internal | diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md index 386f85e6b5..9516e924b7 100644 --- a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md @@ -16,7 +16,7 @@ ACP 子进程可能因为达到远端限制、拒绝必需权限、失去协议 ### 安全失败文本 -首行采用以下固定字段顺序: +通用 error 诊断采用以下固定字段顺序: ```text Subagent failure (provider: ; stage: ; category: ; stop reason: ; exit code: ; signal: ) @@ -24,7 +24,7 @@ Subagent failure (provider: ; stage: ; category: ; st 不可用的可选字段会被省略。共享结算边界会把完整结果限制在 4096 个 UTF-8 字节以内。成功结果和本地取消不携带失败诊断。部分 assistant 输出继续保留在 `SubagentResult.output` 中,并与诊断分开呈现。 -当 ACP 权限请求参与非完成结果时,第二个固定行会记录 `policy`、ACP 闭集工具 `request` 种类和 `decision`。工具标题、raw input、位置、选项名称与 metadata 均被排除。带诊断的远端 `aborted` 结果仍保持公共结束原因;一次性 Job adapter 会把它判为 failed,而不带诊断的本地取消仍是 killed。 +当 ACP 权限请求参与非完成结果时,一个固定行会记录 `policy`、ACP 闭集工具 `request` 种类和 `decision`。工具标题、raw input、位置、选项名称与 metadata 均被排除。对于 `max-tokens`、`refusal` 或远端 `aborted`,公共结束原因已经携带终态事实,因此权限行就是完整诊断;通用 error 路径则把它附在失败行之后。带诊断的远端 `aborted` 结果仍保持公共结束原因;一次性 Job adapter 会把它判为 failed,而不带诊断的本地取消仍是 killed。 ### ACP 事实 @@ -32,7 +32,7 @@ Subagent failure (provider: ; stage: ; category: ; st | --- | --- | --- | | `initialize` | 父工作区解析、spawn 与 ACP initialize | `configuration`、`transport`、`process-start` 或 `process-exit` | | `new-session` | ACP `session/new` 与返回 session id 校验 | `protocol`、`transport` 或 `process-exit` | -| `prompt` | ACP prompt 请求、远端结束原因与权限回调 | `remote-limit`、`remote-refusal`、`permission`、`transport` 或 `unknown` | +| `prompt` | ACP prompt 请求、远端结束原因与权限回调 | `remote-limit`、`transport`、`unknown` 或仅权限诊断 | | `process` | 受管子进程先于 prompt 终态响应退出 | `process-exit`,以及分别观测到的退出码与信号 | | `teardown` | EOF 停稳与受管进程树终止 | 固定 teardown 事实;原始清理失败仍留在内部 | diff --git a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl index 38c400dbcf..5a56377897 100644 --- a/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl +++ b/examples/acp-agent/tests/snapshots/subagent-acp-diagnostic/session.jsonl @@ -15,7 +15,7 @@ {"type":"assistant/chunk","seq":13,"time":1787254574889,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":14,"time":1787254574889,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_acp_foreground","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"ef8e9ff0-886c-4d55-bbdb-8e878258fb53"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[9,10,11,12,13],"surfaceOp":"append"} {"type":"tool/call","seq":15,"time":1787254574890,"data":{"turn":1,"step":1,"callId":"call_acp_foreground","name":"subagent_acp","arguments":"{\"description\":\"Observe ACP foreground failure\",\"prompt\":\"Return the scripted ACP failure.\",\"run_in_background\":false}"}} -{"type":"tool/result","seq":16,"time":1787254574996,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_acp_foreground"},"content":[{"type":"tool-result","toolCallId":"call_acp_foreground","content":[{"type":"text","text":"Error: subagent run was cancelled\nDiagnostic: Subagent failure (provider: ACP; stage: prompt; category: permission; stop reason: cancelled)\nACP unattended decision (policy: reject; request: execute; decision: denied)"}],"isError":true}],"role":"user","id":"720dc6b6-6788-4f6f-8426-b888ccafc84a"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","seq":16,"time":1787254574996,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_acp_foreground"},"content":[{"type":"tool-result","toolCallId":"call_acp_foreground","content":[{"type":"text","text":"Error: subagent run was cancelled\nDiagnostic: ACP unattended decision (policy: reject; request: execute; decision: denied)"}],"isError":true}],"role":"user","id":"b1bef631-eac4-4139-84ab-809d61493b2c"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","seq":17,"time":1787254574996,"data":{"turn":1,"step":1}} {"type":"step/start","seq":18,"time":1787254575002,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":19,"time":1787254575006,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} @@ -35,7 +35,7 @@ {"type":"assistant/chunk","seq":33,"time":1787254575021,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":34,"time":1787254575021,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_acp_output","name":"job_output","arguments":"{\"job_id\":\"subagent-1\",\"wait\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"b20d64f1-7fcf-498d-84ec-afe518983863"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[29,30,31,32,33],"surfaceOp":"append"} {"type":"tool/call","seq":35,"time":1787254575021,"data":{"turn":1,"step":3,"callId":"call_acp_output","name":"job_output","arguments":"{\"job_id\":\"subagent-1\",\"wait\":true}"}} -{"type":"tool/result","seq":36,"time":1787254575110,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"call_acp_output"},"content":[{"type":"tool-result","toolCallId":"call_acp_output","content":[{"type":"text","text":"(no new output)\n[status: failed, aborted; diagnostic: Subagent failure (provider: ACP; stage: prompt; category: permission; stop reason: cancelled)\nACP unattended decision (policy: reject; request: execute; decision: denied)]"}],"isError":false}],"role":"user","id":"372a7fa1-e148-46ba-bc6a-33a3e0963276"}},"sourceEventSeqs":[35],"surfaceOp":"append"} +{"type":"tool/result","seq":36,"time":1787254575110,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"call_acp_output"},"content":[{"type":"tool-result","toolCallId":"call_acp_output","content":[{"type":"text","text":"(no new output)\n[status: failed, aborted; diagnostic: ACP unattended decision (policy: reject; request: execute; decision: denied)]"}],"isError":false}],"role":"user","id":"53294746-f70e-4494-a005-a97df6199d83"}},"sourceEventSeqs":[35],"surfaceOp":"append"} {"type":"step/end","seq":37,"time":1787254575110,"data":{"turn":1,"step":3}} {"type":"step/start","seq":38,"time":1787254575116,"data":{"turn":1,"step":4}} {"type":"assistant/chunk","seq":39,"time":1787254575121,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} diff --git a/packages/subagent/subagent-acp/README.i18n.yaml b/packages/subagent/subagent-acp/README.i18n.yaml index 6aab671122..5bec6571f6 100644 --- a/packages/subagent/subagent-acp/README.i18n.yaml +++ b/packages/subagent/subagent-acp/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-acp/README.md -README.md: e01785a7a8cd5406fa545cc5e97b0a09d4f57fa1 -README.zh.md: 9082ab4d57b4393a07dc2e02cf6ce95ca259ae8d +README.md: 6366a224b8f56f0b86466d6946f75ab45fee3997 +README.zh.md: 490c17dd883224bcfe129bd3b29eea973a4e69c7 diff --git a/packages/subagent/subagent-acp/README.md b/packages/subagent/subagent-acp/README.md index e01785a7a8..6366a224b8 100644 --- a/packages/subagent/subagent-acp/README.md +++ b/packages/subagent/subagent-acp/README.md @@ -58,15 +58,15 @@ ACP advertises no start-time capabilities because this process cannot enforce th ## Failure diagnostics -The first line has a fixed field order: +Failure diagnostics for generic error paths have a fixed field order: ```text Subagent failure (provider: ACP; stage: ; category: ; stop reason: ; exit code: ; signal: ) ``` -Unavailable optional fields are omitted. The provider derives `initialize`, `new-session`, `prompt`, `process`, or `teardown` at the operation that owns the failure. Categories distinguish configuration, protocol or transport failure, process start/exit, remote limits or refusal, permission-related cancellation, and the fixed unknown fallback. Exit code and signal come only from the managed subprocess outcome; stderr, exception messages, task text, tool input, paths, environment values, credentials, and protocol payloads never enter the diagnostic. The shared result boundary limits the complete text to 4096 UTF-8 bytes. +Unavailable optional fields are omitted. The provider derives `initialize`, `new-session`, `prompt`, `process`, or `teardown` at the operation that owns the failure. Categories distinguish configuration, protocol or transport failure, process start/exit, remote limits, and the fixed unknown fallback. Exit code and signal come only from the managed subprocess outcome; stderr, exception messages, task text, tool input, paths, environment values, credentials, and protocol payloads never enter the diagnostic. The shared result boundary limits the complete text to 4096 UTF-8 bytes. -When a run requested permission and did not complete, a second fixed line records the configured policy, the ACP closed tool kind, and whether the provider allowed or denied it. Tool titles, raw input, locations, and option text are excluded. Successful results and local cancellation omit both lines. A permission-diagnosed remote `aborted` result remains `aborted`; foreground presentation includes its diagnostic, while the one-shot Job adapter classifies that diagnostic-bearing remote abort as failed instead of conflating it with local cancellation. +When a run requested permission and did not complete, a fixed permission line records the configured policy, the ACP closed tool kind, and whether the provider allowed or denied it. Tool titles, raw input, locations, and option text are excluded. For `max-tokens`, `refusal`, or remote `aborted`, this is the complete diagnostic because the public stop reason already carries the terminal fact; generic error paths put it after the failure line. Successful results and local cancellation omit it. A permission-diagnosed remote `aborted` result remains `aborted`; foreground presentation includes its diagnostic, while the one-shot Job adapter classifies that diagnostic-bearing remote abort as failed instead of conflating it with local cancellation. ## Process boundary diff --git a/packages/subagent/subagent-acp/README.zh.md b/packages/subagent/subagent-acp/README.zh.md index 9082ab4d57..490c17dd88 100644 --- a/packages/subagent/subagent-acp/README.zh.md +++ b/packages/subagent/subagent-acp/README.zh.md @@ -58,15 +58,15 @@ ACP 不声明任何启动时能力,因为当前进程无法强制执行远程 ## 失败诊断 -首行采用固定字段顺序: +通用 error 路径的失败诊断采用固定字段顺序: ```text Subagent failure (provider: ACP; stage: ; category: ; stop reason: ; exit code: ; signal: ) ``` -不可用的可选字段会被省略。提供方从实际拥有失败的操作派生 `initialize`、`new-session`、`prompt`、`process` 或 `teardown`。category 区分配置、协议或传输失败、进程启动/退出、远端限制或拒绝、权限相关取消以及固定 unknown 回退。退出码与信号只来自受管子进程结果;stderr、异常消息、任务文本、工具输入、路径、环境值、凭证和协议 payload 绝不会进入诊断。共享结果边界会把完整文本限制在 4096 个 UTF-8 字节以内。 +不可用的可选字段会被省略。提供方从实际拥有失败的操作派生 `initialize`、`new-session`、`prompt`、`process` 或 `teardown`。category 区分配置、协议或传输失败、进程启动/退出、远端限制以及固定 unknown 回退。退出码与信号只来自受管子进程结果;stderr、异常消息、任务文本、工具输入、路径、环境值、凭证和协议 payload 绝不会进入诊断。共享结果边界会把完整文本限制在 4096 个 UTF-8 字节以内。 -当运行请求过权限且最终未完成时,第二个固定行会记录已配置策略、ACP 闭集工具种类以及提供方允许还是拒绝。工具标题、raw input、位置与选项文本均被排除。成功结果和本地取消会省略两行。带权限诊断的远端 `aborted` 结果仍保持 `aborted`;前台会呈现该诊断,而一次性 Job adapter 会把这种带诊断的远端取消判为 failed,避免与本地取消混淆。 +当运行请求过权限且最终未完成时,一个固定权限行会记录已配置策略、ACP 闭集工具种类以及提供方允许还是拒绝。工具标题、raw input、位置与选项文本均被排除。对于 `max-tokens`、`refusal` 或远端 `aborted`,公共结束原因已经携带终态事实,因此该权限行就是完整诊断;通用 error 路径则把它放在失败行之后。成功结果和本地取消会省略权限行。带权限诊断的远端 `aborted` 结果仍保持 `aborted`;前台会呈现该诊断,而一次性 Job adapter 会把这种带诊断的远端取消判为 failed,避免与本地取消混淆。 ## 进程边界 diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index 8a70379107..2a2741dff8 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -95,8 +95,6 @@ type AcpFailureCategory = | 'process-start' | 'process-exit' | 'remote-limit' - | 'remote-refusal' - | 'permission' | 'unknown' interface AcpFailureFacts { @@ -311,17 +309,11 @@ function terminalFailure( stopReason: 'max_turn_requests', }, permission) case 'max_tokens': - return permission === undefined - ? undefined - : diagnosticText({ stage: 'prompt', category: 'remote-limit', stopReason: reason }, permission) case 'refusal': - return permission === undefined - ? undefined - : diagnosticText({ stage: 'prompt', category: 'remote-refusal', stopReason: reason }, permission) case 'cancelled': return permission === undefined ? undefined - : diagnosticText({ stage: 'prompt', category: 'permission', stopReason: reason }, permission) + : permissionDiagnostic(permission) default: return diagnosticText({ stage: 'prompt', category: 'unknown', stopReason: 'unknown' }, permission) } diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index f6ec120ba1..17c8440fbd 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -455,9 +455,9 @@ describe('dsh-subagent-acp', () => { }) it.each([ - ['max_tokens', 'max-tokens', 'remote-limit'], - ['refusal', 'refusal', 'remote-refusal'], - ] as const)('adds a permission fact to %s without changing its stop reason', async (remote, stopReason, category) => { + ['max_tokens', 'max-tokens'], + ['refusal', 'refusal'], + ] as const)('adds a permission fact to %s without changing its stop reason', async (remote, stopReason) => { const ctx = await setup({ MOCK_PERMISSION: '1', MOCK_PERMISSION_IGNORE_DECISION: '1', @@ -467,10 +467,7 @@ describe('dsh-subagent-acp', () => { const run = await ctx.subagents.start('acp', request()) const result = await run.result expect(result.stopReason).toBe(stopReason) - expect(result.diagnostic).toBe( - `${expectedFailure(`stage: prompt; category: ${category}; stop reason: ${remote}`)}\n` - + expectedPermission('reject', 'read', 'denied'), - ) + expect(result.diagnostic).toBe(expectedPermission('reject', 'read', 'denied')) await run.dispose() }) @@ -830,10 +827,7 @@ describe('dsh-subagent-acp', () => { const result = await run.result // The child asked permission, the backend rejected, the child returned cancelled. expect(result.stopReason).toBe('aborted') - expect(result.diagnostic).toBe( - `${expectedFailure('stage: prompt; category: permission; stop reason: cancelled')}\n` - + expectedPermission('reject', 'execute', 'denied'), - ) + expect(result.diagnostic).toBe(expectedPermission('reject', 'execute', 'denied')) await run.dispose() }) @@ -854,10 +848,7 @@ describe('dsh-subagent-acp', () => { const run = await ctx.subagents.start('acp', request()) const result = await run.result expect(result.stopReason).toBe('aborted') - expect(result.diagnostic).toBe( - `${expectedFailure('stage: prompt; category: permission; stop reason: cancelled')}\n` - + expectedPermission('allow', 'unknown', 'denied'), - ) + expect(result.diagnostic).toBe(expectedPermission('allow', 'unknown', 'denied')) await run.dispose() }) From 67e038ab3afc9d40e677383508ad5ccd7c66c038 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 06:53:00 +0800 Subject: [PATCH 05/31] fix(subagent): align ACP diagnostic lifecycle facts --- ...ocess-subagent-minimal-diagnostics.i18n.yaml | 4 ++-- ...t-of-process-subagent-minimal-diagnostics.md | 4 ++-- ...f-process-subagent-minimal-diagnostics.zh.md | 4 ++-- packages/subagent/subagent-acp/src/run.ts | 17 +++++++++++------ .../subagent-acp/tests/subagent-acp.spec.ts | 3 +++ 5 files changed, 20 insertions(+), 12 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml index 93c539f1bb..4a52ab0044 100644 --- a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md -2026-08-21-out-of-process-subagent-minimal-diagnostics.md: fa795fc12aafe2d7d7707e97cf8c4ca49103e089 -2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md: 9516e924b7d8d13403cf3944b55efabfd2c80dff +2026-08-21-out-of-process-subagent-minimal-diagnostics.md: 533ace5a13df75fb594e0cecc65a743df27b6baf +2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md: fe8adf764b240d77cfcde95999ee6689bf11b4a4 diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md index fa795fc12a..533ace5a13 100644 --- a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.md @@ -30,10 +30,10 @@ When an ACP permission request contributes to a non-completed result, a fixed li | Stage | Owned operation | Safe categories and facts | | --- | --- | --- | -| `initialize` | Parent workspace resolution, spawn, and ACP initialize | `configuration`, `transport`, `process-start`, or `process-exit` | +| `initialize` | Parent workspace resolution and ACP initialize | `configuration`, `transport`, or `process-exit` | | `new-session` | ACP `session/new` and returned session-id validation | `protocol`, `transport`, or `process-exit` | | `prompt` | ACP prompt request, remote stop reason, and permission callback | `remote-limit`, `transport`, `unknown`, or a permission-only diagnostic | -| `process` | Managed child exits before a prompt terminal response | `process-exit` plus independently observed exit code and signal | +| `process` | Child-process spawn failure, or a managed child exits before a prompt terminal response | `process-start`, or `process-exit` plus independently observed exit code and signal | | `teardown` | EOF quiescence and managed process-tree termination | Fixed teardown facts; the original cleanup failure remains internal | `max_turn_requests` remains the shared `error` stop reason and adds `remote-limit`. An unknown stop reason remains `error` and becomes the fixed `unknown` category without copying the value. `max_tokens`, `refusal`, and `cancelled` keep their existing shared stop reasons; they add a diagnostic only when a permission decision must be explained. diff --git a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md index 9516e924b7..fe8adf764b 100644 --- a/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md +++ b/.agents/notes/implemented/feature/2026-08-21-out-of-process-subagent-minimal-diagnostics.zh.md @@ -30,10 +30,10 @@ Subagent failure (provider: ; stage: ; category: ; st | Stage | 归属操作 | 安全 category 与事实 | | --- | --- | --- | -| `initialize` | 父工作区解析、spawn 与 ACP initialize | `configuration`、`transport`、`process-start` 或 `process-exit` | +| `initialize` | 父工作区解析与 ACP initialize | `configuration`、`transport` 或 `process-exit` | | `new-session` | ACP `session/new` 与返回 session id 校验 | `protocol`、`transport` 或 `process-exit` | | `prompt` | ACP prompt 请求、远端结束原因与权限回调 | `remote-limit`、`transport`、`unknown` 或仅权限诊断 | -| `process` | 受管子进程先于 prompt 终态响应退出 | `process-exit`,以及分别观测到的退出码与信号 | +| `process` | 子进程 spawn 失败,或受管子进程先于 prompt 终态响应退出 | `process-start`,或 `process-exit` 以及分别观测到的退出码与信号 | | `teardown` | EOF 停稳与受管进程树终止 | 固定 teardown 事实;原始清理失败仍留在内部 | `max_turn_requests` 继续映射到共享 `error`,并附加 `remote-limit`。未知结束原因继续映射到 `error`,category 固定为 `unknown`,不会复制原值。`max_tokens`、`refusal` 与 `cancelled` 保持既有共享结束原因;只有需要解释权限决定时才会附加诊断。 diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index 2a2741dff8..0a472a666b 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -137,7 +137,7 @@ function permissionDiagnostic(permission: AcpPermissionDecision): string { return `ACP unattended decision (policy: ${permission.policy}; request: ${permission.request}; decision: ${permission.decision})` } -/** Put the operation failure first, followed by the latest contributing permission fact. */ +/** Put the operation failure first, followed by the latest permission decision. */ function diagnosticText(facts: AcpFailureFacts, permission?: AcpPermissionDecision): string { const failure = failureDiagnostic(facts) return permission === undefined ? failure : `${failure}\n${permissionDiagnostic(permission)}` @@ -378,7 +378,7 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe if (processOutcome !== undefined || child.pid <= 0) return processOutcome try { const exited = await child.waitForExit( - AbortSignal.timeout(Math.min(spec.disposeGraceMs, 100)), + AbortSignal.timeout(Math.ceil(spec.disposeGraceMs)), ) if (exited) return await processDone } catch { @@ -489,11 +489,16 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe request.signal.removeEventListener('abort', onAbort) const cancelledBeforeCleanup = flags.cancelled // A child closing its protocol stream can precede whole-tree exit - // observation. Wait briefly for an already-ending process, but do not let a - // still-live transport failure delay rollback by a full teardown grace. - const startupOutcome = await observeProcessOutcome() + // observation. Local cancellation does not need the discarded startup + // classification; other failures use the configured process grace. + const startupOutcome = cancelledBeforeCleanup + ? processOutcome + : await observeProcessOutcome() const failure = startupFailure(error, startupStage, child, startupOutcome) - if (!cancelledBeforeCleanup) { + if (cancelledBeforeCleanup) { + // Local cancellation owns the startup outcome; only cleanup failure is + // reported below when teardown itself rejects. + } else { reportFailure(spec, error instanceof AcpRunFailure ? error.cause : error) diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index 17c8440fbd..9efc522759 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -635,6 +635,7 @@ describe('dsh-subagent-acp', () => { const ready = join(tmp, 'ready') const go = join(tmp, 'go') const rawCleanup = 'cancel rollback leaked SECRET_TOKEN' + const errors: string[] = [] let realChild: SubprocessHandle | undefined try { const controller = new AbortController() @@ -650,6 +651,7 @@ describe('dsh-subagent-acp', () => { realChild = spawnSubprocess(spec) return rejectFinalExitWait(realChild, rawCleanup) }, + onError: (error) => { errors.push(error.message) }, }) await waitForFile(ready) controller.abort() @@ -661,6 +663,7 @@ describe('dsh-subagent-acp', () => { `subagent-acp: ${expectedFailure('stage: teardown; category: unknown')}`, ) expect((error as Error).message).not.toContain(rawCleanup) + expect(errors).toEqual([rawCleanup]) await realChild?.done } finally { rmSync(tmp, { recursive: true, force: true }) From 0dcb514fc6c1bd4305b4bd3a784d5732d9a42d51 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 07:09:42 +0800 Subject: [PATCH 06/31] refactor(subagent): drop unused ACP cancel classification --- packages/subagent/subagent-acp/src/run.ts | 22 ++++++++++--------- .../subagent-acp/tests/mock-acp-server.ts | 8 +++++++ .../subagent-acp/tests/subagent-acp.spec.ts | 17 ++++++++++++++ 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index 0a472a666b..11737fe78f 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -491,11 +491,13 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe // A child closing its protocol stream can precede whole-tree exit // observation. Local cancellation does not need the discarded startup // classification; other failures use the configured process grace. - const startupOutcome = cancelledBeforeCleanup - ? processOutcome - : await observeProcessOutcome() - const failure = startupFailure(error, startupStage, child, startupOutcome) - if (cancelledBeforeCleanup) { + const startup = cancelledBeforeCleanup + ? { kind: 'cancelled' } as const + : { + kind: 'failed', + failure: startupFailure(error, startupStage, child, await observeProcessOutcome()), + } as const + if (startup.kind === 'cancelled') { // Local cancellation owns the startup outcome; only cleanup failure is // reported below when teardown itself rejects. } else { @@ -512,18 +514,18 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe category: processOutcome === undefined ? 'unknown' : 'process-exit', ...(processOutcome === undefined ? {} : { outcome: processOutcome }), }, cleanupError) - if (cancelledBeforeCleanup) { + if (startup.kind === 'cancelled') { throw new AggregateError([cleanupFailure], cleanupFailure.message) } throw new AggregateError( - [failure, cleanupFailure], - `${failure.message}; ${cleanupFailure.message}`, + [startup.failure, cleanupFailure], + `${startup.failure.message}; ${cleanupFailure.message}`, ) } - if (cancelledBeforeCleanup) { + if (startup.kind === 'cancelled') { throw new Error('subagent request was aborted before the ACP child started') } - throw failure + throw startup.failure } // The startup transaction validates the returned id before it can fulfill. // This assertion carries that cross-closure invariant into TypeScript. diff --git a/packages/subagent/subagent-acp/tests/mock-acp-server.ts b/packages/subagent/subagent-acp/tests/mock-acp-server.ts index 90b335054c..c785ecedd2 100644 --- a/packages/subagent/subagent-acp/tests/mock-acp-server.ts +++ b/packages/subagent/subagent-acp/tests/mock-acp-server.ts @@ -23,6 +23,8 @@ * provider's fixed permission fact. * - `MOCK_CRASH_ON_INITIALIZE` — exit while the unpublished initialize * operation is active. + * - `MOCK_CLOSE_PROTOCOL_ON_INITIALIZE` — close stdout while keeping the + * process alive, producing initialize-stage transport. * - `MOCK_CLOSE_PROTOCOL_ON_PROMPT` — close stdout while keeping the process * alive, producing a prompt-stage transport failure. * - `MOCK_CRASH_AFTER_CHUNK` — exit after streaming the assistant chunk, so @@ -94,6 +96,7 @@ const IGNORE_PERMISSION_DECISION = process.env.MOCK_PERMISSION_IGNORE_DECISION = const NO_ALLOW = process.env.MOCK_NO_ALLOW === '1' const THOUGHT = process.env.MOCK_THOUGHT === '1' const CRASH_ON_INITIALIZE = process.env.MOCK_CRASH_ON_INITIALIZE === '1' +const CLOSE_PROTOCOL_ON_INITIALIZE = process.env.MOCK_CLOSE_PROTOCOL_ON_INITIALIZE === '1' const CRASH_ON_CANCEL = process.env.MOCK_CRASH_ON_CANCEL === '1' const CRASH_ON_PROMPT = process.env.MOCK_CRASH_ON_PROMPT === '1' const CLOSE_PROTOCOL_ON_PROMPT = process.env.MOCK_CLOSE_PROTOCOL_ON_PROMPT === '1' @@ -118,6 +121,11 @@ function makeAgent(conn: AgentSideConnection): Agent { return { initialize(_params: InitializeRequest): Promise { if (CRASH_ON_INITIALIZE) process.exit(11) + if (CLOSE_PROTOCOL_ON_INITIALIZE) { + process.stdout.end() + setInterval(() => { /* keep the process alive after protocol EOF */ }, 1000) + return new Promise(() => {}) + } return Promise.resolve({ protocolVersion: PROTOCOL_VERSION, agentCapabilities: { loadSession: false, promptCapabilities: { image: false, audio: false, embeddedContext: false } }, diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index 9efc522759..b8b40a3750 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -573,6 +573,23 @@ describe('dsh-subagent-acp', () => { ) }) + it('reports initialize-stage transport when the child closes the protocol but stays alive', async () => { + const error = await startAcpRun(request(), { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission: 'reject', + env: { MOCK_CLOSE_PROTOCOL_ON_INITIALIZE: '1' }, + disposeEofGraceMs: 50, + disposeGraceMs: 50, + spawn: spawnSubprocess, + }).catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(Error) + expect((error as Error).message).toBe( + `subagent-acp: ${expectedFailure('stage: initialize; category: transport')}`, + ) + }) + it('reaps a child whose session/new response omits the session id', async () => { const tmp = mkdtempSync(join(tmpdir(), 'acp-malformed-session-')) const flushed = join(tmp, 'flushed') From 2a060adfa828fa126b563f4f115033f2605e6764 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 07:23:14 +0800 Subject: [PATCH 07/31] fix(subagent): keep ACP failure observation cancellable --- .../subagent/subagent-acp/README.i18n.yaml | 4 +- packages/subagent/subagent-acp/README.md | 2 +- packages/subagent/subagent-acp/README.zh.md | 2 +- packages/subagent/subagent-acp/src/index.ts | 4 +- packages/subagent/subagent-acp/src/run.ts | 20 +++++---- .../subagent-acp/tests/subagent-acp.spec.ts | 44 ++++++++++++++++++- 6 files changed, 61 insertions(+), 15 deletions(-) diff --git a/packages/subagent/subagent-acp/README.i18n.yaml b/packages/subagent/subagent-acp/README.i18n.yaml index 5bec6571f6..d8012da7b3 100644 --- a/packages/subagent/subagent-acp/README.i18n.yaml +++ b/packages/subagent/subagent-acp/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-acp/README.md -README.md: 6366a224b8f56f0b86466d6946f75ab45fee3997 -README.zh.md: 490c17dd883224bcfe129bd3b29eea973a4e69c7 +README.md: 00f084c8252c001d98d04c8ccc1dff5f14976683 +README.zh.md: 3b820805d23b39757376edc14a3d75860f2e8eae diff --git a/packages/subagent/subagent-acp/README.md b/packages/subagent/subagent-acp/README.md index 6366a224b8..00f084c825 100644 --- a/packages/subagent/subagent-acp/README.md +++ b/packages/subagent/subagent-acp/README.md @@ -31,7 +31,7 @@ ACP advertises no start-time capabilities because this process cannot enforce th | `permission` | `reject` | Auto-answer permission requests by rejecting or choosing the first `allow_once` or `allow_always` option. | | `env` | `{}` | Explicit child environment layered over a credential-scrubbed parent environment. | | `disposeEofGraceMs` | `6000` | Positive grace after stdin EOF before platform termination; it cannot exceed [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md). | -| `disposeGraceMs` | `3000` | Positive POSIX grace after SIGTERM before SIGKILL (Windows force-terminates directly); it cannot exceed [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md). | +| `disposeGraceMs` | `3000` | Positive bound for observing structured process facts after failure and, on POSIX, the SIGTERM-to-SIGKILL grace (Windows force-terminates directly); it cannot exceed [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md). | ```yaml - id: subagent-acp diff --git a/packages/subagent/subagent-acp/README.zh.md b/packages/subagent/subagent-acp/README.zh.md index 490c17dd88..3b820805d2 100644 --- a/packages/subagent/subagent-acp/README.zh.md +++ b/packages/subagent/subagent-acp/README.zh.md @@ -31,7 +31,7 @@ ACP 不声明任何启动时能力,因为当前进程无法强制执行远程 | `permission` | `reject` | 自动回答权限请求:拒绝,或选择第一个 `allow_once` 或 `allow_always` 选项。 | | `env` | `{}` | 显式子进程环境,叠加到已清理凭据的父进程环境之上。 | | `disposeEofGraceMs` | `6000` | stdin EOF 之后、平台终止之前的宽限时间须为正值,且不得大于 [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.zh.md)。 | -| `disposeGraceMs` | `3000` | POSIX 在 SIGTERM 后、SIGKILL 前的宽限时间(Windows 直接强制终止),须为正值且不得大于 [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.zh.md)。 | +| `disposeGraceMs` | `3000` | 失败后观测结构化进程事实的正数时限;在 POSIX 上也作为 SIGTERM 到 SIGKILL 的宽限时间(Windows 直接强制终止),且不得大于 [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.zh.md)。 | ```yaml - id: subagent-acp diff --git a/packages/subagent/subagent-acp/src/index.ts b/packages/subagent/subagent-acp/src/index.ts index 7cbe1c79c9..debae6b0f2 100644 --- a/packages/subagent/subagent-acp/src/index.ts +++ b/packages/subagent/subagent-acp/src/index.ts @@ -59,7 +59,7 @@ export interface Config { * `MAX_TIMER_DELAY_MS`. */ disposeEofGraceMs?: number - /** Termination-escalation grace (ms); must not exceed `MAX_TIMER_DELAY_MS`. */ + /** Failure-observation and termination-escalation grace (ms); must not exceed `MAX_TIMER_DELAY_MS`. */ disposeGraceMs?: number } @@ -74,7 +74,7 @@ export const Config: z = z.object({ disposeGraceMs: z.number().default(DEFAULT_DISPOSE_GRACE_MS), }) -/** A dispose grace must fit the single Node timer that owns its teardown tier. */ +/** A process grace must fit every Node timer that observes or terminates the child. */ function assertPositiveFinite(name: string, value: number): void { if (!Number.isFinite(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) { throw new Error(`subagent-acp: ${name} must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`) diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index 11737fe78f..1cc76683cb 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -61,9 +61,11 @@ export interface AcpRunSpec { */ disposeEofGraceMs: number /** - * Termination-escalation grace (ms) in {@link SubagentRun.dispose}; POSIX - * waits this long after `SIGTERM` before `SIGKILL`, while Windows - * force-terminates directly. The plugin fills it from `disposeGraceMs`. + * Process-observation and termination-escalation grace (ms). Failure + * classification waits at most this long for structured exit facts; POSIX + * dispose also waits this long after `SIGTERM` before `SIGKILL`, while + * Windows force-terminates directly. The plugin fills it from + * `disposeGraceMs`. */ disposeGraceMs: number /** @@ -282,7 +284,6 @@ function startupFailure( child: SubprocessHandle, outcome: SubprocessOutcome | undefined, ): AcpRunFailure { - if (error instanceof AcpRunFailure) return error if (child.pid <= 0) { return new AcpRunFailure({ stage: 'process', category: 'process-start' }, error) } @@ -374,11 +375,12 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe ) spawnFailed.catch(() => { /* observed by the startup race; never unhandled */ }) - const observeProcessOutcome = async (): Promise => { + const observeProcessOutcome = async (signal?: AbortSignal): Promise => { if (processOutcome !== undefined || child.pid <= 0) return processOutcome try { + const timeout = AbortSignal.timeout(Math.ceil(spec.disposeGraceMs)) const exited = await child.waitForExit( - AbortSignal.timeout(Math.ceil(spec.disposeGraceMs)), + signal === undefined ? timeout : AbortSignal.any([signal, timeout]), ) if (exited) return await processDone } catch { @@ -495,7 +497,9 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe ? { kind: 'cancelled' } as const : { kind: 'failed', - failure: startupFailure(error, startupStage, child, await observeProcessOutcome()), + failure: error instanceof AcpRunFailure + ? error + : startupFailure(error, startupStage, child, await observeProcessOutcome()), } as const if (startup.kind === 'cancelled') { // Local cancellation owns the startup outcome; only cleanup failure is @@ -550,7 +554,7 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe } } catch (error: unknown) { if (!flags.cancelled) { - const outcome = await observeProcessOutcome() + const outcome = await observeProcessOutcome(request.signal) const facts = outcome === undefined ? { stage: 'prompt', category: 'transport' } as const : { stage: 'process', category: 'process-exit', outcome } as const diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index b8b40a3750..3bbf75128a 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -105,6 +105,22 @@ function rejectFinalExitWaitAfterExit(child: SubprocessHandle, message: string): } } +function tapBoundedExitWait(child: SubprocessHandle, onWait: () => void): SubprocessHandle { + return { + pid: child.pid, + stdin: child.stdin, + stdout: child.stdout, + stderr: child.stderr, + collected: child.collected, + done: child.done, + terminate: () => { child.terminate() }, + waitForExit: (signal?: AbortSignal) => { + if (signal !== undefined) onWait() + return child.waitForExit(signal) + }, + } +} + describe('acpStopReason', () => { it('maps each ACP stop reason to the harness vocabulary', () => { expect(acpStopReason('end_turn')).toBe('completed') @@ -593,6 +609,7 @@ describe('dsh-subagent-acp', () => { it('reaps a child whose session/new response omits the session id', async () => { const tmp = mkdtempSync(join(tmpdir(), 'acp-malformed-session-')) const flushed = join(tmp, 'flushed') + let boundedWaits = 0 try { await expect(startAcpRun(request(), { command: process.execPath, @@ -606,13 +623,14 @@ describe('dsh-subagent-acp', () => { }, disposeEofGraceMs: 1000, disposeGraceMs: 100, - spawn: spawnSubprocess, + spawn: spec => tapBoundedExitWait(spawnSubprocess(spec), () => { boundedWaits += 1 }), })).rejects.toThrow( `subagent-acp: ${expectedFailure('stage: new-session; category: protocol')}`, ) // Startup rejects only after its private child reaches quiescence. The // marker proves rollback closed stdin and allowed the child's EOF flush. expect(existsSync(flushed)).toBe(true) + expect(boundedWaits).toBe(1) } finally { rmSync(tmp, { recursive: true, force: true }) } @@ -939,6 +957,30 @@ describe('dsh-subagent-acp', () => { await run.dispose() }) + it('lets local cancellation interrupt prompt-failure process observation', async () => { + const controller = new AbortController() + const observing = Promise.withResolvers() + const run = await startAcpRun(request('p', controller.signal), { + command: process.execPath, + args: [mockServer], + cwd: process.cwd(), + permission: 'reject', + env: { MOCK_CLOSE_PROTOCOL_ON_PROMPT: '1' }, + disposeEofGraceMs: 100, + disposeGraceMs: 5000, + spawn: spec => tapBoundedExitWait(spawnSubprocess(spec), () => { observing.resolve(undefined) }), + }) + await observing.promise + controller.abort() + await expect(Promise.race([ + run.result, + new Promise((_resolve, reject) => { + setTimeout(() => { reject(new Error('cancellation waited for process observation')) }, 500) + }), + ])).resolves.toEqual({ output: [], stopReason: 'aborted' }) + await run.dispose() + }) + it('preserves partial output and structured process facts when the child exits', async () => { const ctx = await setup({ MOCK_TEXT: 'partial answer', MOCK_CRASH_AFTER_CHUNK: '1' }) const run = await ctx.subagents.start('acp', request()) From 075108dc08150e6bcd3d4b0f9815b4d94a0df40b Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 07:34:00 +0800 Subject: [PATCH 08/31] docs(config): refresh ACP process grace catalog --- docs/config-catalog.i18n.yaml | 4 ++-- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index e36ee3568f..d124b8aafb 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 36f3e96e69207076b1a1bdae58032f7b3d0c1b8f -config-catalog.zh.md: f3eaa4326b73bfe8f7a78ccce4f6026ef90f9f12 +config-catalog.md: aa84752c2f5f028b8df5223b3234a8debf1964fd +config-catalog.zh.md: 632e54d72ecca75e37c05b5a4edaee0dac682625 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 36f3e96e69..aa84752c2f 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2175,7 +2175,7 @@ export interface Config { * `MAX_TIMER_DELAY_MS`. */ disposeEofGraceMs?: number - /** Termination-escalation grace (ms); must not exceed `MAX_TIMER_DELAY_MS`. */ + /** Failure-observation and termination-escalation grace (ms); must not exceed `MAX_TIMER_DELAY_MS`. */ disposeGraceMs?: number } diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index f3eaa4326b..632e54d72e 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2178,7 +2178,7 @@ export interface Config { * `MAX_TIMER_DELAY_MS`. */ disposeEofGraceMs?: number - /** Termination-escalation grace (ms); must not exceed `MAX_TIMER_DELAY_MS`. */ + /** Failure-observation and termination-escalation grace (ms); must not exceed `MAX_TIMER_DELAY_MS`. */ disposeGraceMs?: number } From d90003b4e0c428cc493fb44f52cc3098a3d43379 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 07:38:48 +0800 Subject: [PATCH 09/31] docs(subagent): qualify ACP cleanup failure --- packages/subagent/subagent-acp/README.i18n.yaml | 4 ++-- packages/subagent/subagent-acp/README.md | 2 +- packages/subagent/subagent-acp/README.zh.md | 2 +- packages/subagent/subagent-acp/src/run.ts | 7 ++++--- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/subagent/subagent-acp/README.i18n.yaml b/packages/subagent/subagent-acp/README.i18n.yaml index d8012da7b3..438aeb089b 100644 --- a/packages/subagent/subagent-acp/README.i18n.yaml +++ b/packages/subagent/subagent-acp/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-acp/README.md -README.md: 00f084c8252c001d98d04c8ccc1dff5f14976683 -README.zh.md: 3b820805d23b39757376edc14a3d75860f2e8eae +README.md: 93a1578ac060a0493f52da5f85372039333eb5dc +README.zh.md: fd7da81f7202406099b815ff3122454637aa87fb diff --git a/packages/subagent/subagent-acp/README.md b/packages/subagent/subagent-acp/README.md index 00f084c825..93a1578ac0 100644 --- a/packages/subagent/subagent-acp/README.md +++ b/packages/subagent/subagent-acp/README.md @@ -6,7 +6,7 @@ The ACP provider runs each subagent in a fresh subprocess and drives it as an Ag ## Start and ownership -`start(request)` resolves the child's working directory, then performs `spawn` → ACP `initialize` → `newSession` before it fulfills. Fulfillment therefore means a remote session is ready and ownership has transferred to the caller. A spawn, initialization, new-session, or pre-publication cancellation failure rejects only after the subprocess has been reaped; a working-directory resolution failure rejects before anything is spawned. Non-cancellation rejections expose only fixed provider, stage, and category facts in their Error message; the original failure remains on the internal cause chain and in Host diagnostics. +`start(request)` resolves the child's working directory, then performs `spawn` → ACP `initialize` → `newSession` before it fulfills. Fulfillment therefore means a remote session is ready and ownership has transferred to the caller. A spawn, initialization, new-session, or pre-publication cancellation failure ordinarily rejects after the subprocess is reaped; when cleanup itself rejects, ordered safe startup/teardown facts preserve both failures without claiming process exit. A working-directory resolution failure rejects before anything is spawned. Non-cancellation rejections expose only fixed provider, stage, and category facts in their Error message; the original failure remains on the internal cause chain and in Host diagnostics. The working directory is the configured `cwd` override when set, else the delegating parent session's cwd — never the server process's own cwd, because one server process serves sessions from many workspaces. The parent-derived value must be an absolute path naming a directory the harness can enter (search permission — what a subprocess cwd needs), and the same resolved path becomes both the subprocess cwd and the ACP `session/new` workspace. diff --git a/packages/subagent/subagent-acp/README.zh.md b/packages/subagent/subagent-acp/README.zh.md index 3b820805d2..fd7da81f72 100644 --- a/packages/subagent/subagent-acp/README.zh.md +++ b/packages/subagent/subagent-acp/README.zh.md @@ -6,7 +6,7 @@ ACP(Agent Client Protocol)提供方会在全新的子进程中运行每个 s ## 启动与所有权 -`start(request)` 先解析子 agent 的工作目录,再依次执行 `spawn` → ACP `initialize` → `newSession`,然后才兑现。因此,兑现表示远程会话已就绪,所有权也已转移给调用方。spawn 失败、初始化失败、新建会话失败或因发布前取消而失败时,只有在子进程已回收后才会拒绝;工作目录解析失败则会在尚未 spawn 任何进程时拒绝。非取消拒绝的 Error 消息只公开固定的 provider、stage 与 category 事实;原始失败仍保留在内部 cause 链和 Host 诊断中。 +`start(request)` 先解析子 agent 的工作目录,再依次执行 `spawn` → ACP `initialize` → `newSession`,然后才兑现。因此,兑现表示远程会话已就绪,所有权也已转移给调用方。spawn 失败、初始化失败、新建会话失败或因发布前取消而失败时,通常会在子进程已回收后拒绝;若清理自身也拒绝,有序的安全 startup/teardown 事实会保留两项失败,但不会宣称进程已经退出。工作目录解析失败则会在尚未 spawn 任何进程时拒绝。非取消拒绝的 Error 消息只公开固定的 provider、stage 与 category 事实;原始失败仍保留在内部 cause 链和 Host 诊断中。 工作目录优先使用已配置的 `cwd` 覆盖值,否则使用执行委派的父会话 cwd,绝不使用服务器进程自身的 cwd,因为同一个服务器进程会服务来自多个工作区的会话。从父级取得的值必须是绝对路径,指向 harness 可以进入的目录(具备搜索权限,这是子进程 cwd 的要求);解析后的同一路径同时作为子进程 cwd 和 ACP `session/new` 工作区。 diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index 1cc76683cb..acd015f9f6 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -322,9 +322,10 @@ function terminalFailure( /** * Start and publish one ACP child after initialization and session creation. - * Child failures resolve through the run result; startup and teardown failures - * reject with fixed safe facts after process reap, retaining original causes - * for Host observation. Disposal cancels, kills, and reaps the child. + * Child failures resolve through the run result. Startup rejects with fixed + * safe facts after provider-owned cleanup; successful cleanup proves process + * reap, while cleanup failure preserves both causes without claiming + * quiescence. Disposal cancels, kills, and reaps the child. * @param request - the start request; its signal is the cancellation channel. * @param spec - the resolved spawn spec: command/args/cwd, env, permission * policy, dispose graces, and the optional error sink. From 3900de296d766e595d2c536ce96aa7084e13dfe0 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 07:50:00 +0800 Subject: [PATCH 10/31] docs(subagent): distinguish cancelled cleanup failure --- packages/subagent/subagent-acp/README.i18n.yaml | 4 ++-- packages/subagent/subagent-acp/README.md | 2 +- packages/subagent/subagent-acp/README.zh.md | 2 +- packages/subagent/subagent-acp/src/run.ts | 5 +++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/subagent/subagent-acp/README.i18n.yaml b/packages/subagent/subagent-acp/README.i18n.yaml index 438aeb089b..fbd114bfd3 100644 --- a/packages/subagent/subagent-acp/README.i18n.yaml +++ b/packages/subagent/subagent-acp/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-acp/README.md -README.md: 93a1578ac060a0493f52da5f85372039333eb5dc -README.zh.md: fd7da81f7202406099b815ff3122454637aa87fb +README.md: 5c2b0cc7f0bf634f1a810b9cec9b4c040562c8a5 +README.zh.md: 792840cc2516bc53cb0d255b6f5cb8cbbfb7bf0f diff --git a/packages/subagent/subagent-acp/README.md b/packages/subagent/subagent-acp/README.md index 93a1578ac0..5c2b0cc7f0 100644 --- a/packages/subagent/subagent-acp/README.md +++ b/packages/subagent/subagent-acp/README.md @@ -6,7 +6,7 @@ The ACP provider runs each subagent in a fresh subprocess and drives it as an Ag ## Start and ownership -`start(request)` resolves the child's working directory, then performs `spawn` → ACP `initialize` → `newSession` before it fulfills. Fulfillment therefore means a remote session is ready and ownership has transferred to the caller. A spawn, initialization, new-session, or pre-publication cancellation failure ordinarily rejects after the subprocess is reaped; when cleanup itself rejects, ordered safe startup/teardown facts preserve both failures without claiming process exit. A working-directory resolution failure rejects before anything is spawned. Non-cancellation rejections expose only fixed provider, stage, and category facts in their Error message; the original failure remains on the internal cause chain and in Host diagnostics. +`start(request)` resolves the child's working directory, then performs `spawn` → ACP `initialize` → `newSession` before it fulfills. Fulfillment therefore means a remote session is ready and ownership has transferred to the caller. A spawn, initialization, new-session, or pre-publication cancellation failure ordinarily rejects after the subprocess is reaped; when cleanup itself rejects, ordered safe facts preserve startup plus teardown for an ordinary failure, or teardown alone after cancellation, without claiming process exit. A working-directory resolution failure rejects before anything is spawned. Non-cancellation rejections expose only fixed provider, stage, and category facts in their Error message; the original failure remains on the internal cause chain and in Host diagnostics. The working directory is the configured `cwd` override when set, else the delegating parent session's cwd — never the server process's own cwd, because one server process serves sessions from many workspaces. The parent-derived value must be an absolute path naming a directory the harness can enter (search permission — what a subprocess cwd needs), and the same resolved path becomes both the subprocess cwd and the ACP `session/new` workspace. diff --git a/packages/subagent/subagent-acp/README.zh.md b/packages/subagent/subagent-acp/README.zh.md index fd7da81f72..792840cc25 100644 --- a/packages/subagent/subagent-acp/README.zh.md +++ b/packages/subagent/subagent-acp/README.zh.md @@ -6,7 +6,7 @@ ACP(Agent Client Protocol)提供方会在全新的子进程中运行每个 s ## 启动与所有权 -`start(request)` 先解析子 agent 的工作目录,再依次执行 `spawn` → ACP `initialize` → `newSession`,然后才兑现。因此,兑现表示远程会话已就绪,所有权也已转移给调用方。spawn 失败、初始化失败、新建会话失败或因发布前取消而失败时,通常会在子进程已回收后拒绝;若清理自身也拒绝,有序的安全 startup/teardown 事实会保留两项失败,但不会宣称进程已经退出。工作目录解析失败则会在尚未 spawn 任何进程时拒绝。非取消拒绝的 Error 消息只公开固定的 provider、stage 与 category 事实;原始失败仍保留在内部 cause 链和 Host 诊断中。 +`start(request)` 先解析子 agent 的工作目录,再依次执行 `spawn` → ACP `initialize` → `newSession`,然后才兑现。因此,兑现表示远程会话已就绪,所有权也已转移给调用方。spawn 失败、初始化失败、新建会话失败或因发布前取消而失败时,通常会在子进程已回收后拒绝;若清理自身也拒绝,有序的安全事实会在普通失败时保留 startup 与 teardown,在取消后只保留 teardown,且不会宣称进程已经退出。工作目录解析失败则会在尚未 spawn 任何进程时拒绝。非取消拒绝的 Error 消息只公开固定的 provider、stage 与 category 事实;原始失败仍保留在内部 cause 链和 Host 诊断中。 工作目录优先使用已配置的 `cwd` 覆盖值,否则使用执行委派的父会话 cwd,绝不使用服务器进程自身的 cwd,因为同一个服务器进程会服务来自多个工作区的会话。从父级取得的值必须是绝对路径,指向 harness 可以进入的目录(具备搜索权限,这是子进程 cwd 的要求);解析后的同一路径同时作为子进程 cwd 和 ACP `session/new` 工作区。 diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index acd015f9f6..c2ff2f58f3 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -324,8 +324,9 @@ function terminalFailure( * Start and publish one ACP child after initialization and session creation. * Child failures resolve through the run result. Startup rejects with fixed * safe facts after provider-owned cleanup; successful cleanup proves process - * reap, while cleanup failure preserves both causes without claiming - * quiescence. Disposal cancels, kills, and reaps the child. + * reap. Cleanup failure preserves startup plus teardown facts for an ordinary + * failure, or teardown alone after cancellation, without claiming quiescence. + * Disposal cancels, kills, and reaps the child. * @param request - the start request; its signal is the cancellation channel. * @param spec - the resolved spawn spec: command/args/cwd, env, permission * policy, dispose graces, and the optional error sink. From 9a6f5cf7ff8f45a4c002d397599fcaf8ad24be44 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 07:57:32 +0800 Subject: [PATCH 11/31] docs(subagent): name ACP quiescence precisely --- packages/subagent/subagent-acp/README.i18n.yaml | 4 ++-- packages/subagent/subagent-acp/README.md | 2 +- packages/subagent/subagent-acp/README.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/subagent/subagent-acp/README.i18n.yaml b/packages/subagent/subagent-acp/README.i18n.yaml index fbd114bfd3..23d5aa50ac 100644 --- a/packages/subagent/subagent-acp/README.i18n.yaml +++ b/packages/subagent/subagent-acp/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subagent/subagent-acp/README.md -README.md: 5c2b0cc7f0bf634f1a810b9cec9b4c040562c8a5 -README.zh.md: 792840cc2516bc53cb0d255b6f5cb8cbbfb7bf0f +README.md: fb907f0b22ca840969d404a6a9b14b228fcd5ed5 +README.zh.md: 095e44eb51296f427f98761bfe3f5d1fdec63a71 diff --git a/packages/subagent/subagent-acp/README.md b/packages/subagent/subagent-acp/README.md index 5c2b0cc7f0..fb907f0b22 100644 --- a/packages/subagent/subagent-acp/README.md +++ b/packages/subagent/subagent-acp/README.md @@ -6,7 +6,7 @@ The ACP provider runs each subagent in a fresh subprocess and drives it as an Ag ## Start and ownership -`start(request)` resolves the child's working directory, then performs `spawn` → ACP `initialize` → `newSession` before it fulfills. Fulfillment therefore means a remote session is ready and ownership has transferred to the caller. A spawn, initialization, new-session, or pre-publication cancellation failure ordinarily rejects after the subprocess is reaped; when cleanup itself rejects, ordered safe facts preserve startup plus teardown for an ordinary failure, or teardown alone after cancellation, without claiming process exit. A working-directory resolution failure rejects before anything is spawned. Non-cancellation rejections expose only fixed provider, stage, and category facts in their Error message; the original failure remains on the internal cause chain and in Host diagnostics. +`start(request)` resolves the child's working directory, then performs `spawn` → ACP `initialize` → `newSession` before it fulfills. Fulfillment therefore means a remote session is ready and ownership has transferred to the caller. A spawn, initialization, new-session, or pre-publication cancellation failure ordinarily rejects after the subprocess is reaped; when cleanup itself rejects, ordered safe facts preserve startup plus teardown for an ordinary failure, or teardown alone after cancellation, without claiming whole-tree quiescence. A working-directory resolution failure rejects before anything is spawned. Non-cancellation rejections expose only fixed provider, stage, and category facts in their Error message; the original failure remains on the internal cause chain and in Host diagnostics. The working directory is the configured `cwd` override when set, else the delegating parent session's cwd — never the server process's own cwd, because one server process serves sessions from many workspaces. The parent-derived value must be an absolute path naming a directory the harness can enter (search permission — what a subprocess cwd needs), and the same resolved path becomes both the subprocess cwd and the ACP `session/new` workspace. diff --git a/packages/subagent/subagent-acp/README.zh.md b/packages/subagent/subagent-acp/README.zh.md index 792840cc25..095e44eb51 100644 --- a/packages/subagent/subagent-acp/README.zh.md +++ b/packages/subagent/subagent-acp/README.zh.md @@ -6,7 +6,7 @@ ACP(Agent Client Protocol)提供方会在全新的子进程中运行每个 s ## 启动与所有权 -`start(request)` 先解析子 agent 的工作目录,再依次执行 `spawn` → ACP `initialize` → `newSession`,然后才兑现。因此,兑现表示远程会话已就绪,所有权也已转移给调用方。spawn 失败、初始化失败、新建会话失败或因发布前取消而失败时,通常会在子进程已回收后拒绝;若清理自身也拒绝,有序的安全事实会在普通失败时保留 startup 与 teardown,在取消后只保留 teardown,且不会宣称进程已经退出。工作目录解析失败则会在尚未 spawn 任何进程时拒绝。非取消拒绝的 Error 消息只公开固定的 provider、stage 与 category 事实;原始失败仍保留在内部 cause 链和 Host 诊断中。 +`start(request)` 先解析子 agent 的工作目录,再依次执行 `spawn` → ACP `initialize` → `newSession`,然后才兑现。因此,兑现表示远程会话已就绪,所有权也已转移给调用方。spawn 失败、初始化失败、新建会话失败或因发布前取消而失败时,通常会在子进程已回收后拒绝;若清理自身也拒绝,有序的安全事实会在普通失败时保留 startup 与 teardown,在取消后只保留 teardown,且不会宣称整棵进程树已经完全停稳。工作目录解析失败则会在尚未 spawn 任何进程时拒绝。非取消拒绝的 Error 消息只公开固定的 provider、stage 与 category 事实;原始失败仍保留在内部 cause 链和 Host 诊断中。 工作目录优先使用已配置的 `cwd` 覆盖值,否则使用执行委派的父会话 cwd,绝不使用服务器进程自身的 cwd,因为同一个服务器进程会服务来自多个工作区的会话。从父级取得的值必须是绝对路径,指向 harness 可以进入的目录(具备搜索权限,这是子进程 cwd 的要求);解析后的同一路径同时作为子进程 cwd 和 ACP `session/new` 工作区。 From 8dc78528818b403659c95b8c4dbb9c90af241825 Mon Sep 17 00:00:00 2001 From: pku-xht Date: Fri, 21 Aug 2026 08:06:10 +0800 Subject: [PATCH 12/31] refactor(subagent): observe ACP direct process outcome --- packages/subagent/subagent-acp/src/run.ts | 18 ++++++++++++------ .../subagent-acp/tests/subagent-acp.spec.ts | 13 ++++++++++--- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/packages/subagent/subagent-acp/src/run.ts b/packages/subagent/subagent-acp/src/run.ts index c2ff2f58f3..10054edf07 100644 --- a/packages/subagent/subagent-acp/src/run.ts +++ b/packages/subagent/subagent-acp/src/run.ts @@ -379,16 +379,22 @@ export async function startAcpRun(request: SubagentStartRequest, spec: AcpRunSpe const observeProcessOutcome = async (signal?: AbortSignal): Promise => { if (processOutcome !== undefined || child.pid <= 0) return processOutcome + const timeout = AbortSignal.timeout(Math.ceil(spec.disposeGraceMs)) + const bound = signal === undefined ? timeout : AbortSignal.any([signal, timeout]) + const aborted = Promise.withResolvers() + const onObservationAbort = (): void => { aborted.resolve(undefined) } + bound.addEventListener('abort', onObservationAbort, { once: true }) + /* v8 ignore next -- closes the event-loop race between listener registration and the preceding derived-signal check. */ + if (bound.aborted) onObservationAbort() try { - const timeout = AbortSignal.timeout(Math.ceil(spec.disposeGraceMs)) - const exited = await child.waitForExit( - signal === undefined ? timeout : AbortSignal.any([signal, timeout]), - ) - if (exited) return await processDone + return await Promise.race([processDone, aborted.promise]) } catch { // The active protocol failure remains authoritative when exit observation fails. + /* v8 ignore next -- a published child.done cannot reject; spawn rejection is consumed before publication. */ + return processOutcome + } finally { + bound.removeEventListener('abort', onObservationAbort) } - return processOutcome } // Startup rollback and the published handle share one process teardown. diff --git a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts index 3bbf75128a..bc493a35dd 100644 --- a/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts +++ b/packages/subagent/subagent-acp/tests/subagent-acp.spec.ts @@ -959,7 +959,8 @@ describe('dsh-subagent-acp', () => { it('lets local cancellation interrupt prompt-failure process observation', async () => { const controller = new AbortController() - const observing = Promise.withResolvers() + const protocolEnded = Promise.withResolvers() + let boundedExitWaits = 0 const run = await startAcpRun(request('p', controller.signal), { command: process.execPath, args: [mockServer], @@ -968,9 +969,14 @@ describe('dsh-subagent-acp', () => { env: { MOCK_CLOSE_PROTOCOL_ON_PROMPT: '1' }, disposeEofGraceMs: 100, disposeGraceMs: 5000, - spawn: spec => tapBoundedExitWait(spawnSubprocess(spec), () => { observing.resolve(undefined) }), + spawn: (spec) => { + const child = spawnSubprocess(spec) + child.stdout?.once('end', () => { protocolEnded.resolve(undefined) }) + return tapBoundedExitWait(child, () => { boundedExitWaits += 1 }) + }, }) - await observing.promise + await protocolEnded.promise + await new Promise((resolve) => { setImmediate(resolve) }) controller.abort() await expect(Promise.race([ run.result, @@ -978,6 +984,7 @@ describe('dsh-subagent-acp', () => { setTimeout(() => { reject(new Error('cancellation waited for process observation')) }, 500) }), ])).resolves.toEqual({ output: [], stopReason: 'aborted' }) + expect(boundedExitWaits).toBe(0) await run.dispose() }) From 55ef5aad06c0bfa5811dc35bcc74a597e9fb0b19 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 25 Aug 2026 12:02:21 +0800 Subject: [PATCH 13/31] test(windows): try 4 coverage partitions instead of 8 Under high self-hosted concurrency, 8 partitions per Windows native job triggered vitest fork worker startup timeouts. This branch lowers Windows coverage to the same 4 partitions Linux uses, trading some single-job coverage wall time for lower process-creation pressure. --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 429796c3b6..47e8ad6494 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -418,7 +418,7 @@ jobs: timeout-minutes: 120 env: DSH_COVERAGE_MAX_WORKERS: '6' - DSH_COVERAGE_PARTITIONS: '8' + DSH_COVERAGE_PARTITIONS: '4' # Instrumented process and polling fixtures can exceed Vitest's defaults # under the complete lane's concurrent gate load. DSH_COVERAGE_TEST_TIMEOUT_MS: '30000' From 58cc29b4f177c3a64b98ee76f993e501c74090de Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 25 Aug 2026 12:45:47 +0800 Subject: [PATCH 14/31] test(windows): split native job into build/coverage/native-tests/observational Keep the 4-partition coverage profile, split the monolithic windows-native job into smaller required jobs (build, coverage, native-tests) plus a non-blocking observational job. Update ci-workflow.spec for the new topology. --- .github/workflows/ci.yml | 155 ++++++++++++++++++++++++++++-------- scripts/ci-workflow.spec.ts | 80 +++++++++++++------ 2 files changed, 178 insertions(+), 57 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 47e8ad6494..aa36a92dc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -397,63 +397,152 @@ jobs: if: always() run: wineserver -k 2>/dev/null || true - # Every pull request also gets a real Windows-kernel signal. This job keeps - # its own unmasked conclusion but is deliberately absent from - # all-checks-passed.needs, so it never delays or changes that required - # verdict. Under normal operation it runs on the hosted larger runner; under - # Windows failover (DSH_CI_FAILOVER_WINDOWS=selfhosted) it retargets onto the - # in-house self-hosted Windows pool. Dependabot PRs are excluded from the - # self-hosted pool and stay queued for the hosted runner — see the failover - # runbook. This Windows switch is independent of the Linux - # DSH_CI_FAILOVER_LINUX variable that retargets the three required Linux jobs - # and the all-checks-passed verdict above. - windows-native: + # Every pull request also gets real Windows-kernel signals. The former + # monolithic windows-native job is split into smaller jobs so one slow + # coverage gate does not hold up build/static results, while the total + # per-job process count stays lower. Observational checks are non-blocking. + # Dependabot PRs are excluded from the self-hosted pool and stay queued for + # the hosted runner. + windows-build: if: github.event_name == 'pull_request' runs-on: >- ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') || 'dsh-windows-2025-16core' }} - name: windows node 24 / native complete - timeout-minutes: 120 - env: - DSH_COVERAGE_MAX_WORKERS: '6' - DSH_COVERAGE_PARTITIONS: '4' - # Instrumented process and polling fixtures can exceed Vitest's defaults - # under the complete lane's concurrent gate load. - DSH_COVERAGE_TEST_TIMEOUT_MS: '30000' - DSH_GATE_CONCURRENCY: '4' - DSH_PUBLINT_CONCURRENCY: '8' + name: windows node 24 / build + timeout-minutes: 60 steps: - uses: actions/checkout@v6 with: persist-credentials: false - - name: Enable Developer Mode (symlink support) shell: pwsh run: >- reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" - - uses: pnpm/action-setup@v4 with: dest: ${{ runner.temp }}/setup-pnpm-js - - uses: actions/setup-node@v6 with: node-version: ${{ env.PRIMARY_NODE_VERSION }} - - # Extracting the many-file pnpm store cache is slower than a clean - # install on hosted Windows runners, and saving it adds latency after - # the gates. The self-hosted VM's persistent store makes caching - # redundant. - name: Install (immutable) shell: pwsh run: pnpm install --frozen-lockfile - - - name: Run complete native Windows gate inventory + - name: Run blocking Windows builds shell: pwsh - run: pnpm run check:ci:windows-complete + run: pnpm run check:ci:windows-blocking + + windows-coverage: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + name: windows node 24 / coverage + timeout-minutes: 120 + env: + DSH_COVERAGE_MAX_WORKERS: '6' + DSH_COVERAGE_PARTITIONS: '4' + DSH_COVERAGE_TEST_TIMEOUT_MS: '30000' + DSH_GATE_CONCURRENCY: '3' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - name: Enable Developer Mode (symlink support) + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-js + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + - name: Install (immutable) + shell: pwsh + run: pnpm install --frozen-lockfile + - name: Build before coverage + shell: pwsh + run: pnpm run build + - name: Run Windows coverage + shell: pwsh + run: pnpm run check:ci:coverage + + windows-native-tests: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + name: windows node 24 / native tests + timeout-minutes: 60 + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - name: Enable Developer Mode (symlink support) + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-js + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + - name: Install (immutable) + shell: pwsh + run: pnpm install --frozen-lockfile + - name: Run Windows-specific native tests + shell: pwsh + run: >- + pnpm exec vitest run + packages/shell/tool-pwsh/tests/loader.spec.ts + packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.spec.ts + packages/workflow/tool-ralph/tests/integration.spec.ts + packages/subprocess/subprocess-local/tests/process-exit.spec.ts + packages/session/session-persistence-sqlite/tests/differential.spec.ts + + windows-observational: + if: github.event_name == 'pull_request' + continue-on-error: true + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + name: windows node 24 / observational + timeout-minutes: 60 + env: + DSH_PUBLINT_CONCURRENCY: '8' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - name: Enable Developer Mode (symlink support) + shell: pwsh + run: >- + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1" + - uses: pnpm/action-setup@v4 + with: + dest: ${{ runner.temp }}/setup-pnpm-js + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + - name: Install (immutable) + shell: pwsh + run: pnpm install --frozen-lockfile + - name: Run Windows observational gates + shell: pwsh + run: pnpm run check:ci:windows-observational # Single stable required check for branch protection: require "all checks # passed" instead of enumerating matrix legs whose names change as lanes and @@ -479,7 +568,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [node-24, node-24-coverage, node-24-consumers, node-compat, python-sdk, python-runtime, windows] + needs: [node-24, node-24-coverage, node-24-consumers, node-compat, python-sdk, python-runtime, windows, windows-build, windows-coverage, windows-native-tests] if: always() && github.event_name == 'pull_request' steps: - name: Fail if any needed job did not succeed diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index 7f60d75352..e5aceb8e25 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -27,21 +27,24 @@ describe('CI workflow', () => { for (const { jobName, step } of setups) { expect(step, `${jobName} must not share pnpm/action-setup's default destination`).toMatchObject({ with: { - dest: jobName === 'windows-native' + dest: jobName.startsWith('windows-') ? nativeWindowsPnpmDestination : runnerPrivatePnpmDestination, }, }) - if (jobName === 'windows-native') expect(step).not.toMatchObject({ with: { standalone: true } }) + if (jobName.startsWith('windows-')) expect(step).not.toMatchObject({ with: { standalone: true } }) } }) - it('keeps a required Wine Windows job, a non-blocking native Windows job with failover, and a master-only standby', () => { + it('keeps required Wine and split native Windows jobs with failover, plus a master-only standby', () => { const workflow = loadWorkflow('.github/workflows/ci.yml') const masterWorkflow = loadWorkflow('.github/workflows/ci-master.yml') if (!isRecord(workflow.jobs) || !isRecord(workflow.jobs.windows) - || !isRecord(workflow.jobs['windows-native']) + || !isRecord(workflow.jobs['windows-build']) + || !isRecord(workflow.jobs['windows-coverage']) + || !isRecord(workflow.jobs['windows-native-tests']) + || !isRecord(workflow.jobs['windows-observational']) || !isRecord(workflow.jobs['node-24']) || !isRecord(workflow.jobs['node-24-coverage']) || !isRecord(workflow.jobs['node-24-consumers']) @@ -49,11 +52,14 @@ describe('CI workflow', () => { || !isRecord(masterWorkflow.jobs) || !isRecord(masterWorkflow.jobs['wine-apt-cache']) || !isRecord(masterWorkflow.jobs['serial-windows'])) { - throw new TypeError('CI workflow must define windows, windows-native, node-24, node-24-coverage, node-24-consumers, and all-checks-passed; ci-master must define wine-apt-cache and serial-windows') + throw new TypeError('CI workflow must define windows, windows-build, windows-coverage, windows-native-tests, windows-observational, node-24, node-24-coverage, node-24-consumers, and all-checks-passed; ci-master must define wine-apt-cache and serial-windows') } const windows = workflow.jobs.windows - const windowsNative = workflow.jobs['windows-native'] + const windowsBuild = workflow.jobs['windows-build'] + const windowsCoverage = workflow.jobs['windows-coverage'] + const windowsNativeTests = workflow.jobs['windows-native-tests'] + const windowsObservational = workflow.jobs['windows-observational'] const wineAptCache = masterWorkflow.jobs['wine-apt-cache'] const serialWindows = masterWorkflow.jobs['serial-windows'] const node24 = workflow.jobs['node-24'] @@ -73,24 +79,46 @@ describe('CI workflow', () => { expect(windows.if).toBe("github.event_name == 'pull_request'") expect(commandSteps.some(step => step.run.includes('wine-windows-gates.sh'))).toBe(true) - // windows-native: non-blocking native job with failover, runs windows-complete. - // Its pool is resolved by the Windows-specific switch. - expect(typeof windowsNative['runs-on']).toBe('string') - expect(windowsNative['runs-on']).toContain('DSH_CI_FAILOVER_WINDOWS') - expect(windowsNative['runs-on']).not.toContain('DSH_CI_FAILOVER_LINUX') - expect(windowsNative['runs-on']).toContain('self-hosted') - expect(windowsNative['runs-on']).toContain('dsh-win-ci') - expect(windowsNative['runs-on']).toContain('dsh-windows-2025-16core') - expect(windowsNative.name).toBe('windows node 24 / native complete') - expect(windowsNative.if).toBe("github.event_name == 'pull_request'") - expect(windowsNative.env).toMatchObject({ - DSH_COVERAGE_TEST_TIMEOUT_MS: '30000', - }) - const nativeSteps = windowsNative.steps as unknown[] - const nativeCommandSteps = nativeSteps.filter((step): step is Record & { run: string } => ( + // The split native jobs all resolve their pool through the Windows switch. + for (const [jobName, job] of [['windows-build', windowsBuild], ['windows-coverage', windowsCoverage], ['windows-native-tests', windowsNativeTests], ['windows-observational', windowsObservational]] as const) { + expect(typeof job['runs-on']).toBe('string') + expect(job['runs-on'], `${jobName} runs-on must use the Windows failover switch`).toContain('DSH_CI_FAILOVER_WINDOWS') + expect(job['runs-on'], `${jobName} runs-on must not use the Linux failover switch`).not.toContain('DSH_CI_FAILOVER_LINUX') + expect(job['runs-on']).toContain('self-hosted') + expect(job['runs-on']).toContain('dsh-win-ci') + expect(job['runs-on']).toContain('dsh-windows-2025-16core') + expect(job.if).toBe("github.event_name == 'pull_request'") + } + + // windows-build runs the blocking build/site pair. + expect(windowsBuild.name).toBe('windows node 24 / build') + const buildSteps = windowsBuild.steps as unknown[] + const buildCommands = buildSteps.filter((step): step is Record & { run: string } => ( isRecord(step) && typeof step.run === 'string' )) - expect(nativeCommandSteps.map(step => step.run)).toContain('pnpm run check:ci:windows-complete') + expect(buildCommands.map(step => step.run)).toContain('pnpm run check:ci:windows-blocking') + + // windows-coverage uses the lower 4-partition profile. + expect(windowsCoverage.name).toBe('windows node 24 / coverage') + expect(windowsCoverage.env).toMatchObject({ DSH_COVERAGE_PARTITIONS: '4' }) + const coverageSteps = windowsCoverage.steps as unknown[] + const coverageCommands = coverageSteps.filter((step): step is Record & { run: string } => ( + isRecord(step) && typeof step.run === 'string' + )) + expect(coverageCommands.map(step => step.run)).toContain('pnpm run check:ci:coverage') + + // windows-native-tests runs the Windows-specific specs. + expect(windowsNativeTests.name).toBe('windows node 24 / native tests') + const nativeTestSteps = windowsNativeTests.steps as unknown[] + const nativeTestCommands = nativeTestSteps.filter((step): step is Record & { run: string } => ( + isRecord(step) && typeof step.run === 'string' + )) + expect(nativeTestCommands.map(step => step.run).join('\n')).toContain('tool-pwsh/tests/loader.spec.ts') + expect(nativeTestCommands.map(step => step.run).join('\n')).toContain('workflow-worker-thread.spec.ts') + + // windows-observational is non-blocking. + expect(windowsObservational.name).toBe('windows node 24 / observational') + expect(windowsObservational['continue-on-error']).toBe(true) // wine-apt-cache: master-only, seeds the Wine apt cache, lives in ci-master. expect(wineAptCache.if).toBe("github.event_name == 'push' && github.ref == 'refs/heads/master'") @@ -101,9 +129,13 @@ describe('CI workflow', () => { expect(serialWindows['runs-on']).toEqual(['self-hosted', 'dsh-win-ci', 'windows']) expect(serialWindows.name).toBe('serial / windows (self-hosted standby)') - // Aggregate: Wine `windows` required, native `windows-native` excluded. + // Aggregate: Wine and the three required split native jobs are needed; + // observational stays out of the verdict. expect(aggregate.needs).toContain('windows') - expect(aggregate.needs).not.toContain('windows-native') + expect(aggregate.needs).toContain('windows-build') + expect(aggregate.needs).toContain('windows-coverage') + expect(aggregate.needs).toContain('windows-native-tests') + expect(aggregate.needs).not.toContain('windows-observational') expect(aggregate.needs).not.toContain('serial-windows') // Linux failover is a separate switch: the three required Linux workers From 9a12505f86c8272ceabc7ea173d5535f0f298b6b Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 25 Aug 2026 12:53:48 +0800 Subject: [PATCH 15/31] fix(pty): distinguish pipeline reads from terminal input --- ...26-07-16-persistent-pty-sessions.i18n.yaml | 4 +- .../2026-07-16-persistent-pty-sessions.md | 6 +- .../2026-07-16-persistent-pty-sessions.zh.md | 6 +- .../tests/loader-composition.spec.ts | 6 ++ .../subprocess-local/README.i18n.yaml | 4 +- .../subprocess/subprocess-local/README.md | 2 +- .../subprocess/subprocess-local/README.zh.md | 2 +- .../subprocess-local/src/process-inspector.ts | 33 +++++++-- .../subprocess-local/src/terminal.ts | 2 +- .../subprocess-local/src/windows-inspector.ts | 2 +- .../tests/process-inspector.spec.ts | 70 +++++++++++++------ .../subprocess-local/tests/terminal.spec.ts | 7 +- .../tests/windows-inspector.spec.ts | 2 +- 13 files changed, 103 insertions(+), 43 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml index 1bfc08fcc6..3633aa06be 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md -2026-07-16-persistent-pty-sessions.md: 3ca35cdd59f38570be478fddf4213335665556a5 -2026-07-16-persistent-pty-sessions.zh.md: a277a97fc73b8e8a901b6524918cdf4f9997461d +2026-07-16-persistent-pty-sessions.md: 44e87390c9a6e4dc97e9466d3113fdd07cd3c500 +2026-07-16-persistent-pty-sessions.zh.md: 0aad7cc409f951c1d36cf543415c6ac1faf143ba diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md index 3ca35cdd59..44e87390c9 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md @@ -74,7 +74,7 @@ With `run_in_background: true`, `dsh-tool-terminal` registers the in-flight send The local backend first recognizes a private OSC prompt marker emitted by its controlled bash startup, then requires the printable tail after the latest marker to exactly equal the controlled `PS1` before declaring prompt readiness and runs three bounded fallback tiers. Carrying that tail across data callbacks covers delivery where the marker and prompt arrive separately; requiring the exact tail rejects a delayed earlier prompt once echoed input or output follows it, so it cannot settle the current send. The marker is removed before output reaches the model and avoids a fixed silence delay for ordinary shell commands on both platforms. Unpublished startup does not accept zero-output silence as readiness; timeout rejects the spawn. If caller cancellation wins during startup, the backend closes the private session and propagates the exact `AbortSignal.reason`; a foreground PGID that is not observable yet cannot replace cancellation with a lookup error. All timings are validated config fields: `pollIntervalMs`, `exactProbeAfterMs`, `idleSilenceMs`, `handoffGraceMs`, and `timeoutMs`. -On Linux, the inspector reads the shell's terminal foreground PGID from `/proc//stat`, enumerates every process and thread in that process group, and probes their current syscalls. A positive Tier 1 result requires an observed stdin wait: direct `read(0)`, a permitted read of a `select`/`pselect6` or `poll`/`ppoll` argument containing fd 0, or an epoll interest list containing fd 0. A wait already present before terminal input is not post-write readiness: the same PGID must be observed outside that wait before re-entering it, while a changed foreground PGID is new evidence. Unreadable process memory and unrecognized syscalls are misses, never positive guesses. Architecture tables contain only syscall numbers defined by the corresponding Linux UAPI; unsupported architectures skip Tier 1. +On Linux, the inspector reads the shell's terminal foreground PGID from `/proc//stat`, enumerates every process and thread in that process group, and probes their current syscalls. A positive Tier 1 result requires an observed stdin wait: direct `read(0)`, a permitted read of a `select`/`pselect6` or `poll`/`ppoll` argument containing fd 0, or an epoll interest list containing fd 0. The waiting process's `/proc//fd/0` must also resolve to the terminal shell's fd 0 target, so a pipeline reader blocked on its pipe remains a running command rather than terminal-input readiness. A wait already present before terminal input is not post-write readiness: the same PGID must be observed outside that wait before re-entering it, while a changed foreground PGID is new evidence. Unreadable process memory and unrecognized syscalls are misses, never positive guesses. Architecture tables contain only syscall numbers defined by the corresponding Linux UAPI; unsupported architectures skip Tier 1. On macOS there is no exact syscall tier. Output silence returns `inferred_idle` for any foreground process group, including Python and `gdb`; `ps`-derived terminal PGID is used for signaling, not as proof that only the shell can be idle. Pure process-inspector logic is injectable and unit-tested on Linux, while a macOS CI job exercises the real PTY and process-table path. @@ -157,9 +157,9 @@ The package ships concise tool guidance explaining persistent state, owner isola ## Verification - Per-file coverage pins owner fencing, concurrent reservations, cancellation during pre-write inspection, unpublished-spawn cancellation and awaited teardown, sandbox-mode change rejection, retriable lifecycle cleanup, readiness tiers, rejection of pre-write stdin waits and delayed earlier prompts, the configured handoff grace holding the idle fallback past one poll and its rejection below `pollIntervalMs`, sanitizer carry state, complete UTF-8 bounds, task integration, schemas, and exact render intents. -- Subprocess process fixtures cover non-leader and non-main-thread stdin waits, zombie quiescence, unreadable process state, supported syscall tables, unsupported architectures, and false-positive rejection; macOS inspector logic is injected into the same unit suite. +- Subprocess process fixtures cover non-leader and non-main-thread stdin waits, rejection of fd 0 backed by a pipe, zombie quiescence, unreadable process state, supported syscall tables, unsupported architectures, and other false-positive rejection; macOS inspector logic is injected into the same unit suite. - Real `node-pty` and PTY-consumer tests jointly exercise shell state, shared sandbox policy, environment scrubbing, raw-mode foreground `SIGINT`, a TERM-ignoring descendant, and immediate post-disposal quiescence on supported hosts. -- A Loader-driven `cordis.yml` test mounts the real three-package composition. ACP and headless snapshots pin the six schemas, bounded results, and errors through opt-in overlays; TUI snapshots pin terminal and generic card presentation. +- A Loader-driven `cordis.yml` test mounts the real three-package composition and verifies that delayed pipeline output returns with the completed command instead of being classified as terminal-input readiness. ACP and headless snapshots pin the six schemas, bounded results, and errors through opt-in overlays; TUI snapshots pin terminal and generic card presentation. - Package contracts, the architecture map, subsystem pages, generated catalogs, and the website API describe the same shipped surface. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md index a277a97fc7..0aad7cc409 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md @@ -74,7 +74,7 @@ UI 渲染约定精确且不携带位置信息。`terminal_send` 只为前台发 本地后端先识别受控 bash 启动时发出的私有 OSC prompt marker,并且只有在最近一个 marker 后的可打印尾部与受控 `PS1` 完全相等时才声明 prompt 就绪;除此之外,它还运行 3 个有界 fallback 层级。在 data callback 之间保留该尾部,可以适配 marker 与 prompt 被分开交付的情况;如果回显的输入或输出跟在延迟到达的先前 prompt 之后,要求尾部完全相等会拒绝该 prompt,使其无法完成当前 send。marker 在输出到达模型前被移除,使两个平台上的普通 shell 命令都无需固定等待静默阈值。尚未发布的 startup 不会把零输出静默视为就绪;timeout 会拒绝 spawn。若调用方取消在 startup 期间胜出,后端会关闭私有会话并原样抛出 `AbortSignal.reason`;尚不可观察的前台 PGID 不会再用查找错误覆盖取消原因。所有时间参数都是经校验的配置字段:`pollIntervalMs`、`exactProbeAfterMs`、`idleSilenceMs`、`handoffGraceMs` 和 `timeoutMs`。 -在 Linux 上,检查器从 `/proc//stat` 读取 shell 的终端前台 PGID,枚举该进程组中的每个进程与线程,并检查它们当前的 syscall。Tier 1 只有观察到 stdin 等待才返回正结果:直接 `read(0)`、获准读取且含 fd 0 的 `select`/`pselect6` 或 `poll`/`ppoll` 参数,或者含 fd 0 的 epoll interest list。终端输入前就已存在的等待并不代表写入后就绪:必须先观察到同一 PGID 脱离该等待,之后再次进入等待才能使该次 send 完成;前台 PGID 发生变化则构成新的证据。无法读取的进程内存和未识别的 syscall 都是 miss,绝不作为正向猜测。架构表只包含对应 Linux UAPI 定义的 syscall number;不支持的架构跳过 Tier 1。 +在 Linux 上,检查器从 `/proc//stat` 读取 shell 的终端前台 PGID,枚举该进程组中的每个进程与线程,并检查它们当前的 syscall。Tier 1 只有观察到 stdin 等待才返回正结果:直接 `read(0)`、获准读取且含 fd 0 的 `select`/`pselect6` 或 `poll`/`ppoll` 参数,或者含 fd 0 的 epoll interest list。等待进程的 `/proc//fd/0` 还必须与终端 shell 的 fd 0 解析到同一目标,因此阻塞于管道的流水线读取端仍属于正在运行的命令,不构成终端输入就绪。终端输入前就已存在的等待并不代表写入后就绪:必须先观察到同一 PGID 脱离该等待,之后再次进入等待才能使该次 send 完成;前台 PGID 发生变化则构成新的证据。无法读取的进程内存和未识别的 syscall 都是 miss,绝不作为正向猜测。架构表只包含对应 Linux UAPI 定义的 syscall number;不支持的架构跳过 Tier 1。 macOS 没有精确 syscall 层。任何前台进程组输出静默都会返回 `inferred_idle`,包括 Python 和 `gdb`;从 `ps` 推导的终端 PGID 只用于发送信号,不作为「只有 shell 才能 idle」的证明。纯进程检查逻辑可注入,并在 Linux 上经过单元测试,同时由 macOS CI job 驱动真实 PTY 和进程表路径。 @@ -157,9 +157,9 @@ plugins: ## 验证 - 逐文件覆盖测试锁定了 owner 隔离、并发预留、写入前检查期间的取消、未发布 spawn 的取消与等待式 teardown、沙箱模式变更拒绝、可重试的生命周期清理、就绪层级、对写入前 stdin 等待与延迟到达的先前 prompt 的拒绝、配置化交接宽限把 idle fallback 顶过一次轮询以及低于 `pollIntervalMs` 时的拒绝、sanitizer carry state、完整 UTF-8 结果上限、task 集成、schema 和精确 render intent。 -- 子进程 fixture(测试前置数据)覆盖非 leader 与非主线程的 stdin 等待、僵尸进程完全停稳、不可读进程状态、受支持的 syscall 表、不支持的架构和误报拒绝;同一单元测试套件通过注入覆盖 macOS 检查器逻辑。 +- 子进程 fixture(测试前置数据)覆盖非 leader 与非主线程的 stdin 等待、拒绝把指向管道的 fd 0 当作终端输入、僵尸进程完全停稳、不可读进程状态、受支持的 syscall 表、不支持的架构和其他误报拒绝;同一单元测试套件通过注入覆盖 macOS 检查器逻辑。 - 真实 `node-pty` 与 PTY 消费方测试共同在受支持宿主上覆盖 shell 状态、共享沙箱策略、环境清洗、raw mode 前台 `SIGINT`、忽略 `SIGTERM` 的后代进程,以及 dispose 返回后立即完全停稳。 -- Loader 驱动的 `cordis.yml` 测试挂载真实三包组合。ACP 与 headless 快照通过 opt-in overlay 固定 6 个 schema、有界结果和错误;TUI 快照固定 terminal 与 generic 卡片展示。 +- Loader 驱动的 `cordis.yml` 测试挂载真实三包组合,并验证延迟到达的流水线输出随已完成命令返回,而不会被归类为终端输入就绪。ACP 与 headless 快照通过 opt-in overlay 固定 6 个 schema、有界结果和错误;TUI 快照固定 terminal 与 generic 卡片展示。 - 包约定、架构图、子系统页面、生成目录和 website API 描述同一个已发布接口。 ## 后果 diff --git a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts index 6d6affdb44..6909d9eea8 100644 --- a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts @@ -152,6 +152,12 @@ suite('persistent Bash through a real cordis.yml Loader composition', () => { )) expect(heredoc).toBe('alpha\nbeta') + const pipeline = text(await execute( + 'pipeline', + '{ sleep 0.1; printf "delayed\\n"; } | cat', + )) + expect(pipeline).toBe('delayed') + const large = text(await execute('large-output', 'seq 1 12050')) expect(large.startsWith('1\n2\n3\n')).toBe(true) expect(large).toContain('') diff --git a/packages/subprocess/subprocess-local/README.i18n.yaml b/packages/subprocess/subprocess-local/README.i18n.yaml index 2a77e8192c..229008e146 100644 --- a/packages/subprocess/subprocess-local/README.i18n.yaml +++ b/packages/subprocess/subprocess-local/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subprocess/subprocess-local/README.md -README.md: e77aa36d8e6dc4ac999261f3a7d0c21a81ed08ff -README.zh.md: 25f7fed19898c81ececb5308b67e8d8a1140e3af +README.md: 26b23f1e0b9a7efee9a2f20f259c69a832e64d53 +README.zh.md: 797eda99fc131eff93c2eaaf87603588a01b3067 diff --git a/packages/subprocess/subprocess-local/README.md b/packages/subprocess/subprocess-local/README.md index e77aa36d8e..26b23f1e0b 100644 --- a/packages/subprocess/subprocess-local/README.md +++ b/packages/subprocess/subprocess-local/README.md @@ -11,7 +11,7 @@ Local Service Provider for the [`@deepseek-ai/dsh-subprocess`](../subprocess/REA - **Credential scrub + explicit merge** — `process.env` minus credential-shaped vars (`*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`) and all ambient `DSH_*` names; the spec's explicit `env` merges after that scrub with no namespace validation, so a deliberately supplied credential or current `DSH_*` fact wins while stale nested-harness identity cannot leak in ambiently. Supplied stdin is written and closed; otherwise fd 0 is `/dev/null`. See the [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.md) and [managed environment Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md). - **Offset-based reads** — collect-mode readers return deltas in whole-stream byte coordinates; the service never holds a cursor, so consumer-owned cursors (the bash background read path) and full-stream re-reads coexist, before and after settlement. - **Executable lookup** — `resolveExecutable` checks absolute files or searches the scrubbed effective PATH with platform-aware executable extensions; relative paths containing separators are rejected at the seam, and relative PATH entries resolve from the host process cwd. -- **Terminal-process ownership** — `spawnTerminal` allocates `node-pty`, bridges UTF-8 terminal text, inspects and signals the current foreground process group, and exposes one awaited termination operation that sweeps descendants before and after terminating the top-level shell. Each foreground inspection retains exact identities from the rooted tree; Linux also enumerates the POSIX session after its leader exits. A previously observed macOS descendant and any same-session Linux member therefore remain fenced after reparenting, while pid/start identity prevents cleanup from following PID reuse. On Windows the koffi-backed inspector enumerates the process table through Toolhelp32, combines GetProcessTimes start identities with zero-time process-handle waits for liveness, reports the shell pid as the pseudo foreground group (Windows has no POSIX groups), and teardown verifies the shell's termination because externally taskkilled shells may never fire node-pty's exit notification. The higher PTY backend owns prompt readiness, buffers, and model-facing operations. +- **Terminal-process ownership** — `spawnTerminal` allocates `node-pty`, bridges UTF-8 terminal text, inspects and signals the current foreground process group, and exposes one awaited termination operation that sweeps descendants before and after terminating the top-level shell. Linux reports an exact input wait only when the waiting process's fd 0 resolves to the terminal shell's fd 0 target, so a pipeline reader blocked on `pipe:[…]` cannot publish terminal readiness. Each foreground inspection retains exact identities from the rooted tree; Linux also enumerates the POSIX session after its leader exits. A previously observed macOS descendant and any same-session Linux member therefore remain fenced after reparenting, while pid/start identity prevents cleanup from following PID reuse. On Windows the koffi-backed inspector enumerates the process table through Toolhelp32, combines GetProcessTimes start identities with zero-time process-handle waits for liveness, reports the shell pid as the pseudo foreground group (Windows has no POSIX groups), and teardown verifies the shell's termination because externally taskkilled shells may never fire node-pty's exit notification. The higher PTY backend owns prompt readiness, buffers, and model-facing operations. - **Terminate-and-join disposal** — the service retains live handles so its own disposal can escalate every running tree and await its exit; quiescent and spawn-failed handles leave the live set after whole-tree or terminal-session cleanup finishes. - **Synchronous host-exit finalization** — while the service effect is active, a Node `exit` listener force-terminates every ordinary tree and observable terminal session still in the same live sets. The local-only operations send POSIX SIGKILL to the managed group, run Windows `taskkill /T /F`, and synchronously signal captured/current terminal identities around the PTY root kill; they create no promise or timer, preserve the host's exit code and diagnostic, contain each target's failure, and do not claim quiescence. Normal disposal keeps the awaited graceful path above. See the [host-exit cleanup decision](../../../.agents/notes/implemented/bug-fix/2026-08-11-synchronous-subprocess-exit-cleanup.md). diff --git a/packages/subprocess/subprocess-local/README.zh.md b/packages/subprocess/subprocess-local/README.zh.md index 25f7fed198..797eda99fc 100644 --- a/packages/subprocess/subprocess-local/README.zh.md +++ b/packages/subprocess/subprocess-local/README.zh.md @@ -11,7 +11,7 @@ - **凭据清除 + 显式合并**:以 `process.env` 为基础,移除形似凭据的变量(`*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`)和所有环境中已有的 `DSH_*` 名称;spec 的显式 `env` 在该清除之后合并且不做命名空间校验,因此有意提供的凭据或当前 `DSH_*` 事实会胜出,而陈旧的嵌套 harness 身份无法从环境中隐式漏入。提供的 stdin 会被写入后关闭;否则 fd 0 指向 `/dev/null`。参见 [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.zh.md)与[受管环境 Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.zh.md)。 - **基于偏移量的读取**:收集模式的读取器按完整流的字节坐标返回增量;服务自身从不持有游标,因此消费方自有的游标(bash 的后台读取路径)与完整流重读可以共存,结算前后皆然。 - **可执行文件查找**:`resolveExecutable` 检查绝对文件,或根据平台可执行文件扩展名在清理后的有效 PATH 中搜索;含分隔符的相对路径在该 seam 处被拒绝,相对 PATH 条目从宿主进程 cwd 解析。 -- **终端进程所有权**:`spawnTerminal` 分配 `node-pty`,桥接 UTF-8 终端文本,检查当前前台进程组并向其发送信号,还会公开一项须等待的终止操作,在终止顶层 shell 前后清理后代进程。每次前台检查都会保留根进程树中的精确身份;Linux 还会在 POSIX 会话 leader 退出后枚举该会话。因此,之前观察到的 macOS 后代以及同会话 Linux 成员在重新设定父进程后仍受围栏保护,pid/start 身份则防止清理跟随 PID 复用。在 Windows 上,基于 koffi 的检查器通过 Toolhelp32 枚举进程表,把 GetProcessTimes 启动身份与进程句柄零时等待结合起来判断存活状态,并把 shell pid 作为伪前台进程组(Windows 没有 POSIX 进程组)。拆卸会验证 shell 已终止,因为被外部 taskkill 的 shell 可能永远不会触发 node-pty 的退出通知。上层 PTY 后端负责提示符就绪、缓冲区与面向模型的操作。 +- **终端进程所有权**:`spawnTerminal` 分配 `node-pty`,桥接 UTF-8 终端文本,检查当前前台进程组并向其发送信号,还会公开一项须等待的终止操作,在终止顶层 shell 前后清理后代进程。Linux 只有在等待进程的 fd 0 与终端 shell 的 fd 0 解析到同一目标时才报告精确输入等待,因此阻塞于 `pipe:[…]` 的流水线读取端无法发布终端就绪状态。每次前台检查都会保留根进程树中的精确身份;Linux 还会在 POSIX 会话 leader 退出后枚举该会话。因此,之前观察到的 macOS 后代以及同会话 Linux 成员在重新设定父进程后仍受围栏保护,pid/start 身份则防止清理跟随 PID 复用。在 Windows 上,基于 koffi 的检查器通过 Toolhelp32 枚举进程表,把 GetProcessTimes 启动身份与进程句柄零时等待结合起来判断存活状态,并把 shell pid 作为伪前台进程组(Windows 没有 POSIX 进程组)。拆卸会验证 shell 已终止,因为被外部 taskkill 的 shell 可能永远不会触发 node-pty 的退出通知。上层 PTY 后端负责提示符就绪、缓冲区与面向模型的操作。 - **先终止再等待退出的 dispose(资源释放)**:服务保留存活句柄,使自身的 dispose 能对每个仍在运行的进程树执行升级并等待其退出;完全停稳与 spawn 失败的句柄会在整棵进程树或 terminal session 清理完成后离开存活集合。 - **同步宿主退出最终清理**:服务 effect 仍有效时,Node `exit` listener 会强制终止同一组存活集合中仍存在的每棵普通进程树和可观察 terminal session。这些仅供本地实现使用的操作会向受管 POSIX 进程组发送 SIGKILL、在 Windows 运行 `taskkill /T /F`,并在终止 PTY root 前后同步向已捕获及当前可观察的 terminal 身份发送信号;它们不会创建 Promise 或 timer,不改变宿主退出码与诊断,会分别包含每个目标的失败,也不会声称已经完全停稳。正常 dispose 仍使用上面的须等待温和路径。参见[宿主退出清理决策](../../../.agents/notes/implemented/bug-fix/2026-08-11-synchronous-subprocess-exit-cleanup.zh.md)。 diff --git a/packages/subprocess/subprocess-local/src/process-inspector.ts b/packages/subprocess/subprocess-local/src/process-inspector.ts index 89effc0082..05b775e5ef 100644 --- a/packages/subprocess/subprocess-local/src/process-inspector.ts +++ b/packages/subprocess/subprocess-local/src/process-inspector.ts @@ -1,6 +1,6 @@ /** Platform process-table inspection for terminal readiness, signals, and teardown. */ -import { closeSync, openSync, readFileSync, readdirSync, readSync } from 'node:fs' +import { closeSync, openSync, readFileSync, readdirSync, readlinkSync, readSync } from 'node:fs' import { execFileSync } from 'node:child_process' import type { SubprocessTerminalSignal } from '@deepseek-ai/dsh-subprocess' import { createWindowsProcessInspector } from './windows-inspector.ts' @@ -14,7 +14,14 @@ export interface ProcessIdentity { /** Injectable OS process operations used by one local PTY session. */ export interface ProcessInspector { foregroundPgid(shellPid: number): number | undefined - isStdinWaiting(pgid: number): boolean + /** + * Report whether the foreground group waits on the terminal shell's stdin. + * + * @param pgid Foreground process-group identifier. + * @param shellPid Persistent terminal shell process identifier. + * @returns Whether a group member is blocked reading the shell's terminal input. + */ + isStdinWaiting(pgid: number, shellPid: number): boolean /** Return the root and its current transitive descendants, children first. */ processTree(rootPid: number): ProcessIdentity[] /** Return current members of one POSIX process session when the platform exposes them. */ @@ -29,6 +36,7 @@ export interface ProcessInspector { export interface ProcessInspectorInternals { readFile(path: string): string readDir(path: string): string[] + readLink(path: string): string open(path: string): number read(fd: number, buffer: Buffer, length: number, position: number): number close(fd: number): void @@ -40,6 +48,7 @@ export interface ProcessInspectorInternals { const DEFAULT_INTERNALS: ProcessInspectorInternals = { readFile: path => readFileSync(path, 'utf8'), readDir: path => readdirSync(path), + readLink: path => readlinkSync(path, 'utf8'), open: path => openSync(path, 'r'), read: (fd, buffer, length, position) => readSync(fd, buffer, 0, length, position), close: closeSync, @@ -88,6 +97,14 @@ function readLinuxStat(internals: ProcessInspectorInternals, pid: number): ProcS } } +function readLinuxStdinTarget(internals: ProcessInspectorInternals, pid: number): string | undefined { + try { + return internals.readLink(`/proc/${pid}/fd/0`) + } catch (_unreadableStdinTarget) { + return undefined + } +} + /** * Report whether a Linux process group has an executing member. `false` * means the group contains only zombie/dead entries; `undefined` means the @@ -231,7 +248,7 @@ abstract class PosixProcessInspector implements ProcessInspector { constructor(protected readonly internals: ProcessInspectorInternals) {} abstract foregroundPgid(shellPid: number): number | undefined - abstract isStdinWaiting(pgid: number): boolean + abstract isStdinWaiting(pgid: number, shellPid: number): boolean abstract processTree(rootPid: number): ProcessIdentity[] abstract processSession(sessionId: number): ProcessIdentity[] abstract isAlive(identity: ProcessIdentity): boolean @@ -284,14 +301,18 @@ class LinuxProcessInspector extends PosixProcessInspector { return tpgid !== undefined && tpgid > 0 ? tpgid : undefined } - isStdinWaiting(pgid: number): boolean { + isStdinWaiting(pgid: number, shellPid: number): boolean { const table = SYSCALLS[this.arch] if (table === undefined) return false + const terminalStdinTarget = readLinuxStdinTarget(this.internals, shellPid) + if (terminalStdinTarget === undefined) return false for (const pid of numericEntries(this.internals, '/proc')) { if (readLinuxStat(this.internals, pid)?.pgrp !== pgid) continue for (const tid of numericEntries(this.internals, `/proc/${pid}/task`)) { const syscall = readSyscall(this.internals, pid, tid) - if (syscall !== undefined && syscallWaitsOnStdin(this.internals, pid, syscall, table)) return true + if (syscall !== undefined + && syscallWaitsOnStdin(this.internals, pid, syscall, table) + && readLinuxStdinTarget(this.internals, pid) === terminalStdinTarget) return true } } return false @@ -339,7 +360,7 @@ class MacProcessInspector extends PosixProcessInspector { } } - isStdinWaiting(_pgid: number): boolean { + isStdinWaiting(_pgid: number, _shellPid: number): boolean { return false } diff --git a/packages/subprocess/subprocess-local/src/terminal.ts b/packages/subprocess/subprocess-local/src/terminal.ts index 0a51287d24..80782e24e7 100644 --- a/packages/subprocess/subprocess-local/src/terminal.ts +++ b/packages/subprocess/subprocess-local/src/terminal.ts @@ -88,7 +88,7 @@ export class LocalTerminalHandle implements SubprocessTerminalHandle { if (processGroupId === undefined) return undefined return { processGroupId, - inputWaiting: this.inspector.isStdinWaiting(processGroupId), + inputWaiting: this.inspector.isStdinWaiting(processGroupId, this.pid), } } diff --git a/packages/subprocess/subprocess-local/src/windows-inspector.ts b/packages/subprocess/subprocess-local/src/windows-inspector.ts index 7280cbb9ee..6889a3e65d 100644 --- a/packages/subprocess/subprocess-local/src/windows-inspector.ts +++ b/packages/subprocess/subprocess-local/src/windows-inspector.ts @@ -93,7 +93,7 @@ export class WindowsProcessInspector implements ProcessInspector { return shellPid } - isStdinWaiting(_pgid: number): boolean { + isStdinWaiting(_pgid: number, _shellPid: number): boolean { return false } diff --git a/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts b/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts index aadf2e1388..5115db1233 100644 --- a/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts +++ b/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts @@ -23,6 +23,7 @@ function syscall(number: number, ...args: number[]): string { function fakeInternals() { const files = new Map() const dirs = new Map() + const links = new Map() const memories = new Map() const fds = new Map() const kills: Array<[number, NodeJS.Signals]> = [] @@ -40,6 +41,11 @@ function fakeInternals() { if (value === undefined) throw new Error(`missing ${path}`) return value }, + readLink(path) { + const value = links.get(path) + if (value === undefined) throw new Error(`missing ${path}`) + return value + }, open(path) { if (!memories.has(path)) throw new Error(`missing ${path}`) const fd = nextFd++ @@ -61,7 +67,7 @@ function fakeInternals() { kill(pid, signal) { kills.push([pid, signal]) }, } return { - internals, files, dirs, memories, kills, + internals, files, dirs, links, memories, kills, setPs(value: string) { ps = value }, setTpgid(value: string) { tpgid = value }, } @@ -132,29 +138,48 @@ describe('Linux process inspector', () => { fake.files.set('/proc/101/stat', stat(101, 77, 100, 77, '2')) fake.dirs.set('/proc/100/task', ['100']) fake.dirs.set('/proc/101/task', ['101', '102']) + fake.links.set('/proc/100/fd/0', '/dev/pts/1') + fake.links.set('/proc/101/fd/0', '/dev/pts/1') const inspector = createProcessInspector('linux', 'x64', fake.internals) fake.files.set('/proc/100/task/100/syscall', 'running') fake.files.set('/proc/101/task/101/syscall', '-1 0x0') fake.files.set('/proc/101/task/102/syscall', syscall(0, 0)) - expect(inspector.isStdinWaiting(77)).toBe(true) + expect(inspector.isStdinWaiting(77, 100)).toBe(true) fake.files.set('/proc/101/task/102/syscall', syscall(270, 1, 0x10)) const fdSet = Buffer.alloc(0x11) fdSet[0x10] = 1 fake.memories.set('/proc/101/mem', fdSet) - expect(inspector.isStdinWaiting(77)).toBe(true) + expect(inspector.isStdinWaiting(77, 100)).toBe(true) const poll = Buffer.alloc(8) poll.writeInt32LE(0, 0) poll.writeInt16LE(1, 4) fake.files.set('/proc/101/task/102/syscall', syscall(7, 0x20, 1)) fake.memories.set('/proc/101/mem', Buffer.concat([Buffer.alloc(0x20), poll])) - expect(inspector.isStdinWaiting(77)).toBe(true) + expect(inspector.isStdinWaiting(77, 100)).toBe(true) fake.files.set('/proc/101/task/102/syscall', syscall(232, 5, 0, 1)) fake.files.set('/proc/101/fdinfo/5', 'pos: 0\ntfd: 0 events: 19\n') - expect(inspector.isStdinWaiting(77)).toBe(true) + expect(inspector.isStdinWaiting(77, 100)).toBe(true) + }) + + it('rejects pipeline reads whose fd 0 is not the terminal input', () => { + const fake = fakeInternals() + fake.dirs.set('/proc', ['100']) + fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1')) + fake.dirs.set('/proc/100/task', ['100']) + fake.files.set('/proc/100/task/100/syscall', syscall(0, 0)) + fake.links.set('/proc/99/fd/0', '/dev/pts/1') + fake.links.set('/proc/100/fd/0', 'pipe:[123]') + const inspector = createProcessInspector('linux', 'x64', fake.internals) + + expect(inspector.isStdinWaiting(77, 99)).toBe(false) + fake.links.delete('/proc/100/fd/0') + expect(inspector.isStdinWaiting(77, 99)).toBe(false) + fake.links.set('/proc/100/fd/0', '/dev/pts/1') + expect(inspector.isStdinWaiting(77, 99)).toBe(true) }) it('fails closed on unsupported, malformed, unreadable, or non-stdin waits', () => { @@ -162,30 +187,31 @@ describe('Linux process inspector', () => { fake.dirs.set('/proc', ['100']) fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1')) fake.dirs.set('/proc/100/task', ['100']) + fake.links.set('/proc/100/fd/0', '/dev/pts/1') fake.files.set('/proc/100/task/100/syscall', syscall(0, 2)) - expect(createProcessInspector('linux', 'mips', fake.internals).isStdinWaiting(77)).toBe(false) - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'mips', fake.internals).isStdinWaiting(77, 100)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(270, 1, 0)) - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(7, 0, 0)) - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(7, 0, 1)) - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(7, 0x20, 1)) - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(232, 9, 0, 1)) - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(999)) - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', 'not-a-number 0x0') - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.dirs.delete('/proc/100/task') - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) fake.dirs.set('/proc', ['100', '200']) fake.files.set('/proc/200/stat', stat(200, 88, 200, 88, '2')) - expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77)).toBe(false) + expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) }) it('contains unreadable syscall, memory, and fdinfo boundaries', () => { @@ -194,19 +220,21 @@ describe('Linux process inspector', () => { fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1')) fake.dirs.set('/proc/100/task', ['100']) const inspector = createProcessInspector('linux', 'x64', fake.internals) - expect(inspector.isStdinWaiting(77)).toBe(false) + expect(inspector.isStdinWaiting(77, 100)).toBe(false) + fake.links.set('/proc/100/fd/0', '/dev/pts/1') + expect(inspector.isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(270, 1, 0x10)) - expect(inspector.isStdinWaiting(77)).toBe(false) + expect(inspector.isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(232, 5, 0, 1)) - expect(inspector.isStdinWaiting(77)).toBe(false) + expect(inspector.isStdinWaiting(77, 100)).toBe(false) const noStdinPoll = Buffer.alloc(0x28) noStdinPoll.writeInt32LE(2, 0x20) noStdinPoll.writeInt16LE(1, 0x24) fake.memories.set('/proc/100/mem', noStdinPoll) fake.files.set('/proc/100/task/100/syscall', syscall(7, 0x20, 1)) - expect(inspector.isStdinWaiting(77)).toBe(false) + expect(inspector.isStdinWaiting(77, 100)).toBe(false) }) }) @@ -217,7 +245,7 @@ describe('macOS process inspector', () => { fake.setPs(' 10 1 Mon Jul 21 10:00:00 2026\n 11 10 Mon Jul 21 10:00:01 2026\n 12 11 Mon Jul 21 10:00:02 2026\n 13 99 Mon Jul 21 10:00:03 2026\nmalformed\n') const inspector = createProcessInspector('darwin', 'arm64', fake.internals) expect(inspector.foregroundPgid(10)).toBe(55) - expect(inspector.isStdinWaiting(55)).toBe(false) + expect(inspector.isStdinWaiting(55, 10)).toBe(false) expect(inspector.processTree(10)).toEqual([ { pid: 12, started: 'Mon Jul 21 10:00:02 2026' }, { pid: 11, started: 'Mon Jul 21 10:00:01 2026' }, diff --git a/packages/subprocess/subprocess-local/tests/terminal.spec.ts b/packages/subprocess/subprocess-local/tests/terminal.spec.ts index c2aca88085..330660eda3 100644 --- a/packages/subprocess/subprocess-local/tests/terminal.spec.ts +++ b/packages/subprocess/subprocess-local/tests/terminal.spec.ts @@ -59,12 +59,16 @@ class FakeInspector implements ProcessInspector { readonly alive = new Set() readonly groups: Array<[number, SubprocessTerminalSignal]> = [] readonly processes: Array<[number, 'SIGTERM' | 'SIGKILL']> = [] + readonly stdinChecks: Array<[number, number]> = [] throwGroup = false throwProcess = false removeOnSignal = true foregroundPgid() { return this.pgid } - isStdinWaiting() { return this.waiting } + isStdinWaiting(pgid: number, shellPid: number) { + this.stdinChecks.push([pgid, shellPid]) + return this.waiting + } processTree() { return this.root === undefined ? this.members : [this.root, ...this.members] } processSession() { return this.sessionMembers } isAlive(identity: ProcessIdentity) { return this.alive.has(identity.pid) } @@ -182,6 +186,7 @@ describe('LocalTerminalHandle', () => { await handle.write('input\r') expect(pty.writes).toEqual(['input\r']) expect(await handle.inspectForeground()).toEqual({ processGroupId: 456, inputWaiting: true }) + expect(inspector.stdinChecks).toEqual([[456, 123]]) expect(await handle.signalForeground('SIGINT')).toBe(456) expect(inspector.groups).toEqual([[456, 'SIGINT']]) diff --git a/packages/subprocess/subprocess-local/tests/windows-inspector.spec.ts b/packages/subprocess/subprocess-local/tests/windows-inspector.spec.ts index e00bdeb9e2..5950fd9328 100644 --- a/packages/subprocess/subprocess-local/tests/windows-inspector.spec.ts +++ b/packages/subprocess/subprocess-local/tests/windows-inspector.spec.ts @@ -65,7 +65,7 @@ describe('WindowsProcessInspector (injected internals)', () => { const fake = fakeInternals() const inspector = new WindowsProcessInspector(fake.internals) expect(inspector.foregroundPgid(77)).toBe(77) - expect(inspector.isStdinWaiting(77)).toBe(false) + expect(inspector.isStdinWaiting(77, 10)).toBe(false) expect(inspector.processSession(77)).toEqual([]) }) From a813b487ab9b7985dd7d7ce047849c4e18ef1cd6 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 25 Aug 2026 13:17:22 +0800 Subject: [PATCH 16/31] docs(coverage): update Agent Note for Windows 4-partition alignment The PR changes native Windows coverage partitions from 8 to 4 to reduce vitest worker startup pressure under high self-hosted concurrency. Sync the implemented Agent Note (EN/ZH) so the decision record no longer says Windows is fixed at 8, and revise the same-partition-count alternative accordingly. --- .../process/2026-08-18-in-job-partitioned-coverage.md | 6 +++--- .../process/2026-08-18-in-job-partitioned-coverage.zh.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.md b/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.md index 2cf06f6dd3..9b8e6308ec 100644 --- a/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.md +++ b/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.md @@ -12,7 +12,7 @@ The optimization must retain every test and the merged per-file 100% thresholds. ## Decision -The ordinary `pnpm run test:coverage` command remains one Vitest invocation. Linux coverage CI fixes `DSH_COVERAGE_PARTITIONS=4`, while native Windows fixes it at 8; no elapsed-time trigger changes either count while a run is in progress. The [coverage-exempt heavy suite](2026-07-31-coverage-exempt-heavy-suites.md) remains a separate uninstrumented gate beside the instrumented work. +The ordinary `pnpm run test:coverage` command remains one Vitest invocation. Linux coverage CI fixes `DSH_COVERAGE_PARTITIONS=4`; native Windows now also fixes it at 4 to reduce process-creation pressure under high self-hosted concurrency. No elapsed-time trigger changes either count while a run is in progress. The [coverage-exempt heavy suite](2026-07-31-coverage-exempt-heavy-suites.md) remains a separate uninstrumented gate beside the instrumented work. When partitioning is enabled, `scripts/run-gates.ts` selects `pnpm run test:coverage:partitioned` for the instrumented gate. `scripts/coverage-partitions.ts` starts the configured Vitest children concurrently, each with one worker and one `--shard=/` option. Partition mode suppresses thresholds and coverage reporters in each child, gives every child a separate report directory, and writes one blob report per process. @@ -30,7 +30,7 @@ A normal failed test still emits a blob through `--coverage.reportOnFailure`, al `scripts/coverage-partitions.spec.ts` pins argument construction, package-script separator removal, one-worker partitions, the single merged threshold command, failed-test merging, failure diagnostics before complete-blob validation, waiting for sibling partitions after a spawn failure, and link-safe cleanup. `scripts/run-gates.spec.ts` pins opt-in selection, invalid-count rejection, both native Windows coverage gates' complete-build dependency, the complete Windows inventory with its blocking split, and unbuffered streamed output. React fake-timer cases that can move between partitions advance timers inside `act()`; geometry-dependent portal tests stub their element rectangles so a different shard schedule cannot turn deferred updates or jsdom coordinates into coverage-only failures. -Completed native Windows comparisons measured two partitions near 405 seconds and sixteen partitions at 112.66–122.01 seconds under the earlier gate ordering; those values compare partition latency, not the current peak. The current post-build phase runs eight instrumented partition processes beside two exempt workers, for ten coverage execution units. Sixteen partitions would raise that phase to eighteen before any still-running production-site work or system overhead. Eight keeps separate-process isolation while leaving capacity headroom. Two Linux samples measured the conservative two-partition configuration at 276.68 and 282.27 seconds; that configuration was stable but halved the ordinary path's four instrumented workers. Four partitions restore that fan-out, for six total coverage execution units on the 16-core hosted runner and at most 36 across the failover VM's six runner instances. These values come from completed runs or fixed capacity bounds; an unfinished run crossing an arbitrary elapsed-time mark is not evidence for increasing concurrency. +Completed native Windows comparisons measured two partitions near 405 seconds and sixteen partitions at 112.66–122.01 seconds under the earlier gate ordering; those values compare partition latency, not the current peak. The current post-build phase runs four instrumented partition processes beside two exempt workers, for six coverage execution units. Sixteen partitions would raise that phase to eighteen before any still-running production-site work or system overhead. Four partitions keep separate-process isolation and match Linux, at the cost of a longer single-job coverage wall time; the trade-off is accepted to reduce vitest worker startup failures under high self-hosted concurrency. Two Linux samples measured the conservative two-partition configuration at 276.68 and 282.27 seconds; that configuration was stable but halved the ordinary path's four instrumented workers. Four partitions restore that fan-out, for six total coverage execution units on the 16-core hosted runner and at most 36 across the failover VM's six runner instances. These values come from completed runs or fixed capacity bounds; an unfinished run crossing an arbitrary elapsed-time mark is not evidence for increasing concurrency. ## Alternatives considered @@ -38,7 +38,7 @@ Completed native Windows comparisons measured two partitions near 405 seconds an **Raise the Vitest worker count inside one instrumented process.** Rejected because completed Windows trials at higher fan-out exposed worker exits, fixture instability, and Node 24 CJS lexer failures. Separate single-worker processes preserve isolation while still executing the selected partitions concurrently. -**Use one partition count on every host.** Rejected because Linux's four-process run and Windows's eight-process run have different startup costs and resource ceilings. Each fixed configuration requires its own completed end-to-end evidence. +**Use one partition count on every host.** Previously rejected because Linux's four-process run and Windows's eight-process run had different startup costs and resource ceilings. This change aligns both to four partitions after Windows high-concurrency runs exposed worker startup failures at eight. **Apply thresholds independently in each partition.** Rejected because every partition intentionally sees only part of the suite and would report false uncovered files. Threshold ownership belongs to the merged report. diff --git a/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.zh.md b/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.zh.md index 266feed66a..cf4d50996d 100644 --- a/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.zh.md +++ b/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.zh.md @@ -12,7 +12,7 @@ Status: implemented ## 决策 -普通的 `pnpm run test:coverage` 命令仍只启动一次 Vitest。Linux 覆盖率 CI 将 `DSH_COVERAGE_PARTITIONS` 固定为 4,原生 Windows 则固定为 8;运行期间不会由任何耗时触发器改变这两个数量。[覆盖率豁免重型套件](2026-07-31-coverage-exempt-heavy-suites.zh.md)仍作为独立的无插桩门禁与插桩工作并排运行。 +普通的 `pnpm run test:coverage` 命令仍只启动一次 Vitest。Linux 覆盖率 CI 将 `DSH_COVERAGE_PARTITIONS` 固定为 4;原生 Windows 现在也固定为 4,以降低自托管高并发下的进程创建压力。运行期间不会由任何耗时触发器改变这两个数量。[覆盖率豁免重型套件](2026-07-31-coverage-exempt-heavy-suites.zh.md)仍作为独立的无插桩门禁与插桩工作并排运行。 启用分区后,`scripts/run-gates.ts` 为插桩门禁选择 `pnpm run test:coverage:partitioned`。`scripts/coverage-partitions.ts` 按配置数量并发启动 Vitest 子进程,每个进程只用 1 个 worker,并各自接收一个 `--shard=/` 选项。分区模式会在各子进程中关闭阈值与覆盖率报告器,为每个子进程分配独立报告目录,并让每个进程写出 1 份 blob 报告。 @@ -30,7 +30,7 @@ Status: implemented `scripts/coverage-partitions.spec.ts` 固定了参数构造、包脚本分隔符移除、单 worker 分区、唯一一次合并阈值命令、失败测试合并、完整 blob 校验前的失败诊断、spawn 失败后等待兄弟分区,以及链接安全清理。`scripts/run-gates.spec.ts` 固定了显式启用、非法数量拒绝、两道原生 Windows 覆盖率门禁对完整构建的依赖、完整 Windows 清单及其阻断性划分,以及不缓冲的流式输出。可能在分区间移动的 React fake-timer 用例会在 `act()` 内推进计时器;依赖几何位置的 portal 测试会固定元素矩形,使不同分片调度不会把延迟更新或 jsdom 坐标变成只在覆盖率运行中出现的失败。 -已完成的原生 Windows 对比中,双分区耗时约 405 秒,16 分区耗时 112.66–122.01 秒;这些数据来自先前的门禁顺序,只用于比较分区延迟,不代表当前峰值。当前的构建后阶段会让 8 个插桩分区进程与 2 个豁免 worker 并行,共形成 10 个覆盖率执行单元。若改为 16 个分区,则在尚未结束的生产网站工作或系统开销计入之前,该阶段就会达到 18 个执行单元。8 个分区既保留独立进程隔离,也为其他工作留出容量余量。两个 Linux 样本中,保守的双分区配置耗时 276.68 秒和 282.27 秒;该配置运行稳定,却把普通路径原有的 4 个插桩 worker 减半。4 个分区恢复这份并发,使 16 核托管 runner 上的覆盖率执行单元总数为 6,故障切换虚拟机的 6 个 runner 实例最多合计 36 个执行单元。这些数值来自完整运行或固定容量上限;运行尚未结束时跨过任意耗时刻度,不构成增加并发的证据。 +已完成的原生 Windows 对比中,双分区耗时约 405 秒,16 分区耗时 112.66–122.01 秒;这些数据来自先前的门禁顺序,只用于比较分区延迟,不代表当前峰值。当前的构建后阶段会让 4 个插桩分区进程与 2 个豁免 worker 并行,共形成 6 个覆盖率执行单元。若改为 16 个分区,则在尚未结束的生产网站工作或系统开销计入之前,该阶段就会达到 18 个执行单元。4 个分区保留独立进程隔离并与 Linux 对齐,代价是单 job 覆盖率墙钟更长;这是为了降低自托管高并发下 vitest worker 启动失败而接受的取舍。两个 Linux 样本中,保守的双分区配置耗时 276.68 秒和 282.27 秒;该配置运行稳定,却把普通路径原有的 4 个插桩 worker 减半。4 个分区恢复这份并发,使 16 核托管 runner 上的覆盖率执行单元总数为 6,故障切换虚拟机的 6 个 runner 实例最多合计 36 个执行单元。这些数值来自完整运行或固定容量上限;运行尚未结束时跨过任意耗时刻度,不构成增加并发的证据。 ## 曾考虑的替代方案 @@ -38,7 +38,7 @@ Status: implemented **提高单个插桩进程内的 Vitest worker 数。** 不予采用,因为已完成的 Windows 高扇出试验暴露了 worker 退出、fixture(测试前置数据)不稳定和 Node 24 CJS lexer 故障。相互独立的单 worker 进程既保留隔离,也能让所选分区并发执行。 -**在每种宿主上使用相同的分区数量。** 不予采用,因为 Linux 的 4 进程运行与 Windows 的 8 进程运行具有不同的启动成本与资源上限。每种固定配置都必须取得自己的端到端完整证据。 +**在每种宿主上使用相同的分区数量。** 先前不予采用,因为 Linux 的 4 进程运行与 Windows 的 8 进程运行具有不同的启动成本与资源上限。本次变更在 Windows 高并发运行暴露 8 分片 worker 启动失败后,将两者统一为 4 分区。 **在每个分区内独立应用阈值。** 不予采用,因为每个分区有意只看到套件的一部分,会误报未覆盖文件。阈值归合并报告所有。 From 16dbf73348275b5e52f1f32b1887a65aab479fa7 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 25 Aug 2026 13:23:22 +0800 Subject: [PATCH 17/31] docs(windows): sync native CI note to 4 coverage partitions --- .../process/2026-08-08-native-windows-pull-request-ci.md | 4 ++-- .../process/2026-08-08-native-windows-pull-request-ci.zh.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md index a1a783df2a..24f1a5fa0c 100644 --- a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md +++ b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md @@ -18,9 +18,9 @@ Every pull request also starts an ordinary independent `windows-native` job name The native job is deliberately absent from `all-checks-passed.needs` and does not use `continue-on-error`: the aggregate neither waits for it nor changes conclusion because of it, while the job retains its own unmasked result. Workspace build, production-site, and 100%-per-file coverage failures make the native job fail. Static, documentation, package, built-artifact, lint, and snapshot inventories run in the same job as observational gates: their failures remain visible without changing the native aggregate result because Linux owns their blocking verdict. -The 16-core lane admits four concurrent outer gates. Workspace build and production-site validation start immediately. Instrumented and exempt-heavy coverage both wait for the complete build: the instrumented corpus includes packer assertions over built `lib/` output, while the exempt gate's temporary Oxlint contract probes must not race source compilation. Every observational gate waits for both coverage gates to settle, regardless of outcome, before entering an available slot; its own `needs` edges still require their predecessors to pass. This also keeps later static gates that create temporary contract files from racing either coverage scan. [In-job partitioned coverage](2026-08-18-in-job-partitioned-coverage.md) uses eight single-worker shards, while the exempt-heavy gate receives two workers from `DSH_COVERAGE_MAX_WORKERS=6`, for about ten active coverage execution units after build. `publint` is capped at eight workers when the observational inventory starts. Every Vitest project uses forked workers because Node 24's CJS lexer fatal reproduced in shared worker threads on Windows and POSIX. Both coverage gates set Vitest's default per-test and polling budgets to 30 seconds because unrelated process, Git, SQLite, watcher, grammar, and static-gate fixtures can exceed 15 seconds only under the complete lane's concurrent Windows instrumentation. The SQLite busy-journal pacing fixture injects two busy results followed by success under the normal busy budget and observes each inter-attempt delay, keeping schema-setup scheduling outside its timing assertion. The script-only translation-pairing merge suite runs in the exempt-heavy gate because it imports only `scripts/` sources and child processes; V8 instrumentation contributes no threshold coverage there but magnifies Git-process latency. Lefthook concurrency fixtures retain their outcomes with 30-second case budgets and a 10-second process-ready probe, while the installer allows five seconds for a preempted lock owner to publish its record after exclusive creation. Directory-picker composition gives its debounced config write an explicit 15-second poll budget; workspace-context composition fixtures use a test-owned signal without an unrelated one-second deadline. These lane-scoped budgets preserve asserted outcomes, while the 120-minute job deadline still bounds a stuck run. The LSP sources and the ACL-sandbox sources remain in the Windows denominator: stub-based failure-path suites carry every in-process ACL-sandbox file to 100%, and only the runner entry stays excluded — it executes exclusively as a spawned child outside the instrumented run, its behavior pinned end-to-end by the runner suite. Narrow annotated V8 ignores cover only unreachable branches (peer-platform arms and lifecycle-unreachable guards), with their behavior tests retained on the owning platform. +The 16-core lane admits four concurrent outer gates. Workspace build and production-site validation start immediately. Instrumented and exempt-heavy coverage both wait for the complete build: the instrumented corpus includes packer assertions over built `lib/` output, while the exempt gate's temporary Oxlint contract probes must not race source compilation. Every observational gate waits for both coverage gates to settle, regardless of outcome, before entering an available slot; its own `needs` edges still require their predecessors to pass. This also keeps later static gates that create temporary contract files from racing either coverage scan. [In-job partitioned coverage](2026-08-18-in-job-partitioned-coverage.md) uses four single-worker shards, while the exempt-heavy gate receives two workers from `DSH_COVERAGE_MAX_WORKERS=6`, for about six active coverage execution units after build. `publint` is capped at eight workers when the observational inventory starts. Every Vitest project uses forked workers because Node 24's CJS lexer fatal reproduced in shared worker threads on Windows and POSIX. Both coverage gates set Vitest's default per-test and polling budgets to 30 seconds because unrelated process, Git, SQLite, watcher, grammar, and static-gate fixtures can exceed 15 seconds only under the complete lane's concurrent Windows instrumentation. The SQLite busy-journal pacing fixture injects two busy results followed by success under the normal busy budget and observes each inter-attempt delay, keeping schema-setup scheduling outside its timing assertion. The script-only translation-pairing merge suite runs in the exempt-heavy gate because it imports only `scripts/` sources and child processes; V8 instrumentation contributes no threshold coverage there but magnifies Git-process latency. Lefthook concurrency fixtures retain their outcomes with 30-second case budgets and a 10-second process-ready probe, while the installer allows five seconds for a preempted lock owner to publish its record after exclusive creation. Directory-picker composition gives its debounced config write an explicit 15-second poll budget; workspace-context composition fixtures use a test-owned signal without an unrelated one-second deadline. These lane-scoped budgets preserve asserted outcomes, while the 120-minute job deadline still bounds a stuck run. The LSP sources and the ACL-sandbox sources remain in the Windows denominator: stub-based failure-path suites carry every in-process ACL-sandbox file to 100%, and only the runner entry stays excluded — it executes exclusively as a spawned child outside the instrumented run, its behavior pinned end-to-end by the runner suite. Narrow annotated V8 ignores cover only unreachable branches (peer-platform arms and lifecycle-unreachable guards), with their behavior tests retained on the owning platform. -The 16-core allocation is the measured capacity point for this inventory. Six-worker coverage trials produced complete passes in 6 minutes 27 seconds and 7 minutes 50 seconds, while exact-head trials with four, three, and two concurrent workers inside one instrumented Vitest process exposed unreliable fixtures and worker exits. Separate single-worker child processes retain process isolation. Historical sixteen-shard samples reduced instrumented coverage to 112.66–122.01 seconds. Under the current post-build graph, sixteen instrumented shards plus two exempt workers would schedule eighteen coverage execution units on a 16-core runner before any production-site tail or system overhead; eight shards plus two exempt workers schedule ten. Eight deliberately trades some latency for that headroom. A 32-core comparison reduced aggregate gate time by only 1.47 seconds and still triggered the CJS-lexer fatal inside a fork worker, so additional cores did not provide a reliable wall-clock improvement. +The 16-core allocation is the measured capacity point for this inventory. Six-worker coverage trials produced complete passes in 6 minutes 27 seconds and 7 minutes 50 seconds, while exact-head trials with four, three, and two concurrent workers inside one instrumented Vitest process exposed unreliable fixtures and worker exits. Separate single-worker child processes retain process isolation. Historical sixteen-shard samples reduced instrumented coverage to 112.66–122.01 seconds. Under the current post-build graph, sixteen instrumented shards plus two exempt workers would schedule eighteen coverage execution units on a 16-core runner before any production-site tail or system overhead; four shards plus two exempt workers schedule six. Four deliberately trades some single-job latency for lower process-creation pressure under high self-hosted concurrency. A 32-core comparison reduced aggregate gate time by only 1.47 seconds and still triggered the CJS-lexer fatal inside a fork worker, so additional cores did not provide a reliable wall-clock improvement. The first native run exposed two failures hidden by the compatibility lane. Documentation projection tests derived an image basename by splitting only on `/`; they now use Node's platform basename. Chokidar consumers received `%TEMP%` through the `C:\\Users\\RUNNER~1` 8.3 alias while libuv returned the long directory name, tripping its Windows event-path assertion. Shared settings and credentials watchers, plus Cordis module and exact-config HMR, now canonicalize the existing native watch base or deepest existing ancestor before opening the watcher and preserve a missing suffix, while file access and diagnostics retain the configured path. Module HMR attaches listeners and awaits the main watcher's ready event before plugin startup settles, so an immediate post-boot edit cannot race the initial scan. HMR acceptance derives expected identities through the same asynchronous native realpath operation, avoiding a synchronous Windows spelling that can retain the 8.3 alias. diff --git a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.zh.md b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.zh.md index 42db5aa974..8059741925 100644 --- a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.zh.md +++ b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.zh.md @@ -18,9 +18,9 @@ Status: implemented 原生作业被刻意排除在 `all-checks-passed.needs` 之外,且不使用 `continue-on-error`:聚合流程既不等待它,也不会因它改变结论;该作业则保留自身未被掩盖的结果。工作区构建、生产网站和逐文件 100% 覆盖率检查失败会使原生作业失败。静态检查、文档、包、构建产物、lint 与快照清单在同一作业内作为观测性门禁运行;其失败保持可见,但不会改变原生聚合结果,因为这些检查的阻断性判定由 Linux 负责。 -16 核通道最多同时运行 4 道外层门禁。工作区构建与生产网站验证会立即启动。插桩覆盖率与豁免重型覆盖率都等待完整构建:插桩语料包含针对已构建 `lib/` 输出的打包器断言,豁免门禁的临时 Oxlint 约定探针则不得与源码编译竞态。每道观测性门禁只等待两道覆盖率门禁以任意结果结算后再进入可用槽位;各门禁自身的 `needs` 边仍要求前置门禁通过。这也使随后创建临时约定文件的静态门禁不会与任一覆盖率扫描竞态。[job 内分区覆盖率](2026-08-18-in-job-partitioned-coverage.zh.md)使用 8 个单 worker 分片,豁免重型门禁则从 `DSH_COVERAGE_MAX_WORKERS=6` 获得 2 个 worker,因此构建完成后约有 10 个活动覆盖率执行单元。观测性清单启动时,`publint` 最多使用 8 个 worker。每个 Vitest 项目都使用 fork worker,因为 Node 24 的 CJS lexer 致命故障可在 Windows 与 POSIX 的共享 worker 中复现。两项覆盖率门禁都将 Vitest 默认的单测试和轮询时间预算设为 30 秒,因为在完整通道并发的 Windows 插桩下,多个互不相关的进程、Git、SQLite、watcher、语法和静态门禁 fixture(测试前置数据)可能超过 15 秒。SQLite busy-journal 节奏 fixture 会在普通 busy 预算内先注入两次 busy 结果,再返回成功,并观察每次尝试之间的延迟,使 schema 设置的调度时间不进入该断言。translation-pairing 合并套件只导入 `scripts/` 源码和子进程,因此放入豁免重型套件门禁;V8 插桩不会为它贡献任何阈值覆盖率,却会放大 Git 进程延迟。Lefthook 并发 fixture 保留原有结果,采用 30 秒单用例预算与 10 秒进程就绪探测;安装器则允许被抢占的 lock 持有者在独占创建后用 5 秒发布记录。directory-picker 组合为防抖配置写入提供显式的 15 秒轮询预算;workspace-context 组合 fixture 使用测试自有、没有无关 1 秒截止时间的信号。这些只属于该通道的预算保留了原有断言结果,120 分钟的 job 截止时间仍会约束卡死的运行。LSP 源码与 ACL 沙箱源码仍计入 Windows 分母:基于 stub 的失败路径套件把每个进程内 ACL 沙箱文件都带到 100%,只有 runner 入口保持排除——它只作为 spawn 出的子进程在插桩运行之外执行,其行为由 runner 套件端到端钉住。窄范围且带注释的 V8 ignore 只覆盖不可达分支(另一平台专属分支、生命周期内不可达的防御守卫),其行为测试仍保留在所属平台。 +16 核通道最多同时运行 4 道外层门禁。工作区构建与生产网站验证会立即启动。插桩覆盖率与豁免重型覆盖率都等待完整构建:插桩语料包含针对已构建 `lib/` 输出的打包器断言,豁免门禁的临时 Oxlint 约定探针则不得与源码编译竞态。每道观测性门禁只等待两道覆盖率门禁以任意结果结算后再进入可用槽位;各门禁自身的 `needs` 边仍要求前置门禁通过。这也使随后创建临时约定文件的静态门禁不会与任一覆盖率扫描竞态。[job 内分区覆盖率](2026-08-18-in-job-partitioned-coverage.zh.md)使用 4 个单 worker 分片,豁免重型门禁则从 `DSH_COVERAGE_MAX_WORKERS=6` 获得 2 个 worker,因此构建完成后约有 6 个活动覆盖率执行单元。观测性清单启动时,`publint` 最多使用 8 个 worker。每个 Vitest 项目都使用 fork worker,因为 Node 24 的 CJS lexer 致命故障可在 Windows 与 POSIX 的共享 worker 中复现。两项覆盖率门禁都将 Vitest 默认的单测试和轮询时间预算设为 30 秒,因为在完整通道并发的 Windows 插桩下,多个互不相关的进程、Git、SQLite、watcher、语法和静态门禁 fixture(测试前置数据)可能超过 15 秒。SQLite busy-journal 节奏 fixture 会在普通 busy 预算内先注入两次 busy 结果,再返回成功,并观察每次尝试之间的延迟,使 schema 设置的调度时间不进入该断言。translation-pairing 合并套件只导入 `scripts/` 源码和子进程,因此放入豁免重型套件门禁;V8 插桩不会为它贡献任何阈值覆盖率,却会放大 Git 进程延迟。Lefthook 并发 fixture 保留原有结果,采用 30 秒单用例预算与 10 秒进程就绪探测;安装器则允许被抢占的 lock 持有者在独占创建后用 5 秒发布记录。directory-picker 组合为防抖配置写入提供显式的 15 秒轮询预算;workspace-context 组合 fixture 使用测试自有、没有无关 1 秒截止时间的信号。这些只属于该通道的预算保留了原有断言结果,120 分钟的 job 截止时间仍会约束卡死的运行。LSP 源码与 ACL 沙箱源码仍计入 Windows 分母:基于 stub 的失败路径套件把每个进程内 ACL 沙箱文件都带到 100%,只有 runner 入口保持排除——它只作为 spawn 出的子进程在插桩运行之外执行,其行为由 runner 套件端到端钉住。窄范围且带注释的 V8 ignore 只覆盖不可达分支(另一平台专属分支、生命周期内不可达的防御守卫),其行为测试仍保留在所属平台。 -16 核配置是这项清单经实测选定的容量规格。使用 6 个 coverage worker 的试验分别以 6 分 27 秒和 7 分 50 秒跑出完整通过结果,而在单个插桩 Vitest 进程内使用 4 个、3 个和 2 个并发 worker 的分支头精确试验暴露出不稳定的 fixture 与 worker 退出。相互独立的单 worker 子进程保留进程隔离。历史上的 16 分片样本把插桩覆盖率缩短到 112.66–122.01 秒。在当前的构建后拓扑中,16 个插桩分片加 2 个豁免 worker 会在 16 核运行器上调度 18 个覆盖率执行单元,且尚未计入生产网站的尾部工作或系统开销;8 个分片加 2 个豁免 worker 则调度 10 个。8 个分片刻意用部分延迟换取这份余量。32 核对比仅将聚合门禁时间缩短 1.47 秒,且仍在 fork worker 内触发 CJS lexer 致命故障,因此增加核心数没有带来可靠的墙钟时间改善。 +16 核配置是这项清单经实测选定的容量规格。使用 6 个 coverage worker 的试验分别以 6 分 27 秒和 7 分 50 秒跑出完整通过结果,而在单个插桩 Vitest 进程内使用 4 个、3 个和 2 个并发 worker 的分支头精确试验暴露出不稳定的 fixture 与 worker 退出。相互独立的单 worker 子进程保留进程隔离。历史上的 16 分片样本把插桩覆盖率缩短到 112.66–122.01 秒。在当前的构建后拓扑中,16 个插桩分片加 2 个豁免 worker 会在 16 核运行器上调度 18 个覆盖率执行单元,且尚未计入生产网站的尾部工作或系统开销;4 个分片加 2 个豁免 worker 则调度 6 个。4 个分片刻意用部分单 job 延迟换取自托管高并发下更低的进程创建压力。32 核对比仅将聚合门禁时间缩短 1.47 秒,且仍在 fork worker 内触发 CJS lexer 致命故障,因此增加核心数没有带来可靠的墙钟时间改善。 首次原生运行暴露出两项被兼容性通道掩盖的故障。文档投影测试此前只按 `/` 拆分来派生图片 basename;现在改为使用 Node 根据平台计算的 basename。Chokidar 消费方收到的 `%TEMP%` 以 `C:\\Users\\RUNNER~1` 这个 8.3 别名表示,而 libuv 返回的是长目录名,导致其 Windows 事件路径断言失败。共享的设置 watcher 与凭据 watcher,以及 Cordis 的模块 HMR(热模块替换)与精确配置 HMR,现在都会在打开 watcher 前规范化现有的原生监听基准路径或层级最深的现有祖先路径,并保留尚不存在的后缀;文件访问和诊断仍使用配置路径。模块 HMR 会挂接监听器并等待主 watcher 的 ready 事件,之后插件启动才会完成,因此启动后立即发生的编辑无法与初始扫描形成竞态。HMR 验收通过相同的异步原生 realpath 操作派生预期身份,避免同步 Windows 路径写法仍保留 8.3 别名。 From bea14f9fcd5be25df272a7d53415f25ccc9b8059 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Tue, 25 Aug 2026 13:32:23 +0800 Subject: [PATCH 18/31] docs(i18n): re-record translation pairing sidecars after partition update --- .../2026-08-08-native-windows-pull-request-ci.i18n.yaml | 4 ++-- .../process/2026-08-18-in-job-partitioned-coverage.i18n.yaml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.i18n.yaml b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.i18n.yaml index 4526ed12ee..8f6947d232 100644 --- a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.i18n.yaml +++ b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md -2026-08-08-native-windows-pull-request-ci.md: a1a783df2a700eec5436abbb144849629bbecebc -2026-08-08-native-windows-pull-request-ci.zh.md: 42db5aa974c1d1dca6c6151d6c058f39571dcc59 +2026-08-08-native-windows-pull-request-ci.md: 24f1a5fa0c72255f678b837c910eb779445dee27 +2026-08-08-native-windows-pull-request-ci.zh.md: 805974192577b835b565bd42688c574473ac63bf diff --git a/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.i18n.yaml b/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.i18n.yaml index 645326c8f6..70a774f23b 100644 --- a/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.i18n.yaml +++ b/.agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-08-18-in-job-partitioned-coverage.md -2026-08-18-in-job-partitioned-coverage.md: 2cf06f6dd3eb9cdfd563aaa01ecd4ea9b8fb376f -2026-08-18-in-job-partitioned-coverage.zh.md: 266feed66a28833488973db66fbd1f3476bf9ba7 +2026-08-18-in-job-partitioned-coverage.md: 9b8e6308ec746ee9a31465e57f58457130178b85 +2026-08-18-in-job-partitioned-coverage.zh.md: cf4d50996d9ecd4cb14ee762df11ade4aa63dc31 From 5467685bc1307b305962f5aa4086dbf160a5ae48 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 25 Aug 2026 13:35:53 +0800 Subject: [PATCH 19/31] fix(pty): identify waiting thread terminals --- ...26-07-16-persistent-pty-sessions.i18n.yaml | 4 +- .../2026-07-16-persistent-pty-sessions.md | 8 +-- .../2026-07-16-persistent-pty-sessions.zh.md | 8 +-- .../subprocess-local/README.i18n.yaml | 4 +- .../subprocess/subprocess-local/README.md | 2 +- .../subprocess/subprocess-local/README.zh.md | 2 +- .../subprocess-local/src/process-inspector.ts | 62 +++++++++++++---- .../tests/process-inspector.spec.ts | 57 +++++++++++++--- .../terminal-bash/tests/local.spec.ts | 21 ++++++ .../notifications.expected.jsonl | 68 +++++++++++-------- snapshots/sdk/persistent-tools/session.jsonl | 64 +++++++++-------- 11 files changed, 206 insertions(+), 94 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml index 3633aa06be..663a33d56d 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md -2026-07-16-persistent-pty-sessions.md: 44e87390c9a6e4dc97e9466d3113fdd07cd3c500 -2026-07-16-persistent-pty-sessions.zh.md: 0aad7cc409f951c1d36cf543415c6ac1faf143ba +2026-07-16-persistent-pty-sessions.md: b49301aaef6593730c67c3a727e1e82b3ec25379 +2026-07-16-persistent-pty-sessions.zh.md: d98400255a8282b1fa7f529caf85ee03a0fb451a diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md index 44e87390c9..b49301aaef 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md @@ -74,7 +74,7 @@ With `run_in_background: true`, `dsh-tool-terminal` registers the in-flight send The local backend first recognizes a private OSC prompt marker emitted by its controlled bash startup, then requires the printable tail after the latest marker to exactly equal the controlled `PS1` before declaring prompt readiness and runs three bounded fallback tiers. Carrying that tail across data callbacks covers delivery where the marker and prompt arrive separately; requiring the exact tail rejects a delayed earlier prompt once echoed input or output follows it, so it cannot settle the current send. The marker is removed before output reaches the model and avoids a fixed silence delay for ordinary shell commands on both platforms. Unpublished startup does not accept zero-output silence as readiness; timeout rejects the spawn. If caller cancellation wins during startup, the backend closes the private session and propagates the exact `AbortSignal.reason`; a foreground PGID that is not observable yet cannot replace cancellation with a lookup error. All timings are validated config fields: `pollIntervalMs`, `exactProbeAfterMs`, `idleSilenceMs`, `handoffGraceMs`, and `timeoutMs`. -On Linux, the inspector reads the shell's terminal foreground PGID from `/proc//stat`, enumerates every process and thread in that process group, and probes their current syscalls. A positive Tier 1 result requires an observed stdin wait: direct `read(0)`, a permitted read of a `select`/`pselect6` or `poll`/`ppoll` argument containing fd 0, or an epoll interest list containing fd 0. The waiting process's `/proc//fd/0` must also resolve to the terminal shell's fd 0 target, so a pipeline reader blocked on its pipe remains a running command rather than terminal-input readiness. A wait already present before terminal input is not post-write readiness: the same PGID must be observed outside that wait before re-entering it, while a changed foreground PGID is new evidence. Unreadable process memory and unrecognized syscalls are misses, never positive guesses. Architecture tables contain only syscall numbers defined by the corresponding Linux UAPI; unsupported architectures skip Tier 1. +On Linux, the inspector reads the shell's terminal foreground PGID from `/proc//stat`, enumerates every process and thread in that process group, and probes their current syscalls. A positive Tier 1 result requires an observed stdin wait: direct `read(0)`, a permitted read of a `select`/`pselect6` or `poll`/`ppoll` argument containing fd 0, or an epoll interest list containing fd 0. The waiting thread's `/proc//task//fd/0` must identify the shell's controlling terminal device, so a thread-local fd table cannot substitute its leader's terminal descriptor and a pipeline reader blocked on its pipe remains a running command. Direct PTY descriptors use their device number; `/dev/tty` uses the owning process's `tty_nr` because `stat` reports the alias device rather than the selected PTY. A wait already present before terminal input is not post-write readiness: the same PGID must be observed outside that wait before re-entering it, while a changed foreground PGID is new evidence. Unreadable process memory and unrecognized syscalls are misses, never positive guesses. Architecture tables contain only syscall numbers defined by the corresponding Linux UAPI; unsupported architectures skip Tier 1. On macOS there is no exact syscall tier. Output silence returns `inferred_idle` for any foreground process group, including Python and `gdb`; `ps`-derived terminal PGID is used for signaling, not as proof that only the shell can be idle. Pure process-inspector logic is injectable and unit-tested on Linux, while a macOS CI job exercises the real PTY and process-table path. @@ -157,9 +157,9 @@ The package ships concise tool guidance explaining persistent state, owner isola ## Verification - Per-file coverage pins owner fencing, concurrent reservations, cancellation during pre-write inspection, unpublished-spawn cancellation and awaited teardown, sandbox-mode change rejection, retriable lifecycle cleanup, readiness tiers, rejection of pre-write stdin waits and delayed earlier prompts, the configured handoff grace holding the idle fallback past one poll and its rejection below `pollIntervalMs`, sanitizer carry state, complete UTF-8 bounds, task integration, schemas, and exact render intents. -- Subprocess process fixtures cover non-leader and non-main-thread stdin waits, rejection of fd 0 backed by a pipe, zombie quiescence, unreadable process state, supported syscall tables, unsupported architectures, and other false-positive rejection; macOS inspector logic is injected into the same unit suite. -- Real `node-pty` and PTY-consumer tests jointly exercise shell state, shared sandbox policy, environment scrubbing, raw-mode foreground `SIGINT`, a TERM-ignoring descendant, and immediate post-disposal quiescence on supported hosts. -- A Loader-driven `cordis.yml` test mounts the real three-package composition and verifies that delayed pipeline output returns with the completed command instead of being classified as terminal-input readiness. ACP and headless snapshots pin the six schemas, bounded results, and errors through opt-in overlays; TUI snapshots pin terminal and generic card presentation. +- Subprocess process fixtures cover non-leader and non-main-thread stdin waits, thread-local fd tables, the `/dev/tty` alias, rejection of fd 0 backed by a pipe, zombie quiescence, unreadable process state, supported syscall tables, unsupported architectures, and other false-positive rejection; macOS inspector logic is injected into the same unit suite. +- Real `node-pty` and PTY-consumer tests jointly exercise shell state, controlling-terminal input through `/dev/tty`, shared sandbox policy, environment scrubbing, raw-mode foreground `SIGINT`, a TERM-ignoring descendant, and immediate post-disposal quiescence on supported hosts. +- A Loader-driven `cordis.yml` test mounts the real three-package composition and verifies that delayed pipeline output returns with the completed command instead of being classified as terminal-input readiness. The SDK minimal snapshot pins that output through the persistent Bash tool; ACP and headless snapshots pin the six terminal schemas, bounded results, and errors through opt-in overlays; TUI snapshots pin terminal and generic card presentation. - Package contracts, the architecture map, subsystem pages, generated catalogs, and the website API describe the same shipped surface. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md index 0aad7cc409..d98400255a 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md @@ -74,7 +74,7 @@ UI 渲染约定精确且不携带位置信息。`terminal_send` 只为前台发 本地后端先识别受控 bash 启动时发出的私有 OSC prompt marker,并且只有在最近一个 marker 后的可打印尾部与受控 `PS1` 完全相等时才声明 prompt 就绪;除此之外,它还运行 3 个有界 fallback 层级。在 data callback 之间保留该尾部,可以适配 marker 与 prompt 被分开交付的情况;如果回显的输入或输出跟在延迟到达的先前 prompt 之后,要求尾部完全相等会拒绝该 prompt,使其无法完成当前 send。marker 在输出到达模型前被移除,使两个平台上的普通 shell 命令都无需固定等待静默阈值。尚未发布的 startup 不会把零输出静默视为就绪;timeout 会拒绝 spawn。若调用方取消在 startup 期间胜出,后端会关闭私有会话并原样抛出 `AbortSignal.reason`;尚不可观察的前台 PGID 不会再用查找错误覆盖取消原因。所有时间参数都是经校验的配置字段:`pollIntervalMs`、`exactProbeAfterMs`、`idleSilenceMs`、`handoffGraceMs` 和 `timeoutMs`。 -在 Linux 上,检查器从 `/proc//stat` 读取 shell 的终端前台 PGID,枚举该进程组中的每个进程与线程,并检查它们当前的 syscall。Tier 1 只有观察到 stdin 等待才返回正结果:直接 `read(0)`、获准读取且含 fd 0 的 `select`/`pselect6` 或 `poll`/`ppoll` 参数,或者含 fd 0 的 epoll interest list。等待进程的 `/proc//fd/0` 还必须与终端 shell 的 fd 0 解析到同一目标,因此阻塞于管道的流水线读取端仍属于正在运行的命令,不构成终端输入就绪。终端输入前就已存在的等待并不代表写入后就绪:必须先观察到同一 PGID 脱离该等待,之后再次进入等待才能使该次 send 完成;前台 PGID 发生变化则构成新的证据。无法读取的进程内存和未识别的 syscall 都是 miss,绝不作为正向猜测。架构表只包含对应 Linux UAPI 定义的 syscall number;不支持的架构跳过 Tier 1。 +在 Linux 上,检查器从 `/proc//stat` 读取 shell 的终端前台 PGID,枚举该进程组中的每个进程与线程,并检查它们当前的 syscall。Tier 1 只有观察到 stdin 等待才返回正结果:直接 `read(0)`、获准读取且含 fd 0 的 `select`/`pselect6` 或 `poll`/`ppoll` 参数,或者含 fd 0 的 epoll interest list。等待线程的 `/proc//task//fd/0` 还必须标识 shell 的控制终端设备,因此线程本地 fd 表无法用 leader 的终端描述符冒充自身 fd,阻塞于管道的流水线读取端仍属于正在运行的命令。直接 PTY 描述符使用其设备号;`/dev/tty` 则使用所属进程的 `tty_nr`,因为 `stat` 报告的是别名设备而非选定的 PTY。终端输入前就已存在的等待并不代表写入后就绪:必须先观察到同一 PGID 脱离该等待,之后再次进入等待才能使该次 send 完成;前台 PGID 发生变化则构成新的证据。无法读取的进程内存和未识别的 syscall 都是 miss,绝不作为正向猜测。架构表只包含对应 Linux UAPI 定义的 syscall number;不支持的架构跳过 Tier 1。 macOS 没有精确 syscall 层。任何前台进程组输出静默都会返回 `inferred_idle`,包括 Python 和 `gdb`;从 `ps` 推导的终端 PGID 只用于发送信号,不作为「只有 shell 才能 idle」的证明。纯进程检查逻辑可注入,并在 Linux 上经过单元测试,同时由 macOS CI job 驱动真实 PTY 和进程表路径。 @@ -157,9 +157,9 @@ plugins: ## 验证 - 逐文件覆盖测试锁定了 owner 隔离、并发预留、写入前检查期间的取消、未发布 spawn 的取消与等待式 teardown、沙箱模式变更拒绝、可重试的生命周期清理、就绪层级、对写入前 stdin 等待与延迟到达的先前 prompt 的拒绝、配置化交接宽限把 idle fallback 顶过一次轮询以及低于 `pollIntervalMs` 时的拒绝、sanitizer carry state、完整 UTF-8 结果上限、task 集成、schema 和精确 render intent。 -- 子进程 fixture(测试前置数据)覆盖非 leader 与非主线程的 stdin 等待、拒绝把指向管道的 fd 0 当作终端输入、僵尸进程完全停稳、不可读进程状态、受支持的 syscall 表、不支持的架构和其他误报拒绝;同一单元测试套件通过注入覆盖 macOS 检查器逻辑。 -- 真实 `node-pty` 与 PTY 消费方测试共同在受支持宿主上覆盖 shell 状态、共享沙箱策略、环境清洗、raw mode 前台 `SIGINT`、忽略 `SIGTERM` 的后代进程,以及 dispose 返回后立即完全停稳。 -- Loader 驱动的 `cordis.yml` 测试挂载真实三包组合,并验证延迟到达的流水线输出随已完成命令返回,而不会被归类为终端输入就绪。ACP 与 headless 快照通过 opt-in overlay 固定 6 个 schema、有界结果和错误;TUI 快照固定 terminal 与 generic 卡片展示。 +- 子进程 fixture(测试前置数据)覆盖非 leader 与非主线程的 stdin 等待、线程本地 fd 表、`/dev/tty` 别名、拒绝把指向管道的 fd 0 当作终端输入、僵尸进程完全停稳、不可读进程状态、受支持的 syscall 表、不支持的架构和其他误报拒绝;同一单元测试套件通过注入覆盖 macOS 检查器逻辑。 +- 真实 `node-pty` 与 PTY 消费方测试共同在受支持宿主上覆盖 shell 状态、通过 `/dev/tty` 读取控制终端输入、共享沙箱策略、环境清洗、raw mode 前台 `SIGINT`、忽略 `SIGTERM` 的后代进程,以及 dispose 返回后立即完全停稳。 +- Loader 驱动的 `cordis.yml` 测试挂载真实三包组合,并验证延迟到达的流水线输出随已完成命令返回,而不会被归类为终端输入就绪。SDK minimal 快照通过持久 Bash 工具固定该输出;ACP 与 headless 快照通过 opt-in overlay 固定 6 个终端 schema、有界结果和错误;TUI 快照固定 terminal 与 generic 卡片展示。 - 包约定、架构图、子系统页面、生成目录和 website API 描述同一个已发布接口。 ## 后果 diff --git a/packages/subprocess/subprocess-local/README.i18n.yaml b/packages/subprocess/subprocess-local/README.i18n.yaml index 229008e146..5b25e04c1e 100644 --- a/packages/subprocess/subprocess-local/README.i18n.yaml +++ b/packages/subprocess/subprocess-local/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subprocess/subprocess-local/README.md -README.md: 26b23f1e0b9a7efee9a2f20f259c69a832e64d53 -README.zh.md: 797eda99fc131eff93c2eaaf87603588a01b3067 +README.md: deea6b6b291d684c4d3a31bee562a0d99e90cb65 +README.zh.md: be4396df4b85d3a18c5236bc835b50dfd26e5f19 diff --git a/packages/subprocess/subprocess-local/README.md b/packages/subprocess/subprocess-local/README.md index 26b23f1e0b..deea6b6b29 100644 --- a/packages/subprocess/subprocess-local/README.md +++ b/packages/subprocess/subprocess-local/README.md @@ -11,7 +11,7 @@ Local Service Provider for the [`@deepseek-ai/dsh-subprocess`](../subprocess/REA - **Credential scrub + explicit merge** — `process.env` minus credential-shaped vars (`*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`) and all ambient `DSH_*` names; the spec's explicit `env` merges after that scrub with no namespace validation, so a deliberately supplied credential or current `DSH_*` fact wins while stale nested-harness identity cannot leak in ambiently. Supplied stdin is written and closed; otherwise fd 0 is `/dev/null`. See the [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.md) and [managed environment Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md). - **Offset-based reads** — collect-mode readers return deltas in whole-stream byte coordinates; the service never holds a cursor, so consumer-owned cursors (the bash background read path) and full-stream re-reads coexist, before and after settlement. - **Executable lookup** — `resolveExecutable` checks absolute files or searches the scrubbed effective PATH with platform-aware executable extensions; relative paths containing separators are rejected at the seam, and relative PATH entries resolve from the host process cwd. -- **Terminal-process ownership** — `spawnTerminal` allocates `node-pty`, bridges UTF-8 terminal text, inspects and signals the current foreground process group, and exposes one awaited termination operation that sweeps descendants before and after terminating the top-level shell. Linux reports an exact input wait only when the waiting process's fd 0 resolves to the terminal shell's fd 0 target, so a pipeline reader blocked on `pipe:[…]` cannot publish terminal readiness. Each foreground inspection retains exact identities from the rooted tree; Linux also enumerates the POSIX session after its leader exits. A previously observed macOS descendant and any same-session Linux member therefore remain fenced after reparenting, while pid/start identity prevents cleanup from following PID reuse. On Windows the koffi-backed inspector enumerates the process table through Toolhelp32, combines GetProcessTimes start identities with zero-time process-handle waits for liveness, reports the shell pid as the pseudo foreground group (Windows has no POSIX groups), and teardown verifies the shell's termination because externally taskkilled shells may never fire node-pty's exit notification. The higher PTY backend owns prompt readiness, buffers, and model-facing operations. +- **Terminal-process ownership** — `spawnTerminal` allocates `node-pty`, bridges UTF-8 terminal text, inspects and signals the current foreground process group, and exposes one awaited termination operation that sweeps descendants before and after terminating the top-level shell. Linux reports an exact input wait only when the waiting thread's own fd 0 identifies the shell's controlling terminal, including the `/dev/tty` alias, so a pipeline reader blocked on `pipe:[…]` cannot publish terminal readiness. Each foreground inspection retains exact identities from the rooted tree; Linux also enumerates the POSIX session after its leader exits. A previously observed macOS descendant and any same-session Linux member therefore remain fenced after reparenting, while pid/start identity prevents cleanup from following PID reuse. On Windows the koffi-backed inspector enumerates the process table through Toolhelp32, combines GetProcessTimes start identities with zero-time process-handle waits for liveness, reports the shell pid as the pseudo foreground group (Windows has no POSIX groups), and teardown verifies the shell's termination because externally taskkilled shells may never fire node-pty's exit notification. The higher PTY backend owns prompt readiness, buffers, and model-facing operations. - **Terminate-and-join disposal** — the service retains live handles so its own disposal can escalate every running tree and await its exit; quiescent and spawn-failed handles leave the live set after whole-tree or terminal-session cleanup finishes. - **Synchronous host-exit finalization** — while the service effect is active, a Node `exit` listener force-terminates every ordinary tree and observable terminal session still in the same live sets. The local-only operations send POSIX SIGKILL to the managed group, run Windows `taskkill /T /F`, and synchronously signal captured/current terminal identities around the PTY root kill; they create no promise or timer, preserve the host's exit code and diagnostic, contain each target's failure, and do not claim quiescence. Normal disposal keeps the awaited graceful path above. See the [host-exit cleanup decision](../../../.agents/notes/implemented/bug-fix/2026-08-11-synchronous-subprocess-exit-cleanup.md). diff --git a/packages/subprocess/subprocess-local/README.zh.md b/packages/subprocess/subprocess-local/README.zh.md index 797eda99fc..be4396df4b 100644 --- a/packages/subprocess/subprocess-local/README.zh.md +++ b/packages/subprocess/subprocess-local/README.zh.md @@ -11,7 +11,7 @@ - **凭据清除 + 显式合并**:以 `process.env` 为基础,移除形似凭据的变量(`*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`)和所有环境中已有的 `DSH_*` 名称;spec 的显式 `env` 在该清除之后合并且不做命名空间校验,因此有意提供的凭据或当前 `DSH_*` 事实会胜出,而陈旧的嵌套 harness 身份无法从环境中隐式漏入。提供的 stdin 会被写入后关闭;否则 fd 0 指向 `/dev/null`。参见 [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.zh.md)与[受管环境 Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.zh.md)。 - **基于偏移量的读取**:收集模式的读取器按完整流的字节坐标返回增量;服务自身从不持有游标,因此消费方自有的游标(bash 的后台读取路径)与完整流重读可以共存,结算前后皆然。 - **可执行文件查找**:`resolveExecutable` 检查绝对文件,或根据平台可执行文件扩展名在清理后的有效 PATH 中搜索;含分隔符的相对路径在该 seam 处被拒绝,相对 PATH 条目从宿主进程 cwd 解析。 -- **终端进程所有权**:`spawnTerminal` 分配 `node-pty`,桥接 UTF-8 终端文本,检查当前前台进程组并向其发送信号,还会公开一项须等待的终止操作,在终止顶层 shell 前后清理后代进程。Linux 只有在等待进程的 fd 0 与终端 shell 的 fd 0 解析到同一目标时才报告精确输入等待,因此阻塞于 `pipe:[…]` 的流水线读取端无法发布终端就绪状态。每次前台检查都会保留根进程树中的精确身份;Linux 还会在 POSIX 会话 leader 退出后枚举该会话。因此,之前观察到的 macOS 后代以及同会话 Linux 成员在重新设定父进程后仍受围栏保护,pid/start 身份则防止清理跟随 PID 复用。在 Windows 上,基于 koffi 的检查器通过 Toolhelp32 枚举进程表,把 GetProcessTimes 启动身份与进程句柄零时等待结合起来判断存活状态,并把 shell pid 作为伪前台进程组(Windows 没有 POSIX 进程组)。拆卸会验证 shell 已终止,因为被外部 taskkill 的 shell 可能永远不会触发 node-pty 的退出通知。上层 PTY 后端负责提示符就绪、缓冲区与面向模型的操作。 +- **终端进程所有权**:`spawnTerminal` 分配 `node-pty`,桥接 UTF-8 终端文本,检查当前前台进程组并向其发送信号,还会公开一项须等待的终止操作,在终止顶层 shell 前后清理后代进程。Linux 只有在等待线程自身的 fd 0 标识 shell 的控制终端(包括 `/dev/tty` 别名)时才报告精确输入等待,因此阻塞于 `pipe:[…]` 的流水线读取端无法发布终端就绪状态。每次前台检查都会保留根进程树中的精确身份;Linux 还会在 POSIX 会话 leader 退出后枚举该会话。因此,之前观察到的 macOS 后代以及同会话 Linux 成员在重新设定父进程后仍受围栏保护,pid/start 身份则防止清理跟随 PID 复用。在 Windows 上,基于 koffi 的检查器通过 Toolhelp32 枚举进程表,把 GetProcessTimes 启动身份与进程句柄零时等待结合起来判断存活状态,并把 shell pid 作为伪前台进程组(Windows 没有 POSIX 进程组)。拆卸会验证 shell 已终止,因为被外部 taskkill 的 shell 可能永远不会触发 node-pty 的退出通知。上层 PTY 后端负责提示符就绪、缓冲区与面向模型的操作。 - **先终止再等待退出的 dispose(资源释放)**:服务保留存活句柄,使自身的 dispose 能对每个仍在运行的进程树执行升级并等待其退出;完全停稳与 spawn 失败的句柄会在整棵进程树或 terminal session 清理完成后离开存活集合。 - **同步宿主退出最终清理**:服务 effect 仍有效时,Node `exit` listener 会强制终止同一组存活集合中仍存在的每棵普通进程树和可观察 terminal session。这些仅供本地实现使用的操作会向受管 POSIX 进程组发送 SIGKILL、在 Windows 运行 `taskkill /T /F`,并在终止 PTY root 前后同步向已捕获及当前可观察的 terminal 身份发送信号;它们不会创建 Promise 或 timer,不改变宿主退出码与诊断,会分别包含每个目标的失败,也不会声称已经完全停稳。正常 dispose 仍使用上面的须等待温和路径。参见[宿主退出清理决策](../../../.agents/notes/implemented/bug-fix/2026-08-11-synchronous-subprocess-exit-cleanup.zh.md)。 diff --git a/packages/subprocess/subprocess-local/src/process-inspector.ts b/packages/subprocess/subprocess-local/src/process-inspector.ts index 05b775e5ef..e13ced066f 100644 --- a/packages/subprocess/subprocess-local/src/process-inspector.ts +++ b/packages/subprocess/subprocess-local/src/process-inspector.ts @@ -1,6 +1,6 @@ /** Platform process-table inspection for terminal readiness, signals, and teardown. */ -import { closeSync, openSync, readFileSync, readdirSync, readlinkSync, readSync } from 'node:fs' +import { closeSync, openSync, readFileSync, readdirSync, readlinkSync, readSync, statSync } from 'node:fs' import { execFileSync } from 'node:child_process' import type { SubprocessTerminalSignal } from '@deepseek-ai/dsh-subprocess' import { createWindowsProcessInspector } from './windows-inspector.ts' @@ -11,6 +11,11 @@ export interface ProcessIdentity { started: string } +interface FileStatus { + readonly rdev: number + isCharacterDevice(): boolean +} + /** Injectable OS process operations used by one local PTY session. */ export interface ProcessInspector { foregroundPgid(shellPid: number): number | undefined @@ -37,6 +42,7 @@ export interface ProcessInspectorInternals { readFile(path: string): string readDir(path: string): string[] readLink(path: string): string + stat(path: string): FileStatus open(path: string): number read(fd: number, buffer: Buffer, length: number, position: number): number close(fd: number): void @@ -49,6 +55,7 @@ const DEFAULT_INTERNALS: ProcessInspectorInternals = { readFile: path => readFileSync(path, 'utf8'), readDir: path => readdirSync(path), readLink: path => readlinkSync(path, 'utf8'), + stat: path => statSync(path), open: path => openSync(path, 'r'), read: (fd, buffer, length, position) => readSync(fd, buffer, 0, length, position), close: closeSync, @@ -63,6 +70,7 @@ interface ProcStat { pgrp: number session: number state: string + ttyDevice: number tpgid: number started: string } @@ -82,11 +90,12 @@ export function parseProcStat(text: string): ProcStat | undefined { const parentPid = Number(rest[1]) const pgrp = Number(rest[2]) const session = Number(rest[3]) + const ttyDevice = Number(rest[4]) const tpgid = Number(rest[5]) const started = rest[19] - if (![pid, parentPid, pgrp, session, tpgid].every(Number.isSafeInteger) + if (![pid, parentPid, pgrp, session, ttyDevice, tpgid].every(Number.isSafeInteger) || state.length !== 1 || started === undefined) return undefined - return { pid, parentPid, pgrp, session, state, tpgid, started } + return { pid, parentPid, pgrp, session, state, ttyDevice, tpgid, started } } function readLinuxStat(internals: ProcessInspectorInternals, pid: number): ProcStat | undefined { @@ -97,10 +106,31 @@ function readLinuxStat(internals: ProcessInspectorInternals, pid: number): ProcS } } -function readLinuxStdinTarget(internals: ProcessInspectorInternals, pid: number): string | undefined { +// `/proc//stat` renders tty_nr as a signed 32-bit device number, while +// Node exposes the same st_rdev bits as a nonnegative number. +function linuxDeviceNumber(value: number): number { + return value >>> 0 +} + +// `/dev/tty` reports the alias device instead of the selected PTY through stat, +// so its owning process's tty_nr is the only comparable terminal identity. +function readLinuxTerminalDevice( + internals: ProcessInspectorInternals, + pid: number, + ttyDevice: number, + tid?: number, +): number | undefined { + const terminalDevice = linuxDeviceNumber(ttyDevice) + if (terminalDevice === 0) return undefined + const path = tid === undefined ? `/proc/${pid}/fd/0` : `/proc/${pid}/task/${tid}/fd/0` try { - return internals.readLink(`/proc/${pid}/fd/0`) - } catch (_unreadableStdinTarget) { + const target = internals.readLink(path) + if (target === '/dev/tty') return terminalDevice + const status = internals.stat(path) + return status.isCharacterDevice() && linuxDeviceNumber(status.rdev) === terminalDevice + ? terminalDevice + : undefined + } catch (_unreadableStdinDevice) { return undefined } } @@ -199,9 +229,9 @@ function pollHasStdin( return false } -function epollHasStdin(internals: ProcessInspectorInternals, pid: number, epfd: number): boolean { +function epollHasStdin(internals: ProcessInspectorInternals, pid: number, tid: number, epfd: number): boolean { try { - return internals.readFile(`/proc/${pid}/fdinfo/${epfd}`) + return internals.readFile(`/proc/${pid}/task/${tid}/fdinfo/${epfd}`) .split('\n') .some(line => /^tfd:\s+0\b/.test(line.trim())) } catch (_unreadableFdInfo) { @@ -227,6 +257,7 @@ const SYSCALLS: Partial> = { function syscallWaitsOnStdin( internals: ProcessInspectorInternals, pid: number, + tid: number, syscall: SyscallInfo, table: SyscallTable, ): boolean { @@ -239,7 +270,7 @@ function syscallWaitsOnStdin( return a1 >= 1 && pollHasStdin(internals, pid, a0, a1) } if (syscall.number === table.epollWait || syscall.number === table.epollPwait) { - return a2 >= 1 && epollHasStdin(internals, pid, a0) + return a2 >= 1 && epollHasStdin(internals, pid, tid, a0) } return false } @@ -304,15 +335,18 @@ class LinuxProcessInspector extends PosixProcessInspector { isStdinWaiting(pgid: number, shellPid: number): boolean { const table = SYSCALLS[this.arch] if (table === undefined) return false - const terminalStdinTarget = readLinuxStdinTarget(this.internals, shellPid) - if (terminalStdinTarget === undefined) return false + const shell = readLinuxStat(this.internals, shellPid) + if (shell === undefined) return false + const terminalDevice = readLinuxTerminalDevice(this.internals, shellPid, shell.ttyDevice) + if (terminalDevice === undefined) return false for (const pid of numericEntries(this.internals, '/proc')) { - if (readLinuxStat(this.internals, pid)?.pgrp !== pgid) continue + const process = readLinuxStat(this.internals, pid) + if (process?.pgrp !== pgid) continue for (const tid of numericEntries(this.internals, `/proc/${pid}/task`)) { const syscall = readSyscall(this.internals, pid, tid) if (syscall !== undefined - && syscallWaitsOnStdin(this.internals, pid, syscall, table) - && readLinuxStdinTarget(this.internals, pid) === terminalStdinTarget) return true + && syscallWaitsOnStdin(this.internals, pid, tid, syscall, table) + && readLinuxTerminalDevice(this.internals, pid, process.ttyDevice, tid) === terminalDevice) return true } } return false diff --git a/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts b/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts index 5115db1233..a56167bb4d 100644 --- a/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts +++ b/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts @@ -7,8 +7,17 @@ import { import type { ProcessInspectorInternals } from '@deepseek-ai/dsh-subprocess-local/src/process-inspector.ts' import { WindowsProcessInspector } from '@deepseek-ai/dsh-subprocess-local/src/windows-inspector.ts' -function stat(pid: number, pgrp: number, session: number, tpgid: number, started: string, parentPid = 1, state = 'S'): string { - const rest = [state, String(parentPid), String(pgrp), String(session), '99', String(tpgid)] +function stat( + pid: number, + pgrp: number, + session: number, + tpgid: number, + started: string, + parentPid = 1, + state = 'S', + ttyDevice = 99, +): string { + const rest = [state, String(parentPid), String(pgrp), String(session), String(ttyDevice), String(tpgid)] while (rest.length < 19) rest.push('0') rest.push(started) return `${pid} (command with space) ${rest.join(' ')}` @@ -24,6 +33,7 @@ function fakeInternals() { const files = new Map() const dirs = new Map() const links = new Map() + const devices = new Map() const memories = new Map() const fds = new Map() const kills: Array<[number, NodeJS.Signals]> = [] @@ -46,6 +56,11 @@ function fakeInternals() { if (value === undefined) throw new Error(`missing ${path}`) return value }, + stat(path) { + const value = devices.get(path) + if (value === undefined) throw new Error(`missing ${path}`) + return { rdev: value.rdev, isCharacterDevice: () => value.character } + }, open(path) { if (!memories.has(path)) throw new Error(`missing ${path}`) const fd = nextFd++ @@ -67,7 +82,7 @@ function fakeInternals() { kill(pid, signal) { kills.push([pid, signal]) }, } return { - internals, files, dirs, links, memories, kills, + internals, files, dirs, links, devices, memories, kills, setPs(value: string) { ps = value }, setTpgid(value: string) { tpgid = value }, } @@ -94,7 +109,7 @@ describe('Linux process inspector', () => { expect(parseProcStat('1 () ')).toBeUndefined() expect(parseProcStat('1 () S')).toBeUndefined() expect(parseProcStat(stat(10, 20, 30, 40, '500', 1, 'SS'))).toBeUndefined() - expect(parseProcStat(stat(10, 20, 30, 40, '500'))).toEqual({ pid: 10, parentPid: 1, pgrp: 20, session: 30, state: 'S', tpgid: 40, started: '500' }) + expect(parseProcStat(stat(10, 20, 30, 40, '500'))).toEqual({ pid: 10, parentPid: 1, pgrp: 20, session: 30, state: 'S', ttyDevice: 99, tpgid: 40, started: '500' }) const fake = fakeInternals() fake.dirs.set('/proc', ['x', '10', '11', '12', '13', '14']) @@ -139,7 +154,9 @@ describe('Linux process inspector', () => { fake.dirs.set('/proc/100/task', ['100']) fake.dirs.set('/proc/101/task', ['101', '102']) fake.links.set('/proc/100/fd/0', '/dev/pts/1') - fake.links.set('/proc/101/fd/0', '/dev/pts/1') + fake.devices.set('/proc/100/fd/0', { character: true, rdev: 99 }) + fake.links.set('/proc/101/task/102/fd/0', '/dev/pts/1') + fake.devices.set('/proc/101/task/102/fd/0', { character: true, rdev: 99 }) const inspector = createProcessInspector('linux', 'x64', fake.internals) fake.files.set('/proc/100/task/100/syscall', 'running') @@ -161,25 +178,33 @@ describe('Linux process inspector', () => { expect(inspector.isStdinWaiting(77, 100)).toBe(true) fake.files.set('/proc/101/task/102/syscall', syscall(232, 5, 0, 1)) - fake.files.set('/proc/101/fdinfo/5', 'pos: 0\ntfd: 0 events: 19\n') + fake.files.set('/proc/101/task/102/fdinfo/5', 'pos: 0\ntfd: 0 events: 19\n') expect(inspector.isStdinWaiting(77, 100)).toBe(true) }) - it('rejects pipeline reads whose fd 0 is not the terminal input', () => { + it('uses the waiting thread fd table and recognizes the controlling-terminal alias', () => { const fake = fakeInternals() fake.dirs.set('/proc', ['100']) + fake.files.set('/proc/99/stat', stat(99, 99, 99, 77, '0')) fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1')) fake.dirs.set('/proc/100/task', ['100']) fake.files.set('/proc/100/task/100/syscall', syscall(0, 0)) fake.links.set('/proc/99/fd/0', '/dev/pts/1') - fake.links.set('/proc/100/fd/0', 'pipe:[123]') + fake.devices.set('/proc/99/fd/0', { character: true, rdev: 99 }) + fake.links.set('/proc/100/fd/0', '/dev/pts/1') + fake.devices.set('/proc/100/fd/0', { character: true, rdev: 99 }) + fake.links.set('/proc/100/task/100/fd/0', 'pipe:[123]') + fake.devices.set('/proc/100/task/100/fd/0', { character: false, rdev: 0 }) const inspector = createProcessInspector('linux', 'x64', fake.internals) expect(inspector.isStdinWaiting(77, 99)).toBe(false) - fake.links.delete('/proc/100/fd/0') + fake.links.delete('/proc/100/task/100/fd/0') expect(inspector.isStdinWaiting(77, 99)).toBe(false) - fake.links.set('/proc/100/fd/0', '/dev/pts/1') + fake.links.set('/proc/100/task/100/fd/0', '/dev/tty') expect(inspector.isStdinWaiting(77, 99)).toBe(true) + fake.links.set('/proc/100/task/100/fd/0', '/dev/pts/2') + fake.devices.set('/proc/100/task/100/fd/0', { character: true, rdev: 100 }) + expect(inspector.isStdinWaiting(77, 99)).toBe(false) }) it('fails closed on unsupported, malformed, unreadable, or non-stdin waits', () => { @@ -188,6 +213,9 @@ describe('Linux process inspector', () => { fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1')) fake.dirs.set('/proc/100/task', ['100']) fake.links.set('/proc/100/fd/0', '/dev/pts/1') + fake.devices.set('/proc/100/fd/0', { character: true, rdev: 99 }) + fake.links.set('/proc/100/task/100/fd/0', '/dev/pts/1') + fake.devices.set('/proc/100/task/100/fd/0', { character: true, rdev: 99 }) fake.files.set('/proc/100/task/100/syscall', syscall(0, 2)) expect(createProcessInspector('linux', 'mips', fake.internals).isStdinWaiting(77, 100)).toBe(false) expect(createProcessInspector('linux', 'x64', fake.internals).isStdinWaiting(77, 100)).toBe(false) @@ -220,9 +248,18 @@ describe('Linux process inspector', () => { fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1')) fake.dirs.set('/proc/100/task', ['100']) const inspector = createProcessInspector('linux', 'x64', fake.internals) + fake.files.delete('/proc/100/stat') + expect(inspector.isStdinWaiting(77, 100)).toBe(false) + fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1', 1, 'S', 0)) + expect(inspector.isStdinWaiting(77, 100)).toBe(false) + fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1')) expect(inspector.isStdinWaiting(77, 100)).toBe(false) fake.links.set('/proc/100/fd/0', '/dev/pts/1') expect(inspector.isStdinWaiting(77, 100)).toBe(false) + fake.devices.set('/proc/100/fd/0', { character: true, rdev: 99 }) + fake.links.set('/proc/100/task/100/fd/0', '/dev/pts/1') + fake.devices.set('/proc/100/task/100/fd/0', { character: true, rdev: 99 }) + expect(inspector.isStdinWaiting(77, 100)).toBe(false) fake.files.set('/proc/100/task/100/syscall', syscall(270, 1, 0x10)) expect(inspector.isStdinWaiting(77, 100)).toBe(false) diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index ed1b6ab15d..4a90049997 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -163,6 +163,27 @@ describe.skipIf(process.platform === 'win32')('terminal-bash real shell', () => await ctx.terminals.kill(agent, created.sessionId) }, 20_000) + it.skipIf(process.platform !== 'linux')('recognizes a foreground read opened through /dev/tty', async () => { + const { ctx, agent } = await harness('danger-full-access', { + idleSilenceMs: 5_000, + timeoutMs: 8_000, + }) + const created = await ctx.terminals.spawn(agent, { type: 'shell' }) + + const waiting = ctx.terminals.startSend(agent, created.sessionId, { + text: 'bash -c \'exec { const { ctx, root, agent, fiber, sandbox } = await harness('workspace-write') const created = await ctx.terminals.spawn(agent, { type: 'shell' }) diff --git a/snapshots/sdk/persistent-tools/notifications.expected.jsonl b/snapshots/sdk/persistent-tools/notifications.expected.jsonl index abb7e0307d..3b8e08a361 100644 --- a/snapshots/sdk/persistent-tools/notifications.expected.jsonl +++ b/snapshots/sdk/persistent-tools/notifications.expected.jsonl @@ -1,9 +1,9 @@ -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":0,"time":0,"data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Prove that bash state persists. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":0,"time":0,"data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Prove that bash state persists. After the persistence checks, run exactly `{ sleep 0.1; echo delayed; } | cat` as its own bash call and observe `delayed`. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}}} {"method":"session.status","params":{"sessionId":"{{sessionId}}","status":"running"}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"turn/start","seq":1,"time":0,"data":{"turn":1}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":2,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":3,"time":0,"data":{"turn":1,"step":1}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":4,"time":0,"data":{"content":[{"type":"text","text":"Prove that bash state persists. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":4,"time":0,"data":{"content":[{"type":"text","text":"Prove that bash state persists. After the persistence checks, run exactly `{ sleep 0.1; echo delayed; } | cat` as its own bash call and observe `delayed`. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":5,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"session/title","seq":6,"time":0,"data":{"title":"Prove that bash state persists.","messageSeqs":[4],"source":{"kind":"fallback"}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":7,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}}}} @@ -29,51 +29,61 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":27,"time":0,"data":{"turn":1,"step":2}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":28,"time":0,"data":{"turn":1,"step":3}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":29,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":30,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-create","name":"str_replace_editor","argumentsDelta":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":31,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":30,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"bash-delayed-pipeline","name":"bash","argumentsDelta":"{\"command\":\"{ sleep 0.1; echo delayed; } | cat\"}"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":31,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"bash-delayed-pipeline","name":"bash","arguments":"{\"command\":\"{ sleep 0.1; echo delayed; } | cat\"}"}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":32,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":33,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":34,"time":0,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[29,30,31,32,33],"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":35,"time":0,"data":{"turn":1,"step":3,"callId":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":36,"time":0,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"editor-create"},"content":[{"type":"tool-result","toolCallId":"editor-create","content":[{"type":"text","text":"New file created successfully at: {{cwd}}/note.txt"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":34,"time":0,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"bash-delayed-pipeline","name":"bash","arguments":"{\"command\":\"{ sleep 0.1; echo delayed; } | cat\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[29,30,31,32,33],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":35,"time":0,"data":{"turn":1,"step":3,"callId":"bash-delayed-pipeline","name":"bash","arguments":"{\"command\":\"{ sleep 0.1; echo delayed; } | cat\"}"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":36,"time":0,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"bash-delayed-pipeline"},"content":[{"type":"tool-result","toolCallId":"bash-delayed-pipeline","content":[{"type":"text","text":"delayed"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":37,"time":0,"data":{"turn":1,"step":3}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":38,"time":0,"data":{"turn":1,"step":4}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":39,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":40,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-view","name":"str_replace_editor","argumentsDelta":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":41,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":40,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-create","name":"str_replace_editor","argumentsDelta":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":41,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":42,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":43,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":44,"time":0,"data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[39,40,41,42,43],"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":45,"time":0,"data":{"turn":1,"step":4,"callId":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":46,"time":0,"data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"editor-view"},"content":[{"type":"tool-result","toolCallId":"editor-view","content":[{"type":"text","text":"Here's the content of {{cwd}}/note.txt with line numbers (which has a total of 3 lines):\n 1 target:\n 2 \told\n 3 \n"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[45],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":44,"time":0,"data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[39,40,41,42,43],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":45,"time":0,"data":{"turn":1,"step":4,"callId":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":46,"time":0,"data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"editor-create"},"content":[{"type":"tool-result","toolCallId":"editor-create","content":[{"type":"text","text":"New file created successfully at: {{cwd}}/note.txt"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[45],"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":47,"time":0,"data":{"turn":1,"step":4}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":48,"time":0,"data":{"turn":1,"step":5}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":49,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":50,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-replace","name":"str_replace_editor","argumentsDelta":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":51,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":50,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-view","name":"str_replace_editor","argumentsDelta":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":51,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":52,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":53,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":54,"time":0,"data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[49,50,51,52,53],"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":55,"time":0,"data":{"turn":1,"step":5,"callId":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":56,"time":0,"data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"editor-replace"},"content":[{"type":"tool-result","toolCallId":"editor-replace","content":[{"type":"text","text":"The file {{cwd}}/note.txt has been edited successfully."}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[55],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":54,"time":0,"data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[49,50,51,52,53],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":55,"time":0,"data":{"turn":1,"step":5,"callId":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":56,"time":0,"data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"editor-view"},"content":[{"type":"tool-result","toolCallId":"editor-view","content":[{"type":"text","text":"Here's the content of {{cwd}}/note.txt with line numbers (which has a total of 3 lines):\n 1 target:\n 2 \told\n 3 \n"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[55],"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":57,"time":0,"data":{"turn":1,"step":5}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":58,"time":0,"data":{"turn":1,"step":6}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":59,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":60,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"tool-call-delta","index":0,"id":"bash-exit","name":"bash","argumentsDelta":"{\"command\":\"exit 9\"}"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":61,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":60,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-replace","name":"str_replace_editor","argumentsDelta":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":61,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":62,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":63,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":64,"time":0,"data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[59,60,61,62,63],"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":65,"time":0,"data":{"turn":1,"step":6,"callId":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":66,"time":0,"data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"bash-exit"},"content":[{"type":"tool-result","toolCallId":"bash-exit","content":[{"type":"text","text":"exit\n[shell exited: code 9]\nThe persistent bash shell was reset; the next bash call starts from the workspace with a fresh current directory and environment."}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[65],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":64,"time":0,"data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[59,60,61,62,63],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":65,"time":0,"data":{"turn":1,"step":6,"callId":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":66,"time":0,"data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"editor-replace"},"content":[{"type":"tool-result","toolCallId":"editor-replace","content":[{"type":"text","text":"The file {{cwd}}/note.txt has been edited successfully."}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[65],"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":67,"time":0,"data":{"turn":1,"step":6}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":68,"time":0,"data":{"turn":1,"step":7}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":69,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":70,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"text-delta","index":0,"text":"PERSISTENT_TOOLS_OK"}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":71,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PERSISTENT_TOOLS_OK"}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":69,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":70,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"tool-call-delta","index":0,"id":"bash-exit","name":"bash","argumentsDelta":"{\"command\":\"exit 9\"}"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":71,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":72,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":73,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":74,"time":0,"data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"text","text":"PERSISTENT_TOOLS_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[69,70,71,72,73],"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":75,"time":0,"data":{"turn":1,"step":7}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":76,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":73,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":74,"time":0,"data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[69,70,71,72,73],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":75,"time":0,"data":{"turn":1,"step":7,"callId":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":76,"time":0,"data":{"turn":1,"step":7,"message":{"source":{"kind":"tool","callId":"bash-exit"},"content":[{"type":"tool-result","toolCallId":"bash-exit","content":[{"type":"text","text":"exit\n[shell exited: code 9]\nThe persistent bash shell was reset; the next bash call starts from the workspace with a fresh current directory and environment."}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[75],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":77,"time":0,"data":{"turn":1,"step":7}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":78,"time":0,"data":{"turn":1,"step":8}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":79,"time":0,"data":{"turn":1,"step":8,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":80,"time":0,"data":{"turn":1,"step":8,"chunk":{"type":"text-delta","index":0,"text":"PERSISTENT_TOOLS_OK"}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":81,"time":0,"data":{"turn":1,"step":8,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PERSISTENT_TOOLS_OK"}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":82,"time":0,"data":{"turn":1,"step":8,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/chunk","seq":83,"time":0,"data":{"turn":1,"step":8,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":84,"time":0,"data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"text","text":"PERSISTENT_TOOLS_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[79,80,81,82,83],"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":85,"time":0,"data":{"turn":1,"step":8}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":86,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}}} {"method":"session.status","params":{"sessionId":"{{sessionId}}","status":"idle"}} diff --git a/snapshots/sdk/persistent-tools/session.jsonl b/snapshots/sdk/persistent-tools/session.jsonl index c2310c5668..8024d37199 100644 --- a/snapshots/sdk/persistent-tools/session.jsonl +++ b/snapshots/sdk/persistent-tools/session.jsonl @@ -1,9 +1,9 @@ {"type":"session","version":0,"id":"{{session:1}}","createdAt":1785331618309,"cwd":"{{cwd}}","delegationDepth":0} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Prove that bash state persists. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Prove that bash state persists. After the persistence checks, run exactly `{ sleep 0.1; echo delayed; } | cat` as its own bash call and observe `delayed`. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} -{"type":"user/message","data":{"content":[{"type":"text","text":"Prove that bash state persists. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Prove that bash state persists. After the persistence checks, run exactly `{ sleep 0.1; echo delayed; } | cat` as its own bash call and observe `delayed`. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} {"type":"session/title","data":{"title":"Prove that bash state persists.","messageSeqs":[4],"source":{"kind":"fallback"}}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} @@ -29,50 +29,60 @@ {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-create","name":"str_replace_editor","argumentsDelta":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}}} +{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"bash-delayed-pipeline","name":"bash","argumentsDelta":"{\"command\":\"{ sleep 0.1; echo delayed; } | cat\"}"}}} +{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"bash-delayed-pipeline","name":"bash","arguments":"{\"command\":\"{ sleep 0.1; echo delayed; } | cat\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[29,30,31,32,33],"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":3,"callId":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}} -{"type":"tool/result","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"editor-create"},"content":[{"type":"tool-result","toolCallId":"editor-create","content":[{"type":"text","text":"New file created successfully at: {{cwd}}/note.txt"}],"isError":false}],"role":"user","id":"{{message:8}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"bash-delayed-pipeline","name":"bash","arguments":"{\"command\":\"{ sleep 0.1; echo delayed; } | cat\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[29,30,31,32,33],"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":3,"callId":"bash-delayed-pipeline","name":"bash","arguments":"{\"command\":\"{ sleep 0.1; echo delayed; } | cat\"}"}} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"bash-delayed-pipeline"},"content":[{"type":"tool-result","toolCallId":"bash-delayed-pipeline","content":[{"type":"text","text":"delayed"}],"isError":false}],"role":"user","id":"{{message:8}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} {"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-view","name":"str_replace_editor","argumentsDelta":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}}} +{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-create","name":"str_replace_editor","argumentsDelta":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}} +{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[39,40,41,42,43],"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":4,"callId":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}} -{"type":"tool/result","data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"editor-view"},"content":[{"type":"tool-result","toolCallId":"editor-view","content":[{"type":"text","text":"Here's the content of {{cwd}}/note.txt with line numbers (which has a total of 3 lines):\n 1 target:\n 2 \told\n 3 \n"}],"isError":false}],"role":"user","id":"{{message:10}}"}},"sourceEventSeqs":[45],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[39,40,41,42,43],"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":4,"callId":"editor-create","name":"str_replace_editor","arguments":"{\"command\":\"create\",\"path\":\"{{cwd}}/note.txt\",\"file_text\":\"target:\\n\\told\\n\"}"}} +{"type":"tool/result","data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"editor-create"},"content":[{"type":"tool-result","toolCallId":"editor-create","content":[{"type":"text","text":"New file created successfully at: {{cwd}}/note.txt"}],"isError":false}],"role":"user","id":"{{message:10}}"}},"sourceEventSeqs":[45],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} {"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-replace","name":"str_replace_editor","argumentsDelta":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}}} +{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-view","name":"str_replace_editor","argumentsDelta":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}} +{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[49,50,51,52,53],"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":5,"callId":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}} -{"type":"tool/result","data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"editor-replace"},"content":[{"type":"tool-result","toolCallId":"editor-replace","content":[{"type":"text","text":"The file {{cwd}}/note.txt has been edited successfully."}],"isError":false}],"role":"user","id":"{{message:12}}"}},"sourceEventSeqs":[55],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[49,50,51,52,53],"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":5,"callId":"editor-view","name":"str_replace_editor","arguments":"{\"command\":\"view\",\"path\":\"{{cwd}}/note.txt\"}"}} +{"type":"tool/result","data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"editor-view"},"content":[{"type":"tool-result","toolCallId":"editor-view","content":[{"type":"text","text":"Here's the content of {{cwd}}/note.txt with line numbers (which has a total of 3 lines):\n 1 target:\n 2 \told\n 3 \n"}],"isError":false}],"role":"user","id":"{{message:12}}"}},"sourceEventSeqs":[55],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"tool-call-delta","index":0,"id":"bash-exit","name":"bash","argumentsDelta":"{\"command\":\"exit 9\"}"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}}}} +{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"tool-call-delta","index":0,"id":"editor-replace","name":"str_replace_editor","argumentsDelta":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}} +{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[59,60,61,62,63],"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":6,"callId":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}} -{"type":"tool/result","data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"bash-exit"},"content":[{"type":"tool-result","toolCallId":"bash-exit","content":[{"type":"text","text":"exit\n[shell exited: code 9]\nThe persistent bash shell was reset; the next bash call starts from the workspace with a fresh current directory and environment."}],"isError":false}],"role":"user","id":"{{message:14}}"}},"sourceEventSeqs":[65],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:13}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[59,60,61,62,63],"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":6,"callId":"editor-replace","name":"str_replace_editor","arguments":"{\"command\":\"str_replace\",\"path\":\"{{cwd}}/note.txt\",\"old_str\":\"\\told\",\"new_str\":\"\\tnew\"}"}} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"editor-replace"},"content":[{"type":"tool-result","toolCallId":"editor-replace","content":[{"type":"text","text":"The file {{cwd}}/note.txt has been edited successfully."}],"isError":false}],"role":"user","id":"{{message:14}}"}},"sourceEventSeqs":[65],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} -{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"text-delta","index":0,"text":"PERSISTENT_TOOLS_OK"}}} -{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PERSISTENT_TOOLS_OK"}}}} +{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"tool-call-delta","index":0,"id":"bash-exit","name":"bash","argumentsDelta":"{\"command\":\"exit 9\"}"}}} +{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} -{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"text","text":"PERSISTENT_TOOLS_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:15}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[69,70,71,72,73],"surfaceOp":"append"} +{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:15}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[69,70,71,72,73],"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":7,"callId":"bash-exit","name":"bash","arguments":"{\"command\":\"exit 9\"}"}} +{"type":"tool/result","data":{"turn":1,"step":7,"message":{"source":{"kind":"tool","callId":"bash-exit"},"content":[{"type":"tool-result","toolCallId":"bash-exit","content":[{"type":"text","text":"exit\n[shell exited: code 9]\nThe persistent bash shell was reset; the next bash call starts from the workspace with a fresh current directory and environment."}],"isError":false}],"role":"user","id":"{{message:16}}"}},"sourceEventSeqs":[75],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":7}} +{"type":"step/start","data":{"turn":1,"step":8}} +{"type":"assistant/chunk","data":{"turn":1,"step":8,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} +{"type":"assistant/chunk","data":{"turn":1,"step":8,"chunk":{"type":"text-delta","index":0,"text":"PERSISTENT_TOOLS_OK"}}} +{"type":"assistant/chunk","data":{"turn":1,"step":8,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PERSISTENT_TOOLS_OK"}}}} +{"type":"assistant/chunk","data":{"turn":1,"step":8,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}} +{"type":"assistant/chunk","data":{"turn":1,"step":8,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"text","text":"PERSISTENT_TOOLS_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:17}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[79,80,81,82,83],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":8}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} From 2338f4ad1450e75b09765366539e1fe1c590e28d Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 25 Aug 2026 14:01:04 +0800 Subject: [PATCH 20/31] fix(pty): detect emulated kernel syscall ABI --- ...26-07-16-persistent-pty-sessions.i18n.yaml | 4 +- .../2026-07-16-persistent-pty-sessions.md | 4 +- .../2026-07-16-persistent-pty-sessions.zh.md | 4 +- .../subprocess-local/README.i18n.yaml | 4 +- .../subprocess/subprocess-local/README.md | 2 +- .../subprocess/subprocess-local/README.zh.md | 2 +- .../subprocess-local/src/process-inspector.ts | 38 ++++++++++++------- .../tests/process-inspector.spec.ts | 4 +- 8 files changed, 38 insertions(+), 24 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml index 663a33d56d..84c8a040c3 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md -2026-07-16-persistent-pty-sessions.md: b49301aaef6593730c67c3a727e1e82b3ec25379 -2026-07-16-persistent-pty-sessions.zh.md: d98400255a8282b1fa7f529caf85ee03a0fb451a +2026-07-16-persistent-pty-sessions.md: 8cbec14dae0517a82925d871843a1998f4734709 +2026-07-16-persistent-pty-sessions.zh.md: 91d07c2dcd1f58ffb53a20955740c7205ace5d92 diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md index b49301aaef..8cbec14dae 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md @@ -74,7 +74,7 @@ With `run_in_background: true`, `dsh-tool-terminal` registers the in-flight send The local backend first recognizes a private OSC prompt marker emitted by its controlled bash startup, then requires the printable tail after the latest marker to exactly equal the controlled `PS1` before declaring prompt readiness and runs three bounded fallback tiers. Carrying that tail across data callbacks covers delivery where the marker and prompt arrive separately; requiring the exact tail rejects a delayed earlier prompt once echoed input or output follows it, so it cannot settle the current send. The marker is removed before output reaches the model and avoids a fixed silence delay for ordinary shell commands on both platforms. Unpublished startup does not accept zero-output silence as readiness; timeout rejects the spawn. If caller cancellation wins during startup, the backend closes the private session and propagates the exact `AbortSignal.reason`; a foreground PGID that is not observable yet cannot replace cancellation with a lookup error. All timings are validated config fields: `pollIntervalMs`, `exactProbeAfterMs`, `idleSilenceMs`, `handoffGraceMs`, and `timeoutMs`. -On Linux, the inspector reads the shell's terminal foreground PGID from `/proc//stat`, enumerates every process and thread in that process group, and probes their current syscalls. A positive Tier 1 result requires an observed stdin wait: direct `read(0)`, a permitted read of a `select`/`pselect6` or `poll`/`ppoll` argument containing fd 0, or an epoll interest list containing fd 0. The waiting thread's `/proc//task//fd/0` must identify the shell's controlling terminal device, so a thread-local fd table cannot substitute its leader's terminal descriptor and a pipeline reader blocked on its pipe remains a running command. Direct PTY descriptors use their device number; `/dev/tty` uses the owning process's `tty_nr` because `stat` reports the alias device rather than the selected PTY. A wait already present before terminal input is not post-write readiness: the same PGID must be observed outside that wait before re-entering it, while a changed foreground PGID is new evidence. Unreadable process memory and unrecognized syscalls are misses, never positive guesses. Architecture tables contain only syscall numbers defined by the corresponding Linux UAPI; unsupported architectures skip Tier 1. +On Linux, the inspector reads the shell's terminal foreground PGID from `/proc//stat`, enumerates every process and thread in that process group, and probes their current syscalls. A positive Tier 1 result requires an observed stdin wait: direct `read(0)`, a permitted read of a `select`/`pselect6` or `poll`/`ppoll` argument containing fd 0, or an epoll interest list containing fd 0. The waiting thread's `/proc//task//fd/0` must identify the shell's controlling terminal device, so a thread-local fd table cannot substitute its leader's terminal descriptor and a pipeline reader blocked on its pipe remains a running command. Direct PTY descriptors use their device number; `/dev/tty` uses the owning process's `tty_nr` because `stat` reports the alias device rather than the selected PTY. A wait already present before terminal input is not post-write readiness: the same PGID must be observed outside that wait before re-entering it, while a changed foreground PGID is new evidence. Unreadable process memory and unrecognized syscalls are misses, never positive guesses. Architecture tables contain only syscall numbers defined by the corresponding Linux UAPI; the inspector admits the runtime architecture, then checks every supported kernel ABI because `/proc` can report a different ABI under user-mode emulation. Unsupported runtime architectures skip Tier 1. On macOS there is no exact syscall tier. Output silence returns `inferred_idle` for any foreground process group, including Python and `gdb`; `ps`-derived terminal PGID is used for signaling, not as proof that only the shell can be idle. Pure process-inspector logic is injectable and unit-tested on Linux, while a macOS CI job exercises the real PTY and process-table path. @@ -157,7 +157,7 @@ The package ships concise tool guidance explaining persistent state, owner isola ## Verification - Per-file coverage pins owner fencing, concurrent reservations, cancellation during pre-write inspection, unpublished-spawn cancellation and awaited teardown, sandbox-mode change rejection, retriable lifecycle cleanup, readiness tiers, rejection of pre-write stdin waits and delayed earlier prompts, the configured handoff grace holding the idle fallback past one poll and its rejection below `pollIntervalMs`, sanitizer carry state, complete UTF-8 bounds, task integration, schemas, and exact render intents. -- Subprocess process fixtures cover non-leader and non-main-thread stdin waits, thread-local fd tables, the `/dev/tty` alias, rejection of fd 0 backed by a pipe, zombie quiescence, unreadable process state, supported syscall tables, unsupported architectures, and other false-positive rejection; macOS inspector logic is injected into the same unit suite. +- Subprocess process fixtures cover non-leader and non-main-thread stdin waits, thread-local fd tables, the `/dev/tty` alias, supported kernel ABIs under user-mode emulation, rejection of fd 0 backed by a pipe, zombie quiescence, unreadable process state, unsupported architectures, and other false-positive rejection; macOS inspector logic is injected into the same unit suite. - Real `node-pty` and PTY-consumer tests jointly exercise shell state, controlling-terminal input through `/dev/tty`, shared sandbox policy, environment scrubbing, raw-mode foreground `SIGINT`, a TERM-ignoring descendant, and immediate post-disposal quiescence on supported hosts. - A Loader-driven `cordis.yml` test mounts the real three-package composition and verifies that delayed pipeline output returns with the completed command instead of being classified as terminal-input readiness. The SDK minimal snapshot pins that output through the persistent Bash tool; ACP and headless snapshots pin the six terminal schemas, bounded results, and errors through opt-in overlays; TUI snapshots pin terminal and generic card presentation. - Package contracts, the architecture map, subsystem pages, generated catalogs, and the website API describe the same shipped surface. diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md index d98400255a..91d07c2dcd 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md @@ -74,7 +74,7 @@ UI 渲染约定精确且不携带位置信息。`terminal_send` 只为前台发 本地后端先识别受控 bash 启动时发出的私有 OSC prompt marker,并且只有在最近一个 marker 后的可打印尾部与受控 `PS1` 完全相等时才声明 prompt 就绪;除此之外,它还运行 3 个有界 fallback 层级。在 data callback 之间保留该尾部,可以适配 marker 与 prompt 被分开交付的情况;如果回显的输入或输出跟在延迟到达的先前 prompt 之后,要求尾部完全相等会拒绝该 prompt,使其无法完成当前 send。marker 在输出到达模型前被移除,使两个平台上的普通 shell 命令都无需固定等待静默阈值。尚未发布的 startup 不会把零输出静默视为就绪;timeout 会拒绝 spawn。若调用方取消在 startup 期间胜出,后端会关闭私有会话并原样抛出 `AbortSignal.reason`;尚不可观察的前台 PGID 不会再用查找错误覆盖取消原因。所有时间参数都是经校验的配置字段:`pollIntervalMs`、`exactProbeAfterMs`、`idleSilenceMs`、`handoffGraceMs` 和 `timeoutMs`。 -在 Linux 上,检查器从 `/proc//stat` 读取 shell 的终端前台 PGID,枚举该进程组中的每个进程与线程,并检查它们当前的 syscall。Tier 1 只有观察到 stdin 等待才返回正结果:直接 `read(0)`、获准读取且含 fd 0 的 `select`/`pselect6` 或 `poll`/`ppoll` 参数,或者含 fd 0 的 epoll interest list。等待线程的 `/proc//task//fd/0` 还必须标识 shell 的控制终端设备,因此线程本地 fd 表无法用 leader 的终端描述符冒充自身 fd,阻塞于管道的流水线读取端仍属于正在运行的命令。直接 PTY 描述符使用其设备号;`/dev/tty` 则使用所属进程的 `tty_nr`,因为 `stat` 报告的是别名设备而非选定的 PTY。终端输入前就已存在的等待并不代表写入后就绪:必须先观察到同一 PGID 脱离该等待,之后再次进入等待才能使该次 send 完成;前台 PGID 发生变化则构成新的证据。无法读取的进程内存和未识别的 syscall 都是 miss,绝不作为正向猜测。架构表只包含对应 Linux UAPI 定义的 syscall number;不支持的架构跳过 Tier 1。 +在 Linux 上,检查器从 `/proc//stat` 读取 shell 的终端前台 PGID,枚举该进程组中的每个进程与线程,并检查它们当前的 syscall。Tier 1 只有观察到 stdin 等待才返回正结果:直接 `read(0)`、获准读取且含 fd 0 的 `select`/`pselect6` 或 `poll`/`ppoll` 参数,或者含 fd 0 的 epoll interest list。等待线程的 `/proc//task//fd/0` 还必须标识 shell 的控制终端设备,因此线程本地 fd 表无法用 leader 的终端描述符冒充自身 fd,阻塞于管道的流水线读取端仍属于正在运行的命令。直接 PTY 描述符使用其设备号;`/dev/tty` 则使用所属进程的 `tty_nr`,因为 `stat` 报告的是别名设备而非选定的 PTY。终端输入前就已存在的等待并不代表写入后就绪:必须先观察到同一 PGID 脱离该等待,之后再次进入等待才能使该次 send 完成;前台 PGID 发生变化则构成新的证据。无法读取的进程内存和未识别的 syscall 都是 miss,绝不作为正向猜测。架构表只包含对应 Linux UAPI 定义的 syscall number;检查器先准入运行时架构,再检查每个受支持的内核 ABI,因为在用户态模拟下,`/proc` 可能报告不同的 ABI。不受支持的运行时架构会跳过 Tier 1。 macOS 没有精确 syscall 层。任何前台进程组输出静默都会返回 `inferred_idle`,包括 Python 和 `gdb`;从 `ps` 推导的终端 PGID 只用于发送信号,不作为「只有 shell 才能 idle」的证明。纯进程检查逻辑可注入,并在 Linux 上经过单元测试,同时由 macOS CI job 驱动真实 PTY 和进程表路径。 @@ -157,7 +157,7 @@ plugins: ## 验证 - 逐文件覆盖测试锁定了 owner 隔离、并发预留、写入前检查期间的取消、未发布 spawn 的取消与等待式 teardown、沙箱模式变更拒绝、可重试的生命周期清理、就绪层级、对写入前 stdin 等待与延迟到达的先前 prompt 的拒绝、配置化交接宽限把 idle fallback 顶过一次轮询以及低于 `pollIntervalMs` 时的拒绝、sanitizer carry state、完整 UTF-8 结果上限、task 集成、schema 和精确 render intent。 -- 子进程 fixture(测试前置数据)覆盖非 leader 与非主线程的 stdin 等待、线程本地 fd 表、`/dev/tty` 别名、拒绝把指向管道的 fd 0 当作终端输入、僵尸进程完全停稳、不可读进程状态、受支持的 syscall 表、不支持的架构和其他误报拒绝;同一单元测试套件通过注入覆盖 macOS 检查器逻辑。 +- 子进程 fixture(测试前置数据)覆盖非 leader 与非主线程的 stdin 等待、线程本地 fd 表、`/dev/tty` 别名、用户态模拟下受支持的内核 ABI、拒绝把指向管道的 fd 0 当作终端输入、僵尸进程完全停稳、不可读进程状态、不支持的架构和其他误报拒绝;同一单元测试套件通过注入覆盖 macOS 检查器逻辑。 - 真实 `node-pty` 与 PTY 消费方测试共同在受支持宿主上覆盖 shell 状态、通过 `/dev/tty` 读取控制终端输入、共享沙箱策略、环境清洗、raw mode 前台 `SIGINT`、忽略 `SIGTERM` 的后代进程,以及 dispose 返回后立即完全停稳。 - Loader 驱动的 `cordis.yml` 测试挂载真实三包组合,并验证延迟到达的流水线输出随已完成命令返回,而不会被归类为终端输入就绪。SDK minimal 快照通过持久 Bash 工具固定该输出;ACP 与 headless 快照通过 opt-in overlay 固定 6 个终端 schema、有界结果和错误;TUI 快照固定 terminal 与 generic 卡片展示。 - 包约定、架构图、子系统页面、生成目录和 website API 描述同一个已发布接口。 diff --git a/packages/subprocess/subprocess-local/README.i18n.yaml b/packages/subprocess/subprocess-local/README.i18n.yaml index 5b25e04c1e..3e021ac000 100644 --- a/packages/subprocess/subprocess-local/README.i18n.yaml +++ b/packages/subprocess/subprocess-local/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subprocess/subprocess-local/README.md -README.md: deea6b6b291d684c4d3a31bee562a0d99e90cb65 -README.zh.md: be4396df4b85d3a18c5236bc835b50dfd26e5f19 +README.md: b3e74b75b69dc4c726749b4798f24f3058749ea9 +README.zh.md: bdbbc723fd89574425b3391bc6c4d9639b0cfdac diff --git a/packages/subprocess/subprocess-local/README.md b/packages/subprocess/subprocess-local/README.md index deea6b6b29..b3e74b75b6 100644 --- a/packages/subprocess/subprocess-local/README.md +++ b/packages/subprocess/subprocess-local/README.md @@ -11,7 +11,7 @@ Local Service Provider for the [`@deepseek-ai/dsh-subprocess`](../subprocess/REA - **Credential scrub + explicit merge** — `process.env` minus credential-shaped vars (`*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`) and all ambient `DSH_*` names; the spec's explicit `env` merges after that scrub with no namespace validation, so a deliberately supplied credential or current `DSH_*` fact wins while stale nested-harness identity cannot leak in ambiently. Supplied stdin is written and closed; otherwise fd 0 is `/dev/null`. See the [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.md) and [managed environment Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md). - **Offset-based reads** — collect-mode readers return deltas in whole-stream byte coordinates; the service never holds a cursor, so consumer-owned cursors (the bash background read path) and full-stream re-reads coexist, before and after settlement. - **Executable lookup** — `resolveExecutable` checks absolute files or searches the scrubbed effective PATH with platform-aware executable extensions; relative paths containing separators are rejected at the seam, and relative PATH entries resolve from the host process cwd. -- **Terminal-process ownership** — `spawnTerminal` allocates `node-pty`, bridges UTF-8 terminal text, inspects and signals the current foreground process group, and exposes one awaited termination operation that sweeps descendants before and after terminating the top-level shell. Linux reports an exact input wait only when the waiting thread's own fd 0 identifies the shell's controlling terminal, including the `/dev/tty` alias, so a pipeline reader blocked on `pipe:[…]` cannot publish terminal readiness. Each foreground inspection retains exact identities from the rooted tree; Linux also enumerates the POSIX session after its leader exits. A previously observed macOS descendant and any same-session Linux member therefore remain fenced after reparenting, while pid/start identity prevents cleanup from following PID reuse. On Windows the koffi-backed inspector enumerates the process table through Toolhelp32, combines GetProcessTimes start identities with zero-time process-handle waits for liveness, reports the shell pid as the pseudo foreground group (Windows has no POSIX groups), and teardown verifies the shell's termination because externally taskkilled shells may never fire node-pty's exit notification. The higher PTY backend owns prompt readiness, buffers, and model-facing operations. +- **Terminal-process ownership** — `spawnTerminal` allocates `node-pty`, bridges UTF-8 terminal text, inspects and signals the current foreground process group, and exposes one awaited termination operation that sweeps descendants before and after terminating the top-level shell. Linux reports an exact input wait only when the waiting thread's own fd 0 identifies the shell's controlling terminal, including the `/dev/tty` alias, so a pipeline reader blocked on `pipe:[…]` cannot publish terminal readiness. The syscall probe admits supported runtime architectures and matches every supported kernel ABI so user-mode emulation cannot hide the wait. Each foreground inspection retains exact identities from the rooted tree; Linux also enumerates the POSIX session after its leader exits. A previously observed macOS descendant and any same-session Linux member therefore remain fenced after reparenting, while pid/start identity prevents cleanup from following PID reuse. On Windows the koffi-backed inspector enumerates the process table through Toolhelp32, combines GetProcessTimes start identities with zero-time process-handle waits for liveness, reports the shell pid as the pseudo foreground group (Windows has no POSIX groups), and teardown verifies the shell's termination because externally taskkilled shells may never fire node-pty's exit notification. The higher PTY backend owns prompt readiness, buffers, and model-facing operations. - **Terminate-and-join disposal** — the service retains live handles so its own disposal can escalate every running tree and await its exit; quiescent and spawn-failed handles leave the live set after whole-tree or terminal-session cleanup finishes. - **Synchronous host-exit finalization** — while the service effect is active, a Node `exit` listener force-terminates every ordinary tree and observable terminal session still in the same live sets. The local-only operations send POSIX SIGKILL to the managed group, run Windows `taskkill /T /F`, and synchronously signal captured/current terminal identities around the PTY root kill; they create no promise or timer, preserve the host's exit code and diagnostic, contain each target's failure, and do not claim quiescence. Normal disposal keeps the awaited graceful path above. See the [host-exit cleanup decision](../../../.agents/notes/implemented/bug-fix/2026-08-11-synchronous-subprocess-exit-cleanup.md). diff --git a/packages/subprocess/subprocess-local/README.zh.md b/packages/subprocess/subprocess-local/README.zh.md index be4396df4b..bdbbc723fd 100644 --- a/packages/subprocess/subprocess-local/README.zh.md +++ b/packages/subprocess/subprocess-local/README.zh.md @@ -11,7 +11,7 @@ - **凭据清除 + 显式合并**:以 `process.env` 为基础,移除形似凭据的变量(`*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`)和所有环境中已有的 `DSH_*` 名称;spec 的显式 `env` 在该清除之后合并且不做命名空间校验,因此有意提供的凭据或当前 `DSH_*` 事实会胜出,而陈旧的嵌套 harness 身份无法从环境中隐式漏入。提供的 stdin 会被写入后关闭;否则 fd 0 指向 `/dev/null`。参见 [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.zh.md)与[受管环境 Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.zh.md)。 - **基于偏移量的读取**:收集模式的读取器按完整流的字节坐标返回增量;服务自身从不持有游标,因此消费方自有的游标(bash 的后台读取路径)与完整流重读可以共存,结算前后皆然。 - **可执行文件查找**:`resolveExecutable` 检查绝对文件,或根据平台可执行文件扩展名在清理后的有效 PATH 中搜索;含分隔符的相对路径在该 seam 处被拒绝,相对 PATH 条目从宿主进程 cwd 解析。 -- **终端进程所有权**:`spawnTerminal` 分配 `node-pty`,桥接 UTF-8 终端文本,检查当前前台进程组并向其发送信号,还会公开一项须等待的终止操作,在终止顶层 shell 前后清理后代进程。Linux 只有在等待线程自身的 fd 0 标识 shell 的控制终端(包括 `/dev/tty` 别名)时才报告精确输入等待,因此阻塞于 `pipe:[…]` 的流水线读取端无法发布终端就绪状态。每次前台检查都会保留根进程树中的精确身份;Linux 还会在 POSIX 会话 leader 退出后枚举该会话。因此,之前观察到的 macOS 后代以及同会话 Linux 成员在重新设定父进程后仍受围栏保护,pid/start 身份则防止清理跟随 PID 复用。在 Windows 上,基于 koffi 的检查器通过 Toolhelp32 枚举进程表,把 GetProcessTimes 启动身份与进程句柄零时等待结合起来判断存活状态,并把 shell pid 作为伪前台进程组(Windows 没有 POSIX 进程组)。拆卸会验证 shell 已终止,因为被外部 taskkill 的 shell 可能永远不会触发 node-pty 的退出通知。上层 PTY 后端负责提示符就绪、缓冲区与面向模型的操作。 +- **终端进程所有权**:`spawnTerminal` 分配 `node-pty`,桥接 UTF-8 终端文本,检查当前前台进程组并向其发送信号,还会公开一项须等待的终止操作,在终止顶层 shell 前后清理后代进程。Linux 只有在等待线程自身的 fd 0 标识 shell 的控制终端(包括 `/dev/tty` 别名)时才报告精确输入等待,因此阻塞于 `pipe:[…]` 的流水线读取端无法发布终端就绪状态。syscall 探针会准入受支持的运行时架构并匹配每个受支持的内核 ABI,使用户态模拟无法隐藏该等待。每次前台检查都会保留根进程树中的精确身份;Linux 还会在 POSIX 会话 leader 退出后枚举该会话。因此,之前观察到的 macOS 后代以及同会话 Linux 成员在重新设定父进程后仍受围栏保护,pid/start 身份则防止清理跟随 PID 复用。在 Windows 上,基于 koffi 的检查器通过 Toolhelp32 枚举进程表,把 GetProcessTimes 启动身份与进程句柄零时等待结合起来判断存活状态,并把 shell pid 作为伪前台进程组(Windows 没有 POSIX 进程组)。拆卸会验证 shell 已终止,因为被外部 taskkill 的 shell 可能永远不会触发 node-pty 的退出通知。上层 PTY 后端负责提示符就绪、缓冲区与面向模型的操作。 - **先终止再等待退出的 dispose(资源释放)**:服务保留存活句柄,使自身的 dispose 能对每个仍在运行的进程树执行升级并等待其退出;完全停稳与 spawn 失败的句柄会在整棵进程树或 terminal session 清理完成后离开存活集合。 - **同步宿主退出最终清理**:服务 effect 仍有效时,Node `exit` listener 会强制终止同一组存活集合中仍存在的每棵普通进程树和可观察 terminal session。这些仅供本地实现使用的操作会向受管 POSIX 进程组发送 SIGKILL、在 Windows 运行 `taskkill /T /F`,并在终止 PTY root 前后同步向已捕获及当前可观察的 terminal 身份发送信号;它们不会创建 Promise 或 timer,不改变宿主退出码与诊断,会分别包含每个目标的失败,也不会声称已经完全停稳。正常 dispose 仍使用上面的须等待温和路径。参见[宿主退出清理决策](../../../.agents/notes/implemented/bug-fix/2026-08-11-synchronous-subprocess-exit-cleanup.zh.md)。 diff --git a/packages/subprocess/subprocess-local/src/process-inspector.ts b/packages/subprocess/subprocess-local/src/process-inspector.ts index e13ced066f..7a74213baf 100644 --- a/packages/subprocess/subprocess-local/src/process-inspector.ts +++ b/packages/subprocess/subprocess-local/src/process-inspector.ts @@ -254,23 +254,35 @@ const SYSCALLS: Partial> = { arm64: { read: 63, pselect: 72, ppoll: 73, epollPwait: 22 }, } +const SUPPORTED_SYSCALL_TABLES = Object.values(SYSCALLS) + +// `/proc//task//syscall` uses the kernel ABI's numbers. User-mode +// emulation can therefore expose a supported table different from process.arch. +function linuxSyscallTables(arch: NodeJS.Architecture): readonly SyscallTable[] | undefined { + const primary = SYSCALLS[arch] + if (primary === undefined) return undefined + return [primary, ...SUPPORTED_SYSCALL_TABLES.filter(table => table !== primary)] +} + function syscallWaitsOnStdin( internals: ProcessInspectorInternals, pid: number, tid: number, syscall: SyscallInfo, - table: SyscallTable, + tables: readonly SyscallTable[], ): boolean { const [a0 = 0, a1 = 0, a2 = 0] = syscall.args - if (syscall.number === table.read) return a0 === 0 - if (syscall.number === table.select || syscall.number === table.pselect) { - return a0 >= 1 && fdSetHasStdin(internals, pid, a1) - } - if (syscall.number === table.poll || syscall.number === table.ppoll) { - return a1 >= 1 && pollHasStdin(internals, pid, a0, a1) - } - if (syscall.number === table.epollWait || syscall.number === table.epollPwait) { - return a2 >= 1 && epollHasStdin(internals, pid, tid, a0) + for (const table of tables) { + if (syscall.number === table.read) return a0 === 0 + if (syscall.number === table.select || syscall.number === table.pselect) { + return a0 >= 1 && fdSetHasStdin(internals, pid, a1) + } + if (syscall.number === table.poll || syscall.number === table.ppoll) { + return a1 >= 1 && pollHasStdin(internals, pid, a0, a1) + } + if (syscall.number === table.epollWait || syscall.number === table.epollPwait) { + return a2 >= 1 && epollHasStdin(internals, pid, tid, a0) + } } return false } @@ -333,8 +345,8 @@ class LinuxProcessInspector extends PosixProcessInspector { } isStdinWaiting(pgid: number, shellPid: number): boolean { - const table = SYSCALLS[this.arch] - if (table === undefined) return false + const tables = linuxSyscallTables(this.arch) + if (tables === undefined) return false const shell = readLinuxStat(this.internals, shellPid) if (shell === undefined) return false const terminalDevice = readLinuxTerminalDevice(this.internals, shellPid, shell.ttyDevice) @@ -345,7 +357,7 @@ class LinuxProcessInspector extends PosixProcessInspector { for (const tid of numericEntries(this.internals, `/proc/${pid}/task`)) { const syscall = readSyscall(this.internals, pid, tid) if (syscall !== undefined - && syscallWaitsOnStdin(this.internals, pid, tid, syscall, table) + && syscallWaitsOnStdin(this.internals, pid, tid, syscall, tables) && readLinuxTerminalDevice(this.internals, pid, process.ttyDevice, tid) === terminalDevice) return true } } diff --git a/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts b/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts index a56167bb4d..ab34922576 100644 --- a/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts +++ b/packages/subprocess/subprocess-local/tests/process-inspector.spec.ts @@ -146,7 +146,7 @@ describe('Linux process inspector', () => { expect(fake.kills).toEqual([[-40, 'SIGINT'], [10, 'SIGTERM']]) }) - it('detects read, select, poll, and epoll waits across non-leader threads', () => { + it('detects supported kernel ABI waits across non-leader threads', () => { const fake = fakeInternals() fake.dirs.set('/proc', ['100', '101']) fake.files.set('/proc/100/stat', stat(100, 77, 100, 77, '1')) @@ -163,6 +163,8 @@ describe('Linux process inspector', () => { fake.files.set('/proc/101/task/101/syscall', '-1 0x0') fake.files.set('/proc/101/task/102/syscall', syscall(0, 0)) expect(inspector.isStdinWaiting(77, 100)).toBe(true) + fake.files.set('/proc/101/task/102/syscall', syscall(63, 0)) + expect(inspector.isStdinWaiting(77, 100)).toBe(true) fake.files.set('/proc/101/task/102/syscall', syscall(270, 1, 0x10)) const fdSet = Buffer.alloc(0x11) From 133ed2d0f0c86b6c85acf22ac5d21e0ee97a24e8 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 25 Aug 2026 14:08:30 +0800 Subject: [PATCH 21/31] test(pty): report proc state on readiness failure --- .../terminal-bash/tests/local.spec.ts | 53 ++++++++++++++++++- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index 4a90049997..254ea11415 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' +import { existsSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync } from 'node:fs' import { spawnSync } from 'node:child_process' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -118,6 +118,55 @@ function processIsRunning(pid: number): boolean { } } +function linuxBashProcDiagnostics(): string { + const read = (path: string): string => { + try { + return readFileSync(path, 'utf8').trim() + } catch (error) { + return error instanceof Error ? `${error.name}: ${error.message}` : String(error) + } + } + const ps = spawnSync('/bin/ps', ['-eo', 'pid=,ppid=,pgid=,sid=,stat=,args='], { encoding: 'utf8' }) + const bash = ps.stdout.split('\n').filter(line => /(?:^|\s)(?:\/bin\/)?bash(?:\s|$)/.test(line)) + const processes = bash.map((line) => { + const pid = /^\s*(\d+)/.exec(line)?.[1] + if (pid === undefined) return { line } + let tids: string[] + try { + tids = readdirSync(`/proc/${pid}/task`) + } catch (error) { + return { line, tasks: error instanceof Error ? `${error.name}: ${error.message}` : String(error) } + } + return { + line, + stat: read(`/proc/${pid}/stat`), + tasks: tids.map((tid) => { + const fd = `/proc/${pid}/task/${tid}/fd/0` + let fd0: string + let rdev: string + try { + fd0 = readlinkSync(fd) + } catch (error) { + fd0 = error instanceof Error ? `${error.name}: ${error.message}` : String(error) + } + try { + const device = statSync(fd) + rdev = `${device.rdev} character=${device.isCharacterDevice()}` + } catch (error) { + rdev = error instanceof Error ? `${error.name}: ${error.message}` : String(error) + } + return { tid, syscall: read(`/proc/${pid}/task/${tid}/syscall`), fd0, rdev } + }), + } + }) + return JSON.stringify({ + arch: process.arch, + machine: spawnSync('/bin/uname', ['-m'], { encoding: 'utf8' }).stdout.trim(), + ptraceScope: read('/proc/sys/kernel/yama/ptrace_scope'), + processes, + }, undefined, 2) +} + // The real-shell suite drives a POSIX bash over the actual node-pty terminal; // Windows has no bash, and its pwsh counterpart lives in the describe below. describe.skipIf(process.platform === 'win32')('terminal-bash real shell', () => { @@ -175,7 +224,7 @@ describe.skipIf(process.platform === 'win32')('terminal-bash real shell', () => submit: true, }) await waitForOutput(waiting, 'WAITING') - expect((await waiting.done).waitReason).toBe('stdin_read') + expect((await waiting.done).waitReason, linuxBashProcDiagnostics()).toBe('stdin_read') const answer = ctx.terminals.startSend(agent, created.sessionId, { text: 'accepted', submit: true }) const result = await answer.done From a3f67137bc48437b60029322fd0f3a34ab951697 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 25 Aug 2026 14:19:56 +0800 Subject: [PATCH 22/31] test(pty): cover restricted proc syscall access --- ...26-07-16-persistent-pty-sessions.i18n.yaml | 4 +- .../2026-07-16-persistent-pty-sessions.md | 4 +- .../2026-07-16-persistent-pty-sessions.zh.md | 4 +- .../subprocess-local/README.i18n.yaml | 4 +- .../subprocess/subprocess-local/README.md | 2 +- .../subprocess/subprocess-local/README.zh.md | 2 +- .../terminal-bash/tests/local.spec.ts | 72 +++++-------------- 7 files changed, 29 insertions(+), 63 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml index 84c8a040c3..d4e5b38da7 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md -2026-07-16-persistent-pty-sessions.md: 8cbec14dae0517a82925d871843a1998f4734709 -2026-07-16-persistent-pty-sessions.zh.md: 91d07c2dcd1f58ffb53a20955740c7205ace5d92 +2026-07-16-persistent-pty-sessions.md: 08ccf64586034b5a0524889f33da89213ac7275d +2026-07-16-persistent-pty-sessions.zh.md: 5225d781fc8eba1fb4a6c7f4d3b5d4d87547b71d diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md index 8cbec14dae..08ccf64586 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md @@ -74,7 +74,7 @@ With `run_in_background: true`, `dsh-tool-terminal` registers the in-flight send The local backend first recognizes a private OSC prompt marker emitted by its controlled bash startup, then requires the printable tail after the latest marker to exactly equal the controlled `PS1` before declaring prompt readiness and runs three bounded fallback tiers. Carrying that tail across data callbacks covers delivery where the marker and prompt arrive separately; requiring the exact tail rejects a delayed earlier prompt once echoed input or output follows it, so it cannot settle the current send. The marker is removed before output reaches the model and avoids a fixed silence delay for ordinary shell commands on both platforms. Unpublished startup does not accept zero-output silence as readiness; timeout rejects the spawn. If caller cancellation wins during startup, the backend closes the private session and propagates the exact `AbortSignal.reason`; a foreground PGID that is not observable yet cannot replace cancellation with a lookup error. All timings are validated config fields: `pollIntervalMs`, `exactProbeAfterMs`, `idleSilenceMs`, `handoffGraceMs`, and `timeoutMs`. -On Linux, the inspector reads the shell's terminal foreground PGID from `/proc//stat`, enumerates every process and thread in that process group, and probes their current syscalls. A positive Tier 1 result requires an observed stdin wait: direct `read(0)`, a permitted read of a `select`/`pselect6` or `poll`/`ppoll` argument containing fd 0, or an epoll interest list containing fd 0. The waiting thread's `/proc//task//fd/0` must identify the shell's controlling terminal device, so a thread-local fd table cannot substitute its leader's terminal descriptor and a pipeline reader blocked on its pipe remains a running command. Direct PTY descriptors use their device number; `/dev/tty` uses the owning process's `tty_nr` because `stat` reports the alias device rather than the selected PTY. A wait already present before terminal input is not post-write readiness: the same PGID must be observed outside that wait before re-entering it, while a changed foreground PGID is new evidence. Unreadable process memory and unrecognized syscalls are misses, never positive guesses. Architecture tables contain only syscall numbers defined by the corresponding Linux UAPI; the inspector admits the runtime architecture, then checks every supported kernel ABI because `/proc` can report a different ABI under user-mode emulation. Unsupported runtime architectures skip Tier 1. +On Linux, the inspector reads the shell's terminal foreground PGID from `/proc//stat`, enumerates every process and thread in that process group, and probes their current syscalls. A positive Tier 1 result requires an observed stdin wait: direct `read(0)`, a permitted read of a `select`/`pselect6` or `poll`/`ppoll` argument containing fd 0, or an epoll interest list containing fd 0. The waiting thread's `/proc//task//fd/0` must identify the shell's controlling terminal device, so a thread-local fd table cannot substitute its leader's terminal descriptor and a pipeline reader blocked on its pipe remains a running command. Direct PTY descriptors use their device number; `/dev/tty` uses the owning process's `tty_nr` because `stat` reports the alias device rather than the selected PTY. A wait already present before terminal input is not post-write readiness: the same PGID must be observed outside that wait before re-entering it, while a changed foreground PGID is new evidence. Unreadable process memory and unrecognized syscalls are misses, never positive guesses. A host policy that denies `/proc//task//syscall`, including hardened ptrace policy, likewise skips Tier 1 and preserves the bounded Tier 2 idle inference; process sleep state never substitutes for inaccessible syscall evidence. Architecture tables contain only syscall numbers defined by the corresponding Linux UAPI; the inspector admits the runtime architecture, then checks every supported kernel ABI because `/proc` can report a different ABI under user-mode emulation. Unsupported runtime architectures skip Tier 1. On macOS there is no exact syscall tier. Output silence returns `inferred_idle` for any foreground process group, including Python and `gdb`; `ps`-derived terminal PGID is used for signaling, not as proof that only the shell can be idle. Pure process-inspector logic is injectable and unit-tested on Linux, while a macOS CI job exercises the real PTY and process-table path. @@ -158,7 +158,7 @@ The package ships concise tool guidance explaining persistent state, owner isola - Per-file coverage pins owner fencing, concurrent reservations, cancellation during pre-write inspection, unpublished-spawn cancellation and awaited teardown, sandbox-mode change rejection, retriable lifecycle cleanup, readiness tiers, rejection of pre-write stdin waits and delayed earlier prompts, the configured handoff grace holding the idle fallback past one poll and its rejection below `pollIntervalMs`, sanitizer carry state, complete UTF-8 bounds, task integration, schemas, and exact render intents. - Subprocess process fixtures cover non-leader and non-main-thread stdin waits, thread-local fd tables, the `/dev/tty` alias, supported kernel ABIs under user-mode emulation, rejection of fd 0 backed by a pipe, zombie quiescence, unreadable process state, unsupported architectures, and other false-positive rejection; macOS inspector logic is injected into the same unit suite. -- Real `node-pty` and PTY-consumer tests jointly exercise shell state, controlling-terminal input through `/dev/tty`, shared sandbox policy, environment scrubbing, raw-mode foreground `SIGINT`, a TERM-ignoring descendant, and immediate post-disposal quiescence on supported hosts. +- Real `node-pty` and PTY-consumer tests jointly exercise shell state, controlling-terminal input through `/dev/tty`, the exact attribution when process syscalls are readable, its bounded idle fallback when host policy denies them, shared sandbox policy, environment scrubbing, raw-mode foreground `SIGINT`, a TERM-ignoring descendant, and immediate post-disposal quiescence on supported hosts. - A Loader-driven `cordis.yml` test mounts the real three-package composition and verifies that delayed pipeline output returns with the completed command instead of being classified as terminal-input readiness. The SDK minimal snapshot pins that output through the persistent Bash tool; ACP and headless snapshots pin the six terminal schemas, bounded results, and errors through opt-in overlays; TUI snapshots pin terminal and generic card presentation. - Package contracts, the architecture map, subsystem pages, generated catalogs, and the website API describe the same shipped surface. diff --git a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md index 91d07c2dcd..5225d781fc 100644 --- a/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md +++ b/.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.zh.md @@ -74,7 +74,7 @@ UI 渲染约定精确且不携带位置信息。`terminal_send` 只为前台发 本地后端先识别受控 bash 启动时发出的私有 OSC prompt marker,并且只有在最近一个 marker 后的可打印尾部与受控 `PS1` 完全相等时才声明 prompt 就绪;除此之外,它还运行 3 个有界 fallback 层级。在 data callback 之间保留该尾部,可以适配 marker 与 prompt 被分开交付的情况;如果回显的输入或输出跟在延迟到达的先前 prompt 之后,要求尾部完全相等会拒绝该 prompt,使其无法完成当前 send。marker 在输出到达模型前被移除,使两个平台上的普通 shell 命令都无需固定等待静默阈值。尚未发布的 startup 不会把零输出静默视为就绪;timeout 会拒绝 spawn。若调用方取消在 startup 期间胜出,后端会关闭私有会话并原样抛出 `AbortSignal.reason`;尚不可观察的前台 PGID 不会再用查找错误覆盖取消原因。所有时间参数都是经校验的配置字段:`pollIntervalMs`、`exactProbeAfterMs`、`idleSilenceMs`、`handoffGraceMs` 和 `timeoutMs`。 -在 Linux 上,检查器从 `/proc//stat` 读取 shell 的终端前台 PGID,枚举该进程组中的每个进程与线程,并检查它们当前的 syscall。Tier 1 只有观察到 stdin 等待才返回正结果:直接 `read(0)`、获准读取且含 fd 0 的 `select`/`pselect6` 或 `poll`/`ppoll` 参数,或者含 fd 0 的 epoll interest list。等待线程的 `/proc//task//fd/0` 还必须标识 shell 的控制终端设备,因此线程本地 fd 表无法用 leader 的终端描述符冒充自身 fd,阻塞于管道的流水线读取端仍属于正在运行的命令。直接 PTY 描述符使用其设备号;`/dev/tty` 则使用所属进程的 `tty_nr`,因为 `stat` 报告的是别名设备而非选定的 PTY。终端输入前就已存在的等待并不代表写入后就绪:必须先观察到同一 PGID 脱离该等待,之后再次进入等待才能使该次 send 完成;前台 PGID 发生变化则构成新的证据。无法读取的进程内存和未识别的 syscall 都是 miss,绝不作为正向猜测。架构表只包含对应 Linux UAPI 定义的 syscall number;检查器先准入运行时架构,再检查每个受支持的内核 ABI,因为在用户态模拟下,`/proc` 可能报告不同的 ABI。不受支持的运行时架构会跳过 Tier 1。 +在 Linux 上,检查器从 `/proc//stat` 读取 shell 的终端前台 PGID,枚举该进程组中的每个进程与线程,并检查它们当前的 syscall。Tier 1 只有观察到 stdin 等待才返回正结果:直接 `read(0)`、获准读取且含 fd 0 的 `select`/`pselect6` 或 `poll`/`ppoll` 参数,或者含 fd 0 的 epoll interest list。等待线程的 `/proc//task//fd/0` 还必须标识 shell 的控制终端设备,因此线程本地 fd 表无法用 leader 的终端描述符冒充自身 fd,阻塞于管道的流水线读取端仍属于正在运行的命令。直接 PTY 描述符使用其设备号;`/dev/tty` 则使用所属进程的 `tty_nr`,因为 `stat` 报告的是别名设备而非选定的 PTY。终端输入前就已存在的等待并不代表写入后就绪:必须先观察到同一 PGID 脱离该等待,之后再次进入等待才能使该次 send 完成;前台 PGID 发生变化则构成新的证据。无法读取的进程内存和未识别的 syscall 都是 miss,绝不作为正向猜测。宿主策略(包括加固的 ptrace 策略)若拒绝读取 `/proc//task//syscall`,同样会跳过 Tier 1 并保留有界的 Tier 2 idle 推断;进程休眠状态绝不会代替不可访问的 syscall 证据。架构表只包含对应 Linux UAPI 定义的 syscall number;检查器先准入运行时架构,再检查每个受支持的内核 ABI,因为在用户态模拟下,`/proc` 可能报告不同的 ABI。不受支持的运行时架构会跳过 Tier 1。 macOS 没有精确 syscall 层。任何前台进程组输出静默都会返回 `inferred_idle`,包括 Python 和 `gdb`;从 `ps` 推导的终端 PGID 只用于发送信号,不作为「只有 shell 才能 idle」的证明。纯进程检查逻辑可注入,并在 Linux 上经过单元测试,同时由 macOS CI job 驱动真实 PTY 和进程表路径。 @@ -158,7 +158,7 @@ plugins: - 逐文件覆盖测试锁定了 owner 隔离、并发预留、写入前检查期间的取消、未发布 spawn 的取消与等待式 teardown、沙箱模式变更拒绝、可重试的生命周期清理、就绪层级、对写入前 stdin 等待与延迟到达的先前 prompt 的拒绝、配置化交接宽限把 idle fallback 顶过一次轮询以及低于 `pollIntervalMs` 时的拒绝、sanitizer carry state、完整 UTF-8 结果上限、task 集成、schema 和精确 render intent。 - 子进程 fixture(测试前置数据)覆盖非 leader 与非主线程的 stdin 等待、线程本地 fd 表、`/dev/tty` 别名、用户态模拟下受支持的内核 ABI、拒绝把指向管道的 fd 0 当作终端输入、僵尸进程完全停稳、不可读进程状态、不支持的架构和其他误报拒绝;同一单元测试套件通过注入覆盖 macOS 检查器逻辑。 -- 真实 `node-pty` 与 PTY 消费方测试共同在受支持宿主上覆盖 shell 状态、通过 `/dev/tty` 读取控制终端输入、共享沙箱策略、环境清洗、raw mode 前台 `SIGINT`、忽略 `SIGTERM` 的后代进程,以及 dispose 返回后立即完全停稳。 +- 真实 `node-pty` 与 PTY 消费方测试共同在受支持宿主上覆盖 shell 状态、通过 `/dev/tty` 读取控制终端输入、进程 syscall 可读时的精确归因、宿主策略拒绝读取时的有界 idle fallback、共享沙箱策略、环境清洗、raw mode 前台 `SIGINT`、忽略 `SIGTERM` 的后代进程,以及 dispose 返回后立即完全停稳。 - Loader 驱动的 `cordis.yml` 测试挂载真实三包组合,并验证延迟到达的流水线输出随已完成命令返回,而不会被归类为终端输入就绪。SDK minimal 快照通过持久 Bash 工具固定该输出;ACP 与 headless 快照通过 opt-in overlay 固定 6 个终端 schema、有界结果和错误;TUI 快照固定 terminal 与 generic 卡片展示。 - 包约定、架构图、子系统页面、生成目录和 website API 描述同一个已发布接口。 diff --git a/packages/subprocess/subprocess-local/README.i18n.yaml b/packages/subprocess/subprocess-local/README.i18n.yaml index 3e021ac000..2a89608a4e 100644 --- a/packages/subprocess/subprocess-local/README.i18n.yaml +++ b/packages/subprocess/subprocess-local/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/subprocess/subprocess-local/README.md -README.md: b3e74b75b69dc4c726749b4798f24f3058749ea9 -README.zh.md: bdbbc723fd89574425b3391bc6c4d9639b0cfdac +README.md: 9dc9efff220f8d1e60766438be39c3a5a0708cfa +README.zh.md: 0090942019a693025f653a0f52fc4f4243fb679a diff --git a/packages/subprocess/subprocess-local/README.md b/packages/subprocess/subprocess-local/README.md index b3e74b75b6..9dc9efff22 100644 --- a/packages/subprocess/subprocess-local/README.md +++ b/packages/subprocess/subprocess-local/README.md @@ -11,7 +11,7 @@ Local Service Provider for the [`@deepseek-ai/dsh-subprocess`](../subprocess/REA - **Credential scrub + explicit merge** — `process.env` minus credential-shaped vars (`*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`) and all ambient `DSH_*` names; the spec's explicit `env` merges after that scrub with no namespace validation, so a deliberately supplied credential or current `DSH_*` fact wins while stale nested-harness identity cannot leak in ambiently. Supplied stdin is written and closed; otherwise fd 0 is `/dev/null`. See the [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.md) and [managed environment Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md). - **Offset-based reads** — collect-mode readers return deltas in whole-stream byte coordinates; the service never holds a cursor, so consumer-owned cursors (the bash background read path) and full-stream re-reads coexist, before and after settlement. - **Executable lookup** — `resolveExecutable` checks absolute files or searches the scrubbed effective PATH with platform-aware executable extensions; relative paths containing separators are rejected at the seam, and relative PATH entries resolve from the host process cwd. -- **Terminal-process ownership** — `spawnTerminal` allocates `node-pty`, bridges UTF-8 terminal text, inspects and signals the current foreground process group, and exposes one awaited termination operation that sweeps descendants before and after terminating the top-level shell. Linux reports an exact input wait only when the waiting thread's own fd 0 identifies the shell's controlling terminal, including the `/dev/tty` alias, so a pipeline reader blocked on `pipe:[…]` cannot publish terminal readiness. The syscall probe admits supported runtime architectures and matches every supported kernel ABI so user-mode emulation cannot hide the wait. Each foreground inspection retains exact identities from the rooted tree; Linux also enumerates the POSIX session after its leader exits. A previously observed macOS descendant and any same-session Linux member therefore remain fenced after reparenting, while pid/start identity prevents cleanup from following PID reuse. On Windows the koffi-backed inspector enumerates the process table through Toolhelp32, combines GetProcessTimes start identities with zero-time process-handle waits for liveness, reports the shell pid as the pseudo foreground group (Windows has no POSIX groups), and teardown verifies the shell's termination because externally taskkilled shells may never fire node-pty's exit notification. The higher PTY backend owns prompt readiness, buffers, and model-facing operations. +- **Terminal-process ownership** — `spawnTerminal` allocates `node-pty`, bridges UTF-8 terminal text, inspects and signals the current foreground process group, and exposes one awaited termination operation that sweeps descendants before and after terminating the top-level shell. Linux reports an exact input wait only when the waiting thread's own fd 0 identifies the shell's controlling terminal, including the `/dev/tty` alias, so a pipeline reader blocked on `pipe:[…]` cannot publish terminal readiness. The syscall probe admits supported runtime architectures and matches every supported kernel ABI so user-mode emulation cannot hide the wait. When Linux denies `/proc//task//syscall`, the inspector reports no exact wait and leaves the higher PTY backend to its configured idle inference; process sleep state never substitutes for syscall evidence. Each foreground inspection retains exact identities from the rooted tree; Linux also enumerates the POSIX session after its leader exits. A previously observed macOS descendant and any same-session Linux member therefore remain fenced after reparenting, while pid/start identity prevents cleanup from following PID reuse. On Windows the koffi-backed inspector enumerates the process table through Toolhelp32, combines GetProcessTimes start identities with zero-time process-handle waits for liveness, reports the shell pid as the pseudo foreground group (Windows has no POSIX groups), and teardown verifies the shell's termination because externally taskkilled shells may never fire node-pty's exit notification. The higher PTY backend owns prompt readiness, buffers, and model-facing operations. - **Terminate-and-join disposal** — the service retains live handles so its own disposal can escalate every running tree and await its exit; quiescent and spawn-failed handles leave the live set after whole-tree or terminal-session cleanup finishes. - **Synchronous host-exit finalization** — while the service effect is active, a Node `exit` listener force-terminates every ordinary tree and observable terminal session still in the same live sets. The local-only operations send POSIX SIGKILL to the managed group, run Windows `taskkill /T /F`, and synchronously signal captured/current terminal identities around the PTY root kill; they create no promise or timer, preserve the host's exit code and diagnostic, contain each target's failure, and do not claim quiescence. Normal disposal keeps the awaited graceful path above. See the [host-exit cleanup decision](../../../.agents/notes/implemented/bug-fix/2026-08-11-synchronous-subprocess-exit-cleanup.md). diff --git a/packages/subprocess/subprocess-local/README.zh.md b/packages/subprocess/subprocess-local/README.zh.md index bdbbc723fd..0090942019 100644 --- a/packages/subprocess/subprocess-local/README.zh.md +++ b/packages/subprocess/subprocess-local/README.zh.md @@ -11,7 +11,7 @@ - **凭据清除 + 显式合并**:以 `process.env` 为基础,移除形似凭据的变量(`*KEY*`/`*PASSWORD*`/`*SECRET*`/`*TOKEN*`)和所有环境中已有的 `DSH_*` 名称;spec 的显式 `env` 在该清除之后合并且不做命名空间校验,因此有意提供的凭据或当前 `DSH_*` 事实会胜出,而陈旧的嵌套 harness 身份无法从环境中隐式漏入。提供的 stdin 会被写入后关闭;否则 fd 0 指向 `/dev/null`。参见 [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.zh.md)与[受管环境 Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.zh.md)。 - **基于偏移量的读取**:收集模式的读取器按完整流的字节坐标返回增量;服务自身从不持有游标,因此消费方自有的游标(bash 的后台读取路径)与完整流重读可以共存,结算前后皆然。 - **可执行文件查找**:`resolveExecutable` 检查绝对文件,或根据平台可执行文件扩展名在清理后的有效 PATH 中搜索;含分隔符的相对路径在该 seam 处被拒绝,相对 PATH 条目从宿主进程 cwd 解析。 -- **终端进程所有权**:`spawnTerminal` 分配 `node-pty`,桥接 UTF-8 终端文本,检查当前前台进程组并向其发送信号,还会公开一项须等待的终止操作,在终止顶层 shell 前后清理后代进程。Linux 只有在等待线程自身的 fd 0 标识 shell 的控制终端(包括 `/dev/tty` 别名)时才报告精确输入等待,因此阻塞于 `pipe:[…]` 的流水线读取端无法发布终端就绪状态。syscall 探针会准入受支持的运行时架构并匹配每个受支持的内核 ABI,使用户态模拟无法隐藏该等待。每次前台检查都会保留根进程树中的精确身份;Linux 还会在 POSIX 会话 leader 退出后枚举该会话。因此,之前观察到的 macOS 后代以及同会话 Linux 成员在重新设定父进程后仍受围栏保护,pid/start 身份则防止清理跟随 PID 复用。在 Windows 上,基于 koffi 的检查器通过 Toolhelp32 枚举进程表,把 GetProcessTimes 启动身份与进程句柄零时等待结合起来判断存活状态,并把 shell pid 作为伪前台进程组(Windows 没有 POSIX 进程组)。拆卸会验证 shell 已终止,因为被外部 taskkill 的 shell 可能永远不会触发 node-pty 的退出通知。上层 PTY 后端负责提示符就绪、缓冲区与面向模型的操作。 +- **终端进程所有权**:`spawnTerminal` 分配 `node-pty`,桥接 UTF-8 终端文本,检查当前前台进程组并向其发送信号,还会公开一项须等待的终止操作,在终止顶层 shell 前后清理后代进程。Linux 只有在等待线程自身的 fd 0 标识 shell 的控制终端(包括 `/dev/tty` 别名)时才报告精确输入等待,因此阻塞于 `pipe:[…]` 的流水线读取端无法发布终端就绪状态。syscall 探针会准入受支持的运行时架构并匹配每个受支持的内核 ABI,使用户态模拟无法隐藏该等待。当 Linux 拒绝读取 `/proc//task//syscall` 时,检查器不会报告精确等待,而是由上层 PTY 后端按配置执行 idle 推断;进程休眠状态绝不会代替 syscall 证据。每次前台检查都会保留根进程树中的精确身份;Linux 还会在 POSIX 会话 leader 退出后枚举该会话。因此,之前观察到的 macOS 后代以及同会话 Linux 成员在重新设定父进程后仍受围栏保护,pid/start 身份则防止清理跟随 PID 复用。在 Windows 上,基于 koffi 的检查器通过 Toolhelp32 枚举进程表,把 GetProcessTimes 启动身份与进程句柄零时等待结合起来判断存活状态,并把 shell pid 作为伪前台进程组(Windows 没有 POSIX 进程组)。拆卸会验证 shell 已终止,因为被外部 taskkill 的 shell 可能永远不会触发 node-pty 的退出通知。上层 PTY 后端负责提示符就绪、缓冲区与面向模型的操作。 - **先终止再等待退出的 dispose(资源释放)**:服务保留存活句柄,使自身的 dispose 能对每个仍在运行的进程树执行升级并等待其退出;完全停稳与 spawn 失败的句柄会在整棵进程树或 terminal session 清理完成后离开存活集合。 - **同步宿主退出最终清理**:服务 effect 仍有效时,Node `exit` listener 会强制终止同一组存活集合中仍存在的每棵普通进程树和可观察 terminal session。这些仅供本地实现使用的操作会向受管 POSIX 进程组发送 SIGKILL、在 Windows 运行 `taskkill /T /F`,并在终止 PTY root 前后同步向已捕获及当前可观察的 terminal 身份发送信号;它们不会创建 Promise 或 timer,不改变宿主退出码与诊断,会分别包含每个目标的失败,也不会声称已经完全停稳。正常 dispose 仍使用上面的须等待温和路径。参见[宿主退出清理决策](../../../.agents/notes/implemented/bug-fix/2026-08-11-synchronous-subprocess-exit-cleanup.zh.md)。 diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index 254ea11415..ad6dbc010d 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync } from 'node:fs' +import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' import { spawnSync } from 'node:child_process' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -118,53 +118,15 @@ function processIsRunning(pid: number): boolean { } } -function linuxBashProcDiagnostics(): string { - const read = (path: string): string => { - try { - return readFileSync(path, 'utf8').trim() - } catch (error) { - return error instanceof Error ? `${error.name}: ${error.message}` : String(error) - } +function canReadLinuxProcessSyscall(pid: number): boolean { + try { + readFileSync(`/proc/${pid}/task/${pid}/syscall`, 'utf8') + return true + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code === 'EACCES' || code === 'EPERM') return false + throw error } - const ps = spawnSync('/bin/ps', ['-eo', 'pid=,ppid=,pgid=,sid=,stat=,args='], { encoding: 'utf8' }) - const bash = ps.stdout.split('\n').filter(line => /(?:^|\s)(?:\/bin\/)?bash(?:\s|$)/.test(line)) - const processes = bash.map((line) => { - const pid = /^\s*(\d+)/.exec(line)?.[1] - if (pid === undefined) return { line } - let tids: string[] - try { - tids = readdirSync(`/proc/${pid}/task`) - } catch (error) { - return { line, tasks: error instanceof Error ? `${error.name}: ${error.message}` : String(error) } - } - return { - line, - stat: read(`/proc/${pid}/stat`), - tasks: tids.map((tid) => { - const fd = `/proc/${pid}/task/${tid}/fd/0` - let fd0: string - let rdev: string - try { - fd0 = readlinkSync(fd) - } catch (error) { - fd0 = error instanceof Error ? `${error.name}: ${error.message}` : String(error) - } - try { - const device = statSync(fd) - rdev = `${device.rdev} character=${device.isCharacterDevice()}` - } catch (error) { - rdev = error instanceof Error ? `${error.name}: ${error.message}` : String(error) - } - return { tid, syscall: read(`/proc/${pid}/task/${tid}/syscall`), fd0, rdev } - }), - } - }) - return JSON.stringify({ - arch: process.arch, - machine: spawnSync('/bin/uname', ['-m'], { encoding: 'utf8' }).stdout.trim(), - ptraceScope: read('/proc/sys/kernel/yama/ptrace_scope'), - processes, - }, undefined, 2) } // The real-shell suite drives a POSIX bash over the actual node-pty terminal; @@ -213,23 +175,27 @@ describe.skipIf(process.platform === 'win32')('terminal-bash real shell', () => }, 20_000) it.skipIf(process.platform !== 'linux')('recognizes a foreground read opened through /dev/tty', async () => { - const { ctx, agent } = await harness('danger-full-access', { + const { ctx, root, agent } = await harness('danger-full-access', { idleSilenceMs: 5_000, timeoutMs: 8_000, }) const created = await ctx.terminals.spawn(agent, { type: 'shell' }) + const readerPidFile = join(root, 'tty-reader.pid') const waiting = ctx.terminals.startSend(agent, created.sessionId, { - text: 'bash -c \'exec "$1"; printf "WAITING\\n"; read -r answer; printf "ANSWER=%s\\n" "$answer"' dsh "${readerPidFile}"`, submit: true, }) await waitForOutput(waiting, 'WAITING') - expect((await waiting.done).waitReason, linuxBashProcDiagnostics()).toBe('stdin_read') + const result = await waiting.done + const readerPid = Number(readFileSync(readerPidFile, 'utf8')) + expect(readerPid).toBeGreaterThan(0) + expect(result.waitReason).toBe(canReadLinuxProcessSyscall(readerPid) ? 'stdin_read' : 'inferred_idle') const answer = ctx.terminals.startSend(agent, created.sessionId, { text: 'accepted', submit: true }) - const result = await answer.done - expect(result.waitReason).toBe('stdin_read') - expect(result.viewport).toContain('ANSWER=accepted') + const answered = await answer.done + expect(answered.waitReason).toBe('stdin_read') + expect(answered.viewport).toContain('ANSWER=accepted') await ctx.terminals.kill(agent, created.sessionId) }, 20_000) From 3e24087bfaeabe40b58ba2f7b936895b8f93fe27 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Tue, 25 Aug 2026 00:59:04 +0800 Subject: [PATCH 23/31] fix(web): authenticate the browser Host API --- ...07-28-api-browser-trust-boundary.i18n.yaml | 4 +- .../2026-07-28-api-browser-trust-boundary.md | 10 +- ...026-07-28-api-browser-trust-boundary.zh.md | 10 +- ...26-07-30-config-plane-boundaries.i18n.yaml | 4 +- .../2026-07-30-config-plane-boundaries.md | 2 +- .../2026-07-30-config-plane-boundaries.zh.md | 2 +- .../2026-07-30-web-config-plane.i18n.yaml | 4 +- .../2026-07-30-web-config-plane.md | 4 +- .../2026-07-30-web-config-plane.zh.md | 4 +- ...-08-03-per-session-agent-presets.i18n.yaml | 4 +- .../2026-08-03-per-session-agent-presets.md | 2 +- ...2026-08-03-per-session-agent-presets.zh.md | 2 +- ...-provider-endpoint-interrogation.i18n.yaml | 4 +- ...4-draft-provider-endpoint-interrogation.md | 2 +- ...raft-provider-endpoint-interrogation.zh.md | 2 +- ...08-04-websocket-downlink-carrier.i18n.yaml | 4 +- .../2026-08-04-websocket-downlink-carrier.md | 2 +- ...026-08-04-websocket-downlink-carrier.zh.md | 2 +- ...12-plugin-owned-settings-surface.i18n.yaml | 4 +- ...026-08-12-plugin-owned-settings-surface.md | 2 +- ...-08-12-plugin-owned-settings-surface.zh.md | 2 +- ...-24-browser-token-authentication.i18n.yaml | 6 + ...2026-08-24-browser-token-authentication.md | 45 +++ ...6-08-24-browser-token-authentication.zh.md | 45 +++ ...8-06-host-backed-web-preferences.i18n.yaml | 4 +- .../2026-08-06-host-backed-web-preferences.md | 4 +- ...26-08-06-host-backed-web-preferences.zh.md | 4 +- .../2026-07-22-web-bind-address.i18n.yaml | 4 +- .../feature/2026-07-22-web-bind-address.md | 10 +- .../feature/2026-07-22-web-bind-address.zh.md | 10 +- ...-07-28-tool-call-file-open-in-os.i18n.yaml | 4 +- .../2026-07-28-tool-call-file-open-in-os.md | 2 +- ...2026-07-28-tool-call-file-open-in-os.zh.md | 4 +- ...-shared-modal-product-onboarding.i18n.yaml | 4 +- ...6-08-13-shared-modal-product-onboarding.md | 2 +- ...8-13-shared-modal-product-onboarding.zh.md | 2 +- ...08-08-copy-only-preset-authoring.i18n.yaml | 4 +- .../2026-08-08-copy-only-preset-authoring.md | 4 +- ...026-08-08-copy-only-preset-authoring.zh.md | 4 +- ...-unary-apiproxy-remote-migration.i18n.yaml | 4 +- ...6-08-10-unary-apiproxy-remote-migration.md | 19 +- ...8-10-unary-apiproxy-remote-migration.zh.md | 19 +- apps/cli/package.json | 4 +- .../tests/fixtures/web-browser-open/open.mjs | 10 +- apps/cli/tests/github-webhook-real.e2e.ts | 39 ++- apps/cli/tests/web-auth.e2e.ts | 210 +++++++++++++ .../tests/web-browser-open.expected.e2e.ts | 15 +- apps/web/package.json | 4 +- apps/web/tests/smoke-real.e2e.ts | 51 +++- docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 16 +- docs/config-catalog.zh.md | 16 +- docs/subsystems/web-server.i18n.yaml | 4 +- docs/subsystems/web-server.md | 4 +- docs/subsystems/web-server.zh.md | 4 +- packages/api/gateway/src/index.ts | 8 +- packages/api/gateway/src/stream-server.ts | 11 +- .../gateway/tests/gateway-stream.host.spec.ts | 61 +++- .../api/gateway/tests/gateway.host.spec.ts | 41 ++- packages/bundle/web-app/README.i18n.yaml | 4 +- packages/bundle/web-app/README.md | 2 +- packages/bundle/web-app/README.zh.md | 2 +- packages/bundle/web-app/src/index.ts | 82 +++--- packages/bundle/web-app/tests/web-app.spec.ts | 43 ++- packages/bundle/web-app/tsconfig.json | 3 + packages/client/connection/README.i18n.yaml | 4 +- packages/client/connection/README.md | 12 +- packages/client/connection/README.zh.md | 12 +- packages/client/connection/package.json | 2 + .../client/connection/src/browser-auth.ts | 276 ++++++++++++++++++ packages/client/connection/src/index.ts | 103 ++----- packages/client/connection/src/invariant.ts | 11 +- packages/client/connection/src/rpc-host.ts | 53 ++-- packages/client/connection/src/rpc.ts | 49 +++- .../tests/browser-auth.host.spec.ts | 231 +++++++++++++++ .../connection/tests/node-half.host.spec.ts | 262 ++++++++++------- packages/client/connection/tsconfig.host.json | 4 + packages/client/locale/README.i18n.yaml | 4 +- packages/client/locale/README.md | 2 +- packages/client/locale/README.zh.md | 2 +- .../client/ui-agent-preset/README.i18n.yaml | 4 +- packages/client/ui-agent-preset/README.md | 2 +- packages/client/ui-agent-preset/README.zh.md | 2 +- .../src/client/settings-store.ts | 2 +- .../tests/settings-store.client.spec.ts | 4 +- .../src/client/settings-store.ts | 2 +- .../ui-settings-general/README.i18n.yaml | 4 +- packages/client/ui-settings-general/README.md | 2 +- .../client/ui-settings-general/README.zh.md | 2 +- .../tests/apply.client.spec.ts | 2 +- .../tests/welcome-store.client.spec.ts | 2 +- packages/client/ui-settings/README.i18n.yaml | 4 +- packages/client/ui-settings/README.md | 2 +- packages/client/ui-settings/README.zh.md | 2 +- .../ui-settings/src/client/settings-mirror.ts | 2 +- .../ui-settings/src/client/settings-scope.ts | 2 +- packages/client/ui-theme/README.i18n.yaml | 4 +- packages/client/ui-theme/README.md | 2 +- packages/client/ui-theme/README.zh.md | 2 +- packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 6 +- packages/host/apiproxy/README.zh.md | 6 +- packages/host/apiproxy/src/api-proxy.ts | 5 +- .../host/apiproxy/src/api/agent-presets.ts | 10 +- packages/host/apiproxy/src/api/host.ts | 4 +- packages/host/apiproxy/src/api/settings.ts | 4 +- .../apiproxy/tests/api-proxy-config.spec.ts | 4 +- .../host/frontend-static/README.i18n.yaml | 4 +- packages/host/frontend-static/README.md | 2 + packages/host/frontend-static/README.zh.md | 2 + packages/host/frontend-static/package.json | 3 + packages/host/frontend-static/src/index.ts | 22 +- .../tests/frontend-static.spec.ts | 46 ++- packages/host/frontend-static/tsconfig.json | 3 + pnpm-lock.yaml | 21 ++ 115 files changed, 1617 insertions(+), 522 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md create mode 100644 .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md create mode 100644 apps/cli/tests/web-auth.e2e.ts create mode 100644 packages/client/connection/src/browser-auth.ts create mode 100644 packages/client/connection/tests/browser-auth.host.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml index c206e01dba..f2e1a2ed33 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md -2026-07-28-api-browser-trust-boundary.md: 92b76c109aa9b55bc72bb76f8b208ea2d814d8ce -2026-07-28-api-browser-trust-boundary.zh.md: 653ff32f2e62bf0e2982517f82649ff2d06e40d4 +2026-07-28-api-browser-trust-boundary.md: 2997b0f2affaac59be9cd58108bc20086442f6db +2026-07-28-api-browser-trust-boundary.zh.md: ff952ede9adc53c9d590ad2ba24a32b448172f82 diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md index 92b76c109a..2997b0f2af 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md @@ -6,7 +6,7 @@ English | [中文](2026-07-28-api-browser-trust-boundary.zh.md) ## Problem -The web GUI host serves `/api` over plain HTTP (default `127.0.0.1:3080`, `--host 0.0.0.0` supported), and the surface includes remote-code-execution-grade methods — `session.prompt` drives an agent that runs bash. A browser turns the operator into a confused deputy against such a local API in two classic ways: a malicious page fires a "simple" cross-site POST (`text/plain` — sent without a CORS preflight) whose side effects execute even though the response stays unreadable, and a DNS-rebound origin talks to the socket as if same-origin, making CORS inapplicable entirely, with only the `Host` header betraying the attacker's domain. Before this decision the system's only browser-trust check (`isTrustedNativeDialogRequest`: loopback socket + same-origin + loopback Host) guarded exactly one cosmetic route — `host.pickDirectory`, whose native dialog pops on the host's screen — while every consequential method was unguarded. Guarding per-RPC also could not survive the in-app directory browser, whose whole point is serving legitimately remote clients that a loopback rule would refuse. +The web GUI host serves `/api` over plain loopback HTTP (default `127.0.0.1:3080`; the CLI rejects `--host 0.0.0.0`), and the surface includes remote-code-execution-grade methods — `session.prompt` drives an agent that runs bash. A browser turns the operator into a confused deputy against such a local API in two classic ways: a malicious page fires a "simple" cross-site POST (`text/plain` — sent without a CORS preflight) whose side effects execute even though the response stays unreadable, and a DNS-rebound origin talks to the socket as if same-origin, making CORS inapplicable entirely, with only the `Host` header betraying the attacker's domain. Before this decision the system's only browser-trust check (`isTrustedNativeDialogRequest`: loopback socket + same-origin + loopback Host) guarded exactly one cosmetic route — `host.pickDirectory`, whose native dialog pops on the host's screen — while every consequential method was unguarded. Guarding per-RPC also could not survive the in-app directory browser, whose whole point is serving legitimately remote clients that a loopback rule would refuse. ## Decision @@ -15,17 +15,17 @@ Enforce browser trust once, at the carrier, for the entire `/api` prefix — two - **Media-type fence (dsh-host-apiproxy)**: every `/api` POST must declare `application/json`, else 415 before parsing. Cross-site "simple" requests thereby stop existing: any cross-site attempt is forced into a CORS preflight this server never answers. - **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: every request must present a `Host` that is loopback or matches a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense). Deliberately no shortcut for unmarked requests: over plain HTTP a browser attaches neither `Origin` nor Fetch-Metadata to reads (EventSource, images, navigations — those headers go only to trustworthy destinations), so an unmarked request may be a rebound browser read whose response the page can read, and Host is the one header rebinding cannot forge; non-browser clients pass via loopback, the derived LAN IP literals, or a declared authority. An attached `Origin` must equal the Host authority; `sec-fetch-site: cross-site` is refused outright. A `trustedHosts` entry that is not a bare, canonical authority fails the plugin load — WHATWG parsing would otherwise quietly authorize the hostname inside a typo or broaden an exact-port grant. `host.pickDirectory` loses its bespoke guard and rides the same fence. -Two boundaries stay deliberately out of scope: reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and authentication for genuinely remote deployments is deferred work recorded in the connection README — the fence is a confused-deputy defense, not an auth layer. The old guard's loopback-socket check was dropped rather than generalized: with binding expressing reachability and `trustedHosts` naming remote authorities, the socket address adds nothing a header fence does not already cover. +Reachability remains the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and this fence remains a confused-deputy defense rather than identity. Connection applies the separate [browser token authentication](2026-08-24-browser-token-authentication.md) after the fence. The old guard's loopback-socket check was dropped rather than generalized: with binding expressing reachability and `trustedHosts` naming accepted authorities, the socket address adds nothing the Host/Origin checks need. ## Alternatives considered - **Per-RPC guards (status quo extended).** Rejected: the guard list trails the method list forever, the highest-value methods were already unguarded, and a loopback rule on browse RPCs would break the remote deployments they exist for. - **CORS headers + credential omission.** Rejected: we never want cross-origin reads at all, so answering preflights only widens the surface; refusing them is strictly stronger and simpler. -- **Authentication tokens.** Rejected for this change: token minting/storage/rotation is real product surface; the fence closes the browser-deputy holes without pre-deciding the auth design. +- **Authentication tokens.** Rejected for this change: token minting, storage, and rotation are separate product decisions. The later [browser token authentication](2026-08-24-browser-token-authentication.md) owns them without changing this fence. ## Consequences - Any future `/api` method is covered by construction; there is no per-route trust decision left to forget. -- Non-loopback deployments must have their serving authorities trusted or requests are refused. The dsh CLI keeps its advertised `--host 0.0.0.0` LAN URL working by deriving the machine's LAN IP literals into the connection row (port-less entries — an IP-literal Host cannot be a rebound name, and the bound port may be OS-assigned) and offers `dsh web --trusted-host` for named authorities; compositions the CLI does not boot declare `trustedHosts` themselves. Non-browser automation rides the same fence: loopback, a derived LAN IP, or a declared authority passes; an undeclared DNS alias is refused. +- A custom non-loopback composition must trust its serving authorities or requests are refused, then satisfy browser authentication like every loopback request. The shipped CLI rejects `--host 0.0.0.0`; `--trusted-host` only extends the Host/Origin fence and grants no identity. - Clients must label POST bodies `application/json` (ours always did; raw-fetch tests gained the header). -- The trusted-network assumption of an unauthenticated `0.0.0.0` deployment is now documented instead of implicit. +- Host and Origin remain request-routing evidence only. The process token and signed cookie establish the browser identity used by every Host method. diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md index 653ff32f2e..ff952ede9a 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md @@ -6,7 +6,7 @@ Status: implemented ## 问题 -Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--host 0.0.0.0`),而这个面上有远程代码执行级别的方法——`session.prompt` 驱动的 agent(智能体)可以运行 bash。浏览器会用两种经典方式把操作者变成攻击此类本地 API 的「混淆代理人」:恶意页面发出跨站「简单请求」 POST(`text/plain`——不经 CORS 预检即发出),其副作用照常执行、只是响应不可读;以及 DNS rebinding 后的源以「同源」身份直连 socket,CORS 整体失效,只有 `Host` 头会暴露攻击者的域名。在本决策之前,系统里唯一的浏览器信任检查(`isTrustedNativeDialogRequest`:回环 socket、同源、回环 Host)只守着一个装饰性的路由——`host.pickDirectory`,其原生对话框弹在宿主屏幕上——而所有真正具有严重后果的方法都没有防护。按 RPC 逐个设防也活不过应用内目录浏览器:它存在的意义就是服务合法的远程客户端,回环规则恰恰会拒绝它们。 +Web GUI 宿主以纯 loopback HTTP 提供 `/api`(默认 `127.0.0.1:3080`;CLI 拒绝 `--host 0.0.0.0`),而这个面上有远程代码执行级别的方法——`session.prompt` 驱动的 agent(智能体)可以运行 bash。浏览器会用两种经典方式把操作者变成攻击此类本地 API 的「混淆代理人」:恶意页面发出跨站「简单请求」 POST(`text/plain`——不经 CORS 预检即发出),其副作用照常执行、只是响应不可读;以及 DNS rebinding 后的源以「同源」身份直连 socket,CORS 整体失效,只有 `Host` 头会暴露攻击者的域名。在本决策之前,系统里唯一的浏览器信任检查(`isTrustedNativeDialogRequest`:回环 socket、同源、回环 Host)只守着一个装饰性的路由——`host.pickDirectory`,其原生对话框弹在宿主屏幕上——而所有真正具有严重后果的方法都没有防护。按 RPC 逐个设防也活不过应用内目录浏览器:它存在的意义就是服务合法的远程客户端,回环规则恰恰会拒绝它们。 ## 决策 @@ -15,17 +15,17 @@ Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--ho - **媒体类型栅栏(dsh-host-apiproxy)**:每个 `/api` POST 必须声明 `application/json`,否则在解析前以 415 拒绝。跨站「简单请求」由此不复存在:任何跨站尝试都被逼进一次本服务器从不应答的 CORS 预检。 - **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:每个请求的 `Host` 都必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御)。刻意不为无标记请求开捷径:明文 HTTP 下浏览器的读取(EventSource、图片、导航——这些头只发给可信目标)既不带 `Origin` 也不带 Fetch-Metadata,因此无标记请求可能是被重绑页面发起且响应可被读走的读取,而 Host 是重绑唯一伪造不了的请求头;非浏览器客户端经由回环地址、推导的 LAN IP 字面量或已声明的权威通过。若带 `Origin` 则必须与 Host 权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不是单纯规范化 authority 的 `trustedHosts` 条目会导致插件加载失败——否则 WHATWG 解析会悄悄授权笔误里的 hostname,或放大精确端口授权。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 -两条边界刻意留在范围之外:可达性由 webserver 的绑定配置(`host: 127.0.0.1 | 0.0.0.0`)控制;真正远程部署的认证是延期工作,记录在 connection README——这道栅栏是混淆代理人防御,不是认证层。旧守卫的回环 socket 检查被放弃而非泛化:绑定表达可达性、`trustedHosts` 点名远程权威之后,socket 地址提供不了头部栅栏覆盖不到的任何东西。 +可达性仍由 webserver 的绑定配置(`host: 127.0.0.1 | 0.0.0.0`)控制,这道栅栏仍是混淆代理人防御,而不是身份。Connection 在栅栏之后应用独立的[浏览器令牌认证](2026-08-24-browser-token-authentication.zh.md)。旧守卫的回环 socket 检查被放弃而非泛化:绑定表达可达性、`trustedHosts` 点名接受的 authority 之后,socket 地址提供不了 Host/Origin 校验需要的额外信息。 ## 曾考虑的替代方案 - **按 RPC 设防(延续现状)。** 否决:守卫清单永远追着方法清单跑,价值最高的方法本来就没被守住,而 browse RPC 上的回环规则会破坏它们为之存在的远程部署。 - **CORS 头与省略凭据。** 否决:我们根本不想要任何跨源读取,应答预检只会扩大暴露面;拒绝预检严格更强也更简单。 -- **认证令牌。** 在本变更中否决:令牌的签发、存储、轮换是真实的产品面;栅栏能够封死浏览器混淆代理人漏洞,无需预先决定认证设计。 +- **认证令牌。** 在本变更中否决:令牌签发、存储与轮换属于独立产品决策。后续[浏览器令牌认证](2026-08-24-browser-token-authentication.zh.md)持有这些机制,不改变本栅栏。 ## 后果 - 未来任何 `/api` 方法天然在覆盖范围内;不存在会被遗忘的按路由信任决定。 -- 非回环部署的对外服务 authority 必须列入信任范围,否则请求会被拒绝。dsh CLI 通过把本机 LAN IP 字面量推导进 connection 行(不带端口的条目——IP 字面量 Host 不可能是被重绑的域名,且绑定端口可能由操作系统分配)来保住它公布的 `--host 0.0.0.0` LAN URL,并提供 `dsh web --trusted-host` 声明具名权威;并非由 CLI 启动的组合自行声明 `trustedHosts`。非浏览器自动化走同一道栅栏:回环地址、推导的 LAN IP 或已声明的权威可通过;未声明的 DNS 别名会被拒绝。 +- 自定义非 loopback 组合必须信任其服务 authority,否则请求会被拒绝;随后仍像每个 loopback 请求一样满足浏览器认证。随附 CLI 拒绝 `--host 0.0.0.0`;`--trusted-host` 只扩展 Host/Origin 栅栏,绝不授予身份。 - 客户端必须给 POST 体标注 `application/json`(我们自己的客户端一向如此;裸 fetch 测试补上了该头)。 -- 无认证 `0.0.0.0` 部署的「可信网络」假设从隐含变为成文。 +- Host 与 Origin 仍只是请求路由证据。进程令牌与签名 cookie 建立每个 Host 方法使用的浏览器身份。 diff --git a/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.i18n.yaml index ac8f90ed76..08e1de4e5f 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.md -2026-07-30-config-plane-boundaries.md: 7b234ec64669cc1e6f0d5a67437005747edcea98 -2026-07-30-config-plane-boundaries.zh.md: f543c511d9374a50955331911b2eb2d62dab0675 +2026-07-30-config-plane-boundaries.md: d7ae13f08ca5c3957a8a5c1871b0022453e9b562 +2026-07-30-config-plane-boundaries.zh.md: e53a68f91f4d961af5a01fd7bbfb4472b4b17dfe diff --git a/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.md b/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.md index 7b234ec646..d7ae13f08c 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.md +++ b/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.md @@ -20,7 +20,7 @@ Three smaller defects sat beside them. `llm/adapters-updated` documented contain ## Decision -**Reading configuration is as privileged as writing it.** `settings.describe` and `credentials.describe` join the loopback-only set, so the whole configuration plane stays same-origin until real authentication exists. The model catalog (`llm.providers`, `llm.models`) deliberately does not: it carries provider ids, display names, and model lists — no endpoints, no key state — and a LAN client's model picker needs it. The boundary is asserted over a real HTTP server rather than a hand-assembled request, because the `Host` header a browser actually sends is what decides it. +**Reading configuration is as privileged as writing it.** `settings.describe`, `credentials.describe`, the model catalog, and every other Host operation require one browser session. The configuration plane still redacts secrets independently of authentication. The boundary is asserted over a real HTTP server rather than a hand-assembled request, proving that a forged loopback `Host` value never establishes identity. **The plane serves exactly the namespaces a registered model provider addresses.** `ctx.llm.listConfigurableProviders()` is the allow-list, so the product boundary is enforced rather than inferred from the installed plugin set, and a future namespace becomes web-configurable only by joining that directory. An unregistered namespace and an unexposed one answer identically (`settings-not-exposed`), so probing cannot enumerate the registry. diff --git a/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.zh.md b/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.zh.md index f543c511d9..e53a68f91f 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-30-config-plane-boundaries.zh.md @@ -20,7 +20,7 @@ Status: implemented ## 决策 -**读取配置与写入配置同样属于特权操作。**`settings.describe` 与 `credentials.describe` 加入仅限回环的集合,因此在真正的认证层出现之前,整个配置面都保持同源。模型目录(`llm.providers`、`llm.models`)刻意不在其中:它携带的是提供方 id、显示名与模型列表——没有端点、没有密钥状态——而 LAN 客户端的模型选择器正需要它。这条边界由一台真实 HTTP 服务器来断言,而不是手工拼装的请求,因为真正决定它的,是浏览器实际发出的那个 `Host` 头。 +**读取配置与写入配置同样属于特权操作。**`settings.describe`、`credentials.describe`、模型目录及其他所有 Host 操作都要求同一个浏览器会话。配置面仍独立于认证对 secret 脱敏。这条边界由真实 HTTP 服务器而非手工请求来断言,证明伪造 loopback `Host` 值绝不建立身份。 **这个面恰好服务于已注册模型提供方所指向的那些 namespace。**`ctx.llm.listConfigurableProviders()` 就是允许列表,于是产品边界是被执行的,而不是从已安装的插件集合里推断出来的;将来的 namespace 只有加入该目录才会变得可在 Web 上配置。未注册的 namespace 与未暴露的 namespace 得到完全相同的答复(`settings-not-exposed`),因此探测无法枚举注册表。 diff --git a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml index ca0cd569c9..a345f69828 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-30-web-config-plane.md -2026-07-30-web-config-plane.md: c8397d03cd7b8eb4ea127cdc26124f5e721e822d -2026-07-30-web-config-plane.zh.md: b0724c3a8cb160cbac5fc88fe07d35e79accfc49 +2026-07-30-web-config-plane.md: d5bd9c05e8352536c5c6f8b265db7dbd56a4fb84 +2026-07-30-web-config-plane.zh.md: 3c7f801766b1a6c197cc208a3c4a030b8aaac771 diff --git a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md index c8397d03cd..d5bd9c05e8 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md +++ b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.md @@ -12,11 +12,11 @@ The request-level configuration seam made LLM adapter configuration restart-free ## Decision -**Wire domains on the compiled RPC map, rejections as codes, owner events forwarded verbatim.** `settings.describe/openDocument/update/replace/mutate`, `credentials.describe/set/unset`, `llm.providers`, and `llm.models` join `RpcMethodMap`, so the compiler-locked wiring sites keep schema, handler, and client in lockstep. Seam rejections fold into `settings-rejected {ns}` / `credential-rejected {ref}` business errors, while clients subscribe to forwarded settings, credentials, and LLM owner events and converge without polling ([forwarded Remote events](2026-08-10-remote-event-delivery.md)). Settings reads, native actions, and writes join `pickDirectory`/`openPath` in the connection guard's privileged set: loopback + same-origin or 403, because a LAN-exposed dsh web must not accept configuration access from another origin. +**Wire domains on the compiled RPC map, rejections as codes, owner events forwarded verbatim.** `settings.describe/openDocument/update/replace/mutate`, `credentials.describe/set/unset`, `llm.providers`, and `llm.models` join `RpcMethodMap`, so the compiler-locked wiring sites keep schema, handler, and client in lockstep. Seam rejections fold into `settings-rejected {ns}` / `credential-rejected {ref}` business errors, while clients subscribe to forwarded settings, credentials, and LLM owner events and converge without polling ([forwarded Remote events](2026-08-10-remote-event-delivery.md)). Connection authenticates settings reads, native actions, writes, `pickDirectory`, `openPath`, and every other Host operation with one browser session; Host/Origin failures still return 403 before identity is checked. **`describe()` grows layers and structural secret redaction.** `SettingsDescriptor` carries `base`/`user` beside the effective value, so the form marks "overridden" by presence in the user layer, not value inequality (an override *equal* to the base is still an override). `describe({ redactSecrets: true })` — mandatory at every wire face — strips `role('secret')` subtrees from all three layers via a pure structural walk of the schema (object/dict/array containers; a secret-role subtree is one opaque leaf) and enumerates the stripped slots as `{path, set}`, so a page can render write-only inputs without ever receiving a value. -**The Host identifies and opens the local settings document.** The settings seam exposes optional `documentPath` provider metadata and a `prepareDocument()` operation; `settings-file` returns its fully resolved custom or `$DSH_HOME/settings.yaml` filename and exclusively creates an absent empty document with owner-only permissions, while non-file providers retain the base `undefined`. The loopback-only `settings.describe` response carries only the boolean `hasDocument` capability beside the redacted namespace views. `ui-settings-general` registers a `settings.action` entry only on loopback pages, shows it only after the metadata confirms that a provider-owned local document can be prepared, and invokes pathless `settings.openDocument`; the Host resolves the provider path again before a text-document handoff (`open -t` on macOS so an arbitrary YAML file association cannot redirect the gesture, `xdg-open` on desktop Linux, `Invoke-Item` on Windows, and `wslpath -w` followed by that Windows handoff on WSL). Generic workspace paths retain the default intent, including its browser preference for browser-renderable documents. The browser neither derives `$DSH_HOME` nor receives a filesystem target; remote pages make no privileged settings read for this action. +**The Host identifies and opens the local settings document.** The settings seam exposes optional `documentPath` provider metadata and a `prepareDocument()` operation; `settings-file` returns its fully resolved custom or `$DSH_HOME/settings.yaml` filename and exclusively creates an absent empty document with owner-only permissions, while non-file providers retain the base `undefined`. The browser-authenticated `settings.describe` response carries only the boolean `hasDocument` capability beside the redacted namespace views. `ui-settings-general` registers a `settings.action` entry only on loopback pages, shows it only after the metadata confirms that a provider-owned local document can be prepared, and invokes pathless `settings.openDocument`; the Host resolves the provider path again before a text-document handoff (`open -t` on macOS so an arbitrary YAML file association cannot redirect the gesture, `xdg-open` on desktop Linux, `Invoke-Item` on Windows, and `wslpath -w` followed by that Windows handoff on WSL). Generic workspace paths retain the default intent, including its browser preference for browser-renderable documents. The browser neither derives `$DSH_HOME` nor receives a filesystem target; non-loopback pages retain the Client policy that makes no Host settings read for this action. **The llm seam declares configurability and announces topology.** `registerConfigurableProviders()` is an all-or-nothing, fiber-scoped directory of `{provider, displayName, settingsNs, settingsPath}` — the addressing a config page needs to open the right settings subtree for a route that may not exist yet; `listConfigurableProviders()` merges with live routes in the wire handler so undeclared live routes still report active. The zero-payload `'llm/adapters-updated'` event fires from all four registration/unregistration commit points with contained listener dispatch (INVARIANT rethrow), following the settings/commands precedent. `llm-deepseek`'s route renamed to `deepseek-official` because the pi-ai catalog legitimately owns `deepseek` as an aggregator entry; pre-release stance, no alias. diff --git a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md index b0724c3a8c..3c7f801766 100644 --- a/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-30-web-config-plane.zh.md @@ -12,11 +12,11 @@ Status: implemented ## 决策 -**wire 领域挂上编译期 RPC 映射,拒绝落为错误码,owner 事件原样转发。**`settings.describe/openDocument/update/replace/mutate`、`credentials.describe/set/unset`、`llm.providers` 与 `llm.models` 一同加入 `RpcMethodMap`,由编译器锁定的接线位点让 schema、处理器与客户端保持步调一致。seam 侧拒绝折叠为业务错误,客户端则订阅转发的 settings、credentials 与 LLM owner 事件,无需轮询即可收敛(见[转发的 Remote 事件](2026-08-10-remote-event-delivery.zh.md))。settings 读取、原生操作与写入和 `pickDirectory`/`openPath` 一起进入连接守卫的特权集合:回环 + 同源,否则 403,因为暴露在局域网上的 dsh web 绝不能接受来自其他源的配置访问。 +**wire 领域挂上编译期 RPC 映射,拒绝落为错误码,owner 事件原样转发。**`settings.describe/openDocument/update/replace/mutate`、`credentials.describe/set/unset`、`llm.providers` 与 `llm.models` 一同加入 `RpcMethodMap`,由编译器锁定的接线位点让 schema、处理器与客户端保持步调一致。seam 侧拒绝折叠为业务错误,客户端则订阅转发的 settings、credentials 与 LLM owner 事件,无需轮询即可收敛(见[转发的 Remote 事件](2026-08-10-remote-event-delivery.zh.md))。Connection 用一个浏览器会话认证 settings 读取、原生操作、写入、`pickDirectory`、`openPath` 与其他所有 Host 操作;Host/Origin 失败仍会在身份校验前返回 403。 **`describe()` 增加分层与结构化 secret 脱敏。**`SettingsDescriptor` 在生效值之外携带 `base`/`user`,表单据此按「字段是否出现在用户层」来标记「已覆盖」,而非按值是否不等(与 base *相等*的覆盖仍然是覆盖)。`describe({ redactSecrets: true })`——在每个 wire 面都强制启用——经由对 schema 的纯结构遍历(object/dict/array 容器;secret 角色子树整体是一个不透明叶节点)从全部三层剥除 `role('secret')` 子树,并把剥除的槽位枚举为 `{path, set}`,页面因此不必收到任何值就能渲染只写输入框。 -**Host 识别并打开本地设置文档。** settings seam 暴露可选的 `documentPath` 提供方元数据和 `prepareDocument()` 操作;`settings-file` 返回已完全解析的自定义文件名或 `$DSH_HOME/settings.yaml` 文件名,并在文档缺失时以仅属主可访问的权限独占创建空文档,非文件提供方则保留基类的 `undefined`。仅限回环访问的 `settings.describe` 响应会在脱敏 namespace 视图旁只携带布尔型 `hasDocument` 能力。`ui-settings-general` 只在回环页面注册一条 `settings.action` 条目,只有元数据确认可准备好一份由提供方持有的本地文档后才显示,并调用无路径参数的 `settings.openDocument`;Host 会在文本文档交接前再次解析提供方路径(macOS 上使用 `open -t`,使任意 YAML 文件关联无法重定向这次操作;桌面 Linux 上使用 `xdg-open`;Windows 上使用 `Invoke-Item`;WSL 上先执行 `wslpath -w`,再使用同一 Windows 交接)。通用 Workspace 路径仍保留默认意图,包括针对浏览器可渲染文档的浏览器偏好。浏览器既不推导 `$DSH_HOME`,也不会收到文件系统目标;远程页面不会为这项操作发起特权 settings 读取。 +**Host 识别并打开本地设置文档。** settings seam 暴露可选的 `documentPath` 提供方元数据和 `prepareDocument()` 操作;`settings-file` 返回已完全解析的自定义文件名或 `$DSH_HOME/settings.yaml` 文件名,并在文档缺失时以仅属主可访问的权限独占创建空文档,非文件提供方则保留基类的 `undefined`。经浏览器认证的 `settings.describe` 响应会在脱敏 namespace 视图旁只携带布尔型 `hasDocument` 能力。`ui-settings-general` 只在回环页面注册一条 `settings.action` 条目,只有元数据确认可准备好一份由提供方持有的本地文档后才显示,并调用无路径参数的 `settings.openDocument`;Host 会在文本文档交接前再次解析提供方路径(macOS 上使用 `open -t`,使任意 YAML 文件关联无法重定向这次操作;桌面 Linux 上使用 `xdg-open`;Windows 上使用 `Invoke-Item`;WSL 上先执行 `wslpath -w`,再使用同一 Windows 交接)。通用 Workspace 路径仍保留默认意图,包括针对浏览器可渲染文档的浏览器偏好。浏览器既不推导 `$DSH_HOME`,也不会收到文件系统目标;非 loopback 页面保留 Client 策略,不为这项操作发起 Host settings 读取。 **llm seam 声明可配置性并公布拓扑。**`registerConfigurableProviders()` 是一个全有或全无、以 fiber 为作用域的目录,条目为 `{provider, displayName, settingsNs, settingsPath}`——这正是配置页要为一条可能尚不存在的路由打开正确设置子树时所需要的寻址;`listConfigurableProviders()` 在 wire 处理器里与存活路由合并,未声明的存活路由因此仍报告为激活。零负载的 `'llm/adapters-updated'` 事件从全部四个注册/注销提交点触发,listener 派发带异常隔离(INVARIANT 重抛),沿用 settings/commands 的先例。`llm-deepseek` 的路由重命名为 `deepseek-official`,因为 pi-ai catalog 名正言顺地拥有 `deepseek` 这个聚合器条目;依预发布立场,不设别名。 diff --git a/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.i18n.yaml index 0a95947eaf..21995b0838 100644 --- a/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.md -2026-08-03-per-session-agent-presets.md: b2195004580e1f4bf4be5527c61a8ee9b816c964 -2026-08-03-per-session-agent-presets.zh.md: 9f689c74dd570d6ec9aaa7cd1274618326a836dd +2026-08-03-per-session-agent-presets.md: 97352a0e3376ce1fe26bac62b88c2c674202adc7 +2026-08-03-per-session-agent-presets.zh.md: b62baf3e3097ba99247c2e86cc3fb5b7e43e2fab diff --git a/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.md b/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.md index b219500458..97352a0e33 100644 --- a/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.md +++ b/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.md @@ -53,7 +53,7 @@ Which preset an unnamed session gets is a user setting (`agent-presets.default`) **Switching is allowed only while a session is blank.** Once a turn has run, that history was produced under the preset's tools and swapping them would strand logged tool calls, so `agentPreset.select` answers `agent-preset-locked`. A blank switch keeps the agent and the session and replaces only the subtree, because the host discards the `AgentHandle` it creates and there is no delete RPC — and keeping them is the better outcome anyway, since the session id, its workspace attachment, and its projections all stay put. The swap is unmount-then-mount (two compositions would register the same tool names into one layer), so it resolves the new preset before tearing anything down and restores the previous one when the new mount fails. -**Authoring a preset is an RPC, and a privileged one.** A composition is a file, but "edit it on the filesystem" is not a browser affordance, so the roster gained `read`/`write`/`remove` beside `select`. Those three are loopback-pinned: a composition names the plugins a session runs, so reading one is reconnaissance and writing one is arbitrary capability. `list` and `select` deliberately stay ordinary. The roster carries ids and trust only, and a LAN client's picker needs it; and choosing a preset looked like escalation — one of them mounts the toolset that edits the live runtime — but `session.create` already takes an `agentPreset`, so pinning only the switch would have left the same capability one method over. The capability is not the preset's to grant either: the deployment's own default already carries `bash` and the filesystem tools, so any caller that may start a session at all can already run commands as this process. Containment is a property of the id (`[a-z0-9][a-z0-9-]*`), checked before it becomes a directory name rather than by inspecting the joined path afterwards; the text is parsed with the loader's own schema and dialect, so a save cannot leave a file no session could load. Shipped presets are refused for writes and deletes, because the deployment's copy is what a broken local preset is compared against — which also makes "duplicate, then edit" the authoring path rather than an afterthought. +**Authoring a preset is an RPC, and a privileged one.** A composition is a file, but "edit it on the filesystem" is not a browser affordance, so the roster gained `read`/`write`/`remove` beside `select`. Connection authenticates authoring, `list`, `select`, and the complete Host API with one browser session: a composition names the plugins a session runs, so reading one is reconnaissance and writing one is arbitrary capability, while choosing a preset grants nothing `session.create` with `agentPreset` did not already grant. The capability is not the preset's to grant either: the deployment's own default already carries `bash` and the filesystem tools, so any caller that may start a session at all can already run commands as this process. Containment is a property of the id (`[a-z0-9][a-z0-9-]*`), checked before it becomes a directory name rather than by inspecting the joined path afterwards; the text is parsed with the loader's own schema and dialect, so a save cannot leave a file no session could load. Shipped presets are refused for writes and deletes, because the deployment's copy is what a broken local preset is compared against — which also makes "duplicate, then edit" the authoring path rather than an afterthought. **A service with a consumer outside the agent plane cannot move into a preset.** The aggressive split moved the `subagents` registry and its spawn/fork backends into the delegation group's entry-local realm, and `dsh web` then failed to boot: `dsh-host-apiproxy` is a HOST row that injects `subagents` to answer the browser's cross-session queries (`listChildren`, `followup`), so it waited forever for a service only sessions now provided. A per-session copy is wrong twice over — a provider name registers once, so the second session would have collided anyway. The registry and every shared backend, including the [fixed Codex and Claude Code product providers](2026-08-10-product-subagent-providers-in-shared-host.md), are host-plane; a preset contributes whichever delegation TOOLS its agent should see, and those tools resolve the host registry. `workflows` stays entry-local because nothing outside an agent reads it. Grepping injectors is what should have caught this and did not: the search has to include the host packages, not just the agent-plane ones. diff --git a/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.zh.md b/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.zh.md index 9f689c74dd..b62baf3e30 100644 --- a/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-03-per-session-agent-presets.zh.md @@ -54,7 +54,7 @@ Status: implemented **只有空白会话才允许切换。** 一旦跑过任何轮次,那段历史就是在该 preset 的工具下产生的,替换会留下无法执行的已记录 tool call,因此 `agentPreset.select` 返回 `agent-preset-locked`。空白期的切换保留 agent 与 session,只替换子树——因为宿主丢弃了它创建的 `AgentHandle`,也没有 delete RPC;而保留它们本身就是更好的结果,会话 id、workspace 挂接与 projections 都原地不动。该替换是"先卸后装"(两份组装会把同名工具注册进同一分层),因此它在拆除任何东西之前先解析新 preset,并在新组装装载失败时恢复原来的那一份。 -**创作 preset 是一次 RPC,而且是特权 RPC。** 组装是一个文件,但“去文件系统里改它”并不是浏览器能提供的操作,因此名单在 `select` 之外新增了 `read`/`write`/`remove`。这三者被固定在环回地址:组装指明了一个会话所运行的插件,因此读取它是侦察,写入它是任意能力。`list` 与 `select` 刻意保持为普通方法。名单只携带 id 与信任级别,而局域网客户端的选择器需要它;至于选择本身,它看起来像提权——其中一个 preset 会挂载可编辑活动运行时的工具集——但 `session.create` 本就接受 `agentPreset`,只固定切换会把同一能力留在隔壁一个方法上。这份能力也不由 preset 授予:部署自带的默认 preset 本就带着 `bash` 与文件系统工具,因此任何被允许开启会话的调用方,早已能以本进程的身份执行命令。约束是 id 自身的性质(`[a-z0-9][a-z0-9-]*`),在它成为目录名之前就检查,而不是事后再去审视拼接出的路径;文本使用 loader 自身的 schema 与方言解析,因此保存不会留下任何会话都无法加载的文件。随部署提供的 preset 拒绝写入与删除,因为部署自带的那一份正是用来对照有问题的本地 preset 的——这也让“先复制、再编辑”成为创作路径本身,而非事后补充。 +**创作 preset 是一次 RPC,而且是特权 RPC。** 组装是一个文件,但“去文件系统里改它”并不是浏览器能提供的操作,因此名单在 `select` 之外新增了 `read`/`write`/`remove`。Connection 用一个浏览器会话认证创作操作、`list`、`select` 与完整 Host API:组装指明一个会话所运行的插件,因此读取它是侦察,写入它是任意能力;选择 preset 则没有授予 `session.create` 携带 `agentPreset` 时尚未拥有的能力。这份能力也不由 preset 授予:部署自带的默认 preset 本就带着 `bash` 与文件系统工具,因此任何被允许开启会话的调用方,早已能以本进程的身份执行命令。约束是 id 自身的性质(`[a-z0-9][a-z0-9-]*`),在它成为目录名之前就检查,而不是事后再去审视拼接出的路径;文本使用 loader 自身的 schema 与方言解析,因此保存不会留下任何会话都无法加载的文件。随部署提供的 preset 拒绝写入与删除,因为部署自带的那一份正是用来对照有问题的本地 preset 的——这也让“先复制、再编辑”成为创作路径本身,而非事后补充。 **在 agent 平面之外还有消费方的服务,不能搬进 preset。** 激进拆分把 `subagents` 注册表连同 spawn/fork 后端一起搬进了 delegation 组的 entry-local realm,于是 `dsh web` 直接起不来:`dsh-host-apiproxy` 是宿主行,它注入 `subagents` 来回答浏览器的跨会话查询(`listChildren`、`followup`),因而永远等待一个此刻只有会话才提供的服务。按会话各一份在两个层面上都是错的——provider 名只能注册一次,第二个会话本来也会相撞。注册表与所有共享后端,包括[固定的 Codex 与 Claude Code 产品 provider](2026-08-10-product-subagent-providers-in-shared-host.zh.md),都属于宿主平面;preset 只贡献自己的 agent 应看见的委派**工具**,这些工具解析宿主注册表。`workflows` 保持 entry-local,因为 agent 之外没有任何东西读它。本该拦下它的是「检索注入方」这一步,而它没拦住:检索必须覆盖宿主包,而不只是 agent 平面的包。 diff --git a/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.i18n.yaml index f620af93e3..9647bf2513 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.md -2026-08-04-draft-provider-endpoint-interrogation.md: 6a545ea5c97ef7e7f0e916c1676c1361f7a9bf3b -2026-08-04-draft-provider-endpoint-interrogation.zh.md: eb8133d0f2ec4a1999770468782db9c47ba170c8 +2026-08-04-draft-provider-endpoint-interrogation.md: 0132dba5888faa1b9e6a4e59b45ee56a259eeef7 +2026-08-04-draft-provider-endpoint-interrogation.zh.md: 8cea5d2809611696606113b2e38578f1b54b4e09 diff --git a/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.md b/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.md index 6a545ea5c9..0132dba588 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.md +++ b/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.md @@ -19,7 +19,7 @@ Interrogation is keyed by **settings namespace**, not by provider route: - `ctx.llm.registerModelDiscovery(settingsNs, discover)` lets an adapter plugin offer to interrogate endpoints for the namespace it owns, and `ctx.llm.discoverModels(settingsNs, request)` asks. There is no way to enumerate which namespaces registered: a surface that cannot interrogate learns it from the refusal, and a list nothing consumed would be a required wire field doing nothing. The namespace is the right key because a configuration surface already holds it from the configurable-provider directory, and because a provider being added has no route to name. - `LlmModelDiscoveryRequest` carries the draft — an optional `provider`, an optional `baseURL`, an optional `api`, an optional `apiKey`, and a signal — and needs at least one of `provider` or `baseURL` to have anything to answer about. `provider` exists because a route the adapter already describes is answered from its own registry with no network call at all; only a route it does not describe reaches an endpoint. Nothing in this path writes settings or credentials. The one read is the credential of a route the request names: a configuration surface holds a redacted descriptor rather than the stored secret, so the draft's `apiKey` is present only while the user is typing one, and without that read an already-configured route would be interrogated unauthenticated and answer 401. The typed key wins, being the one under test. - `LlmDiscoveredModel` makes every field but `id` optional, because most listings disclose an id and nothing else. The reply is candidates, not a catalog: a surface adopting one still owes the capacities the adapter requires. -- `llm.discoverModels` carries the same draft over the wire. Its `apiKey` is the third and last payload on which a secret may ride, alongside `settings.update`/`mutate` and `credentials.set`, and it is never stored or echoed back. It does ride the client's outgoing envelope like every other secret-bearing payload, where a `subscribeEnvelopes()` observer can see it; redacting that tap is a configuration-plane-wide change, not this method's to make alone. The method is loopback-only for a second reason besides the key: it makes the host issue a GET to a caller-chosen URL and reports the outcome, which is a probe an anonymous LAN caller must not have. Every refusal folds into `model-discovery-failed`, whose message is the adapter's own text and whose details name the endpoint asked but never the credential offered. +- `llm.discoverModels` carries the same draft over the wire. Its `apiKey` is the third and last payload on which a secret may ride, alongside `settings.update`/`mutate` and `credentials.set`, and it is never stored or echoed back. It does ride the client's outgoing envelope like every other secret-bearing payload, where a `subscribeEnvelopes()` observer can see it; redacting that tap is a configuration-plane-wide change, not this method's to make alone. Connection authenticates the method with the complete Host API: it makes the host issue a GET to a caller-chosen URL and reports the outcome, which an anonymous caller must not receive. Every refusal folds into `model-discovery-failed`, whose message is the adapter's own text and whose details name the endpoint asked but never the credential offered. `dsh-llm-pi-ai` implements the wire path as a plain `GET {baseURL}/models`, reading `openai-completions` and `openai-responses`: their `GET /models` shape with bearer auth is the one a gateway, a self-hosted server, and the official endpoints all agree on. Azure is excluded despite its OpenAI lineage — it authenticates with an `api-key` header and requires an `api-version` query — and Codex uses OAuth; both would have reported an authentication failure as a provider with no models. Every other protocol answers `DISCOVERY_UNSUPPORTED`, so the surface falls back to hand-entry rather than reporting a guessed response shape as an empty provider. `baseURL` is treated as a prefix rather than a URL to resolve against, so a deployment path such as `https://gateway.example/openai/v1` keeps its segments. The reply is read under a four-megabyte ceiling enforced on the bytes actually received — the endpoint is a URL the user typed, so a declared `content-length` is checked first as a courtesy but never trusted as the bound, matching `dsh-web-fetch`'s two-stage shape for its own caller-supplied URLs. diff --git a/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.zh.md b/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.zh.md index eb8133d0f2..8cea5d2809 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-04-draft-provider-endpoint-interrogation.zh.md @@ -19,7 +19,7 @@ Status: implemented - `ctx.llm.registerModelDiscovery(settingsNs, discover)` 让适配器插件为自己拥有的 namespace 提供「询问端点」的能力,`ctx.llm.discoverModels(settingsNs, request)` 发起询问。没有任何办法枚举哪些 namespace 注册过:询问不了的界面会从那句拒绝里知道,而一份无人消费的列表只会变成一个什么都不做的必填协议字段。以 namespace 为键是对的,因为配置界面已经从可配置提供方目录里拿到了它,也因为正在新增的提供方没有路由可点名。 - `LlmModelDiscoveryRequest` 携带草稿——可选的 `provider`、可选的 `baseURL`、可选的 `api`、可选的 `apiKey`,以及一个 signal——且 `provider` 与 `baseURL` 至少要有一个,才有东西可答。`provider` 之所以存在,是因为适配器已经描述过的路由直接由它自己的注册表作答、完全不联网;只有它未描述的路由才会抵达某个端点。这条路径不写 settings 与 credentials。唯一的读取是请求所点名路由的凭据:配置界面拿到的是脱敏描述符而非已存的机密,因此草稿里的 `apiKey` 只在用户正键入时才存在;没有这次读取,已配置好的路由就会被不带认证地询问,只换回一个 401。键入的密钥优先,因为那正是被测试的那一把。 - `LlmDiscoveredModel` 除 `id` 外每个字段都可选,因为大多数列表只公布 id。回复是候选而非 catalog:采纳其中一条的界面仍要补上适配器所需的容量。 -- `llm.discoverModels` 把同一份草稿送过协议层。它的 `apiKey` 是可承载机密的第三个、也是最后一个载荷(另两个是 `settings.update`/`mutate` 与 `credentials.set`),且绝不被存储或回显。它确实会像其他承载机密的载荷一样随客户端外发信封同行,`subscribeEnvelopes()` 观察者看得到;把那个抽头脱敏是整个配置面的改动,不该由这一个方法独自决定。除密钥之外,将它限制为仅可通过回环访问还有第二个理由:它让宿主向调用方选定的 URL 发起 GET 并回报结果,这是匿名 LAN 调用者不该拥有的探测能力。每一种拒绝都折叠为 `model-discovery-failed`,其消息是适配器自己的文本,details 点名被询问的端点,绝不点名所提供的凭据。 +- `llm.discoverModels` 把同一份草稿送过协议层。它的 `apiKey` 是可承载机密的第三个、也是最后一个载荷(另两个是 `settings.update`/`mutate` 与 `credentials.set`),且绝不被存储或回显。它确实会像其他承载机密的载荷一样随客户端外发信封同行,`subscribeEnvelopes()` 观察者看得到;把那个抽头脱敏是整个配置面的改动,不该由这一个方法独自决定。Connection 用与完整 Host API 相同的会话认证该方法:它让宿主向调用方选定的 URL 发起 GET 并回报结果,匿名调用者绝不能获得这类探测能力。每一种拒绝都折叠为 `model-discovery-failed`,其消息是适配器自己的文本,details 点名被询问的端点,绝不点名所提供的凭据。 `dsh-llm-pi-ai` 的实现只是一次朴素的 `GET {baseURL}/models`,且仅限 OpenAI 兼容协议。它们的列表形状是网关、自建服务与官方端点三方一致认可的那一种,而这正是该动作存在的场景。其余协议一律以 `DISCOVERY_UNSUPPORTED` 回答,让界面回退到手工填写,而不是把猜错的响应形状报成一个空提供方。`baseURL` 按前缀而非待解析 URL 处理,因此 `https://gateway.example/openai/v1` 这类部署路径会保留其路径段。回复在四兆字节上限下读取,且上限落在实际收到的字节上——端点是用户自己填的 URL,因此会先看声明的 `content-length` 作为善意提示,但绝不把它当作边界;这与 `dsh-web-fetch` 面对自己的调用方提供 URL 时所用的两段式形状一致。 diff --git a/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.i18n.yaml index 28a4778928..8ded320f05 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md -2026-08-04-websocket-downlink-carrier.md: f757487c7b0880cfff25b93644341dc85b5e0e38 -2026-08-04-websocket-downlink-carrier.zh.md: 5fa603b9a8dc66146c777f54dfbdc25cb131debd +2026-08-04-websocket-downlink-carrier.md: 420a0d30f31cca58448adc0afd46a5d6d5e9107f +2026-08-04-websocket-downlink-carrier.zh.md: 5f277a4ed33ffe97b51587fef960746b93eff1c1 diff --git a/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md b/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md index f757487c7b..420a0d30f3 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md +++ b/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md @@ -16,7 +16,7 @@ WebSocket carries only the host→browser downlink. All client→host unary call ## Upgrade and lifecycle boundaries -`dsh-host-webserver` provides an exact upgrade-route registration point alongside ordinary routes, dispatches Node upgrade sockets by pathname only, contains raw-socket errors, and waits for surviving upgraded connections to close during server teardown; it knows nothing about Harness frames or WebSocket messages. `dsh-client-connection` owns the WebSocket handshake, frame output, and stream cancellation, and reuses the `/api` Host/Origin trust fence before upgrade. An untrusted authority or cross-origin Origin is rejected before `ctx.apiProxy.events.*` starts. +`dsh-host-webserver` provides an exact upgrade-route registration point alongside ordinary routes, dispatches Node upgrade sockets by pathname only, contains raw-socket errors, and waits for surviving upgraded connections to close during server teardown; it knows nothing about Harness frames or WebSocket messages. `dsh-client-connection` owns the WebSocket handshake, frame output, and stream cancellation. Before upgrade it applies the `/api` Host/Origin checks followed by the same signed browser-cookie authentication as unary HTTP. An untrusted authority or cross-origin Origin receives 403; a trusted but unauthenticated request receives 401; neither starts a Remote stream. A browser abort or socket close cancels the corresponding host stream; plugin teardown also waits for that source iterator's cleanup. If a host stream throws midway, the carrier sends one existing `stream/error` frame and then closes the socket; the client treats that frame as connection loss rather than delivering it to a business sink. Each WebSocket reports open independently, and the existing readiness handshake still waits until mux and host are both open and the `host.describe` HTTP call has succeeded before publishing connected. diff --git a/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.zh.md b/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.zh.md index 5fa603b9a8..5f277a4ed3 100644 --- a/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.zh.md @@ -16,7 +16,7 @@ WebSocket 只承担 host→browser 下行。所有 client→host unary 调用和 ## Upgrade 与生命周期边界 -`dsh-host-webserver` 提供与普通 route 并列的精确 upgrade-route 注册点,只按 pathname 分发 Node upgrade socket,隔离原始 socket 错误,并在 server teardown 期间等待仍存活的升级连接关闭;它不认识 Harness 帧或 WebSocket 消息。`dsh-client-connection` 拥有 WebSocket handshake、frame 写出和流取消,并在 upgrade 前复用 `/api` 的 Host/Origin 信任栅栏。未受信任的 authority 或跨来源 Origin 在 `ctx.apiProxy.events.*` 启动前即被拒绝。 +`dsh-host-webserver` 提供与普通 route 并列的精确 upgrade-route 注册点,只按 pathname 分发 Node upgrade socket,隔离原始 socket 错误,并在 server teardown 期间等待仍存活的升级连接关闭;它不认识 Harness 帧或 WebSocket 消息。`dsh-client-connection` 拥有 WebSocket handshake、frame 写出和流取消。upgrade 前先执行 `/api` Host/Origin 校验,再执行与一元 HTTP 相同的签名浏览器 cookie 认证。未受信任的 authority 或跨来源 Origin 得到 403;Host 可信但未认证的请求得到 401;两者都不会启动 Remote stream。 浏览器 abort 或 socket close 会取消对应的 host 流;插件 teardown 还会等待该 source iterator 完成清理。host 流中途抛错时,载体发送一个现有的 `stream/error` frame 后关闭 socket;客户端把该 frame 收敛为连接丢失,不投递给业务 sink。每条 WebSocket 独立报告 open,既有 readiness handshake 仍等待 mux、host 都 open 且 `host.describe` HTTP 调用成功后才发布 connected。 diff --git a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.i18n.yaml index 8ae275a581..822f8fa0e2 100644 --- a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md -2026-08-12-plugin-owned-settings-surface.md: daed91b8ac4ce0acb81e19908ec08c9f3f7ac21e -2026-08-12-plugin-owned-settings-surface.zh.md: ba39b84faaf90be413ad8d7b8327c67b2fa27cea +2026-08-12-plugin-owned-settings-surface.md: f1c9b48abd3459ed58e3e10fbdd95558884c9a22 +2026-08-12-plugin-owned-settings-surface.zh.md: ff9f37290a8dd8f1ab9ef1bfef3790a3ef20086b diff --git a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md index daed91b8ac..f1c9b48abd 100644 --- a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md +++ b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.md @@ -32,7 +32,7 @@ Keying makes absence the signal, and that is what removes the bookkeeping the pr The gate did keep one thing off the wire, and this note states it plainly because the decision has to survive the accurate version: a registered namespace the list did not name never had its resolved, `base`, or `user` values reach the browser at all. The plugin inventory page is not a substitute — `PluginInventoryEntry` carries `entryId`, `moduleName`, `enabled`, and `fiberPhase`, and its "configuration" row renders an enabled/disabled tag, never a stored value. -What the gate was not is the boundary its position suggested. Every `settings.*` method sits in `PRIVILEGED_METHODS` (`packages/client/connection`), so a non-loopback or cross-origin request is refused with 403 before reaching this code; `role('secret')` fields are structurally stripped from every layer of every response; and the document the plane edits is the user's own `settings.yaml`, which the same settings page offers to open. The writes it did not block were also the consequential ones: `permission` (which can widen the approval preset) and `agent-presets` (which decides what a session mounts) were both already served. +What the gate was not is the security boundary its position suggested. Connection authenticates every Host API request before reaching this code; `role('secret')` fields are structurally stripped from every layer of every response; and the document the plane edits is the user's own `settings.yaml`, which the same settings page offers to open. The writes it did not block were also the consequential ones: `permission` (which can widen the approval preset) and `agent-presets` (which decides what a session mounts) were both already served. So the exposure this change actually adds, in this repository, is one namespace: `agent-default-model`, whose two fields name a provider and a model and which no browser half renders. A future namespace whose values genuinely must not cross the wire is answered per field by `role('secret')` — finer than a namespace switch, and already enforced. diff --git a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.zh.md b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.zh.md index ba39b84faa..ff9f37290a 100644 --- a/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-12-plugin-owned-settings-surface.zh.md @@ -32,7 +32,7 @@ Status: implemented 这道门确实挡住了一样东西,本 note 如实写出,因为这个决策必须在准确版本下也站得住:不在名单上的已注册命名空间,其 resolved、`base` 与 `user` 值根本不会抵达浏览器。插件清单页不能替代它——`PluginInventoryEntry` 携带的是 `entryId`、`moduleName`、`enabled` 与 `fiberPhase`,它那一行「configuration」渲染的是启用/停用标签,从不是任何已存值。 -这道门不是的,是它所处位置暗示的那种边界。每个 `settings.*` 方法都在 `PRIVILEGED_METHODS` 里(`packages/client/connection`),非回环或跨源请求在到达这段代码之前就以 403 被拒;`role('secret')` 字段在每种响应的每一层都被结构性剥离;而这个面所编辑的文档,本就是用户自己的 `settings.yaml`,同一个设置页还提供了打开它的入口。它没有挡住的写入,恰恰是有分量的那些:`permission`(能放宽审批预设)与 `agent-presets`(决定一个会话挂载什么)本来就已被服务。 +这道门不是的,是它所处位置暗示的那种安全边界。Connection 在到达这段代码前认证每个 Host API 请求;`role('secret')` 字段在每种响应的每一层都被结构性剥离;而这个面所编辑的文档,本就是用户自己的 `settings.yaml`,同一个设置页还提供了打开它的入口。它没有挡住的写入,恰恰是有分量的那些:`permission`(能放宽审批预设)与 `agent-presets`(决定一个会话挂载什么)本来就已被服务。 因此本次改动在本仓库实际新增的暴露面是一个命名空间:`agent-default-model`——它的两个字段指明一个提供方与一个模型,且没有任何浏览器半侧渲染它。将来若某个命名空间的值确实不该跨越协议,由 `role('secret')` 逐字段作答:比整命名空间开关更精细,而且已经在执行。 diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml new file mode 100644 index 0000000000..e8c68740aa --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +2026-08-24-browser-token-authentication.md: fb55a35018b7c8df45213f9b9e59dccc3512c0ab +2026-08-24-browser-token-authentication.zh.md: 6cd77117395ff753d36d39da0ec247e064bdb393 diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md new file mode 100644 index 0000000000..fb55a35018 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -0,0 +1,45 @@ +# Agent Note: Browser launch-token authentication + +Status: implemented + +English | [中文](2026-08-24-browser-token-authentication.zh.md) + +## Problem + +The Web Host runs tool-capable Sessions with the current operating-system user's authority, but its HTTP interface identified privileged callers from request routing facts. In particular, the method-specific loopback list treated a loopback `Host` value as local authority even though an HTTP client controls that header. A caller that could reach the server could therefore name `localhost`, enter configuration methods, and use Host-side operations such as model discovery to disclose stored credentials. Binding the shipped CLI to loopback limits ordinary reachability but does not authenticate a request forwarded or otherwise delivered to that socket. + +## Decision + +`dsh-client-connection` authenticates the complete Host API before dispatch. Every API Proxy method, Remote unary call, generic Connection channel, and Remote WebSocket stream requires the same browser session; endpoint ownership and method names do not alter authority. The existing Host/Origin checks run first and retain their DNS-rebinding and cross-site-request role, returning 403 when they fail. A trusted Host without a valid browser session receives 401. The browser-trust rules remain owned by the [carrier-level browser trust decision](2026-07-28-api-browser-trust-boundary.md). + +Each Connection process generates a random launch token. `dsh-web-app` prints and opens the normal root URL with that token in the query. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `/`; the token is not accepted on API paths or in an Authorization header. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public. + +The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. It omits `Secure` because the shipped server uses loopback HTTP. There is no logout operation or reverse-proxy-specific handling. + +The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection reads the record for each verification, so deletion or replacement revokes every existing cookie without restarting the process. A missing record is recreated only by a valid process-token exchange. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. + +The shipped CLI continues to reject `--host 0.0.0.0`. Authentication does not imply supported network deployment, TLS, forwarding-header interpretation, or proxy configuration. + +## Verification + +Unit coverage pins token comparison, cookie attributes, HMAC and payload validation, authority and lifetime checks, persistent-secret reuse, record deletion, and invalid durable records. Host transport suites pin uniform 401/403 behavior for API Proxy, generic RPC, Typert Remote HTTP, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `host.describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. + +## Alternatives considered + +**Determine privileged callers from the TCP peer address.** A direct peer address still identifies a local forwarding process rather than the browser user, retains a second authority model beside the API's command-execution capability, and requires proxy policy to answer who the original caller was. One application credential is the enforceable identity used for every operation. + +**Keep a method-specific privileged list and restrict stored credentials to configured targets.** The list can omit new endpoints and does not constrain callers that already control a tool-capable Session. A `discoverModels` target rule would not form a security boundary because the same authenticated principal can update settings and run commands. Uniform authentication covers the operation that grants process control. + +**Persist or accept the launch token as an API bearer.** A durable launch token would become a second long-lived credential, while Authorization-header support would add a non-browser client contract with no current consumer. The process token performs one browser-cookie exchange only. + +**Rotate the signing secret on every restart.** This prevents an existing browser from reconnecting after an ordinary DSH restart. Persisting only the signing secret keeps that workflow while process-token rotation limits the startup URL to one process lifetime. + +**Add logout, TLS-proxy, and forwarding-header configuration.** None is required by the loopback Web application or the reported authentication gap. Adding them would define deployment contracts without current consumers. Browser site-data controls and credential-record deletion provide the two revocation operations this decision needs. + +## Consequences + +Possession of the browser cookie authorizes the complete tool-capable Host API, matching the authority the Web application already exposes after Session creation. `Host` no longer grants a higher method tier, and a method migration between API Proxy and Typert Remote cannot change its caller set. + +The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime; deletion or rotation of the record is the global revocation mechanism. Omitting `Secure` preserves loopback HTTP and permits plaintext transmission if an operator makes the same cookie authority reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it. + +The decision partially supersedes the authentication deferral and unauthenticated non-loopback consequences in the [browser trust note](2026-07-28-api-browser-trust-boundary.md). That note remains active authority for media-type, Host, Origin, Fetch-Metadata, and configured-authority validation. No active Agent Note is archived: the overlap is partial and both security rules retain future decision value. diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md new file mode 100644 index 0000000000..6cd7711739 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -0,0 +1,45 @@ +# Agent Note: 浏览器启动令牌认证 + +Status: implemented + +[English](2026-08-24-browser-token-authentication.md) | 中文 + +## 问题 + +Web Host 以当前操作系统用户的权限运行具有工具能力的 Session,但其 HTTP 接口用请求路由事实识别特权调用者。具体而言,按方法维护的 loopback 列表把 loopback `Host` 值视为本地 authority,尽管 HTTP 客户端可以控制该 header。能够到达服务器的调用者因此可以声明 `localhost`、进入配置方法,再利用模型发现等 Host 侧操作披露存储的凭据。随附 CLI 绑定 loopback 可以限制普通可达性,却不能认证被转发或以其他方式送达该 socket 的请求。 + +## 决策 + +`dsh-client-connection` 在分发前认证完整 Host API。每个 API Proxy 方法、Remote 一元调用、通用 Connection channel 和 Remote WebSocket stream 都要求同一个浏览器会话;endpoint 所有权与方法名称不改变 authority。既有 Host/Origin 校验先执行,继续负责 DNS rebinding 和跨站请求防御,失败时返回 403。Host 可信但没有有效浏览器会话时返回 401。浏览器信任规则仍由[载体级浏览器信任决策](2026-07-28-api-browser-trust-boundary.zh.md)持有。 + +每个 Connection 进程生成随机启动令牌。`dsh-web-app` 打印并打开 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `/`;API 路径和 Authorization header 都不接受该令牌。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。 + +cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。随附服务器使用 loopback HTTP,因此不设置 `Secure`。这里没有 logout 操作或反向代理专用处理。 + +HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 每次校验都读取记录,因此删除或替换记录无需重启进程即可撤销全部既有 cookie。缺失记录只能由有效进程令牌交换重新创建。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 + +随附 CLI 继续拒绝 `--host 0.0.0.0`。认证不代表支持网络部署、TLS、转发 header 解释或代理配置。 + +## 验证 + +单元覆盖固定令牌比较、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、持久密钥复用、记录删除及无效持久记录。Host 传输套件固定 API Proxy、通用 RPC、Typert Remote HTTP 和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `host.describe`,观测新的进程令牌,并在重启后复用旧 cookie。 + +## 曾考虑的替代方案 + +**从 TCP 对端地址判定特权调用者。** 直接对端地址仍可能只识别本地转发进程,而非浏览器用户;它会在 API 的命令执行能力旁保留第二套 authority 模型,并要求代理策略回答原始调用者是谁。一个应用凭据才是每项操作都能执行的身份。 + +**保留按方法的特权列表,并把存储凭据限制在已配置目标。** 列表可能漏掉新 endpoint,也不能约束已经控制工具型 Session 的调用者。`discoverModels` 目标规则不构成安全边界,因为同一已认证主体可以更新 settings 并运行命令。统一认证覆盖授予进程控制权的操作。 + +**持久化启动令牌或把它作为 API bearer 接受。** 持久启动令牌会成为第二份长期凭据;Authorization header 支持则会增加没有当前 consumer 的非浏览器客户端约定。进程令牌只完成一次浏览器 cookie 交换。 + +**每次重启都轮换签名密钥。** 这会阻止既有浏览器在普通 DSH 重启后重连。只持久化签名密钥既保留该工作流,又由进程令牌轮换把启动 URL 限定在一个进程生命周期。 + +**增加 logout、TLS 代理和转发 header 配置。** loopback Web 应用与已报告认证缺口都不需要这些能力;加入它们会在没有当前 consumer 时定义部署约定。浏览器站点数据控制与凭据记录删除已经提供本决策所需的两种撤销操作。 + +## 后果 + +持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后本就暴露的 authority 一致。`Host` 不再授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。 + +持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期;删除或轮换记录是全局撤销机制。不设置 `Secure` 保留 loopback HTTP,但如果操作者让同一 cookie authority 经未加密网络可达,cookie 会以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。 + +本决策部分取代[浏览器信任说明](2026-07-28-api-browser-trust-boundary.zh.md)中的认证延期与未认证非 loopback 后果。该说明仍是媒体类型、Host、Origin、Fetch-Metadata 和配置 authority 校验的有效权威。没有 active Agent Note 被归档:重叠只发生在局部,两条安全规则都保有未来决策价值。 diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.i18n.yaml index 26fc02785a..a0c01325bf 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md -2026-08-06-host-backed-web-preferences.md: 2e33d05417bf6c347a57b5c0b6c7281ff1392b5b -2026-08-06-host-backed-web-preferences.zh.md: 79c15af723347b92fb0b0a15ccb8de80841dd3b0 +2026-08-06-host-backed-web-preferences.md: 83d4b87f35e2bb3710ecea60d64a8c800ce5df08 +2026-08-06-host-backed-web-preferences.zh.md: ead4a0d27a3bf94f6ef3ffc2915ba721c8379075 diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md index 2e33d05417..83d4b87f35 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md +++ b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md @@ -12,13 +12,13 @@ The first theme implementation moved only Appearance to Host settings but awaite ## Decision -The owning Host halves register three schemas: optional `locale.preference` (`zh` or `en`, where absence delegates to the browser), `ui-theme.preference` (`light`, `dark`, or `system`, default `system`), and `ui-conversation.busyEnter` (`queue` or `steer`, default `queue`). The local settings provider stores explicit choices in `$DSH_HOME/settings.yaml`, which resolves to `~/.dsh/settings.yaml` under the default home. The API proxy serves every registered namespace to a loopback client; field roles still redact secrets. +The owning Host halves register three schemas: optional `locale.preference` (`zh` or `en`, where absence delegates to the browser), `ui-theme.preference` (`light`, `dark`, or `system`, default `system`), and `ui-conversation.busyEnter` (`queue` or `steer`, default `queue`). The local settings provider stores explicit choices in `$DSH_HOME/settings.yaml`, which resolves to `~/.dsh/settings.yaml` under the default home. The API proxy serves every registered namespace behind Connection's browser authentication; field roles still redact secrets. `dsh-client-ui-settings` owns one browser-wide settings describe mirror and provides `ctx.settingsScope.bind(spec)` as a per-namespace selector over it. The mirror installs `settings/document-updated` and `connection/reset` listeners before starting its background read, so no settings transport can block plugin activation and an invalidation cannot fall into a read-before-subscribe gap. Each bound scope publishes a snapshot store (status, section value, revision, writability, host/memory mode) the domain service subscribes to, without adding a wire read or listener of its own. The default decoder validates each incoming section against the namespace's own serialized wire schema, rehydrated through the colocated `ctx.settingsSchema` service, so domains carry no hand-written wire guards. Domain services take the scope as an ordinary constructor collaborator, publish their provisional defaults immediately—browser-derived locale, system theme, and Queue—then adopt an accepted Host section without writing it back; a service constructed without a scope (standalone dictionary or policy fixtures) simply stays process-local. The shared read and invalidation lifecycle is specified by the later [settings describe mirror decision](../architecture/2026-08-17-settings-describe-mirror.md). User changes update the live service synchronously and queue a `settings.mutate` path operation through `scope.set`. The scope serializes gestures, sends the latest known namespace revision as `expectedRevision`, records every successful revision, and lets only the latest write settlement republish live state. A rejected or failed latest write reloads Host state. Disposal rejects new work, skips queued operations, suppresses publication by the in-flight operation, and waits for that operation to settle before the plugin reaches quiescence. -Remote browsers cannot call the loopback-only configuration API, so their preferences remain process-local. Dynamic third-party theme ids remain in-process extensions outside the built-in Host schema; removing one resets the live registry without replacing the last durable built-in preference. +The Client keeps Host persistence disabled on non-loopback pages, so their preferences remain process-local even though Connection authenticates the complete API. Dynamic third-party theme ids remain in-process extensions outside the built-in Host schema; removing one resets the live registry without replacing the last durable built-in preference. ## Alternatives considered diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md index 79c15af723..ead4a0d27a 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md @@ -12,13 +12,13 @@ Web 的 Appearance、Language 和繁忙态 Enter 偏好原本存在浏览器 `lo ## 决策 -各领域所属的 Host half 注册三份 schema:可选的 `locale.preference`(`zh` 或 `en`,缺失时交由浏览器决定)、`ui-theme.preference`(`light`、`dark` 或 `system`,默认为 `system`),以及 `ui-conversation.busyEnter`(`queue` 或 `steer`,默认为 `queue`)。本地 settings 提供方将显式选择存入 `$DSH_HOME/settings.yaml`,在使用默认 home 时,该路径解析为 `~/.dsh/settings.yaml`。API 代理会向回环客户端服务每一个已注册的 namespace;字段角色仍会脱敏机密值。 +各领域所属的 Host half 注册三份 schema:可选的 `locale.preference`(`zh` 或 `en`,缺失时交由浏览器决定)、`ui-theme.preference`(`light`、`dark` 或 `system`,默认为 `system`),以及 `ui-conversation.busyEnter`(`queue` 或 `steer`,默认为 `queue`)。本地 settings 提供方将显式选择存入 `$DSH_HOME/settings.yaml`,在使用默认 home 时,该路径解析为 `~/.dsh/settings.yaml`。API 代理在 Connection 浏览器认证之后服务每一个已注册的 namespace;字段角色仍会脱敏机密值。 `dsh-client-ui-settings` 持有一个浏览器全局的 settings describe 镜像,并提供 `ctx.settingsScope.bind(spec)` 作为该镜像上的逐 namespace selector。镜像在开始后台读取之前安装 `settings/document-updated` 和 `connection/reset` 监听器,因此任何 settings 传输都不会阻塞插件激活,失效通知也不会掉入先读取、后订阅的空档。每个绑定的 scope 会发布一个供领域服务订阅的快照 store(状态、分节值、revision、可写性、host/内存模式),自身不再增加协议读取或监听器。默认解码器会对照该 namespace 自身的序列化 wire schema(经同包的 `ctx.settingsSchema` 服务还原)校验每个传入分节,因此各领域无需携带手写的 wire 校验器。领域服务把 scope 当作普通的构造函数协作者接收,立即发布各自的暂定默认值:由浏览器派生的 locale、系统主题和 Queue;随后采纳已获接受的 Host 分节,但不将其写回;不带 scope 构造的服务——独立词典或政策 fixture(测试前置数据)——则仅停留在进程本地。共享读取与失效生命周期由后续的 [settings describe 镜像决策](../architecture/2026-08-17-settings-describe-mirror.zh.md)规定。 用户变更会同步更新实时服务,并经 `scope.set` 将一项 `settings.mutate` 路径操作排入队列。scope 会串行处理手势,以最新已知 namespace revision 作为 `expectedRevision` 发送,记录每次成功写入的 revision,并且只允许最新写入的结算结果重新发布实时状态。最新写入被拒或失败时,scope 会重新加载 Host 状态。插件释放会拒绝新工作、跳过已排队操作、抑制运行中操作发布状态,并等待该操作结算后才让插件达到完全停稳。 -远程浏览器无法调用仅限回环请求的配置 API,因此其偏好仅保留在进程内。动态第三方主题 id 仍是内置 Host schema 之外的进程内扩展;移除其中一个会重置实时注册表,但不会替换上一个持久化的内置偏好。 +Client 在非 loopback 页面禁用 Host 持久化,因此这些页面的偏好仍只保留在进程内,尽管 Connection 认证完整 API。动态第三方主题 id 仍是内置 Host schema 之外的进程内扩展;移除其中一个会重置实时注册表,但不会替换上一个持久化的内置偏好。 ## 曾考虑的替代方案 diff --git a/.agents/notes/implemented/feature/2026-07-22-web-bind-address.i18n.yaml b/.agents/notes/implemented/feature/2026-07-22-web-bind-address.i18n.yaml index ac5e4cb4c6..ec7451e28d 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-bind-address.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-22-web-bind-address.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-22-web-bind-address.md -2026-07-22-web-bind-address.md: 3332176c0cee940648ad334a44edd30879225503 -2026-07-22-web-bind-address.zh.md: 5ad73b8916d9cedce1073f4a2d025f40197b7d65 +2026-07-22-web-bind-address.md: 68275d220f2270ef924efdbc6a72f3dfcbfd10f8 +2026-07-22-web-bind-address.zh.md: 5bb4fdbbc3e58285b0d227c3ec376786be2782da diff --git a/.agents/notes/implemented/feature/2026-07-22-web-bind-address.md b/.agents/notes/implemented/feature/2026-07-22-web-bind-address.md index 3332176c0c..68275d220f 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-bind-address.md +++ b/.agents/notes/implemented/feature/2026-07-22-web-bind-address.md @@ -6,15 +6,15 @@ English | [中文](2026-07-22-web-bind-address.zh.md) ## Problem -`dsh web` binds every network interface even when its browser runs on the same machine. Local use therefore exposes an unauthenticated development server without an explicit operator choice, while remote-container and LAN-browser use still needs a supported way to accept non-loopback connections. +The Web application can run commands with the Host user's authority. Same-machine use needs only loopback reachability, while an all-interface CLI mode would imply a supported network deployment without TLS or a defined proxy contract. The HTTP carrier also hides the bind address inside `startWebServer()`, so alternate shells cannot state their own network policy at the package boundary. ## Decision -`dsh web` binds `127.0.0.1` by default. The CLI accepts `--host 0.0.0.0` as the explicit all-interface mode and rejects other values so its network modes remain a small, deliberate contract. All-interface mode keeps printing the loopback URL and, when available, the first external IPv4 URL. +`dsh web` binds `127.0.0.1` and rejects `--host 0.0.0.0`; the CLI exposes no network mode. The process-token and browser-cookie authentication does not broaden that deployment contract ([decision](../architecture/2026-08-24-browser-token-authentication.md)). -`WebServerOptions.host` is required. The HTTP carrier passes that value to `node:http` without supplying a fallback, leaving each shell responsible for its bind policy. Programmatic carrier consumers may select another hostname or address directly. +`WebServer` still requires `host: '127.0.0.1' | '0.0.0.0'` and passes it to `node:http` without a fallback. The generic carrier leaves custom composition policy visible at its package interface; the product CLI owns the stricter loopback choice. ## Alternatives considered @@ -22,8 +22,10 @@ The HTTP carrier also hides the bind address inside `startWebServer()`, so alter **Use a boolean exposure flag.** Rejected because `--host 0.0.0.0` names the resulting socket behavior directly and matches the underlying server option without introducing a second term. +**Keep an explicit `--host 0.0.0.0` mode.** Rejected because authentication alone does not supply TLS, forwarding semantics, or a supported remote-deployment contract for the tool-capable Host. + **Default inside `startWebServer()`.** Rejected because the carrier has multiple possible shells and no basis for choosing their deployment policy. Requiring `host` makes the choice visible at every assembly call. ## Consequences -Local `dsh web` starts remain reachable at `http://127.0.0.1:3080`; a browser on another machine must opt in with `dsh web --host 0.0.0.0`. The CLI does not yet expose custom interface addresses or IPv6 modes, while programmatic carrier consumers retain that flexibility. Server tests pin both loopback and all-interface forwarding into the Node listen boundary, and the web smoke continues to exercise the default CLI path. +Local `dsh web` starts remain reachable at `http://127.0.0.1:3080`. The CLI exposes no custom interface, all-interface, or IPv6 mode; custom WebServer compositions retain the carrier's two-address choice and own every consequence. Server tests pin both carrier values into Node listen, while CLI tests pin rejection of the all-interface flag. diff --git a/.agents/notes/implemented/feature/2026-07-22-web-bind-address.zh.md b/.agents/notes/implemented/feature/2026-07-22-web-bind-address.zh.md index 5ad73b8916..5bb4fdbbc3 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-bind-address.zh.md +++ b/.agents/notes/implemented/feature/2026-07-22-web-bind-address.zh.md @@ -6,15 +6,15 @@ Status: implemented ## 问题 -即便浏览器与服务器运行在同一台机器上,`dsh web` 也会绑定所有网络接口。因此,本地使用会在操作者未明确选择的情况下暴露一个未经身份验证的开发服务器;另一方面,远程容器和局域网浏览器场景仍需要一种受支持的方式来接受非环回连接。 +Web 应用可以用 Host 用户的 authority 运行命令。同机使用只需要 loopback 可达性;CLI 若提供全接口模式,就会在没有 TLS 或明确代理约定时暗示支持网络部署。 HTTP 承载层还把绑定地址隐藏在 `startWebServer()` 内部,导致其他壳层无法在包边界明确表达自己的网络策略。 ## 决策 -`dsh web` 默认绑定 `127.0.0.1`。CLI(命令行界面)接受 `--host 0.0.0.0` 作为显式启用的全接口模式,并拒绝其他取值,使网络模式保持为一份规模小、经过审慎限定的约定。全接口模式仍然输出本机环回 URL,并在可用时输出第一个外部 IPv4 URL。 +`dsh web` 绑定 `127.0.0.1` 并拒绝 `--host 0.0.0.0`;CLI 不开放网络模式。进程令牌与浏览器 cookie 认证不扩大该部署约定([决策](../architecture/2026-08-24-browser-token-authentication.zh.md))。 -`WebServerOptions.host` 为必填项。HTTP 承载层将该值直接传给 `node:http`,不提供回退值,因此每个壳层负责制定自己的绑定策略。以编程方式使用承载层的消费方可以直接选择其他主机名或地址。 +`WebServer` 仍要求 `host: '127.0.0.1' | '0.0.0.0'`,并在没有 fallback 的情况下传给 `node:http`。通用承载层让自定义组合策略显式留在包接口上;产品 CLI 持有更严格的 loopback 选择。 ## 曾考虑的替代方案 @@ -22,8 +22,10 @@ HTTP 承载层还把绑定地址隐藏在 `startWebServer()` 内部,导致其 **使用布尔型暴露标志。** 不予采纳,因为 `--host 0.0.0.0` 直接说明最终的套接字行为,并与底层服务器选项一致,无需再引入第二套术语。 +**保留显式 `--host 0.0.0.0` 模式。** 不予采纳,因为仅有认证并不能为工具型 Host 提供 TLS、转发语义或受支持的远程部署约定。 + **在 `startWebServer()` 内设置默认值。** 不予采纳,因为承载层可能由多种壳层调用,没有依据替它们选择部署策略。要求传入 `host`,可使每次装配调用都明确作出这一选择。 ## 后果 -`dsh web` 的本地启动仍可通过 `http://127.0.0.1:3080` 访问;其他机器上的浏览器必须使用 `dsh web --host 0.0.0.0` 显式启用。CLI 尚未开放自定义接口地址或 IPv6 模式,而以编程方式使用承载层的消费方仍保留这种灵活性。服务器测试将环回模式和全接口模式向 Node 监听边界的传递固定为约定,Web 冒烟测试继续覆盖默认 CLI 路径。 +`dsh web` 的本地启动仍可通过 `http://127.0.0.1:3080` 访问。CLI 不开放自定义接口、全接口或 IPv6 模式;自定义 WebServer 组合保留承载层的两个地址选择并自行承担全部后果。服务器测试固定两个承载值都会进入 Node listen,CLI 测试则固定全接口 flag 被拒绝。 diff --git a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.i18n.yaml index 22ba3ccbe8..824846180a 100644 --- a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md -2026-07-28-tool-call-file-open-in-os.md: 08fc51cc3a5d2fb43b67dc158fd1ee789fafdb68 -2026-07-28-tool-call-file-open-in-os.zh.md: c99a99dcd91a8cfabbbc381af79bb3570f4295f6 +2026-07-28-tool-call-file-open-in-os.md: e6e590b2a97654b8b68d5a9842de10818f544088 +2026-07-28-tool-call-file-open-in-os.zh.md: eb600a69cb2a2c3cc0d7463519d3de4dce76047b diff --git a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md index 08fc51cc3a..e6e590b2a9 100644 --- a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md +++ b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md @@ -23,7 +23,7 @@ File-tool path summaries (`read` / `write` / `edit` args carrying `path` or `fil ## Consequences -Clicking a file path in a tool row opens that path on the host. Non-file tool rows are inert summaries (expand toggles remain where the row already supported them). Remote or non-loopback clients cannot invoke `host.openPath`. A Host or OS refusal is owned by the chat view: it shows the thrown reason and retries the same path ([file-open failure](../bug-fix/2026-08-18-tool-row-file-open-failure.md)). +Clicking a file path in a tool row opens that path on the host. Non-file tool rows are inert summaries (expand toggles remain where the row already supported them). The Client withholds `host.openPath` on non-loopback pages; every exposed Host invocation still requires the browser session. A Host or OS refusal is owned by the chat view: it shows the thrown reason and retries the same path ([file-open failure](../bug-fix/2026-08-18-tool-row-file-open-failure.md)). ## Risks diff --git a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.zh.md b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.zh.md index c99a99dcd9..eb600a69cb 100644 --- a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.zh.md @@ -12,7 +12,7 @@ Status: implemented 文件工具的路径摘要(`read`/`write`/`edit` 参数中的 `path` 或 `file_path`)渲染为静止状态下即带下划线的链接,并使用 pointer 光标。点击路径会经 `WorkspaceRuntime.openPath` 调用 `host.openPath`,相对路径以会话 cwd 为基准解析。带文件链接的行关闭参数展开(左侧图标不可点);工具行(含 bash 与 todo 注册)去掉整行点击、整行悬停底色,以及点击打开 details 的手势。details 面板及其 inject 面仍保留供程序化选择;工具行不再驱动它们。 -`host.openPath` 是特权一元 RPC,仅接受来自回环地址且同源的浏览器请求(与 `host.pickDirectory` 相同的载体守卫)。平台适配器不经 shell 打开:macOS 为 `open`,Windows 为 PowerShell `Invoke-Item`,桌面 Linux 为 `xdg-open`;浏览器可渲染的文档会在 macOS 与桌面 Linux 上优先使用指定的默认浏览器。尽管 Node 将 WSL 报告为 `linux`,WSL 仍是一种独立的宿主形态:适配器根据其环境或 Microsoft 内核 release 识别它,用 `wslpath -w` 转换 Linux 路径,并将所得 Windows/UNC 路径交给同一 PowerShell 交接。打开器的平台信息和命令运行器可在测试中注入。仅含 URL 的 read 参数(`web_fetch`)不是文件链接。 +`host.openPath` 是一元 RPC,与每个 Host API 方法一样要求通过 Host/Origin 校验和浏览器会话认证。平台适配器不经 shell 打开:macOS 为 `open`,Windows 为 PowerShell `Invoke-Item`,桌面 Linux 为 `xdg-open`;浏览器可渲染的文档会在 macOS 与桌面 Linux 上优先使用指定的默认浏览器。尽管 Node 将 WSL 报告为 `linux`,WSL 仍是一种独立的宿主形态:适配器根据其环境或 Microsoft 内核 release 识别它,用 `wslpath -w` 转换 Linux 路径,并将所得 Windows/UNC 路径交给同一 PowerShell 交接。打开器的平台信息和命令运行器可在测试中注入。仅含 URL 的 read 参数(`web_fetch`)不是文件链接。 ## 考虑过的替代方案 @@ -23,7 +23,7 @@ Status: implemented ## 后果 -点击工具行中的文件路径会在宿主上打开该路径。非文件工具行只是不可交互的摘要(行内已有的展开开关仍保留)。远程或非回环客户端无法调用 `host.openPath`。Host 或操作系统拒绝由聊天视图拥有:它展示抛出的原因,并对同一路径提供重试([打开失败](../bug-fix/2026-08-18-tool-row-file-open-failure.zh.md))。 +点击工具行中的文件路径会在宿主上打开该路径。非文件工具行只是不可交互的摘要(行内已有的展开开关仍保留)。Client 在非 loopback 页面不提供 `host.openPath`;每次已暴露的 Host 调用仍要求浏览器会话。Host 或操作系统拒绝由聊天视图拥有:它展示抛出的原因,并对同一路径提供重试([打开失败](../bug-fix/2026-08-18-tool-row-file-open-failure.zh.md))。 ## 风险 diff --git a/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.i18n.yaml b/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.i18n.yaml index fda5e932c9..fac721984b 100644 --- a/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.md -2026-08-13-shared-modal-product-onboarding.md: ec3d3e5f112b04736a15645c6e62e942367bb4fa -2026-08-13-shared-modal-product-onboarding.zh.md: 78b17d02dba52170722042126cc5616e9272c722 +2026-08-13-shared-modal-product-onboarding.md: 9f72ee5b4e2abd8dd9ad70c819976be73f3f8116 +2026-08-13-shared-modal-product-onboarding.zh.md: 867b23202f2e15701d72dd5e11cbe6ff2346ef11 diff --git a/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.md b/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.md index ec3d3e5f11..9f72ee5b4e 100644 --- a/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.md +++ b/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.md @@ -14,7 +14,7 @@ First-run onboarding mixed two interaction models: a viewport takeover for produ **Both steps share one modal component.** `OnboardingModal` wraps the existing ui-primitives `Modal`, supplies the common title and content geometry, and owns `#root` inert for exactly the visible lifetime. Escape and mask clicks do not silently complete mandatory onboarding; each step exposes only its explicit actions. A step still loading private facts returns `null`, so it paints and blocks nothing. -**The welcome notice reuses the existing durable field.** Its exact copy and version live in `onboarding-copy.ts`. Loopback clients compare and write `ui-onboarding.welcomeNoticeVersion` through the existing settings API, and only Continue acknowledges the current version. Remote clients retain the existing process-local fallback because the settings namespace is loopback-only. No Host schema, API-proxy allowlist, or persistence implementation changes. +**The welcome notice reuses the existing durable field.** Its exact copy and version live in `onboarding-copy.ts`. Loopback clients compare and write `ui-onboarding.welcomeNoticeVersion` through the existing settings API, and only Continue acknowledges the current version. Non-loopback pages retain the existing process-local fallback because the Client keeps Host settings persistence disabled there. No Host schema, API-proxy allowlist, or persistence implementation changes. **The credential dialog reuses the existing editor and write boundary.** The Models join still decides whether any provider is usable. When the official DeepSeek reference is writable and missing, `ProviderEditor` renders in credential-only mode inside the shared modal. It validates the key and calls the existing `credentials.set`; it does not mutate provider settings. Save and continue waits for the write and refreshed readiness, while Configure later completes only the current coordinator pass. diff --git a/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.zh.md b/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.zh.md index 78b17d02db..867b23202f 100644 --- a/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.zh.md +++ b/.agents/notes/implemented/feature/2026-08-13-shared-modal-product-onboarding.zh.md @@ -14,7 +14,7 @@ Status: implemented **两个步骤共用同一个弹窗组件。** `OnboardingModal` 包装既有 ui-primitives `Modal`,提供统一的标题和内容布局,并只在可见期间持有 `#root` 的 inert 状态。Escape 和遮罩点击不会静默完成强制引导;每个步骤只暴露自己的明确操作。步骤仍在加载私有事实时返回 `null`,因此不会绘制或阻塞界面。 -**欢迎声明复用既有持久化字段。** 完整文案与版本由 `onboarding-copy.ts` 持有。回环客户端通过既有 settings API 比较和写入 `ui-onboarding.welcomeNoticeVersion`,且只有点击「继续」才确认当前版本。远程客户端继续使用既有的进程内回退,因为该 settings namespace 仅限回环访问。不改变 Host schema、API Proxy 允许列表或持久化实现。 +**欢迎声明复用既有持久化字段。** 完整文案与版本由 `onboarding-copy.ts` 持有。回环客户端通过既有 settings API 比较和写入 `ui-onboarding.welcomeNoticeVersion`,且只有点击「继续」才确认当前版本。非 loopback 页面继续使用既有的进程内回退,因为 Client 在那里禁用 Host settings 持久化。不改变 Host schema、API Proxy 允许列表或持久化实现。 **凭据弹窗复用既有编辑器与写入边界。** Models 联接仍负责判断是否已有任意可用提供方。当 DeepSeek 官方引用可写但缺失时,`ProviderEditor` 以仅凭据模式渲染在共用弹窗中。它校验密钥并调用既有 `credentials.set`,不会修改提供方设置。「保存并继续」会等待写入与就绪状态刷新;「稍后配置」只完成协调器当前这一轮。 diff --git a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.i18n.yaml b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.i18n.yaml index 241d95f649..df36182179 100644 --- a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.i18n.yaml +++ b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.md -2026-08-08-copy-only-preset-authoring.md: c16518b087c7acedbee3d89ce5cc8dbcaa0a0cde -2026-08-08-copy-only-preset-authoring.zh.md: 63a184f5825530a2c99a26b8afa606412decab6e +2026-08-08-copy-only-preset-authoring.md: bfe0d49755abf47314a7b4cf56c738537fca3963 +2026-08-08-copy-only-preset-authoring.zh.md: fc2d9ac5c6ace45c46fc920e1f7f28aca508ba9c diff --git a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.md b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.md index c16518b087..bfe0d49755 100644 --- a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.md +++ b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.md @@ -14,7 +14,7 @@ Authoring is a host-side copy, and files are the editor. `agentPreset.write` bec ## Consequences -- No composition text and no path crosses the browser wire in either authoring direction; the `entryListSchema`/`!!js` concern dissolves with `assertComposition` itself (deleted). The privileged set is now `read`/`copy`/`openDocument`/`remove` — none accepts a filesystem target. +- No composition text and no path crosses the browser wire in either authoring direction; the `entryListSchema`/`!!js` concern dissolves with `assertComposition` itself (deleted). The authoring operations are `read`/`copy`/`openDocument`/`remove` — none accepts a filesystem target, and Connection authenticates them with the complete Host API. - With the editor gone, hand-editing `agent.cordis.yml` is the ONLY composition edit, so the standing-mount layer grew stamp-keyed generations: `ensureStanding` compares the file's mtime+size and starts the next generation for later sessions ([standing-mounts note](../architecture/2026-08-08-per-preset-standing-mounts.md), updated in place). Without this, an edited file would serve stale compositions until process restart. - A copy is a full snapshot that drifts from an upgraded shipped source — accepted; the preset layer has no patch semantics (that is the bundle layer's `cordis.patch.yml`), and the shipped set itself pays the same cost (`cordis`/`code` are full copies of `standard`) for one-file readability. - `read` dropped `writable` (no editor to gate) and builtin directories are never opened (`openDocument` refuses non-`user` trust like `remove`): the install is overwritten by upgrades, and pointing an editor into it invites edits an upgrade silently discards. @@ -22,7 +22,7 @@ Authoring is a host-side copy, and files are the editor. `agentPreset.write` bec ## Load-bearing details - **Copy target refusal is two checks on purpose.** The roster check refuses any id a root supplies — a user directory named like a shipped preset would be shadowed, so "create" would land a file nothing ever lists; the disk check (`PresetExistsError` before `cp` with `errorOnExist` as the race backstop) refuses a directory occupying the name without being a preset, which discovery cannot see. -- **The revealed path is response-direction disclosure, loopback-pinned.** The invariant "no browser payload can select an arbitrary filesystem target" is about the request direction; showing the resolved directory to the loopback user is the fallback the plan requires. It never rides the unprivileged `list`. +- **The revealed path is response-direction disclosure, browser-authenticated.** The invariant "no browser payload can select an arbitrary filesystem target" is about the request direction; showing the resolved directory to the authenticated browser is the fallback the plan requires. It never rides `list`. - **The e2e lane pins `nativeOpen: false`** (`agent-preset-authoring.overlay.yml`) — both so goldens render the same branch on macOS dev and headless Linux CI, and so test runs never pop a real file manager. The revealed directory is tokenized as `{{presetRoot}}` by the lane itself, since `normalizeAria` only knows the workspace cwd. ## Alternatives considered diff --git a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.zh.md b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.zh.md index 63a184f582..fc2d9ac5c6 100644 --- a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.zh.md +++ b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.zh.md @@ -14,7 +14,7 @@ agent-preset 设置页带着一个网页 YAML 编辑器:`agentPreset.write` ## 后果 -- 创作两个方向都不再有组装文本或路径跨越浏览器传输层;`entryListSchema`/`!!js` 的顾虑随 `assertComposition` 本身(已删除)一并消解。特权集现为 `read`/`copy`/`openDocument`/`remove`——没有一个接收文件系统目标。 +- 创作两个方向都不再有组装文本或路径跨越浏览器传输层;`entryListSchema`/`!!js` 的顾虑随 `assertComposition` 本身(已删除)一并消解。创作操作现为 `read`/`copy`/`openDocument`/`remove`——没有一个接收文件系统目标,且 Connection 用完整 Host API 的同一会话认证它们。 - 编辑器移除后,手改 `agent.cordis.yml` 成为唯一的组装编辑方式,因此常驻挂载层增加了以 stamp 为键的代际:`ensureStanding` 比对文件的 mtime+大小,为后续会话开启下一代际([常驻挂载 note](../architecture/2026-08-08-per-preset-standing-mounts.zh.md),已就地更新)。没有它,改过的文件要等进程重启才生效。 - 副本是完整快照,会随随附来源升级而漂移——接受;preset 层没有 patch 语义(那是 bundle 层 `cordis.patch.yml` 的能力),随附集合自己也为「一个文件读完整份组装」付了同样的代价(`cordis`/`code` 就是 `standard` 的完整副本)。 - `read` 去掉了 `writable`(没有编辑器可门控),内置目录绝不被打开(`openDocument` 与 `remove` 一样拒绝非 `user` 信任):安装目录会被升级覆盖,把编辑器指向它等于招揽会被升级悄悄丢弃的编辑。 @@ -22,7 +22,7 @@ agent-preset 设置页带着一个网页 YAML 编辑器:`agentPreset.write` ## 关键实现细节 - **复制目标的拒绝刻意分两道检查。** roster 检查拒绝任一根目录提供的 id——与随附 preset 同名的用户目录会被遮蔽,「创建」只会落下一个永远不被列出的文件;磁盘检查(`cp` 之前的 `PresetExistsError`,`errorOnExist` 作竞态兜底)拒绝占着名字却不是 preset 的目录,那是 discovery 看不见的。 -- **展示的路径是响应方向的披露,且钉在环回。**「没有任何浏览器载荷能选中任意文件系统目标」这条不变量说的是请求方向;把解析出的目录展示给环回用户正是方案要求的降级。它绝不搭乘非特权的 `list`。 +- **展示的路径是响应方向的披露,且经过浏览器认证。**「没有任何浏览器载荷能选中任意文件系统目标」这条不变量说的是请求方向;把解析出的目录展示给已认证浏览器正是方案要求的降级。它绝不搭乘 `list`。 - **e2e lane 钉死 `nativeOpen: false`**(`agent-preset-authoring.overlay.yml`)——既让 golden 在 macOS 开发机与无头 Linux CI 上渲染同一分支,也让测试运行永不弹出真实文件管理器。揭示的目录由 lane 自己 token 化为 `{{presetRoot}}`,因为 `normalizeAria` 只认识 workspace cwd。 ## 考虑过的替代方案 diff --git a/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.i18n.yaml b/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.i18n.yaml index d327972db7..67e708c2ff 100644 --- a/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.md -2026-08-10-unary-apiproxy-remote-migration.md: c4a308e16bee994df69f16228e859dd88d90c346 -2026-08-10-unary-apiproxy-remote-migration.zh.md: db263e1a7843963cf38082a88405453ee4b66af7 +2026-08-10-unary-apiproxy-remote-migration.md: cd019ef10c6d584a98b185ac50856a3fe63b8bd0 +2026-08-10-unary-apiproxy-remote-migration.zh.md: e6842cc82cfd7f850bb58e9d640ec23394287427 diff --git a/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.md b/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.md index c4a308e16b..cd019ef10c 100644 --- a/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.md +++ b/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.md @@ -12,7 +12,7 @@ Moving a method mechanically is not sufficient. Agent-bound API Proxy methods ca The API Proxy also contains BFF operations whose contract is not a business method: Session lifecycle and transcript assembly, model-selection state, live-only input control, configuration filtering, skill presentation, Host composition facts, and native desktop operations. Stateful interactions and streams have different lifecycles again. Treating all unary syntax as evidence that a method is simple would move product policy into arbitrary Service packages or force new packages that have no independent business owner. -Finally, Connection currently applies its loopback-only privileged-method list inside the API Proxy fallback. A Typert interceptor claims its endpoint before that fallback, so migrating credential or preset authoring calls without moving the privilege check would grant trusted-LAN callers operations that are currently loopback-only. +Finally, Connection must authenticate a request before choosing the API Proxy fallback or a Typert interceptor. A migration that authenticates only the fallback would let Remote-owned endpoints bypass the browser identity required by every Host operation. ## Proposal @@ -76,14 +76,9 @@ Generated Remote methods return business values and throw an Error whose `cause` Resolver-owned `session-not-found` and `agent-busy` errors remain stable because the shared resolver raises `TypertLookupFailure`. Ordinary business exceptions become the Gateway's existing `internal` RPC failure. A selected Client consumer may migrate only if it does not branch on a more specific legacy business error code; if implementation finds such a branch, that RPC leaves this set unless the business package gains a transport-independent typed failure. -## Privileged authority +## Browser authentication -Connection must enforce privileged endpoint authority before choosing the Typert interceptor or API Proxy fallback. The check must recognize both legacy dotted names and Remote slash endpoints and keep these migrated operations loopback-only: - -- `agentPresets/readDocument`, `agentPresets/copy`, and `agentPresets/remove`; -- `credentials/describe`, `credentials/set`, and `credentials/unset`. - -The carrier-wide trusted-host and origin checks remain unchanged. This is a non-escalation requirement: endpoint ownership may change, but the set of callers authorized to invoke the operation may not widen. +Connection authenticates the complete `/api` request before choosing the Typert interceptor or API Proxy fallback. Legacy dotted names and Remote slash endpoints therefore use the same process-token-established browser session without an endpoint list. This is a non-escalation requirement: endpoint ownership may change, but an unauthenticated request can reach neither dispatch path. ## Commit boundaries @@ -101,14 +96,14 @@ The final commit generates every `/remote` artifact from a clean state, updates **Preserve every legacy RPC name and response envelope.** That would turn business packages into copies of the old protocol. Service-oriented names and business values let the Client own joins while Connection continues to own the one RPC envelope. -**Trust the API Proxy fallback to enforce privileged methods.** Interceptor selection bypasses that fallback, so this would silently widen authority for migrated methods. +**Trust the API Proxy fallback to authenticate requests.** Interceptor selection bypasses that fallback, so Remote methods would become anonymously callable. ## Acceptance criteria - Every migration-table method is callable through its listed `ctx.remote` Service and has no production legacy API Proxy route, schema, map row, client stub, or invocation. - Existing methods with matching signatures carry `@Remote` directly; every added method performs the adaptation stated in the table and no identity `remote*` wrapper remains. - Agent/Session integration tests prove the shared lookup outcomes, and subagent interrupt tests prove no cold resume occurs. -- Privileged migrated endpoints reject trusted non-loopback callers and accept loopback callers before either dispatch path runs. +- Migrated endpoints reject unauthenticated requests and accept the same valid browser session as legacy endpoints before either dispatch path runs. - Client behavior and immediate state settlement remain equivalent for every migrated call, including cancellation where supported. - Deferred methods remain on the API Proxy with their existing behavior. - A clean generation/build produces and consumes every selected Remote contribution, and focused tests plus final repository gates pass. @@ -119,6 +114,6 @@ Removing legacy schemas also removes their protocol-specific error taxonomy. A h Generated Remote contracts add build ordering and publication entries to each business package. Missing one runtime mount, declaration export, source-map source, package dependency, or Project Reference can pass a narrow source test while failing a clean Client build. -Moving privilege enforcement to composite dispatch changes security-sensitive carrier code. Tests must exercise both a Remote-owned endpoint and a legacy fallback endpoint so neither path can bypass the loopback decision. +Composite dispatch changes security-sensitive carrier code. Tests must exercise both a Remote-owned endpoint and a legacy fallback endpoint so neither path can bypass browser authentication. -This note applies the existing Typert Remote architecture rather than superseding it. It partially supersedes the central unary ownership and five-step extension checklist in the [GUI RPC protocol note](../../implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md) and the central wiring inventory in the [Web configuration plane note](../../implemented/architecture/2026-07-30-web-config-plane.md); those notes remain authoritative for Connection envelopes and configuration behavior outside the migrated methods. The title, command, configuration-boundary, subagent-interrupt, and archive notes continue to own their business behavior and require factual transport updates rather than archival. The [browser trust boundary](../../implemented/architecture/2026-07-28-api-browser-trust-boundary.md) and [generated-contract build order](../../implemented/process/2026-08-08-api-remotes-generated-contract-build.md) remain authoritative and require no archival action. +This note applies the existing Typert Remote architecture rather than superseding it. It partially supersedes the central unary ownership and five-step extension checklist in the [GUI RPC protocol note](../../implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md) and the central wiring inventory in the [Web configuration plane note](../../implemented/architecture/2026-07-30-web-config-plane.md); those notes remain authoritative for Connection envelopes and configuration behavior outside the migrated methods. The title, command, configuration-boundary, subagent-interrupt, and archive notes continue to own their business behavior and require factual transport updates rather than archival. The [browser trust boundary](../../implemented/architecture/2026-07-28-api-browser-trust-boundary.md), [browser authentication](../../implemented/architecture/2026-08-24-browser-token-authentication.md), and [generated-contract build order](../../implemented/process/2026-08-08-api-remotes-generated-contract-build.md) remain authoritative and require no archival action. diff --git a/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.zh.md b/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.zh.md index db263e1a78..e6842cc82c 100644 --- a/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.zh.md +++ b/.agents/notes/proposed/architecture/2026-08-10-unary-apiproxy-remote-migration.zh.md @@ -12,7 +12,7 @@ Host API Proxy 仍承载许多一元方法。这些方法的实现仅执行服 API Proxy 还包含一些不以业务方法为约定的 BFF 操作:Session 生命周期与 transcript(文本记录)组装、模型选择状态、仅限 live 的输入控制、配置过滤、skill(技能)呈现、Host 组合信息和原生桌面操作。有状态交互与流又具有不同的生命周期。若把一元调用的语法一概视为方法简单的依据,就会把产品策略移入任意服务包,或者迫使系统新增没有独立业务所有者的包。 -最后,Connection 目前在 API Proxy 回退路径内执行仅限环回地址的特权方法清单。Typert interceptor 会先于该回退路径认领自己的端点,因此,如果迁移凭据或 preset 创作调用时不一并迁移权限检查,受信任的局域网调用方就会获得目前仅向环回调用方开放的操作权限。 +最后,Connection 必须在选择 API Proxy 回退路径或 Typert interceptor 前认证请求。若迁移只在回退路径执行认证,由 Remote 持有的 endpoint 就能绕过每个 Host 操作都要求的浏览器身份。 ## 提案 @@ -76,14 +76,9 @@ Lookup 策略作用于整个 key,而非特定端点。提示词输入、队列 Resolver 拥有的 `session-not-found` 和 `agent-busy` 错误保持稳定,因为共享 resolver 会抛出 `TypertLookupFailure`。普通业务异常会变成 Gateway 现有的 `internal` RPC 失败。只有在选定的 Client 消费方不根据更具体的旧版业务错误码进行分支时,才能迁移该调用;如果实现过程中发现这种分支,除非业务包新增与传输无关的类型化失败,否则该 RPC 将退出此集合。 -## 特权调用权限 +## 浏览器认证 -Connection 必须在选择 Typert interceptor 或 API Proxy 回退路径之前检查调用方是否有权访问特权端点。该检查必须同时识别旧式点分名称和 Remote 斜杠端点,并保持以下已迁移操作仅限环回地址: - -- `agentPresets/readDocument`、`agentPresets/copy` 和 `agentPresets/remove`; -- `credentials/describe`、`credentials/set` 和 `credentials/unset`。 - -贯穿整个载体的 trusted-host 和 origin 检查保持不变。这是一项非升权要求:端点所有权可以变化,但获准调用该操作的调用方集合不得扩大。 +Connection 在选择 Typert interceptor 或 API Proxy 回退路径前认证完整 `/api` 请求。旧式点分名称和 Remote 斜杠 endpoint 因此无需 endpoint 清单,就能使用同一个由进程令牌建立的浏览器会话。这是一条非提权要求:endpoint 所有权可以变化,但未认证请求不能进入任一分发路径。 ## 提交边界 @@ -101,14 +96,14 @@ Connection 必须在选择 Typert interceptor 或 API Proxy 回退路径之前 **保留每一个旧版 RPC 名称和响应 envelope。** 这会使业务包变成旧协议的副本。面向服务的名称和业务值让 Client 负责关联操作,而 Connection 继续负责统一的 RPC envelope。 -**依赖 API Proxy 回退路径强制执行特权方法权限。** interceptor 选择会绕过该回退路径,因此这会悄然扩大已迁移方法的权限范围。 +**依赖 API Proxy 回退路径认证请求。** interceptor 选择会绕过该回退路径,使 Remote 方法变成匿名可调用。 ## 验收标准 - 迁移表中的每个方法都可通过表中列出的 `ctx.remote` 服务调用,并且不存在生产环境中的旧版 API Proxy 路由、schema、映射表行、客户端 stub 或调用。 - 签名匹配的现有方法直接带有 `@Remote`;每个新增方法都执行表中所述的适配,且不保留只做恒等转发的 `remote*` 包装层。 - Agent/Session 集成测试证明共享 lookup 的各项结果,subagent 中断测试证明不会发生冷恢复。 -- 已迁移的特权端点拒绝受信任的非环回调用方,并接受环回调用方,且该判定在任一分发路径运行前完成。 +- 已迁移 endpoint 拒绝未认证请求,并在任一分发路径运行前接受与旧 endpoint 相同的有效浏览器会话。 - 每项已迁移调用的 Client 行为和立即提交状态的行为保持等价,包括支持取消之处的取消行为。 - 暂缓迁移的方法及其现有行为仍保留在 API Proxy 上。 - 一次从干净状态开始的生成与构建会生成并消费所选的每项 Remote 贡献,且聚焦测试和最终仓库门禁均通过。 @@ -119,6 +114,6 @@ Connection 必须在选择 Typert interceptor 或 API Proxy 回退路径之前 生成的 Remote 约定会为每个业务包引入构建顺序要求和发布条目。如果遗漏运行时挂载、声明导出、source map 来源、包依赖或 Project Reference 中的任何一项,局部源码测试可能仍会通过,但从干净状态开始的 Client 构建会失败。 -将权限强制执行移至复合分发会改变安全敏感的载体代码。测试必须覆盖一个由 Remote 拥有的端点和一个旧版回退端点,确保两条路径都无法绕过环回判定。 +复合分发会改变安全敏感的载体代码。测试必须覆盖一个由 Remote 拥有的 endpoint 和一个旧版回退 endpoint,确保两条路径都无法绕过浏览器认证。 -本文应用现有 Typert Remote 架构,而非取代它。本文部分取代 [GUI RPC 协议笔记](../../implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.zh.md)中的中央一元调用所有权和五步扩展检查清单,以及 [Web 配置平面笔记](../../implemented/architecture/2026-07-30-web-config-plane.zh.md)中的中央接线清单;对于已迁移方法之外的 Connection envelope 和配置行为,这些笔记仍具权威性。标题、命令、配置边界、subagent 中断和归档笔记继续负责各自的业务行为,只需如实更新传输相关事实,无需归档。[浏览器信任边界](../../implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)和[生成约定构建顺序](../../implemented/process/2026-08-08-api-remotes-generated-contract-build.zh.md)仍具权威性,无需执行归档操作。 +本文应用现有 Typert Remote 架构,而非取代它。本文部分取代 [GUI RPC 协议笔记](../../implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.zh.md)中的中央一元调用所有权和五步扩展检查清单,以及 [Web 配置平面笔记](../../implemented/architecture/2026-07-30-web-config-plane.zh.md)中的中央接线清单;对于已迁移方法之外的 Connection envelope 和配置行为,这些笔记仍具权威性。标题、命令、配置边界、subagent 中断和归档笔记继续负责各自的业务行为,只需如实更新传输相关事实,无需归档。[浏览器信任边界](../../implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)、[浏览器认证](../../implemented/architecture/2026-08-24-browser-token-authentication.zh.md)和[生成约定构建顺序](../../implemented/process/2026-08-08-api-remotes-generated-contract-build.zh.md)仍具权威性,无需执行归档操作。 diff --git a/apps/cli/package.json b/apps/cli/package.json index 3d785a12cd..d940c56bb4 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -136,6 +136,8 @@ "@deepseek-ai/dsh-tool-subagent-report": "workspace:^", "@deepseek-ai/dsh-user-approval": "workspace:^", "@types/js-yaml": "^4.0.9", - "execa": "^10.0.0" + "@types/ws": "8.18.1", + "execa": "^10.0.0", + "ws": "8.21.0" } } diff --git a/apps/cli/tests/fixtures/web-browser-open/open.mjs b/apps/cli/tests/fixtures/web-browser-open/open.mjs index 0f196f0e3f..85ca246fbd 100644 --- a/apps/cli/tests/fixtures/web-browser-open/open.mjs +++ b/apps/cli/tests/fixtures/web-browser-open/open.mjs @@ -22,7 +22,15 @@ export default async function open(url) { if (process.env.BROWSER_OPEN_TEST_FAILURE !== undefined) { throw new Error(process.env.BROWSER_OPEN_TEST_FAILURE) } - const response = await fetch(url) + const exchange = await fetch(url, { redirect: 'manual' }) + const setCookie = exchange.headers.get('set-cookie') + const location = exchange.headers.get('location') + if (exchange.status !== 303 || setCookie === null || location === null) { + throw new Error(`browser authentication exchange returned HTTP ${exchange.status}`) + } + const response = await fetch(new URL(location, url), { + headers: { cookie: setCookie.split(';', 1)[0] }, + }) const html = await response.text() console.log(`dsh browser-open: ${JSON.stringify({ url, diff --git a/apps/cli/tests/github-webhook-real.e2e.ts b/apps/cli/tests/github-webhook-real.e2e.ts index e16aef8b3e..fd465714d3 100644 --- a/apps/cli/tests/github-webhook-real.e2e.ts +++ b/apps/cli/tests/github-webhook-real.e2e.ts @@ -12,6 +12,7 @@ import { join } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' +import WebSocket from 'ws' const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url)) const BUILT_BIN = join(REPO_ROOT, 'apps/cli/lib/bin.js') @@ -23,6 +24,23 @@ const SECRET = 'github-webhook-real-e2e-secret' const DELIVERY = 'github-webhook-real-e2e-delivery' const MARKER = 'DSH_GITHUB_WEBHOOK_REAL_E2E_OK' const TITLE = 'GitHub webhook real e2e' +const authenticatedCookies = new Map>() + +/** Exchange the printed process token once for Node-side API probes. */ +function authenticatedWeb(launchUrl: string): Promise<{ origin: string; cookie: string }> { + const existing = authenticatedCookies.get(launchUrl) + if (existing !== undefined) return existing + const exchange = (async () => { + const response = await fetch(launchUrl, { redirect: 'manual' }) + const setCookie = response.headers.get('set-cookie') + if (response.status !== 303 || setCookie === null) { + throw new Error(`dsh web authentication returned HTTP ${String(response.status)}`) + } + return { origin: new URL(launchUrl).origin, cookie: setCookie.split(';', 1)[0]! } + })() + authenticatedCookies.set(launchUrl, exchange) + return exchange +} interface SessionList { items: Array<{ @@ -111,9 +129,10 @@ async function freePort(): Promise { /** Invoke one public Remote method over its HTTP carrier. */ async function remoteRpc(baseUrl: string, endpoint: string, args: object): Promise { - const response = await fetch(`${baseUrl}/api/${endpoint}`, { + const authenticated = await authenticatedWeb(baseUrl) + const response = await fetch(`${authenticated.origin}/api/${endpoint}`, { method: 'POST', - headers: { 'content-type': 'application/json' }, + headers: { 'content-type': 'application/json', cookie: authenticated.cookie }, body: JSON.stringify({ type: 'client-request', rpcId: `github-webhook-real-${endpoint}-${randomUUID()}`, @@ -140,7 +159,10 @@ async function openingStreamItem( args: object, accepts: (value: unknown) => boolean, ): Promise> { - const socket = new WebSocket(`${baseUrl.replace(/^http/u, 'ws')}/api/remote.mux`) + const authenticated = await authenticatedWeb(baseUrl) + const socket = new WebSocket(`${authenticated.origin.replace(/^http/u, 'ws')}/api/remote.mux`, { + headers: { cookie: authenticated.cookie }, + }) const streamId = `github-webhook-real-${endpoint}-${randomUUID()}` try { await new Promise((resolve, reject) => { @@ -179,10 +201,13 @@ async function openingStreamItem( else if (value === undefined) reject(new Error(`${endpoint} opening item was absent`)) else resolve(value) } - const message = (event: MessageEvent): void => { + const message = (event: WebSocket.MessageEvent): void => { try { - if (typeof event.data !== 'string') throw new Error(`${endpoint} published a non-text frame`) - const frame: unknown = JSON.parse(event.data) + const text = typeof event.data === 'string' + ? event.data + : Buffer.isBuffer(event.data) ? event.data.toString('utf8') : undefined + if (text === undefined) throw new Error(`${endpoint} published a non-text frame`) + const frame: unknown = JSON.parse(text) if (!isRecord(frame) || frame.streamId !== streamId) return if (frame.type === 'error') { finish(new Error(`${endpoint} failed: ${JSON.stringify(frame.error)}`)) @@ -356,7 +381,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('GitHub webhook through the real const webhookOrigin = `http://127.0.0.1:${String(webhookPort)}` expect((await fetch(`${webhookOrigin}/api`)).status).toBe(404) - expect((await sendGitHubDelivery(baseUrl)).status).not.toBe(202) + expect((await sendGitHubDelivery(new URL(baseUrl).origin)).status).not.toBe(202) expect((await sendGitHubDelivery(webhookOrigin)).status).toBe(202) const workspaces = await eventually( diff --git a/apps/cli/tests/web-auth.e2e.ts b/apps/cli/tests/web-auth.e2e.ts new file mode 100644 index 0000000000..b22f611306 --- /dev/null +++ b/apps/cli/tests/web-auth.e2e.ts @@ -0,0 +1,210 @@ +/** Real `dsh web` authentication against a temporary Harness home. */ + +import type { ChildProcess } from 'node:child_process' +import { spawn } from 'node:child_process' +import { stat } from 'node:fs/promises' +import { request as httpRequest } from 'node:http' +import { createRequire } from 'node:module' +import { createServer } from 'node:net' +import type { AddressInfo } from 'node:net' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { describe, expect, it } from 'vitest' + +const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url)) +const DSH_SOURCE_BIN = join(REPO_ROOT, 'apps/cli/src/bin.ts') +const TSX_LOADER = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href + +interface RunningWeb { + readonly child: ChildProcess + readonly launchUrl: string + readonly output: () => string +} + +interface HttpResult { + readonly status: number + readonly body: string +} + +function redact(output: string): string { + return output.replace(/([?&]token=)[^\s)]+/gu, '$1') +} + +/** Reserve one concrete loopback port, then release it for the CLI process. */ +async function freePort(): Promise { + const server = createServer() + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', resolve) + }) + const port = (server.address() as AddressInfo).port + await new Promise((resolve, reject) => { + server.close((error) => { + if (error === undefined) resolve() + else reject(error) + }) + }) + return port +} + +function cleanEnvironment(root: string, dshHome: string): NodeJS.ProcessEnv { + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => + !/(?:KEY|SECRET|TOKEN|PASSWORD)/iu.test(name))) + return { + ...env, + DSH_AGENTS_HOME: join(root, '.agents'), + DSH_HOME: dshHome, + DSH_TELEMETRY_DISABLED: '1', + NODE_NO_WARNINGS: '1', + SSH_CONNECTION: '', + SSH_TTY: '', + TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json'), + } +} + +/** Start the public source CLI and wait for its authenticated readiness URL. */ +async function startWeb(root: string, dshHome: string, port: number): Promise { + const child = spawn(process.execPath, [ + '--import', TSX_LOADER, + DSH_SOURCE_BIN, + 'web', + '--no-open', + '--port', String(port), + ], { + cwd: root, + env: cleanEnvironment(root, dshHome), + stdio: ['ignore', 'pipe', 'pipe'], + }) + let output = '' + const launchUrl = await new Promise((resolve, reject) => { + let settled = false + const fail = (error: Error): void => { + if (settled) return + settled = true + clearTimeout(timer) + reject(error) + } + const timer = setTimeout(() => { + fail(new Error(`dsh web did not become ready:\n${redact(output)}`)) + }, 90_000) + const append = (chunk: Buffer | string): void => { + output = `${output}${String(chunk)}`.slice(-100_000) + const match = /dsh web: (http:\/\/[^\s]+)/u.exec(output) + if (settled || match?.[1] === undefined) return + settled = true + clearTimeout(timer) + resolve(match[1]) + } + child.stdout?.on('data', append) + child.stderr?.on('data', append) + child.once('error', (error) => { + fail(error) + }) + child.once('exit', (code) => { + fail(new Error(`dsh web exited before readiness (${String(code)}):\n${redact(output)}`)) + }) + }) + return { child, launchUrl, output: () => output } +} + +async function stopWeb(running: RunningWeb): Promise { + if (running.child.exitCode !== null) return + const exited = new Promise((resolve) => { running.child.once('exit', () => { resolve() }) }) + running.child.kill('SIGTERM') + const forced = setTimeout(() => { running.child.kill('SIGKILL') }, 10_000) + forced.unref() + await exited + clearTimeout(forced) +} + +/** POST one real API Proxy envelope while controlling the wire Host header. */ +function describeHost(port: number, host: string, cookie?: string): Promise { + const body = JSON.stringify({ + type: 'client-request', + rpcId: 'web-auth-real-cli', + method: 'host.describe', + payload: {}, + }) + return new Promise((resolve, reject) => { + const req = httpRequest({ + hostname: '127.0.0.1', + port, + path: '/api/host.describe', + method: 'POST', + headers: { + host, + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(body), + ...cookie === undefined ? {} : { cookie }, + }, + }, (res) => { + const chunks: Uint8Array[] = [] + res.on('data', (chunk: Buffer) => { chunks.push(chunk) }) + res.on('end', () => { + resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }) + }) + }) + req.once('error', reject) + req.end(body) + }) +} + +describe('dsh web authentication through the real CLI', () => { + it('rejects a forged loopback Host and preserves the browser cookie across restart', { timeout: 180_000 }, async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-web-auth-real-cli-')) + const dshHome = join(root, '.dsh') + const port = await freePort() + let first: RunningWeb | undefined + let second: RunningWeb | undefined + try { + first = await startWeb(root, dshHome, port) + const firstUrl = new URL(first.launchUrl) + expect(firstUrl.origin).toBe(`http://127.0.0.1:${String(port)}`) + expect(firstUrl.pathname).toBe('/') + expect(firstUrl.searchParams.get('token')).toMatch(/^[A-Za-z0-9_-]{43}$/u) + + expect(await describeHost(port, `localhost:${String(port)}`)).toEqual({ + status: 401, + body: 'unauthorized', + }) + + const exchange = await fetch(first.launchUrl, { redirect: 'manual' }) + expect(exchange.status).toBe(303) + expect(exchange.headers.get('location')).toBe('/') + const setCookie = exchange.headers.get('set-cookie') + if (setCookie === null) throw new Error('real CLI token exchange omitted Set-Cookie') + expect(setCookie).toContain('HttpOnly') + expect(setCookie).toContain('SameSite=Strict') + expect(setCookie).not.toContain('Secure') + const cookie = setCookie.split(';', 1)[0]! + + const authenticated = await describeHost(port, firstUrl.host, cookie) + expect(authenticated.status).toBe(200) + const authenticatedBody = JSON.parse(authenticated.body) as unknown + expect(authenticatedBody).toMatchObject({ + type: 'server-response', + rpcId: 'web-auth-real-cli', + result: { ok: true, value: { version: expect.any(String) as unknown } }, + }) + + await stopWeb(first) + first = undefined + second = await startWeb(root, dshHome, port) + const secondUrl = new URL(second.launchUrl) + expect(secondUrl.searchParams.get('token')).not.toBe(firstUrl.searchParams.get('token')) + expect((await describeHost(port, secondUrl.host, cookie)).status).toBe(200) + + const credentialMode = (await stat(join(dshHome, '.credentials.yaml'))).mode & 0o777 + expect(credentialMode).toBe(0o600) + } catch (error) { + const evidence = [first?.output(), second?.output()].filter(value => value !== undefined).join('\n') + throw new Error(`${error instanceof Error ? error.message : String(error)}\n${redact(evidence)}`, { cause: error }) + } finally { + if (second !== undefined) await stopWeb(second) + if (first !== undefined) await stopWeb(first) + await rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/apps/cli/tests/web-browser-open.expected.e2e.ts b/apps/cli/tests/web-browser-open.expected.e2e.ts index 0441ab6e17..96bbbc0215 100644 --- a/apps/cli/tests/web-browser-open.expected.e2e.ts +++ b/apps/cli/tests/web-browser-open.expected.e2e.ts @@ -32,7 +32,9 @@ interface BrowserOpenRecord { } function normalizeLocalUrl(url: string): string { - return url.replace(/:\d+$/, ':{{port}}') + return url + .replace(/:\d+/u, ':{{port}}') + .replace(/token=[^&]+/u, 'token={{token}}') } describe.skipIf(!builtArtifactsExist)('dsh web browser-open assembled snapshot', () => { @@ -85,9 +87,9 @@ describe.skipIf(!builtArtifactsExist)('dsh web browser-open assembled snapshot', "bootManifest": true, "dshHomePresent": false, "exitCode": 0, - "openedUrl": "http://127.0.0.1:{{port}}", + "openedUrl": "http://127.0.0.1:{{port}}/?token={{token}}", "opening": true, - "readyUrl": "http://127.0.0.1:{{port}}", + "readyUrl": "http://127.0.0.1:{{port}}/?token={{token}}", "status": 200, "stderr": "", } @@ -124,7 +126,6 @@ describe.skipIf(!builtArtifactsExist)('dsh web browser-open assembled snapshot', const readyUrl = /dsh web: (http:\/\/[^\s]+)/u.exec(result.stdout)?.[1] const diagnostic = result.stderr.split(/\r?\n/u) .find(line => line.startsWith('web-app: could not open the default browser because ')) - ?.replace(/http:\/\/127\.0\.0\.1:\d+/u, 'http://127.0.0.1:{{port}}') expect({ diagnostic, @@ -134,11 +135,11 @@ describe.skipIf(!builtArtifactsExist)('dsh web browser-open assembled snapshot', readyUrl: readyUrl === undefined ? undefined : normalizeLocalUrl(readyUrl), }).toMatchInlineSnapshot(` { - "diagnostic": "web-app: could not open the default browser because fixture desktop unavailable; visit http://127.0.0.1:{{port}} manually", + "diagnostic": "web-app: could not open the default browser because fixture desktop unavailable; use the dsh web URL printed at startup", "exitCode": 0, "opened": false, "opening": true, - "readyUrl": "http://127.0.0.1:{{port}}", + "readyUrl": "http://127.0.0.1:{{port}}/?token={{token}}", } `) }) @@ -183,7 +184,7 @@ describe.skipIf(!builtArtifactsExist)('dsh web browser-open assembled snapshot', "exitCode": 0, "opened": false, "opening": false, - "readyUrl": "http://127.0.0.1:{{port}}", + "readyUrl": "http://127.0.0.1:{{port}}/?token={{token}}", "stderr": "", } `) diff --git a/apps/web/package.json b/apps/web/package.json index d1f70bedfc..eeb6693e6b 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -43,6 +43,7 @@ "@types/node": "^22.0.0", "@types/react": "~18.3.1", "@types/react-dom": "~18.3.0", + "@types/ws": "8.18.1", "@vitejs/plugin-react": "^4.0.0", "http-server": "^14.1.1", "fflate": "^0.8.2", @@ -51,6 +52,7 @@ "react-dom": "^18.2.0", "typescript": "^6.0.3", "vite": "^6.0.0", - "vitest": "^4.1.8" + "vitest": "^4.1.8", + "ws": "8.21.0" } } diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index 7271449361..763e3746fd 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -26,9 +26,30 @@ import { fileURLToPath, pathToFileURL } from 'node:url' import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import WebSocket from 'ws' import { REPO_ROOT, connectFreshWorkspace, newEnglishPage, probeFreePort, requireDist, saveFailureShot } from './support.ts' const WEB_SURFACE_PROMPT = fileURLToPath(new URL('./expected/web-runtime-context/web-surface-prompt.expected.md', import.meta.url)) +const authenticatedCookies = new Map>() + +/** Exchange a printed process token once for Node-side HTTP/WebSocket probes. */ +function authenticatedWeb(launchUrl: string): Promise<{ origin: string; cookie: string }> { + const existing = authenticatedCookies.get(launchUrl) + if (existing !== undefined) return existing + const exchange = (async () => { + const response = await fetch(launchUrl, { redirect: 'manual' }) + const setCookie = response.headers.get('set-cookie') + if (response.status !== 303 || setCookie === null) { + throw new Error(`dsh web authentication returned HTTP ${String(response.status)}`) + } + return { + origin: new URL(launchUrl).origin, + cookie: setCookie.split(';', 1)[0]!, + } + })() + authenticatedCookies.set(launchUrl, exchange) + return exchange +} const comboMapUrl = (url: string): string => url.replace(/\/client\.js(?=,|&rev=)/g, '/client.js.map') @@ -54,9 +75,10 @@ function waitForReadyLine(child: ChildProcess): Promise { } async function remoteRpc(baseUrl: string, endpoint: string, args: object): Promise { - const response = await fetch(`${baseUrl}/api/${endpoint}`, { + const authenticated = await authenticatedWeb(baseUrl) + const response = await fetch(`${authenticated.origin}/api/${endpoint}`, { method: 'POST', - headers: { 'content-type': 'application/json' }, + headers: { 'content-type': 'application/json', cookie: authenticated.cookie }, body: JSON.stringify({ type: 'client-request', rpcId: `smoke-${endpoint}`, @@ -74,7 +96,10 @@ async function remoteRpc(baseUrl: string, endpoint: string, args: object): Pr /** Read the explicit page cut from a freshly opened Session follow stream. */ async function sessionCursor(baseUrl: string, sessionId: string): Promise { - const socket = new WebSocket(`${baseUrl.replace(/^http/, 'ws')}/api/remote.mux`) + const authenticated = await authenticatedWeb(baseUrl) + const socket = new WebSocket(`${authenticated.origin.replace(/^http/u, 'ws')}/api/remote.mux`, { + headers: { cookie: authenticated.cookie }, + }) const streamId = `smoke-history-${randomUUID()}` try { await new Promise((resolve, reject) => { @@ -112,10 +137,13 @@ async function sessionCursor(baseUrl: string, sessionId: string): Promise): void => { + const message = (event: WebSocket.MessageEvent): void => { try { - if (typeof event.data !== 'string') throw new Error('session/follow published a non-text frame') - const frame: unknown = JSON.parse(event.data) + const text = typeof event.data === 'string' + ? event.data + : Buffer.isBuffer(event.data) ? event.data.toString('utf8') : undefined + if (text === undefined) throw new Error('session/follow published a non-text frame') + const frame: unknown = JSON.parse(text) if (!isRecord(frame) || frame.streamId !== streamId) return if (frame.type === 'error') { finish(new Error(`session/follow failed: ${JSON.stringify(frame.error)}`)) @@ -278,8 +306,8 @@ describe('dsh web keyless CLI smoke', () => { let browser: Browser | undefined try { const readyUrl = await waitForReadyLine(child) - expect(readyUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/) - expect((await fetch(readyUrl)).status).toBe(200) + expect(readyUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/\?token=[A-Za-z0-9_-]+$/u) + expect((await fetch(readyUrl, { redirect: 'manual' })).status).toBe(303) browser = await chromium.launch({ headless: true }) const page = await newEnglishPage(browser) const pluginScripts: string[] = [] @@ -310,14 +338,15 @@ describe('dsh web keyless CLI smoke', () => { expect(batchPaths).toContainEqual(expect.stringMatching( /^\/plugins\/\?\?@deepseek-ai\/dsh-client-modules\/client\.js&rev=[a-f\d]{12}$/, )) + const readyOrigin = new URL(readyUrl).origin expect([...cacheHeaders.values()]).toEqual([ 'public, max-age=31536000, immutable', 'public, max-age=31536000, immutable', ]) for (const path of batchPaths) { const [scriptResponse, mapResponse] = await Promise.all([ - fetch(`${readyUrl}${path}`), - fetch(`${readyUrl}${comboMapUrl(path)}`), + fetch(`${readyOrigin}${path}`), + fetch(`${readyOrigin}${comboMapUrl(path)}`), ]) expect(scriptResponse.status).toBe(200) expect(mapResponse.status).toBe(200) @@ -421,7 +450,7 @@ describe('dsh web keyless CLI smoke', () => { message.role === 'user' && message.content?.includes('web-workspace-context-probe')) const systemMessage = captured.messages?.find(message => message.role === 'system') const expectedWebSection = readFileSync(WEB_SURFACE_PROMPT, 'utf8').trimEnd() - .replace('{{webUrl}}', baseUrl) + .replace('{{webUrl}}', new URL(baseUrl).origin) expect(systemMessage?.content).toContain(expectedWebSection) expect(workspaceMessage).toMatchInlineSnapshot(` { diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 14ac7c7714..15b0eabc28 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: d6145e898e07614a771f24cf7e7ed5ab31390a17 -config-catalog.zh.md: 28c36a899b452686de2bc2428e1a2246f2519b4e +config-catalog.md: a4eeb7ffbe09253d7f0f979cd8dc681b4ae038ac +config-catalog.zh.md: 8490829a7881e6503fdf7b7652c679e5d3cc0f3c diff --git a/docs/config-catalog.md b/docs/config-catalog.md index d6145e898e..a4eeb7ffbe 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -376,7 +376,7 @@ Source: [`packages/shell/bash-sandbox/src/index.ts:35`](../packages/shell/bash-s ## `@deepseek-ai/dsh-client-connection` -Requires: `webServer` +Requires: `webServer` · `credentials` ```ts config-catalog /** Plugin config: the deployment's non-loopback serving authorities. */ @@ -386,16 +386,18 @@ export interface ConnectionConfig { * port-less `host` matching any port. The /api trust fence refuses any * request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached - * by (the dsh CLI derives the machine's LAN IP literals itself). An entry - * that is not a bare, canonical authority fails the plugin load. + * by; the Web runtime derives LAN IP literals from an active all-interface + * bind. An entry that is not a bare, canonical authority fails plugin load. */ trustedHosts?: string[] + /** Absolute browser-session lifetime in days. Default: 30. */ + cookieMaxAgeDays?: number /** Maximum buffered JSON body for every `/api` request. Default: 300 MiB. */ maxRequestBodyBytes?: number } ``` -Source: [`packages/client/connection/src/index.ts:52`](../packages/client/connection/src/index.ts) +Source: [`packages/client/connection/src/index.ts:55`](../packages/client/connection/src/index.ts) @@ -814,7 +816,7 @@ Source: [`packages/host/directory-picker-browse/src/index.ts:181`](../packages/h ## `@deepseek-ai/dsh-host-frontend-static` -Requires: `webServer` +Requires: `webServer` · `connection` ```ts config-catalog /** Plugin config: the dist anchor. */ @@ -824,7 +826,7 @@ export interface Config { } ``` -Source: [`packages/host/frontend-static/src/index.ts:28`](../packages/host/frontend-static/src/index.ts) +Source: [`packages/host/frontend-static/src/index.ts:30`](../packages/host/frontend-static/src/index.ts) @@ -3141,7 +3143,7 @@ export interface Config { } ``` -Source: [`packages/bundle/web-app/src/index.ts:43`](../packages/bundle/web-app/src/index.ts) +Source: [`packages/bundle/web-app/src/index.ts:44`](../packages/bundle/web-app/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 28c36a899b..8490829a78 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -378,7 +378,7 @@ export type Config = LocalConfig ## `@deepseek-ai/dsh-client-connection` -需要:`webServer` +需要:`webServer` · `credentials` ```ts config-catalog /** Plugin config: the deployment's non-loopback serving authorities. */ @@ -388,16 +388,18 @@ export interface ConnectionConfig { * port-less `host` matching any port. The /api trust fence refuses any * request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached - * by (the dsh CLI derives the machine's LAN IP literals itself). An entry - * that is not a bare, canonical authority fails the plugin load. + * by; the Web runtime derives LAN IP literals from an active all-interface + * bind. An entry that is not a bare, canonical authority fails plugin load. */ trustedHosts?: string[] + /** Absolute browser-session lifetime in days. Default: 30. */ + cookieMaxAgeDays?: number /** Maximum buffered JSON body for every `/api` request. Default: 300 MiB. */ maxRequestBodyBytes?: number } ``` -来源:[`packages/client/connection/src/index.ts:52`](../packages/client/connection/src/index.ts) +来源:[`packages/client/connection/src/index.ts:55`](../packages/client/connection/src/index.ts) @@ -816,7 +818,7 @@ export interface Config { ## `@deepseek-ai/dsh-host-frontend-static` -需要:`webServer` +需要:`webServer` · `connection` ```ts config-catalog /** Plugin config: the dist anchor. */ @@ -826,7 +828,7 @@ export interface Config { } ``` -来源:[`packages/host/frontend-static/src/index.ts:28`](../packages/host/frontend-static/src/index.ts) +来源:[`packages/host/frontend-static/src/index.ts:30`](../packages/host/frontend-static/src/index.ts) @@ -3143,7 +3145,7 @@ export interface Config { } ``` -来源:[`packages/bundle/web-app/src/index.ts:43`](../packages/bundle/web-app/src/index.ts) +来源:[`packages/bundle/web-app/src/index.ts:44`](../packages/bundle/web-app/src/index.ts) diff --git a/docs/subsystems/web-server.i18n.yaml b/docs/subsystems/web-server.i18n.yaml index 76eb0f109e..87cca8b0b2 100644 --- a/docs/subsystems/web-server.i18n.yaml +++ b/docs/subsystems/web-server.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/web-server.md -web-server.md: 9e1e88d6c796e457fa6c185c1927b46cca9fcf52 -web-server.zh.md: 4401ccf628360a9571e77ea14ae6c29bd22af151 +web-server.md: b806f5b40a2f5ddada40752367e3da23e86ea13d +web-server.zh.md: e5f4a8794d46a2b55d4a69e2cdd13c7dc4c2a6dd diff --git a/docs/subsystems/web-server.md b/docs/subsystems/web-server.md index 9e1e88d6c7..b806f5b40a 100644 --- a/docs/subsystems/web-server.md +++ b/docs/subsystems/web-server.md @@ -24,7 +24,7 @@ interface WebRoute { } ``` -Match order is fixed: exact table first, then longest matching prefix, then the registered fallback. Registration order carries no request-facing semantics — named routes are composed to be disjoint, and the fallback seat answers anything no named route claims; one owner only, a second registration throws. The shipped Web composition claims the seat with [`dsh-host-frontend-static`](../../packages/host/frontend-static/src/index.ts), the SPA dist server with locked semantics: non-GET/HEAD is 405, traversal outside the dist root is 403, a readable index renders at the dist root and configured index path, existing files are served directly, absent or non-file targets are empty 404 responses, and unknown extensions ship as octet-stream. +Match order is fixed: exact table first, then longest matching prefix, then the registered fallback. Registration order carries no request-facing semantics — named routes are composed to be disjoint, and the fallback seat answers anything no named route claims; one owner only, a second registration throws. The shipped Web composition claims the seat with [`dsh-host-frontend-static`](../../packages/host/frontend-static/src/index.ts), the SPA dist server with locked semantics: Connection authenticates the dist root and configured index before their HTML is read; non-index assets remain public; non-GET/HEAD is 405, traversal outside the dist root is 403, existing files are served directly, absent or non-file targets are empty 404 responses, and unknown extensions ship as octet-stream. ## Config @@ -44,7 +44,7 @@ interface Config { } ``` -`host` accepts only `127.0.0.1` (default posture) and `0.0.0.0` (deliberate network exposure); there is no TLS, auth, or origin policy, so a non-loopback bind exposes the server to that network. `compression` defaults to `none`; the shipped Web bundle selects gzip level 1 with a 1024-byte threshold. The dist location is an assembly fact of the frontend plugin that claims the seat. +`host` accepts only `127.0.0.1` (default posture) and `0.0.0.0` (deliberate network exposure). The carrier itself owns no TLS, authentication, or Origin policy, so a non-loopback bind exposes the server unless the composition supplies those controls. `compression` defaults to `none`; the shipped Web bundle selects gzip level 1 with a 1024-byte threshold. The shipped `dsh web` command selects loopback and rejects `--host 0.0.0.0`; its Connection plugin supplies Host/Origin checks plus browser-session authentication for every Host API route and stream. Other compositions own their bind and route-authentication policy. The dist location is an assembly fact of the frontend plugin that claims the seat. ## The service diff --git a/docs/subsystems/web-server.zh.md b/docs/subsystems/web-server.zh.md index 4401ccf628..e5f4a8794d 100644 --- a/docs/subsystems/web-server.zh.md +++ b/docs/subsystems/web-server.zh.md @@ -24,7 +24,7 @@ interface WebRoute { } ``` -匹配顺序固定:先查 exact 表,再取最长匹配前缀,最后落到已注册的回退。注册顺序不携带任何面向请求的语义:具名路由在组合上互不相交,任何未被具名路由认领的请求都由回退席位应答;席位只有一个所有者,第二次注册会抛出异常。发布的 Web 组合用 [`dsh-host-frontend-static`](../../packages/host/frontend-static/src/index.ts) 认领席位,即遵循固定语义的 SPA dist 服务器:非 GET/HEAD 返回 405,越出 dist 根目录的遍历返回 403,可读的 index 在 dist 根目录和配置的 index 路径渲染,现有文件直接提供,缺失或不是文件的目标返回空的 404,未知扩展名按 octet-stream 发送。 +匹配顺序固定:先查 exact 表,再取最长匹配前缀,最后落到已注册的回退。注册顺序不携带任何面向请求的语义:具名路由在组合上互不相交,任何未被具名路由认领的请求都由回退席位应答;席位只有一个所有者,第二次注册会抛出异常。发布的 Web 组合用 [`dsh-host-frontend-static`](../../packages/host/frontend-static/src/index.ts) 认领席位,即遵循固定语义的 SPA dist 服务器:Connection 在读取 dist 根目录和配置 index 的 HTML 前完成认证;非 index 资产保持公开;非 GET/HEAD 返回 405,越出 dist 根目录的遍历返回 403,现有文件直接提供,缺失或不是文件的目标返回空的 404,未知扩展名按 octet-stream 发送。 ## 配置 @@ -44,7 +44,7 @@ interface Config { } ``` -`host` 只接受 `127.0.0.1`(默认姿态)和 `0.0.0.0`(刻意的网络暴露);没有 TLS、认证或 origin 策略,因此绑定到非回环地址会把服务器暴露给该网络。`compression` 默认为 `none`;随附的 Web 组合选择 gzip level 1 和 1024 字节阈值。dist 位置是认领席位的前端插件的组装事实。 +`host` 只接受 `127.0.0.1`(默认姿态)和 `0.0.0.0`(刻意的网络暴露)。载体本身不拥有 TLS、认证或 Origin 策略,因此绑定到非回环地址会暴露服务器,除非组合层提供这些控制。`compression` 默认为 `none`;随附的 Web 组合选择 gzip level 1 和 1024 字节阈值。随附的 `dsh web` 命令选择 loopback 并拒绝 `--host 0.0.0.0`;其 Connection 插件为每个 Host API route 与 stream 提供 Host/Origin 校验和浏览器会话认证。其他组合自行拥有绑定与路由认证策略。dist 位置是认领席位的前端插件的组装事实。 ## 服务 diff --git a/packages/api/gateway/src/index.ts b/packages/api/gateway/src/index.ts index 208090851e..edc3f8697e 100644 --- a/packages/api/gateway/src/index.ts +++ b/packages/api/gateway/src/index.ts @@ -182,7 +182,6 @@ export class TypertGatewayService extends Service implements TypertGateway { '/api', endpoint => this.claimsEndpoint(endpoint), (endpoint, payload, signal) => this.dispatchRpc(endpoint, payload, signal), - { authority: 'trusted-host' }, ) }) ctx.inject(['connection', 'webServer'], (webCtx) => { @@ -193,9 +192,10 @@ export class TypertGatewayService extends Service implements TypertGateway { webCtx.effect(() => { const route: WebUpgradeRoute = { path: REMOTE_STREAM_MUX_PATH, - handler: (req, socket, head) => { - if (!webCtx.connection.isTrustedRequest(req, 'trusted-host')) { - rejectRemoteStreamUpgrade(socket) + handler: async (req, socket, head) => { + const rejection = await webCtx.connection.requestRejection(req) + if (rejection !== undefined) { + rejectRemoteStreamUpgrade(socket, rejection) return } mux.handleUpgrade(req, socket, head) diff --git a/packages/api/gateway/src/stream-server.ts b/packages/api/gateway/src/stream-server.ts index bf7711b81b..04b0df0427 100644 --- a/packages/api/gateway/src/stream-server.ts +++ b/packages/api/gateway/src/stream-server.ts @@ -175,14 +175,17 @@ function rawText(data: RawData): string { /** * Reject an upgrade without transferring socket ownership to ws. * @param socket - carrier socket that receives the HTTP rejection. + * @param status - authentication or browser-trust rejection status. */ -export function rejectRemoteStreamUpgrade(socket: Duplex): void { +export function rejectRemoteStreamUpgrade(socket: Duplex, status: 401 | 403): void { + const reason = status === 401 ? 'Unauthorized' : 'Forbidden' + const body = reason.toLowerCase() socket.end([ - 'HTTP/1.1 403 Forbidden', + `HTTP/1.1 ${String(status)} ${reason}`, 'Connection: close', 'Content-Type: text/plain; charset=utf-8', - 'Content-Length: 9', + `Content-Length: ${String(Buffer.byteLength(body))}`, '', - 'forbidden', + body, ].join('\r\n')) } diff --git a/packages/api/gateway/tests/gateway-stream.host.spec.ts b/packages/api/gateway/tests/gateway-stream.host.spec.ts index cf95c84f27..273d5f9b99 100644 --- a/packages/api/gateway/tests/gateway-stream.host.spec.ts +++ b/packages/api/gateway/tests/gateway-stream.host.spec.ts @@ -14,6 +14,7 @@ import { TypertRemoteFailure, } from '@deepseek-ai/dsh-typert-protocol' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts' import TypertGatewayService, { TypertGatewayError, type TypertRemoteEventDispatch, @@ -32,9 +33,33 @@ vi.mock('node:crypto', async (importOriginal) => { }) const randomUuid = vi.mocked(randomUUID) +const browserCookies = new WeakMap>() type AgentWireId = TypertContextWire const agentId = (value: string): AgentWireId => value as AgentWireId +/** Exchange this test Host's process token for its WebSocket/HTTP Cookie header. */ +function browserCookie(ctx: Context): Promise { + const existing = browserCookies.get(ctx) + if (existing !== undefined) return existing + const exchange = (async () => { + const origin = `http://127.0.0.1:${String(ctx.webServer.port)}` + const target = new URL(ctx.connection.authenticatedUrl(origin)) + let setCookie: string | undefined + await ctx.connection.authorizeIndex({ + method: 'GET', + url: `${target.pathname}${target.search}`, + headers: { host: target.host }, + }, { + writeHead(_status, headers) { setCookie = headers?.['set-cookie'] }, + end() {}, + }) + if (setCookie === undefined) throw new Error('gateway stream fixture did not receive a browser cookie') + return setCookie.split(';', 1)[0]! + })() + browserCookies.set(ctx, exchange) + return exchange +} + class FeedService extends Service { readonly typertRemote = bindTypertRemote(this, 'feed') readonly signals: AbortSignal[] = [] @@ -259,7 +284,9 @@ describe('Typert Remote streams', () => { it('multiplexes independent streams over one WebSocket and propagates cancellation', async () => { const { ctx, service } = await setup(true) - const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`) + const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { + headers: { cookie: await browserCookie(ctx) }, + }) await once(socket, 'open') const frames: Record[] = [] socket.on('message', (data) => { frames.push(JSON.parse(rawText(data)) as Record) }) @@ -341,7 +368,9 @@ describe('Typert Remote streams', () => { expect(() => { ctx.typertGateway.registerRemoteEvents(source) }) .toThrow('forwarded Remote event source is already registered') - const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`) + const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { + headers: { cookie: await browserCookie(ctx) }, + }) await once(socket, 'open') const frames: Record[] = [] socket.on('message', (data) => { frames.push(JSON.parse(rawText(data)) as Record) }) @@ -861,7 +890,9 @@ describe('Typert Remote streams', () => { it('validates the internal Remote event request and reports an absent source', async () => { const { ctx } = await setup(true) - const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`) + const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { + headers: { cookie: await browserCookie(ctx) }, + }) await once(socket, 'open') const frames: Record[] = [] socket.on('message', (data) => { frames.push(JSON.parse(rawText(data)) as Record) }) @@ -920,6 +951,19 @@ describe('Typert Remote streams', () => { rejected.resume() ;(request as { abort(): void }).abort() }) + + it('answers an unauthenticated trusted Host with 401 before opening a stream', async () => { + const { ctx } = await setup(true) + const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`) + socket.on('error', () => {}) + const responseEvent: unknown[] = await once(socket, 'unexpected-response') + const request = responseEvent[0] + const response = responseEvent[1] + const rejected = response as { statusCode?: number; resume(): void } + expect(rejected.statusCode).toBe(401) + rejected.resume() + ;(request as { abort(): void }).abort() + }) }) async function setup(transport: boolean): Promise<{ readonly ctx: Context; readonly service: FeedService }> { @@ -927,6 +971,7 @@ async function setup(transport: boolean): Promise<{ readonly ctx: Context; reado roots.push(ctx) if (transport) { await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }) + await ctx.plugin(MemoryCredentials) } await ctx.plugin(TypertRegistry) await ctx.plugin(TypertGatewayService) @@ -989,11 +1034,15 @@ interface RemoteEventTestClient { readonly streamId: string readonly clientId: RemoteEventClientId readonly origin: string + readonly cookie: string } async function openEventClient(ctx: Context, streamId: string): Promise { const origin = `http://127.0.0.1:${String(ctx.webServer.port)}` - const socket = new WebSocket(`${origin.replace('http:', 'ws:')}/api/remote.mux`) + const cookie = await browserCookie(ctx) + const socket = new WebSocket(`${origin.replace('http:', 'ws:')}/api/remote.mux`, { + headers: { cookie }, + }) await once(socket, 'open') const frames: Record[] = [] socket.on('message', (data) => { frames.push(JSON.parse(rawText(data)) as Record) }) @@ -1010,7 +1059,7 @@ async function openEventClient(ctx: Context, streamId: string): Promise boolean) | undefined handler: FakeRpcHandler | undefined @@ -119,22 +120,23 @@ class FakeConnectionService extends Service { channel: string, matches: (endpoint: string) => boolean, handler: FakeRpcHandler, - options: { readonly authority: string }, ) => owner.effect(() => { this.channel = channel - this.authority = options.authority this.matches = matches this.handler = handler return () => { this.channel = undefined - this.authority = undefined this.matches = undefined this.handler = undefined } }), } } + + requestRejection(): Promise { + return Promise.resolve(undefined) + } } function fakeHttpServer(routes: WebRoute[]): Pick { @@ -168,6 +170,22 @@ async function serveRoute(route: WebRoute): Promise<{ readonly origin: string; c } } +/** Exchange a Connection launch token without mounting the frontend fallback. */ +async function browserCookie(connection: HostConnectionHandle, origin: string): Promise { + const target = new URL(connection.authenticatedUrl(origin)) + let setCookie: string | undefined + await connection.authorizeIndex({ + method: 'GET', + url: `${target.pathname}${target.search}`, + headers: { host: target.host }, + }, { + writeHead(_status, headers) { setCookie = headers?.['set-cookie'] }, + end() {}, + }) + if (setCookie === undefined) throw new Error('gateway fixture did not receive an authentication cookie') + return setCookie.split(';', 1)[0]! +} + class FirstSharedService extends Service { readonly typertRemote = bindTypertRemote(this, 'firstShared', { namespace: 'shared' }) @@ -958,7 +976,7 @@ describe('TypertGatewayService', () => { await gatewayFiber await ctx.plugin(GoalService) const connection = rawConnection(ctx) - expect(connection).toMatchObject({ channel: '/api', authority: 'trusted-host' }) + expect(connection).toMatchObject({ channel: '/api' }) registerAgentLookup(ctx, { id: 'agent-1' }) registerStrict(ctx, [createDescriptor(), maybeDescriptor()]) @@ -1150,6 +1168,7 @@ describe('TypertGatewayService', () => { it('dispatches claimed invocations through /api and leaves unclaimed endpoints to its fallback', async () => { const ctx = new Context().extend({ fixtureScope: 'http-caller' }) const routes: WebRoute[] = [] + await ctx.plugin(MemoryCredentials) ctx.provide('webServer', fakeHttpServer(routes) as WebServer) const connectionFiber = ctx.plugin({ inject: [...connectionInject], apply: applyConnection }) await connectionFiber @@ -1163,11 +1182,12 @@ describe('TypertGatewayService', () => { let strictActive = true expect(routes).toHaveLength(1) const server = await serveRoute(routes[0]!) + const cookie = await browserCookie(ctx.connection, server.origin) try { const response = await fetch(`${server.origin}/api/goals/create`, { method: 'POST', - headers: { 'content-type': 'application/json' }, + headers: { 'content-type': 'application/json', cookie }, body: JSON.stringify({ type: 'client-request', rpcId: 'rpc-http', @@ -1187,7 +1207,7 @@ describe('TypertGatewayService', () => { const invalid = await fetch(`${server.origin}/api/goals/create`, { method: 'POST', - headers: { 'content-type': 'application/json' }, + headers: { 'content-type': 'application/json', cookie }, body: JSON.stringify({ type: 'client-request', rpcId: 'rpc-invalid', @@ -1211,7 +1231,7 @@ describe('TypertGatewayService', () => { strictActive = false const withdrawn = await fetch(`${server.origin}/api/goals/create`, { method: 'POST', - headers: { 'content-type': 'application/json' }, + headers: { 'content-type': 'application/json', cookie }, body: JSON.stringify({ type: 'client-request', rpcId: 'rpc-withdrawn', @@ -1231,7 +1251,10 @@ describe('TypertGatewayService', () => { }) expect(JSON.stringify(withdrawnBody)).toContain('strict definition was withdrawn') - const unclaimed = await fetch(`${server.origin}/api/legacy/list`, { method: 'POST' }) + const unclaimed = await fetch(`${server.origin}/api/legacy/list`, { + method: 'POST', + headers: { cookie }, + }) expect(unclaimed.status).toBe(404) } finally { await server.close() diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index d22a500223..bc9ac5d953 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/bundle/web-app/README.md -README.md: c428bbd352f7f58fe4b76cd078e2c1a1993b422a -README.zh.md: 0d5a33fe356d749fa619ad980ab9ee13ed9ba3fc +README.md: c330e5557c2fa70f60ededcd368ec713db11269e +README.zh.md: b2170c762a2e9425417df09e7ba6e7c16f612e96 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index c428bbd352..c330e5557c 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The dsh browser-surface bundle. [`cordis.patch.yml`](cordis.patch.yml) rides over [`dsh-base`](../base/README.md): it sets the coding persona, inserts the Web host rows (webserver, API gateway, workspace, projection cache, storage) and the browser plugin roster, the always-on client-plugin reload chain ([`dsh-client-hmr`](../../client/hmr/README.md), idle until a rebuild watcher rewrites client bundles), and mounts this package's `web-runtime` glue plugin (config `{openBrowser, printUrl, surfaceContext, trustedHosts}`). That plugin resolves the built frontend dist through `@deepseek-ai/dsh-web-frontend`'s exports, samples bind-dependent LAN trust once, provides it as `webRuntime` to the browser-trust fence and client roster, mounts the [`frontend-static`](../../host/frontend-static/README.md) fallback owner, and registers the harness-source and web-surface prompt sections plus the bash-visible `DSH_WEB_URL` runtime variable when `surfaceContext` is true. After its Loader tree settles, it prints the `dsh web:` URL line when `printUrl` is true and opens the canonical host URL in the default browser when `openBrowser` is true and the inherited `SSH_CONNECTION` and `SSH_TTY` are blank or absent. An SSH launch keeps the URL line but suppresses browser handoff because the SSH client or editor owns the local forwarded address. Immediately before a handoff, the runtime prints `dsh web: opening the default browser; pass --no-open to disable`. A short-lived Node helper runs the maintained platform opener with the canonical scrubbed child environment. On Windows it stays alive until the short-lived PowerShell launcher exits, because `open` reports spawn before that launcher has handed the URL to the shell; elsewhere the helper stops after the opener accepts spawn. A helper failure writes a diagnostic with its reason and the manual URL to stderr without stopping the server, and no path waits for the browser to exit. This bundle also owns the app command line: the ordinary `web-startup` provider ([`src/startup.ts`](src/startup.ts)) injects `ctx.cmdlineArgs` ([`dsh-cmdline`](../../boot/cmdline/README.md)), parses `--host`, `--port`, repeatable `--trusted-host`, `--no-open`, and the app's `--help`, then provides `webStartup`; browser opening defaults on for local launches, and `--no-open` turns it off for this invocation. It rejects `--host 0.0.0.0` before publishing that service because the CLI intentionally does not support all-interfaces binding yet. Flag-configured rows inject the service and read it directly from lazy config, so nothing binds a port before argument resolution and `dsh --profile web --help` starts no server. [`dsh-headless`](../headless/README.md) is a sibling surface over the same base and does not mount this bundle. +The dsh browser-surface bundle. [`cordis.patch.yml`](cordis.patch.yml) rides over [`dsh-base`](../base/README.md): it sets the coding persona, inserts the Web host rows (webserver, API gateway, workspace, projection cache, storage) and the browser plugin roster, the always-on client-plugin reload chain ([`dsh-client-hmr`](../../client/hmr/README.md), idle until a rebuild watcher rewrites client bundles), and mounts this package's `web-runtime` glue plugin (config `{openBrowser, printUrl, surfaceContext, trustedHosts}`). That plugin resolves the built frontend dist through `@deepseek-ai/dsh-web-frontend`'s exports, samples bind-dependent LAN trust once, provides it as `webRuntime` to the browser-trust fence and client roster, mounts the [`frontend-static`](../../host/frontend-static/README.md) fallback owner, and registers the harness-source and web-surface prompt sections plus the bash-visible `DSH_WEB_URL` runtime variable when `surfaceContext` is true. After its Loader tree settles and Connection authentication is available, it prints the `dsh web:` root URL with the fresh process token when `printUrl` is true and opens that authenticated URL in the default browser when `openBrowser` is true and the inherited `SSH_CONNECTION` and `SSH_TTY` are blank or absent. The model prompt and `DSH_WEB_URL` retain the clean canonical URL without credentials. An SSH launch keeps the tokenized URL line but suppresses browser handoff because the SSH client or editor owns the local forwarded address. Immediately before a handoff, the runtime prints `dsh web: opening the default browser; pass --no-open to disable`. A short-lived Node helper runs the maintained platform opener with the canonical scrubbed child environment. On Windows it stays alive until the short-lived PowerShell launcher exits, because `open` reports spawn before that launcher has handed the URL to the shell; elsewhere the helper stops after the opener accepts spawn. A helper failure writes a credential-free diagnostic with its reason and points to the startup URL without stopping the server, and no path waits for the browser to exit. This bundle also owns the app command line: the ordinary `web-startup` provider ([`src/startup.ts`](src/startup.ts)) injects `ctx.cmdlineArgs` ([`dsh-cmdline`](../../boot/cmdline/README.md)), parses `--host`, `--port`, repeatable `--trusted-host`, `--no-open`, and the app's `--help`, then provides `webStartup`; browser opening defaults on for local launches, and `--no-open` turns it off for this invocation. It rejects `--host 0.0.0.0` before publishing that service because the CLI intentionally does not support all-interfaces binding. Flag-configured rows inject the service and read it directly from lazy config, so nothing binds a port before argument resolution and `dsh --profile web --help` starts no server. [`dsh-headless`](../headless/README.md) is a sibling surface over the same base and does not mount this bundle. The base module-HMR row remains disabled. The Web profile's `patchReload: live` lifecycle uses the launcher's config-only watcher; the browser-facing `dsh-client-hmr` reload chain is separate from server module HMR. diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index 0d5a33fe35..b2170c762a 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -dsh 浏览器表层组合包。[`cordis.patch.yml`](cordis.patch.yml) 叠加在 [`dsh-base`](../base/README.zh.md) 之上:设置 coding persona,插入 Web 宿主行(webserver、API 网关、workspace、投影缓存、存储)、浏览器插件名录与始终挂载的客户端插件重载链([`dsh-client-hmr`](../../client/hmr/README.zh.md),在重建 watcher 改写客户端 bundle 之前保持空闲),并挂载本包的 `web-runtime` 粘合插件(配置为 `{openBrowser, printUrl, surfaceContext, trustedHosts}`)。该插件通过 `@deepseek-ai/dsh-web-frontend` 的 exports 解析已构建的前端 dist,只采样一次依赖 bind 的 LAN 信任信息并将其作为 `webRuntime` 提供给浏览器信任栅栏和客户端名录,挂载 [`frontend-static`](../../host/frontend-static/README.zh.md) 回退席位所有者,并在 `surfaceContext` 为 true 时注册 Harness 源码与 Web 表层提示词段落,以及 bash 可见的 `DSH_WEB_URL` 运行时变量。自身 Loader 配置树结算后,它在 `printUrl` 为 true 时打印 `dsh web:` URL 行;`openBrowser` 为 true 且继承的 `SSH_CONNECTION` 与 `SSH_TTY` 均为空或不存在时,才会用默认浏览器打开规范宿主机 URL。SSH 启动仍保留 URL 行,但会跳过浏览器交接,因为本地转发地址由 SSH 客户端或编辑器持有。交接前,运行时会打印英文提示 `dsh web: opening the default browser; pass --no-open to disable`。短生命周期 Node helper 使用规范的脱敏子进程环境运行受维护的平台 opener。在 Windows 上,helper 会保持存活,直至短生命周期的 PowerShell launcher 退出,因为 `open` 会在 launcher 把 URL 交给 shell 之前、仅在 spawn 时返回;其他平台则在 opener 接受 spawn 后结束。helper 失败时会向 stderr 写入包含原因和手动访问 URL 的诊断,不会停止服务器,且任何路径都不会等待浏览器退出。本组合包还持有应用命令行:普通 `web-startup` 提供方([`src/startup.ts`](src/startup.ts))注入 `ctx.cmdlineArgs`([`dsh-cmdline`](../../boot/cmdline/README.zh.md)),解析 `--host`、`--port`、可重复的 `--trusted-host`、`--no-open` 以及应用自己的 `--help`,再提供 `webStartup`;本机启动默认会打开浏览器,`--no-open` 则只对本次调用关闭该行为。它会在发布该服务前拒绝 `--host 0.0.0.0`,因为 CLI 目前有意不支持绑定所有网络接口。由 flag 配置的行会注入该服务,并在惰性配置中直接读取它,因此参数解析完成前不会有任何东西绑定端口,`dsh --profile web --help` 也不会启动服务器。[`dsh-headless`](../headless/README.zh.md) 是同一 base 之上的同级表层,不挂载本组合包。 +dsh 浏览器表层组合包。[`cordis.patch.yml`](cordis.patch.yml) 叠加在 [`dsh-base`](../base/README.zh.md) 之上:设置 coding persona,插入 Web 宿主行(webserver、API 网关、workspace、投影缓存、存储)、浏览器插件名录与始终挂载的客户端插件重载链([`dsh-client-hmr`](../../client/hmr/README.zh.md),在重建 watcher 改写客户端 bundle 之前保持空闲),并挂载本包的 `web-runtime` 粘合插件(配置为 `{openBrowser, printUrl, surfaceContext, trustedHosts}`)。该插件通过 `@deepseek-ai/dsh-web-frontend` 的 exports 解析已构建的前端 dist,只采样一次依赖 bind 的 LAN 信任信息并将其作为 `webRuntime` 提供给浏览器信任栅栏和客户端名录,挂载 [`frontend-static`](../../host/frontend-static/README.zh.md) 回退席位所有者,并在 `surfaceContext` 为 true 时注册 Harness 源码与 Web 表层提示词段落,以及 bash 可见的 `DSH_WEB_URL` 运行时变量。Loader 配置树结算且 Connection 认证可用后,它在 `printUrl` 为 true 时打印带新进程令牌的 `dsh web:` 根 URL;`openBrowser` 为 true 且继承的 `SSH_CONNECTION` 与 `SSH_TTY` 均为空或不存在时,才会用默认浏览器打开该认证 URL。模型提示词与 `DSH_WEB_URL` 仍携带不含凭据的干净规范 URL。SSH 启动仍保留带令牌的 URL 行,但会跳过浏览器交接,因为本地转发地址由 SSH 客户端或编辑器持有。交接前,运行时会打印英文提示 `dsh web: opening the default browser; pass --no-open to disable`。短生命周期 Node helper 使用规范的脱敏子进程环境运行受维护的平台 opener。在 Windows 上,helper 会保持存活,直至短生命周期的 PowerShell launcher 退出,因为 `open` 会在 launcher 把 URL 交给 shell 之前、仅在 spawn 时返回;其他平台则在 opener 接受 spawn 后结束。helper 失败时会向 stderr 写入不含凭据的原因并指向启动 URL,不会停止服务器,且任何路径都不会等待浏览器退出。本组合包还持有应用命令行:普通 `web-startup` 提供方([`src/startup.ts`](src/startup.ts))注入 `ctx.cmdlineArgs`([`dsh-cmdline`](../../boot/cmdline/README.zh.md)),解析 `--host`、`--port`、可重复的 `--trusted-host`、`--no-open` 以及应用自己的 `--help`,再提供 `webStartup`;本机启动默认会打开浏览器,`--no-open` 则只对本次调用关闭该行为。它会在发布该服务前拒绝 `--host 0.0.0.0`,因为 CLI 不支持绑定所有网络接口。由 flag 配置的行会注入该服务,并在惰性配置中直接读取它,因此参数解析完成前不会有任何东西绑定端口,`dsh --profile web --help` 也不会启动服务器。[`dsh-headless`](../headless/README.zh.md) 是同一 base 之上的同级表层,不挂载本组合包。 base 的模块 HMR 配置项保持禁用。Web profile 的 `patchReload: live` 生命周期使用启动器的仅配置 watcher;面向浏览器的 `dsh-client-hmr` 重载链与服务器模块 HMR 相互独立。 diff --git a/packages/bundle/web-app/src/index.ts b/packages/bundle/web-app/src/index.ts index 713f6d10a4..5ec4ae7072 100644 --- a/packages/bundle/web-app/src/index.ts +++ b/packages/bundle/web-app/src/index.ts @@ -5,9 +5,9 @@ * the built frontend dist (workspace knowledge of this bundle, never user * config), mounts the `frontend-static` fallback owner over it, registers the * harness-source and web-surface prompt sections, the bash-visible web runtime - * variable, the URL line, and the default-browser handoff. App command-line - * values arrive through the `webStartup` service expressions in the bundle - * patch. + * variable, the process-token URL line, and the default-browser handoff. The + * model and shell retain the clean URL. App command-line values arrive through + * the `webStartup` service expressions in the bundle patch. * @module @deepseek-ai/dsh-web-app */ @@ -19,6 +19,7 @@ import { fileURLToPath } from 'node:url' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { addHarnessSourceSection } from '@deepseek-ai/dsh-app-boot' +import type {} from '@deepseek-ai/dsh-client-connection' import * as FrontendStatic from '@deepseek-ai/dsh-host-frontend-static' import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' @@ -258,41 +259,48 @@ export function apply(ctx: Context, config: Config): void { }) } if (config.printUrl || handoffBrowser) { - // The URL line and browser handoff are readiness signals: supervisors RPC - // as soon as they observe the line, while a browser requests the page as - // soon as it opens. Neither may run while sibling rows such as the /api - // route owner are still mounting. Await Loader settlement first; a - // hand-built tree without a Loader is already the complete tree. - const announceReady = (): void => { - const webUrl = localWebUrl(ctx) - // Reuse the exact LAN snapshot provided to the /api trust fence. - const lanCandidate = runtime.lanAddresses[0] - const port = ctx.webServer.port - if (config.printUrl) { - console.log(`dsh web: ${webUrl}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${String(port)})`}`) + ctx.inject(['connection'], (connectionCtx) => { + // The URL line and browser handoff are readiness signals: supervisors RPC + // as soon as they observe the line, while a browser requests the page as + // soon as it opens. Neither may run while sibling rows such as the /api + // route owner are still mounting. Await Loader settlement first; a + // hand-built tree without a Loader is already the complete tree. + const announceReady = (): void => { + const webUrl = localWebUrl(connectionCtx) + const authenticatedUrl = connectionCtx.connection.authenticatedUrl(webUrl) + // Reuse the exact LAN snapshot provided to the /api trust fence. + const lanCandidate = runtime.lanAddresses[0] + const port = connectionCtx.webServer.port + const lanUrl = lanCandidate === undefined + ? undefined + : connectionCtx.connection.authenticatedUrl(`http://${lanCandidate}:${String(port)}`) + if (config.printUrl) { + console.log(`dsh web: ${authenticatedUrl}${lanUrl === undefined ? '' : ` (LAN: ${lanUrl})`}`) + } + if (handoffBrowser) { + console.log('dsh web: opening the default browser; pass --no-open to disable') + void internals.openBrowser(authenticatedUrl).catch((error: unknown) => { + const reason = error instanceof Error ? error.message : String(error) + console.error(`web-app: could not open the default browser because ${reason}; use the dsh web URL printed at startup`) + }) + } } - if (handoffBrowser) { - console.log('dsh web: opening the default browser; pass --no-open to disable') - void internals.openBrowser(webUrl).catch((error: unknown) => { - const reason = error instanceof Error ? error.message : String(error) - console.error(`web-app: could not open the default browser because ${reason}; visit ${webUrl} manually`) - }) + // This row's own activation can precede a sibling failure. The app owns + // readiness by waiting for its Loader tree, or announces at once in a + // hand-built tree without Loader. + const settled = connectionCtx.get('loader')?.await() + if (settled === undefined) announceReady() + else { + void settled.then(() => { + // The tree can be disposed while the boot was in flight (early + // SIGTERM); a URL line or browser tab for a dead server would only + // mislead, and reading torn-down services would turn a clean shutdown + // into a crash. + if (connectionCtx.get('webServer') !== undefined + && connectionCtx.get('connection') !== undefined) announceReady() + // Loader reports a failed boot; this row only stays quiet. + }, () => {}) } - } - // This row's own activation can precede a sibling failure. The app owns - // readiness by waiting for its Loader tree, or announces at once in a - // hand-built context without Loader. - const settled = ctx.get('loader')?.await() - if (settled === undefined) announceReady() - else { - void settled.then(() => { - // The tree can be disposed while the boot was in flight (early - // SIGTERM); a URL line or browser tab for a dead server would only - // mislead, and reading the torn-down port would turn a clean shutdown - // into a crash. - if (ctx.get('webServer') !== undefined) announceReady() - // Loader reports a failed boot; this row only stays quiet. - }, () => {}) - } + }) } } diff --git a/packages/bundle/web-app/tests/web-app.spec.ts b/packages/bundle/web-app/tests/web-app.spec.ts index 5639129362..90f7063bf7 100644 --- a/packages/bundle/web-app/tests/web-app.spec.ts +++ b/packages/bundle/web-app/tests/web-app.spec.ts @@ -83,6 +83,21 @@ function fakeHttpServer(host: '127.0.0.1' | '0.0.0.0' = '127.0.0.1'): { server: return { server, seat: () => fallback } } +/** Deterministic Host Connection face for URL publication and frontend injection. */ +function provideConnection(ctx: Context): void { + ctx.provide('connection', { + authenticatedUrl(baseUrl: string) { + const url = new URL(baseUrl) + url.pathname = '/' + url.searchParams.set('token', 'test-token') + return url.href + }, + authorizeIndex: () => Promise.resolve(true), + requestRejection: () => Promise.resolve(undefined), + rpc: {}, + } as never) +} + /** A fake Loader whose settlement the test controls (the URL line waits on it). */ function provideLoader(ctx: Context, settle: () => Promise = async () => {}): void { ctx.provide('loader', { await: settle } as never) @@ -105,6 +120,7 @@ describe('web-app runtime glue', () => { ])) const { server, seat } = fakeHttpServer('0.0.0.0') ctx.provide('webServer', server) + provideConnection(ctx) const contributions: BashContribution[] = [] ctx.provide('shellEnv', { register: (contribution: BashContribution) => { @@ -127,13 +143,13 @@ describe('web-app runtime glue', () => { lanAddresses: ['192.168.1.5'], trustedHosts: ['192.168.1.5', 'lab.internal'], }) - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567 (LAN: http://192.168.1.5:4567)') + expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token (LAN: http://192.168.1.5:4567/?token=test-token)') expect(log).toHaveBeenCalledWith('dsh web: opening the default browser; pass --no-open to disable') - expect(openBrowser).toHaveBeenCalledWith('http://127.0.0.1:4567') + expect(openBrowser).toHaveBeenCalledWith('http://127.0.0.1:4567/?token=test-token') expect(lifecycle).toEqual([ - 'dsh web: http://127.0.0.1:4567 (LAN: http://192.168.1.5:4567)', + 'dsh web: http://127.0.0.1:4567/?token=test-token (LAN: http://192.168.1.5:4567/?token=test-token)', 'dsh web: opening the default browser; pass --no-open to disable', - 'open:http://127.0.0.1:4567', + 'open:http://127.0.0.1:4567/?token=test-token', ]) const assembly = await ctx.systemPrompt.assemble() expect(assembly.sections.find(entry => entry.name === 'harness:source')?.text).toContain('DeepSeek Harness implementation checkout') @@ -151,6 +167,7 @@ describe('web-app runtime glue', () => { stageDist() const ctx = new Context() ctx.provide('webServer', fakeHttpServer().server) + provideConnection(ctx) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) const openBrowser = vi.fn(async () => {}) internals.openBrowser = openBrowser @@ -169,6 +186,7 @@ describe('web-app runtime glue', () => { stageDist() const ctx = new Context() ctx.provide('webServer', fakeHttpServer().server) + provideConnection(ctx) const contributions: BashContribution[] = [] ctx.provide('shellEnv', { register: (contribution: BashContribution) => { @@ -190,10 +208,11 @@ describe('web-app runtime glue', () => { stageDist() const ctx = new Context() ctx.provide('webServer', fakeHttpServer().server) + provideConnection(ctx) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: true, trustedHosts: [] })) await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567') + expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') await ctx.fiber.dispose() }) @@ -205,12 +224,13 @@ describe('web-app runtime glue', () => { stageDist() const ctx = new Context() ctx.provide('webServer', fakeHttpServer().server) + provideConnection(ctx) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) const openBrowser = vi.fn(async () => {}) internals.openBrowser = openBrowser apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: false, trustedHosts: [] })) await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567') + expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') expect(openBrowser).not.toHaveBeenCalled() await ctx.fiber.dispose() }) @@ -223,6 +243,7 @@ describe('web-app runtime glue', () => { // can request the complete app immediately. const settled = new Context() settled.provide('webServer', fakeHttpServer().server) + provideConnection(settled) let release: () => void const settlement = new Promise((resolve) => { release = resolve }) provideLoader(settled, () => settlement) @@ -233,8 +254,8 @@ describe('web-app runtime glue', () => { expect(openBrowser).not.toHaveBeenCalled() release!() await new Promise(resolve => setTimeout(resolve, 0)) - expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567') - expect(openBrowser).toHaveBeenCalledWith('http://127.0.0.1:4567') + expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') + expect(openBrowser).toHaveBeenCalledWith('http://127.0.0.1:4567/?token=test-token') await settled.fiber.dispose() // Failed path: Loader reports the sibling failure; the app prints no URL @@ -243,6 +264,7 @@ describe('web-app runtime glue', () => { openBrowser.mockClear() const failed = new Context() failed.provide('webServer', fakeHttpServer().server) + provideConnection(failed) provideLoader(failed, async () => { throw new Error('boot failed') }) apply(failed, new Config({ openBrowser: true, printUrl: true, surfaceContext: true, trustedHosts: [] })) await new Promise(resolve => setTimeout(resolve, 0)) @@ -257,6 +279,7 @@ describe('web-app runtime glue', () => { const torn = new Context() const child = torn.plugin((childCtx: Context) => { childCtx.provide('webServer', fakeHttpServer().server) + provideConnection(childCtx) }) await child let releaseTorn: () => void @@ -279,6 +302,7 @@ describe('web-app runtime glue', () => { const { server } = fakeHttpServer() Object.defineProperty(server, 'port', { get: () => undefined }) ctx.provide('webServer', server) + provideConnection(ctx) apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: true, trustedHosts: [] })) await ctx.plugin(SystemPrompt, { persona: '' }) await new Promise(resolve => setTimeout(resolve, 0)) @@ -301,6 +325,7 @@ describe('web-app runtime glue', () => { stageDist() const ctx = new Context() ctx.provide('webServer', fakeHttpServer().server) + provideConnection(ctx) internals.openBrowser = vi.fn(async () => { throw failure }) const log = vi.spyOn(console, 'log').mockImplementation(() => {}) const diagnostic = vi.spyOn(console, 'error').mockImplementation(() => {}) @@ -308,7 +333,7 @@ describe('web-app runtime glue', () => { await new Promise(resolve => setTimeout(resolve, 0)) expect(log).toHaveBeenCalledWith('dsh web: opening the default browser; pass --no-open to disable') expect(diagnostic).toHaveBeenCalledWith( - `web-app: could not open the default browser because ${reason}; visit http://127.0.0.1:4567 manually`, + `web-app: could not open the default browser because ${reason}; use the dsh web URL printed at startup`, ) expect(ctx.get('webServer')).toBeDefined() await ctx.fiber.dispose() diff --git a/packages/bundle/web-app/tsconfig.json b/packages/bundle/web-app/tsconfig.json index c00b64f5a9..2f8cc6c3b2 100644 --- a/packages/bundle/web-app/tsconfig.json +++ b/packages/bundle/web-app/tsconfig.json @@ -23,6 +23,9 @@ { "path": "../../boot/cmdline" }, + { + "path": "../../client/connection/tsconfig.host.json" + }, { "path": "../../host/frontend-static" }, diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index 8f1d179212..83d376368b 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/connection/README.md -README.md: d2614515744ee69ca11443a7bc440a589d3f26b3 -README.zh.md: 13df74ddf7bb21455bb5528119bd7c3d5d149b87 +README.md: 293e9f9d6b158e325325f4f741a244031b1d2e02 +README.zh.md: e3cea191ab1c9745a1920b5cfd13fcd8d8b77692 diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index d261451574..293e9f9d6b 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -4,13 +4,15 @@ English | [中文](README.zh.md) Protocol and connection-generation layer. The Client plugin mounts `ctx.connection`, containing the shared API client, current-page loopback state, generation-scoped observable `hostDescription`, a generic RPC carrier, and the registration point for one generation source and the connection loop. A generation publishes `hostDescription` and calls `onConnected` only after its source is ready and `host.describe` succeeds; source completion, failure, withdrawal, or an explicit stop clears that value before `ConnectionController` reconnects with backoff. -The browser uses HTTP POST for API Proxy and generic Remote unary calls. API Gateway owns the `/api/remote.mux` WebSocket and its logical streams; in-process compositions provide equivalent Remote streams through `connection.rpc.open` without opening a WebSocket. The Host half owns the sole `/api` route, Fetch bridge, and trust checks. Typert Gateway claims its Remote endpoints first, and unclaimed requests fall through to API Proxy. Loopback hostname classification remains package-internal: the Host fence and WebSocket upgrade use it directly, while other Client plugins consume `ctx.connection.isLoopback`. +The browser uses HTTP POST for API Proxy and generic Remote unary calls. API Gateway owns the `/api/remote.mux` WebSocket and its logical streams; in-process compositions provide equivalent Remote streams through `connection.rpc.open` without opening a WebSocket. The Host half owns the sole `/api` route, Fetch bridge, browser authentication, and Host/Origin checks. Typert Gateway claims its Remote endpoints first, and unclaimed requests fall through to API Proxy. Loopback hostname classification remains package-internal to the browser-facing Client state. -The Node half keeps privileged methods (`host.pickDirectory`, `host.openPath`, the settings and credentials configuration planes, `llm.discoverModels`, and `agentPreset.read`/`copy`/`openDocument`/`remove`) loopback-only by passing an empty trust list to the fence. `agentPreset.list` and `agentPreset.select` are excluded: the roster carries only ids and trust levels, while `session.create` already selects a preset. Declared `trustedHosts` authorities can reach other methods; privileged operations remain loopback-only until a real authentication layer exists. +## Browser authentication and request trust -## /api browser-trust fence +Every Host RPC method and WebSocket stream requires one browser session; there is no method-specific loopback tier. Each process mints a random launch token. `dsh-web-app` prints and opens the ordinary root URL with `?token=...`; `frontend-static` delegates root and index requests to `ctx.connection.authorizeIndex`, which accepts that token only on `GET /`, writes an authority-bound signed cookie, and redirects to clean `/`. A missing, expired, malformed, or wrong-authority cookie returns 401 before RPC dispatch. Static assets remain public. The HTTP carrier accepts no query token outside the root exchange and no Authorization-header token. -The node half guards every entry under `/api` before bridging or upgrading (`src/api-request-trust.ts`). Every request — browser-marked or not — must present a `Host` that is a loopback authority or matches a `trustedHosts` entry: exact on `host:port` entries, any port on port-less entries, both sides compared through WHATWG normalization (DNS-rebinding defense). There is deliberately no shortcut for unmarked HTTP requests: over plain HTTP a browser attaches neither `Origin` nor Fetch-Metadata to image and navigation reads, so an unmarked request may still be a rebound browser read with a readable response, and Host is the one header rebinding cannot forge; a browser WebSocket handshake carries `Origin` and passes the same comparison. Non-browser clients pass the same fence via loopback, deployment-derived LAN IP literals, or a declared authority. When markers are present, an attached `Origin` must equal the Host authority, and an explicit `sec-fetch-site: cross-site` marker is refused. A `trustedHosts` entry that is not a bare, canonical `host[:port]` authority — one WHATWG parsing reads back exactly as written — fails the plugin load loudly: parsing would otherwise quietly authorize the hostname inside `harness.internal/path`, or broaden a dangling-colon or zero-padded port to an any-port grant. HTTP failures answer plain 403 before any RPC dispatch; upgrade failures reject the handshake before any event stream starts. Non-loopback compositions must trust their serving authorities explicitly: the Web runtime derives LAN IP literals from an all-interfaces server config, while `trustedHosts` in cordis.yml and the CLI's `--trusted-host` flag declare named authorities. `dsh web --host 0.0.0.0` is intentionally unsupported until remote access has an authentication layer. The fence is a reachability policy, not authentication; the Web carrier provides no authentication layer. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). +The cookie signing secret is the owner-scoped `client-connection/browser-session` grant record in `ctx.credentials`. The local provider persists it in `$DSH_HOME/.credentials.yaml`; `BrowserAuth` reads the current record for every verification, so deletion or rotation revokes cookies without restarting the process. Cookies carry an absolute issue/expiry interval, defaulting to 30 days through `cookieMaxAgeDays`, and bind the normalized hostname plus port in both their deterministic name and signed payload. They are host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`; they deliberately omit `Secure` because the shipped server uses loopback HTTP. + +Before authentication, every request still passes `src/api-request-trust.ts`. Its `Host` must be loopback or match a `trustedHosts` entry: exact on `host:port`, any port on port-less entries, both sides WHATWG-normalized. An attached `Origin` must equal that Host and `sec-fetch-site: cross-site` is refused. Malformed configured authorities fail plugin load. These checks defend DNS rebinding and cross-site browser requests; they never establish identity. A failed Host/Origin check returns 403, while a trusted but unauthenticated request returns 401. `dsh web --host 0.0.0.0` remains unsupported. Decision records: [browser request trust](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md) and [browser token authentication](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md). ## Connection generation @@ -29,3 +31,5 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **The `/api` bridge buffers each request body in memory** — `maxRequestBodyBytes` (default 300 MiB, sized for the default 200 MiB aggregate image limit after base64 expansion plus envelope headroom) is therefore also the per-request resident bound; a streaming body path would be needed to lower it without shrinking the image limits. +- **The browser cookie is not marked `Secure`** — loopback HTTP is the shipped transport, so deployments that make the same authority reachable over plaintext networking can expose the bearer cookie in transit. +- **There is no logout operation** — clearing the browser cookie ends one browser session; deleting the owner credential record revokes every session and the next launch-token exchange creates a new signing secret. diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index 13df74ddf7..e3cea191ab 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -4,13 +4,15 @@ 协议与连接世代层:Client 插件挂载 `ctx.connection`,包含共享 API 客户端、当前页面的 loopback 状态、按 generation 生效的可观察 `hostDescription`、通用 RPC carrier,以及单一 generation source 与连接循环的注册面。每个 generation 只在 source 已就绪且 `host.describe` 成功后发布 `hostDescription` 并调用 `onConnected`;source 结束、失败、被撤回或显式 stop 都会清空该值,再由 `ConnectionController` 退避重连。 -浏览器通过 HTTP POST 执行 API Proxy 一元调用与通用 Remote 一元调用;API Gateway 自己拥有 `/api/remote.mux` WebSocket 及其逻辑流。进程内组合通过 `connection.rpc.open` 提供等价的 Remote 流,不打开 WebSocket。Host half 拥有唯一 `/api` route、Fetch bridge 和信任校验;Typert Gateway 先认领自己的 Remote endpoint,未认领的请求再回退 API Proxy。Loopback hostname 判定留在包内:Host fence 与 WebSocket upgrade 直接使用它,其他 Client 插件消费 `ctx.connection.isLoopback`。 +浏览器通过 HTTP POST 执行 API Proxy 一元调用与通用 Remote 一元调用;API Gateway 自己拥有 `/api/remote.mux` WebSocket 及其逻辑流。进程内组合通过 `connection.rpc.open` 提供等价的 Remote 流,不打开 WebSocket。Host half 拥有唯一 `/api` route、Fetch bridge、浏览器认证与 Host/Origin 校验;Typert Gateway 先认领自己的 Remote endpoint,未认领的请求再回退 API Proxy。Loopback hostname 判定只供浏览器侧当前页面状态使用,留在包内。 -node 半侧的 `/api` 路由让特权方法集(`host.pickDirectory`、`host.openPath`,整个 settings 与 credentials 配置面,`llm.discoverModels`,以及 `agentPreset.read`/`copy`/`openDocument`/`remove`)以空信任表过 fence,从而钉在回环本机。`agentPreset.list` 与 `agentPreset.select` 不在其中:名单只携带 id 与信任级别,而 `session.create` 已能选择 preset。已声明的 `trustedHosts` 授权可达其余方法;在真正的认证层出现前,特权面始终只限回环。 +## 浏览器认证与请求信任 -## /api 浏览器信任栅栏 +每个 Host RPC 方法和 WebSocket stream 都要求同一个浏览器会话,不再存在按方法区分的 loopback 层。每个进程生成一个随机启动令牌。`dsh-web-app` 打印并打开带 `?token=...` 的普通根 URL;`frontend-static` 把根路径和 index 请求交给 `ctx.connection.authorizeIndex`,后者只在 `GET /` 接受该令牌,写入绑定 authority 的签名 cookie,再重定向到干净的 `/`。缺失、过期、畸形或 authority 不匹配的 cookie 会在 RPC 分发前得到 401。静态资源保持公开。HTTP 载体不在根路径交换之外接受 query token,也不接受 Authorization header token。 -node 半侧在桥接或 upgrade 前守卫 `/api` 下的每个入口(`src/api-request-trust.ts`)。每个请求——无论是否带浏览器标记——`Host` 都必须是回环地址权威,或与某个 `trustedHosts` 条目匹配:带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化后比较(DNS rebinding 防御)。刻意不为无浏览器标记的 HTTP 请求开捷径:明文 HTTP 下浏览器的图片与导航读取既不带 `Origin` 也不带 Fetch-Metadata,因此无标记请求仍可能是被重绑页面发起的、响应可被读走的读取,而 Host 是重绑唯一伪造不了的请求头;WebSocket 浏览器握手会带 `Origin` 并通过同一道比较。非浏览器客户端经由回环地址、部署推导的 LAN IP 字面量或已声明的权威通过同一道栅栏。当标记存在时,如附带 `Origin`,则它必须与 Host 权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不是纯的、规范形 `host[:port]` 权威的 `trustedHosts` 条目——即 WHATWG 解析读回后与原文不完全一致的——会让插件加载明确报错:否则解析会悄悄授权 `harness.internal/path` 这类笔误里的 hostname,或把悬空冒号、补零端口放大成任意端口授权。HTTP 失败在任何 RPC 分发之前以纯 403 应答,upgrade 失败在启动任何事件流前拒绝握手。非回环组合必须显式信任其服务权威:Web 运行时从全接口服务器配置推导 LAN IP 字面量,cordis.yml 中的 `trustedHosts` 与 CLI(命令行界面)的 `--trusted-host` flag 则声明具名权威。`dsh web --host 0.0.0.0` 在远程访问具备认证层之前有意不受支持。这道栅栏是可达性策略,而不是认证;Web 载体不提供认证层。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)。 +cookie 签名密钥是 `ctx.credentials` 中由 `client-connection/browser-session` 拥有的 grant 记录。本地提供方把它持久化到 `$DSH_HOME/.credentials.yaml`;`BrowserAuth` 每次校验都读取当前记录,因此删除或轮换记录无需重启进程即可撤销 cookie。cookie 携带绝对签发与过期区间,`cookieMaxAgeDays` 默认设为 30 天,并在确定性名称与签名 payload 中同时绑定规范化 hostname 和 port。它是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`;随附服务器使用 loopback HTTP,因此刻意不设置 `Secure`。 + +认证之前,每个请求仍经过 `src/api-request-trust.ts`。其 `Host` 必须是 loopback,或与 `trustedHosts` 条目匹配:带端口的 `host:port` 精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化。若附带 `Origin`,它必须等于该 Host;`sec-fetch-site: cross-site` 一律拒绝。畸形配置 authority 会让插件加载失败。这些检查防御 DNS rebinding 与跨站浏览器请求,绝不建立身份。Host/Origin 校验失败返回 403;Host 可信但未认证的请求返回 401。`dsh web --host 0.0.0.0` 仍不受支持。决策记录:[浏览器请求信任](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)与[浏览器令牌认证](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md)。 ## Connection generation @@ -29,3 +31,5 @@ API Gateway Client 把内部 `$events` logical stream 注册为唯一 generation ## 已知限制与暂缓事项 - **`/api` 桥把每个请求体整体缓冲在内存里**:`maxRequestBodyBytes`(默认 300 MiB,按默认 200 MiB 图片总量上限经 base64 膨胀加信封余量得出)因此同时是单请求的驻留内存上界;要降低它而不缩小图片限额,需要流式请求体路径。 +- **浏览器 cookie 不带 `Secure`**:随附载体是 loopback HTTP;若部署把同一 authority 经明文网络暴露,bearer cookie 可能在传输中泄露。 +- **没有 logout 操作**:清除浏览器 cookie 会结束单个浏览器会话;删除 owner 凭据记录会撤销全部会话,下一次启动令牌交换会创建新的签名密钥。 diff --git a/packages/client/connection/package.json b/packages/client/connection/package.json index 95ce0d1981..5c7e53bb70 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -51,6 +51,7 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-attachment": "workspace:^", + "@deepseek-ai/dsh-credentials": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", @@ -62,6 +63,7 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-attachment": "workspace:^", + "@deepseek-ai/dsh-credentials": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", diff --git a/packages/client/connection/src/browser-auth.ts b/packages/client/connection/src/browser-auth.ts new file mode 100644 index 0000000000..7c57622bb2 --- /dev/null +++ b/packages/client/connection/src/browser-auth.ts @@ -0,0 +1,276 @@ +/** Browser-session authentication for the Host Connection carrier. */ + +import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import type { CredentialProvider, CredentialRecord } from '@deepseek-ai/dsh-credentials' +import type { + ConnectionIndexRequest, + ConnectionIndexResponse, + ConnectionTrustRequest, +} from './rpc.ts' + +const AUTH_RECORD_KEY = credentialKey('client-connection', 'browser-session') +const DAY_MILLISECONDS = 24 * 60 * 60 * 1000 +const SECRET_BYTES = 32 +const TOKEN_QUERY = 'token' +const COOKIE_PREFIX = 'dsh-auth-' +const COOKIE_PAYLOAD_VERSION = 1 +const STORED_SECRET_VERSION = 1 + +interface StoredSecretPayload { + readonly version: typeof STORED_SECRET_VERSION + readonly secret: string +} + +interface BrowserCookiePayload { + readonly version: typeof COOKIE_PAYLOAD_VERSION + readonly authority: string + readonly issuedAt: number + readonly expiresAt: number +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function header( + headers: ConnectionTrustRequest['headers'], + name: string, +): string | undefined { + if (headers instanceof Headers) return headers.get(name) ?? undefined + const value = headers[name] + return typeof value === 'string' ? value : undefined +} + +/** Canonical request authority used as the cookie name and signed audience. */ +function requestAuthority(headers: ConnectionTrustRequest['headers']): string | undefined { + const host = header(headers, 'host') + if (host === undefined) return undefined + try { + return new URL(`http://${host}`).host + } catch { + return undefined + } +} + +function canonicalSecret(value: unknown): Buffer | undefined { + if (typeof value !== 'string') return undefined + const decoded = Buffer.from(value, 'base64url') + if (decoded.byteLength !== SECRET_BYTES || decoded.toString('base64url') !== value) return undefined + return decoded +} + +function storedSecret(record: CredentialRecord | undefined): Buffer | undefined { + if (record === undefined) return undefined + if (record.kind !== 'grant' || !isRecord(record.payload) + || record.payload.version !== STORED_SECRET_VERSION) { + throw new Error('client-connection: browser-session credential record has an unsupported format') + } + const secret = canonicalSecret(record.payload.secret) + if (secret === undefined) { + throw new Error('client-connection: browser-session credential record has an invalid secret') + } + return secret +} + +function tokenMatches(actual: string, expected: string): boolean { + const actualBytes = Buffer.from(actual, 'utf8') + const expectedBytes = Buffer.from(expected, 'utf8') + return actualBytes.byteLength === expectedBytes.byteLength && timingSafeEqual(actualBytes, expectedBytes) +} + +function cookieName(authority: string): string { + return COOKIE_PREFIX + createHash('sha256').update(authority).digest('base64url') +} + +/** Read the exact generated cookie without implementing general Cookie decoding. */ +function cookieValue(headerValue: string, name: string): string | undefined { + for (const segment of headerValue.split(';')) { + const at = segment.indexOf('=') + if (at === -1 || segment.slice(0, at).trim() !== name) continue + return segment.slice(at + 1).trim() + } + return undefined +} + +/** Serialize the fixed browser-session attributes; generated names and values are cookie-safe base64url. */ +function sessionCookie(name: string, value: string, expiresAt: number, maxAgeSeconds: number): string { + return `${name}=${value}; Max-Age=${String(maxAgeSeconds)}; Path=/; Expires=${new Date(expiresAt).toUTCString()}; HttpOnly; SameSite=Strict` +} + +function signature(secret: Buffer, body: string): Buffer { + return createHmac('sha256', secret).update(body).digest() +} + +function encodeCookie(payload: BrowserCookiePayload, secret: Buffer): string { + const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url') + return `v1.${body}.${signature(secret, body).toString('base64url')}` +} + +function decodeCookie(value: string, secret: Buffer): BrowserCookiePayload | undefined { + const parts = value.split('.') + const [version, body, encodedSignature] = parts + if (parts.length !== 3 || version !== 'v1' || body === undefined || encodedSignature === undefined) { + return undefined + } + const actualSignature = Buffer.from(encodedSignature, 'base64url') + if (actualSignature.toString('base64url') !== encodedSignature) return undefined + const expectedSignature = signature(secret, body) + if (actualSignature.byteLength !== expectedSignature.byteLength + || !timingSafeEqual(actualSignature, expectedSignature)) return undefined + let decoded: unknown + try { + decoded = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) + } catch { + return undefined + } + if (!isRecord(decoded) + || decoded.version !== COOKIE_PAYLOAD_VERSION + || typeof decoded.authority !== 'string' + || !Number.isSafeInteger(decoded.issuedAt) + || !Number.isSafeInteger(decoded.expiresAt)) return undefined + return decoded as unknown as BrowserCookiePayload +} + +/** + * Process launch-token exchange and persistent signed-cookie verification. + * The credential provider owns the signing secret; this object reads it for + * each operation so deletion or rotation revokes existing cookies without a + * process restart. + */ +export class BrowserAuth { + private readonly launchToken = randomBytes(SECRET_BYTES).toString('base64url') + private readonly maxAgeMilliseconds: number + + private constructor( + private readonly credentials: CredentialProvider, + maxAgeDays: number, + ) { + this.maxAgeMilliseconds = maxAgeDays * DAY_MILLISECONDS + if (!Number.isSafeInteger(this.maxAgeMilliseconds) + || !Number.isSafeInteger(Date.now() + this.maxAgeMilliseconds)) { + throw new Error('client-connection: cookieMaxAgeDays exceeds the safe timestamp range') + } + } + + /** + * Initialize browser authentication and create its durable signing secret + * when this Harness home has none. + * @param credentials - persistent credential provider for the Web profile. + * @param maxAgeDays - positive absolute browser-cookie lifetime in days. + * @returns initialized authentication owner with a fresh process token. + */ + static async create(credentials: CredentialProvider, maxAgeDays: number): Promise { + const auth = new BrowserAuth(credentials, maxAgeDays) + await auth.ensureSecret() + return auth + } + + /** + * Add this process's launch token to the ordinary application root URL. + * @param baseUrl - canonical browser origin without credentials. + * @returns root URL carrying the process token as its sole authentication input. + */ + authenticatedUrl(baseUrl: string): string { + const url = new URL(baseUrl) + url.pathname = '/' + url.search = '' + url.hash = '' + url.searchParams.set(TOKEN_QUERY, this.launchToken) + return url.href + } + + /** + * Authenticate an index request. A valid root query token mints the cookie + * and redirects to clean `/`; a valid cookie lets the caller serve the + * index; every other request receives the same minimal 401 response. + * @param req - incoming root or configured-index request. + * @param res - response owned when this method returns false. + * @returns true only when the caller may serve index.html. + */ + async authorizeIndex(req: ConnectionIndexRequest, res: ConnectionIndexResponse): Promise { + /* v8 ignore next -- node:http always supplies url on server requests. */ + const url = new URL(req.url ?? '/', 'http://dsh.invalid') + const tokens = url.searchParams.getAll(TOKEN_QUERY) + if (tokens.length > 0) { + const authority = requestAuthority(req.headers) + if (req.method === 'GET' && url.pathname === '/' && tokens.length === 1 + && authority !== undefined && tokenMatches(tokens.join(''), this.launchToken)) { + const issuedAt = Date.now() + const expiresAt = issuedAt + this.maxAgeMilliseconds + const value = encodeCookie({ + version: COOKIE_PAYLOAD_VERSION, + authority, + issuedAt, + expiresAt, + }, await this.ensureSecret()) + res.writeHead(303, { + 'cache-control': 'no-store', + 'location': '/', + 'referrer-policy': 'no-referrer', + 'set-cookie': sessionCookie( + cookieName(authority), value, expiresAt, Math.floor(this.maxAgeMilliseconds / 1000), + ), + }) + res.end() + return false + } + this.writeUnauthorized(req, res) + return false + } + if (await this.isAuthenticated(req)) return true + this.writeUnauthorized(req, res) + return false + } + + /** + * Verify the authority-bound browser cookie on a Host request. + * @param request - request headers carrying Host and Cookie. + * @returns true only for an unexpired cookie signed by the current durable secret. + */ + async isAuthenticated(request: ConnectionTrustRequest): Promise { + const authority = requestAuthority(request.headers) + const rawCookie = header(request.headers, 'cookie') + if (authority === undefined || rawCookie === undefined) return false + const value = cookieValue(rawCookie, cookieName(authority)) + if (value === undefined) return false + const secret = storedSecret(await this.credentials.readRecord(AUTH_RECORD_KEY)) + if (secret === undefined) return false + const payload = decodeCookie(value, secret) + if (payload === undefined || payload.authority !== authority) return false + const now = Date.now() + return payload.issuedAt <= now + && payload.expiresAt > now + && payload.expiresAt > payload.issuedAt + && payload.expiresAt - payload.issuedAt <= this.maxAgeMilliseconds + } + + private async ensureSecret(): Promise { + const generated: StoredSecretPayload = { + version: STORED_SECRET_VERSION, + secret: randomBytes(SECRET_BYTES).toString('base64url'), + } + const record = await this.credentials.modifyRecord(AUTH_RECORD_KEY, (current) => { + if (current !== undefined) { + storedSecret(current) + return Promise.resolve(undefined) + } + return Promise.resolve({ kind: 'grant', payload: generated }) + }) + const secret = storedSecret(record) + if (secret === undefined) { + throw new Error('client-connection: browser-session credential record was not created') + } + return secret + } + + private writeUnauthorized(req: ConnectionIndexRequest, res: ConnectionIndexResponse): void { + res.writeHead(401, { + 'cache-control': 'no-store', + 'content-type': 'text/plain; charset=utf-8', + }) + res.end(req.method === 'HEAD' + ? undefined + : 'dsh web authentication required; reopen the URL printed by dsh web.\n') + } +} diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index 1944e09722..0d43a322a3 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -2,20 +2,23 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-attachment' +import type {} from '@deepseek-ai/dsh-credentials' // Activates the webServer Context merge used below. import type { WebRoute } from '@deepseek-ai/dsh-host-webserver' import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy' import { API_PATH } from './api-path.ts' import { bridge, DEFAULT_MAX_REQUEST_BODY_BYTES } from './http-bridge.ts' -import { assertTrustedAuthority, isTrustedApiRequest } from './api-request-trust.ts' +import { assertTrustedAuthority } from './api-request-trust.ts' +import { BrowserAuth } from './browser-auth.ts' import { HostConnectionService } from './rpc-host.ts' export type { - ConnectionRpcAuthority, + ConnectionIndexRequest, + ConnectionIndexResponse, ConnectionRpcEndpointMatcher, ConnectionRpcFailure, ConnectionRpcHandler, - ConnectionRpcHandlerOptions, + ConnectionRequestRejection, ConnectionRpcResult, ConnectionTrustRequest, HostConnectionHandle, @@ -46,7 +49,7 @@ function assertImageBodyCapacity(ctx: Context, maxRequestBodyBytes: number): voi } /** Services required before providing Connection; API Proxy is an optional `/api` fallback. */ -export const inject = ['webServer'] +export const inject = ['webServer', 'credentials'] /** Plugin config: the deployment's non-loopback serving authorities. */ export interface ConnectionConfig { @@ -55,112 +58,58 @@ export interface ConnectionConfig { * port-less `host` matching any port. The /api trust fence refuses any * request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached - * by (the dsh CLI derives the machine's LAN IP literals itself). An entry - * that is not a bare, canonical authority fails the plugin load. + * by; the Web runtime derives LAN IP literals from an active all-interface + * bind. An entry that is not a bare, canonical authority fails plugin load. */ trustedHosts?: string[] + /** Absolute browser-session lifetime in days. Default: 30. */ + cookieMaxAgeDays?: number /** Maximum buffered JSON body for every `/api` request. Default: 300 MiB. */ maxRequestBodyBytes?: number } export const Config: z = z.object({ trustedHosts: z.array(String).default([]), + cookieMaxAgeDays: z.natural().min(1).default(30), maxRequestBodyBytes: z.natural().min(1).default(DEFAULT_MAX_REQUEST_BODY_BYTES), }) -/** - * Methods gated to loopback even on a trusted-host deployment. Native dialogs - * act on the host machine; the settings and credential domains mutate the - * user's configuration and secret store, and READING them is equally - * privileged — `settings.describe` returns every exposed namespace's - * configuration and `credentials.describe` reports whether an arbitrary - * environment-variable name is configured and where from, which is - * reconnaissance no anonymous caller should have. `trustedHosts` is a - * DNS-rebinding fence, explicitly not authentication, so the whole - * configuration plane stays loopback-same-origin until a real authentication - * layer exists. `llm.discoverModels` belongs to that plane on both counts: it - * carries a draft credential, and it makes the HOST issue a GET to a URL the - * caller chose and reports back the status or the parsed body — an anonymous - * LAN caller would have a probe for whatever the host can reach and the - * browser cannot. - * - * The model catalog (`llm.providers`, `llm.models`) is deliberately NOT here: - * it carries provider ids, display names, and model lists — no endpoints, - * keys, or key state — and a LAN client's model picker legitimately needs it. - */ -const PRIVILEGED_METHODS = new Set([ - // A preset composition names the plugins a session runs, so reading one is - // reconnaissance; copy and remove rearrange what the deployment offers, and - // openDocument drives the host desktop — all more than the roster beside - // them. (Authoring is copy-only, so no method here accepts composition text - // or a path; the pin is about who may manage the roster at all.) - // - // CHOOSING one is not pinned, and `agentPreset.list` is not either. Picking a - // preset looks like escalation — one of them mounts the toolset that edits the - // live runtime — but `session.create` already takes an `agentPreset`, so - // pinning only the switch would leave the same capability one method over. - // The deeper reason is that the capability is not the preset's to grant: the - // deployment's own default already carries `bash` and the filesystem tools, so - // any caller that may start a session at all can already run commands as this - // process. Pinning the switch would be a fence beside an open gate. - 'agentPreset.read', - 'agentPreset.copy', - 'agentPreset.openDocument', - 'agentPreset.remove', - 'host.pickDirectory', - 'host.openPath', - 'settings.describe', - 'settings.openDocument', - 'settings.update', - 'settings.replace', - 'settings.mutate', - 'credentials.describe', - 'credentials.set', - 'credentials.unset', - 'llm.discoverModels', -]) - /** * Mounts the API gateway under the browser transport prefix. Every request on - * the prefix passes the browser-trust fence first (DNS-rebinding and - * cross-site defense — [api-request-trust](./api-request-trust.ts)); - * privileged methods additionally pass it with an empty trust list, which - * pins them to loopback. + * the prefix passes the Host/Origin browser-trust fence and persistent browser + * authentication before dispatch. * @param ctx - Host plugin context. * @param config - resolved plugin config (schema defaults applied). */ -export function apply(ctx: Context, config?: ConnectionConfig): void { +export async function apply(ctx: Context, config?: ConnectionConfig): Promise { // The Loader resolves schema defaults; hand-built test contexts may pass none. const trustedHosts = config?.trustedHosts ?? [] + const cookieMaxAgeDays = config?.cookieMaxAgeDays ?? 30 const maxRequestBodyBytes = config?.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY_BYTES // Config boundary: a malformed entry fails the load loudly here rather than // silently authorizing its hostname prefix at request time. for (const entry of trustedHosts) assertTrustedAuthority(entry) if (ctx.get('apiProxy') !== undefined) assertImageBodyCapacity(ctx, maxRequestBodyBytes) - const connection = new HostConnectionService(ctx, trustedHosts) + const connection = new HostConnectionService( + ctx, + trustedHosts, + await BrowserAuth.create(ctx.credentials, cookieMaxAgeDays), + ) const fetchHandler = connection.createSharedFetchHandler(API_PATH, { async fetch(request) { - const pathname = new URL(request.url).pathname - const method = pathname.startsWith(`${API_PATH}/`) - ? pathname.slice(API_PATH.length + 1) - : undefined - if (method !== undefined - && PRIVILEGED_METHODS.has(method) - && !isTrustedApiRequest(request, [])) { - return new Response('forbidden', { status: 403 }) - } const apiProxy = ctx.get('apiProxy') if (apiProxy === undefined) return new Response('not found', { status: 404 }) - return toFetchHandler(apiProxy).fetch(request) + return await toFetchHandler(apiProxy).fetch(request) }, }) const route: WebRoute = { kind: 'prefix', path: API_PATH, handler: async (req, res) => { - if (!isTrustedApiRequest(req, trustedHosts)) { - res.writeHead(403) - res.end('forbidden') + const rejection = await connection.requestRejection(req) + if (rejection !== undefined) { + res.writeHead(rejection) + res.end(rejection === 401 ? 'unauthorized' : 'forbidden') return } await bridge(req, res, fetchHandler, maxRequestBodyBytes) diff --git a/packages/client/connection/src/invariant.ts b/packages/client/connection/src/invariant.ts index 78394263cf..5a187545b5 100644 --- a/packages/client/connection/src/invariant.ts +++ b/packages/client/connection/src/invariant.ts @@ -15,11 +15,12 @@ export const name = 'client-connection-invariant' export const inject = ['invariants'] /** - * No runtime invariant: the wire layer emits no cordis events and owns no - * mutable cross-plugin relation — stream/reconnect sequencing is exercised - * directly by its behavior specs, rpcId round-trip discipline is owned by the - * apiproxy contract layer, and the node half's single route registration's - * register/dispose symmetry is audited by the webserver package's invariant. + * No runtime invariant: browser-session verification reads the credential + * record asynchronously at the request that authorizes work, while the + * credentials companion owns record commit-event lifetime. Stream/reconnect + * sequencing is exercised directly by behavior specs, rpcId round-trip + * discipline belongs to apiproxy, and route register/dispose symmetry is + * audited by the webserver companion. */ const install: InvariantInstaller = () => {} diff --git a/packages/client/connection/src/rpc-host.ts b/packages/client/connection/src/rpc-host.ts index 162045ed0d..5c079e092a 100644 --- a/packages/client/connection/src/rpc-host.ts +++ b/packages/client/connection/src/rpc-host.ts @@ -13,12 +13,14 @@ import { import { bridge, type FetchHandler } from './http-bridge.ts' import { isTrustedApiRequest } from './api-request-trust.ts' import { API_PATH } from './api-path.ts' +import type { BrowserAuth } from './browser-auth.ts' import type { + ConnectionIndexRequest, + ConnectionIndexResponse, ConnectionRpcEndpointMatcher, ConnectionRpcHandler, - ConnectionRpcHandlerOptions, ConnectionRpcResult, - ConnectionRpcAuthority, + ConnectionRequestRejection, ConnectionTrustRequest, HostConnectionHandle, HostConnectionRpc, @@ -31,7 +33,6 @@ const ENDPOINT_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/ interface ConnectionRpcInterceptor { readonly matches: ConnectionRpcEndpointMatcher readonly fetchHandler: FetchHandler - readonly options: ConnectionRpcHandlerOptions } interface ConnectionServerResponse { @@ -54,9 +55,14 @@ export class HostConnectionService extends Service implements HostConnectionHand /** * Provide the Host half over the active HTTP server. * @param ctx - owning Connection plugin context. - * @param trustedHosts - deployment authorities accepted by trusted-host channels. + * @param trustedHosts - deployment authorities accepted by the Host/Origin fence. + * @param browserAuth - process token and persistent browser-session owner. */ - constructor(ctx: Context, private readonly trustedHosts: readonly string[]) { + constructor( + ctx: Context, + private readonly trustedHosts: readonly string[], + private readonly browserAuth: BrowserAuth, + ) { super(ctx, 'connection') } @@ -64,15 +70,26 @@ export class HostConnectionService extends Service implements HostConnectionHand get rpc(): HostConnectionRpc { const owner = this.ctx return { - handle: (channel, handler, options) => this.register(owner, channel, handler, options), - intercept: (channel, matches, handler, options) => - this.registerInterceptor(owner, channel, matches, handler, options), + handle: (channel, handler) => this.register(owner, channel, handler), + intercept: (channel, matches, handler) => + this.registerInterceptor(owner, channel, matches, handler), } } - /** Apply the existing configured request trust policy to a sibling Web route. */ - isTrustedRequest(request: ConnectionTrustRequest, authority: ConnectionRpcAuthority): boolean { - return isTrustedApiRequest(request, authority === 'loopback' ? [] : this.trustedHosts) + /** Apply the configured Host/Origin fence, then browser authentication. */ + async requestRejection(request: ConnectionTrustRequest): Promise { + if (!isTrustedApiRequest(request, this.trustedHosts)) return 403 + return await this.browserAuth.isAuthenticated(request) ? undefined : 401 + } + + /** Authenticate an index request through the process-token exchange or cookie. */ + authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): Promise { + return this.browserAuth.authorizeIndex(request, response) + } + + /** Add this process's launch token to the clean application URL. */ + authenticatedUrl(baseUrl: string): string { + return this.browserAuth.authenticatedUrl(baseUrl) } /** @@ -92,9 +109,6 @@ export class HostConnectionService extends Service implements HostConnectionHand if (endpoint === undefined || interceptor === undefined || !interceptor.matches(endpoint)) { return fallback.fetch(request) } - if (interceptor.options.authority === 'loopback' && !isTrustedApiRequest(request, [])) { - return Promise.resolve(new Response('forbidden', { status: 403 })) - } return interceptor.fetchHandler.fetch(request) }, } @@ -104,18 +118,17 @@ export class HostConnectionService extends Service implements HostConnectionHand owner: Context, channel: string, handler: ConnectionRpcHandler, - options: ConnectionRpcHandlerOptions, ): () => Promise { assertChannel(channel) - const trustedHosts = options.authority === 'loopback' ? [] : this.trustedHosts const fetchHandler = rpcFetchHandler(channel, handler) const route: WebRoute = { kind: 'prefix', path: channel, handler: async (req, res) => { - if (!isTrustedApiRequest(req, trustedHosts)) { - res.writeHead(403) - res.end('forbidden') + const rejection = await this.requestRejection(req) + if (rejection !== undefined) { + res.writeHead(rejection) + res.end(rejection === 401 ? 'unauthorized' : 'forbidden') return } await bridge(req, res, fetchHandler) @@ -132,7 +145,6 @@ export class HostConnectionService extends Service implements HostConnectionHand channel: string, matches: ConnectionRpcEndpointMatcher, handler: ConnectionRpcHandler, - options: ConnectionRpcHandlerOptions, ): () => Promise { if (channel !== API_PATH) { throw new Error(`connection: invalid shared RPC channel ${JSON.stringify(channel)}`) @@ -140,7 +152,6 @@ export class HostConnectionService extends Service implements HostConnectionHand const interceptor: ConnectionRpcInterceptor = { matches, fetchHandler: rpcFetchHandler(channel, handler), - options, } return owner.effect(() => { if (this.interceptors.has(channel)) { diff --git a/packages/client/connection/src/rpc.ts b/packages/client/connection/src/rpc.ts index e8dc585d38..d05e2f0b81 100644 --- a/packages/client/connection/src/rpc.ts +++ b/packages/client/connection/src/rpc.ts @@ -12,19 +12,25 @@ export type ConnectionRpcResult = | { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: ConnectionRpcFailure } -/** HTTP request facts consumed by the existing browser trust fence. */ +/** HTTP request facts consumed by browser trust and authentication. */ export interface ConnectionTrustRequest { /** Request headers supplied by either the Fetch or node:http representation. */ readonly headers: Headers | Readonly> } -/** Trust fence applied before a Host RPC channel reaches its handler. */ -export type ConnectionRpcAuthority = 'trusted-host' | 'loopback' +/** HTTP status returned before dispatch, or undefined when the request may proceed. */ +export type ConnectionRequestRejection = 401 | 403 | undefined -/** Registration policy for one logical RPC channel. */ -export interface ConnectionRpcHandlerOptions { - /** Browser authority accepted by every endpoint in this channel. */ - readonly authority: ConnectionRpcAuthority +/** Root/index request facts used by the browser-token exchange. */ +export interface ConnectionIndexRequest extends ConnectionTrustRequest { + readonly method?: string | undefined + readonly url?: string | undefined +} + +/** Root/index response operations owned by the browser-token exchange. */ +export interface ConnectionIndexResponse { + writeHead(status: number, headers?: Readonly>): unknown + end(body?: string): unknown } /** Handler invoked after Connection has decoded the transport envelope. */ @@ -40,16 +46,14 @@ export type ConnectionRpcEndpointMatcher = (endpoint: string) => boolean /** Host registry for logical RPC channels carried by the current transport. */ export interface HostConnectionRpc { /** - * Register one absolute channel prefix and its trust policy. + * Register one authenticated absolute channel prefix. * @param channel - absolute logical channel such as `/rpc`. * @param handler - decoded endpoint handler returning the existing RPC result shape. - * @param options - channel trust policy. * @returns asynchronous disposer removing the channel and its physical route. */ handle( channel: string, handler: ConnectionRpcHandler, - options: ConnectionRpcHandlerOptions, ): () => Promise /** @@ -57,14 +61,12 @@ export interface HostConnectionRpc { * @param channel - reserved shared channel; currently `/api`. * @param matches - synchronous endpoint ownership test. * @param handler - decoded endpoint handler returning the existing RPC result shape. - * @param options - trust policy for every endpoint claimed by this interceptor. * @returns asynchronous disposer removing the interceptor. */ intercept( channel: '/api', matches: ConnectionRpcEndpointMatcher, handler: ConnectionRpcHandler, - options: ConnectionRpcHandlerOptions, ): () => Promise } @@ -74,12 +76,27 @@ export interface HostConnectionHandle { readonly rpc: HostConnectionRpc /** - * Apply Connection's configured browser trust policy to another Web route. + * Apply Connection's Host/Origin checks and browser authentication to + * another Web route. * @param request - request headers from the HTTP or upgrade request. - * @param authority - configured trusted hosts or loopback-only policy. - * @returns whether the route may accept the request. + * @returns rejection status, or undefined when the route may accept the request. */ - isTrustedRequest(request: ConnectionTrustRequest, authority: ConnectionRpcAuthority): boolean + requestRejection(request: ConnectionTrustRequest): Promise + + /** + * Authenticate one frontend index request, owning a token redirect or 401. + * @param request - root or configured-index HTTP request. + * @param response - response owned when the result is false. + * @returns true only when the frontend may serve index.html. + */ + authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): Promise + + /** + * Add the fresh process token to an ordinary Web application URL. + * @param baseUrl - clean canonical browser origin. + * @returns root URL accepted by {@link authorizeIndex} for initial login. + */ + authenticatedUrl(baseUrl: string): string } /** Client caller for logical RPC channels carried by the current transport. */ diff --git a/packages/client/connection/tests/browser-auth.host.spec.ts b/packages/client/connection/tests/browser-auth.host.spec.ts new file mode 100644 index 0000000000..21ce8f592b --- /dev/null +++ b/packages/client/connection/tests/browser-auth.host.spec.ts @@ -0,0 +1,231 @@ +/** Browser launch-token and persistent-cookie behavior. */ + +import { createHmac } from 'node:crypto' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { CredentialProvider, CredentialRecord } from '@deepseek-ai/dsh-credentials' +import { BrowserAuth } from '../src/browser-auth.ts' +import type { ConnectionIndexRequest, ConnectionIndexResponse } from '../src/rpc.ts' + +class RecordCredentials { + record: CredentialRecord | undefined + discardWrites = false + + readRecord(): Promise { + return Promise.resolve(this.record) + } + + async modifyRecord( + _key: unknown, + mutate: (current: CredentialRecord | undefined) => Promise, + ): Promise { + const next = await mutate(this.record) + if (this.discardWrites) return undefined + if (next !== undefined) this.record = next + return this.record + } + + deleteRecord(): Promise { + this.record = undefined + return Promise.resolve() + } +} + +function signedCookie(store: RecordCredentials, name: string, payload: unknown): string { + const record = store.record + if (record?.kind !== 'grant' || typeof record.payload !== 'object' || record.payload === null) { + throw new Error('test credential store has no signing secret') + } + const secret: unknown = Reflect.get(record.payload, 'secret') + if (typeof secret !== 'string') throw new Error('test credential record has no string secret') + const body = typeof payload === 'string' + ? Buffer.from(payload, 'utf8').toString('base64url') + : Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url') + const signature = createHmac('sha256', Buffer.from(secret, 'base64url')).update(body).digest('base64url') + return `${name}=v1.${body}.${signature}` +} + +interface ResponseState { + status?: number + headers?: Readonly> + body?: string +} + +function response(): { value: ConnectionIndexResponse; state: ResponseState } { + const state: ResponseState = {} + return { + value: { + writeHead(status, headers) { + state.status = status + if (headers !== undefined) state.headers = headers + }, + end(body) { + if (body !== undefined) state.body = body + }, + }, + state, + } +} + +function credentials(store: RecordCredentials): CredentialProvider { + return store as unknown as CredentialProvider +} + +function request(url: string, authority = '127.0.0.1:3080', init?: { + cookie?: string + method?: string +}): ConnectionIndexRequest { + return { + method: init?.method ?? 'GET', + url, + headers: { + host: authority, + ...init?.cookie === undefined ? {} : { cookie: init.cookie }, + }, + } +} + +async function exchange( + auth: BrowserAuth, + authority = '127.0.0.1:3080', +): Promise<{ cookie: string; launchUrl: string; state: ResponseState }> { + const launchUrl = auth.authenticatedUrl(`http://${authority}`) + const target = new URL(launchUrl) + const res = response() + expect(await auth.authorizeIndex(request(`${target.pathname}${target.search}`, authority), res.value)).toBe(false) + const setCookie = res.state.headers?.['set-cookie'] + if (setCookie === undefined) throw new Error('token exchange did not set a cookie') + return { cookie: setCookie.split(';', 1)[0]!, launchUrl, state: res.state } +} + +afterEach(() => { + vi.useRealTimers() +}) + +describe('BrowserAuth', () => { + it('mints one process token and a persistent authority-bound cookie', async () => { + const store = new RecordCredentials() + const first = await BrowserAuth.create(credentials(store), 30) + const login = await exchange(first) + + expect(login.state).toMatchObject({ + status: 303, + headers: { + 'cache-control': 'no-store', + 'location': '/', + 'referrer-policy': 'no-referrer', + }, + }) + expect(login.state.headers?.['set-cookie']).toMatch(/; Max-Age=2592000; Path=\/; Expires=.*; HttpOnly; SameSite=Strict$/u) + expect(login.state.headers?.['set-cookie']).not.toContain('Secure') + expect(await first.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) + expect(await first.isAuthenticated({ + headers: new Headers({ host: '127.0.0.1:3080', cookie: login.cookie }), + })).toBe(true) + expect(await first.isAuthenticated({ headers: new Headers() })).toBe(false) + expect(await first.isAuthenticated(request('/', 'localhost:3080', { cookie: login.cookie }))).toBe(false) + expect(await first.isAuthenticated(request('/', '127.0.0.1:3081', { cookie: login.cookie }))).toBe(false) + + const restarted = await BrowserAuth.create(credentials(store), 30) + expect(new URL(restarted.authenticatedUrl('http://127.0.0.1:3080')).searchParams.get('token')) + .not.toBe(new URL(login.launchUrl).searchParams.get('token')) + expect(await restarted.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) + }) + + it('accepts the cookie for index serving and gives every unauthenticated request one response', async () => { + const auth = await BrowserAuth.create(credentials(new RecordCredentials()), 30) + const { cookie } = await exchange(auth) + const allowed = response() + expect(await auth.authorizeIndex(request('/index.html', '127.0.0.1:3080', { cookie }), allowed.value)).toBe(true) + expect(allowed.state).toEqual({}) + + for (const candidate of [ + request('/'), + request('/?token=wrong'), + request('/?token=wrong&token=again'), + request('/index.html?token=wrong'), + request(auth.authenticatedUrl('http://127.0.0.1:3080'), '127.0.0.1:3080', { method: 'HEAD' }), + ]) { + const denied = response() + expect(await auth.authorizeIndex(candidate, denied.value)).toBe(false) + expect(denied.state.status).toBe(401) + expect(denied.state.headers).toEqual({ + 'cache-control': 'no-store', + 'content-type': 'text/plain; charset=utf-8', + }) + expect(denied.state.body).toBe(candidate.method === 'HEAD' + ? undefined + : 'dsh web authentication required; reopen the URL printed by dsh web.\n') + } + }) + + it('rejects tampering, expiry, future issuance, and a longer lifetime than configured', async () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-08-24T00:00:00.000Z')) + const store = new RecordCredentials() + const auth = await BrowserAuth.create(credentials(store), 30) + const { cookie } = await exchange(auth) + const [name, value] = cookie.split('=') as [string, string] + + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=broken` }))).toBe(false) + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=${value.slice(0, -1)}x` }))).toBe(false) + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=%` }))).toBe(false) + expect(await auth.isAuthenticated({ headers: {} })).toBe(false) + expect(await auth.isAuthenticated({ headers: { host: 'bad host', cookie } })).toBe(false) + expect(await auth.isAuthenticated({ headers: { host: '127.0.0.1:3080' } })).toBe(false) + + const invalidPayloads: unknown[] = [ + 'not json', + null, + { version: 2, authority: '127.0.0.1:3080', issuedAt: Date.now(), expiresAt: Date.now() + 1000 }, + { version: 1, authority: 42, issuedAt: Date.now(), expiresAt: Date.now() + 1000 }, + { version: 1, authority: '127.0.0.1:3080', issuedAt: 'now', expiresAt: Date.now() + 1000 }, + { version: 1, authority: '127.0.0.1:3080', issuedAt: Date.now(), expiresAt: 'later' }, + ] + for (const payload of invalidPayloads) { + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { + cookie: signedCookie(store, name, payload), + }))).toBe(false) + } + + const shorter = await BrowserAuth.create(credentials(store), 1) + expect(await shorter.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) + vi.setSystemTime(new Date('2026-09-24T00:00:00.000Z')) + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) + vi.setSystemTime(new Date('2026-08-23T00:00:00.000Z')) + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) + }) + + it('revokes on record deletion and creates a new secret on the next token exchange', async () => { + const store = new RecordCredentials() + const auth = await BrowserAuth.create(credentials(store), 30) + const first = await exchange(auth) + await store.deleteRecord() + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: first.cookie }))).toBe(false) + + const second = await exchange(auth) + expect(second.cookie).not.toBe(first.cookie) + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: first.cookie }))).toBe(false) + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: second.cookie }))).toBe(true) + }) + + it('fails loud on an invalid owner record instead of replacing it', async () => { + const unsupported = new RecordCredentials() + unsupported.record = { kind: 'api-key', key: 'not-a-cookie-secret' } + await expect(BrowserAuth.create(credentials(unsupported), 30)).rejects.toThrow(/unsupported format/u) + + const malformed = new RecordCredentials() + malformed.record = { kind: 'grant', payload: { version: 1, secret: 'short' } } + await expect(BrowserAuth.create(credentials(malformed), 30)).rejects.toThrow(/invalid secret/u) + + const nonString = new RecordCredentials() + nonString.record = { kind: 'grant', payload: { version: 1, secret: 42 } } + await expect(BrowserAuth.create(credentials(nonString), 30)).rejects.toThrow(/invalid secret/u) + + const discarded = new RecordCredentials() + discarded.discardWrites = true + await expect(BrowserAuth.create(credentials(discarded), 30)).rejects.toThrow(/was not created/u) + + await expect(BrowserAuth.create(credentials(new RecordCredentials()), Number.MAX_SAFE_INTEGER)) + .rejects.toThrow(/safe timestamp range/u) + }) +}) diff --git a/packages/client/connection/tests/node-half.host.spec.ts b/packages/client/connection/tests/node-half.host.spec.ts index 504e50d9fd..a175a7f005 100644 --- a/packages/client/connection/tests/node-half.host.spec.ts +++ b/packages/client/connection/tests/node-half.host.spec.ts @@ -12,6 +12,7 @@ import { RpcId, type ClientRequest } from '@deepseek-ai/dsh-host-apiproxy/api' import type { WebServer, WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' import { API_PATH, apply, inject, type HostConnectionHandle } from '../src/index.ts' import { DEFAULT_MAX_REQUEST_BODY_BYTES } from '../src/http-bridge.ts' +import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts' /** Structural webServer fake recording both route registries. */ function fakeHttpServer( @@ -57,12 +58,19 @@ function fakeRawPost(headers: Record, url: string, body: string) } /** Response recorder compatible with both the fence's short-circuit and the bridge. */ -function fakeResponse(): { response: ServerResponse; state: { status?: number; body?: unknown } } { - const state: { status?: number; body?: unknown } = {} +function fakeResponse(): { + response: ServerResponse + state: { status?: number; headers?: Record; body?: unknown } +} { + const state: { status?: number; headers?: Record; body?: unknown } = {} const chunks: Buffer[] = [] const response = Object.assign(new EventEmitter(), { writableEnded: false, - writeHead(value: number) { state.status = value; return this }, + writeHead(value: number, headers?: Record) { + state.status = value + if (headers !== undefined) state.headers = headers + return this + }, write(value: string | Uint8Array) { chunks.push(Buffer.from(value)); return true }, end(this: { writableEnded: boolean }, value?: unknown) { if (typeof value === 'string' || value instanceof Uint8Array) chunks.push(Buffer.from(value)) @@ -84,6 +92,7 @@ async function mounted(config?: { trustedHosts?: string[] }): Promise<{ const ctx = new Context() const routes: WebRoute[] = [] const upgrades: WebUpgradeRoute[] = [] + await ctx.plugin(MemoryCredentials) ctx.provide('webServer', fakeHttpServer(routes, upgrades) as WebServer) ctx.provide('apiProxy', {} as unknown as ApiProxy) const fiber = ctx.plugin({ inject: [...inject], apply }, config) @@ -96,13 +105,26 @@ async function mounted(config?: { trustedHosts?: string[] }): Promise<{ } } +/** Exchange a service's process token for one authority-bound Cookie header. */ +async function browserCookie(connection: HostConnectionHandle, authority: string): Promise { + const url = new URL(connection.authenticatedUrl(`http://${authority}`)) + const exchanged = fakeResponse() + await connection.authorizeIndex( + fakeRequest({ host: authority }, `${url.pathname}${url.search}`), + exchanged.response, + ) + const setCookie = exchanged.state.headers?.['set-cookie'] + if (setCookie === undefined) throw new Error('browser token exchange did not set a cookie') + return setCookie.split(';', 1)[0]! +} + describe('connection node half', () => { it('reserves enough default carrier capacity for the 200 MiB image batch', () => { expect(DEFAULT_MAX_REQUEST_BODY_BYTES).toBe(300 * 1024 * 1024) expect(DEFAULT_MAX_REQUEST_BODY_BYTES).toBeGreaterThan(Math.ceil(200 * 1024 * 1024 * 4 / 3) + 1024 * 1024) }) - it('fails loud when the carrier cap cannot hold the configured image batch', () => { + it('fails loud when the carrier cap cannot hold the configured image batch', async () => { const ctx = new Context() const routes: WebRoute[] = [] ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) @@ -110,8 +132,8 @@ describe('connection node half', () => { imageLimits: { maxMessageImageBytes: 20 * 1024 * 1024 }, } as AttachmentStore) ctx.provide('apiProxy', {} as ApiProxy) - expect(() => { apply(ctx, { maxRequestBodyBytes: 1024 }) }) - .toThrow(/must be at least .* aggregate image limit/) + await expect(apply(ctx, { maxRequestBodyBytes: 1024 })) + .rejects.toThrow(/must be at least .* aggregate image limit/) expect(routes).toHaveLength(0) }) @@ -119,6 +141,7 @@ describe('connection node half', () => { const routes: WebRoute[] = [] const upgrades: WebUpgradeRoute[] = [] const ctx = new Context() + await ctx.plugin(MemoryCredentials) ctx.provide('webServer', fakeHttpServer(routes, upgrades) as WebServer) ctx.provide('apiProxy', {} as unknown as ApiProxy) const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.internal/path'] }) @@ -148,72 +171,83 @@ describe('connection node half', () => { await dispose() }) - it('pins privileged methods to loopback even for a declared trusted authority', async () => { - const { routes, dispose } = await mounted({ trustedHosts: ['harness.example'] }) - // The privileged set: native dialogs plus the whole settings/credential - // configuration plane, reads included, plus the one method that makes the - // host fetch a caller-chosen URL. The same declared authority reaches - // ordinary reads (carrier-level 404 from the empty proxy proves the fence - // passed), but each privileged method stays loopback-only and 403s. - for (const method of [ + it('requires the same browser session for every method on every trusted authority', async () => { + const { routes, connection, dispose } = await mounted({ trustedHosts: ['harness.example'] }) + const methods = [ 'host.pickDirectory', 'host.openPath', - 'settings.describe', 'settings.openDocument', 'settings.update', 'settings.replace', 'settings.mutate', - 'credentials.describe', 'credentials.set', 'credentials.unset', - 'llm.discoverModels', - // A composition names the plugins a session runs: reading one is - // reconnaissance, and copy/remove/openDocument manage the roster and - // drive the host desktop. - 'agentPreset.read', 'agentPreset.copy', 'agentPreset.openDocument', 'agentPreset.remove', - ]) { + 'settings.describe', 'settings.update', 'credentials.describe', 'credentials.set', + 'llm.discoverModels', 'llm.models', 'agentPreset.read', 'agentPreset.list', + ] + for (const method of methods) { const denied = fakeResponse() - await routes[0]!.handler( - fakeRequest({ host: 'harness.example' }, `${API_PATH}/${method}`), - denied.response, - ) - expect(denied.state.status).toBe(403) - expect(denied.state.body).toBe('forbidden') + await routes[0]!.handler(fakeRequest({ host: 'harness.example' }, `${API_PATH}/${method}`), denied.response) + expect([method, denied.state.status, denied.state.body]).toEqual([method, 401, 'unauthorized']) } - const read = fakeResponse() - await routes[0]!.handler(fakeRequest({ host: 'harness.example' }), read.response) - expect(read.state.status).not.toBe(403) + + const cookie = await browserCookie(connection, 'harness.example') + for (const method of methods) { + const allowed = fakeResponse() + await routes[0]!.handler( + fakeRequest({ host: 'harness.example', cookie }, `${API_PATH}/${method}`), + allowed.response, + ) + expect([method, allowed.state.status]).toEqual([method, 404]) + } + + const forged = fakeResponse() + await routes[0]!.handler(fakeRequest({ host: 'localhost:3080' }), forged.response) + expect(forged.state).toMatchObject({ status: 401, body: 'unauthorized' }) await dispose() }) it('passes loopback and declared-authority requests through to the bridge', async () => { - const { routes, dispose } = await mounted({ trustedHosts: ['harness.example:3080', '192.168.1.5'] }) + const { routes, connection, dispose } = await mounted({ trustedHosts: ['harness.example:3080', '192.168.1.5'] }) // Loopback, no browser markers (curl shape): the fence passes; the carrier // answers 404 for a GET unary path — proof the bridge ran. const loopback = fakeResponse() - await routes[0]!.handler(fakeRequest({ host: '127.0.0.1:3080' }), loopback.response) + await routes[0]!.handler(fakeRequest({ + host: '127.0.0.1:3080', + cookie: await browserCookie(connection, '127.0.0.1:3080'), + }), loopback.response) expect(loopback.state.status).toBe(404) // An all-interfaces composition derives port-less LAN IP literals, which // pass markerless curl on any port. const lan = fakeResponse() - await routes[0]!.handler(fakeRequest({ host: '192.168.1.5:3080' }), lan.response) + await routes[0]!.handler(fakeRequest({ + host: '192.168.1.5:3080', + cookie: await browserCookie(connection, '192.168.1.5:3080'), + }), lan.response) expect(lan.state.status).toBe(404) // Declared public authority, same-origin browser shape. const declared = fakeResponse() await routes[0]!.handler(fakeRequest({ - host: 'harness.example:3080', origin: 'http://harness.example:3080', 'sec-fetch-site': 'same-origin', + host: 'harness.example:3080', + origin: 'http://harness.example:3080', + 'sec-fetch-site': 'same-origin', + cookie: await browserCookie(connection, 'harness.example:3080'), }), declared.response) expect(declared.state.status).toBe(404) await dispose() }) - it('shares its configured trust policy with sibling routes', async () => { + it('shares its configured trust and authentication policy with sibling routes', async () => { const { connection, dispose } = await mounted({ trustedHosts: ['harness.example'] }) const loopback = fakeRequest({ host: '127.0.0.1:3080' }) const declared = fakeRequest({ host: 'harness.example' }) - expect(connection.isTrustedRequest(loopback, 'loopback')).toBe(true) - expect(connection.isTrustedRequest(declared, 'loopback')).toBe(false) - expect(connection.isTrustedRequest(declared, 'trusted-host')).toBe(true) + expect(await connection.requestRejection(loopback)).toBe(401) + expect(await connection.requestRejection(declared)).toBe(401) + expect(await connection.requestRejection(fakeRequest({ + host: 'harness.example', + cookie: await browserCookie(connection, 'harness.example'), + }))).toBeUndefined() await dispose() }) it('provides a disposable dedicated RPC channel without requiring apiProxy', async () => { const ctx = new Context() const routes: WebRoute[] = [] + await ctx.plugin(MemoryCredentials) ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() @@ -225,7 +259,7 @@ describe('connection node half', () => { const remove = connection.rpc.handle('/rpc', async (endpoint, payload) => { calls.push({ endpoint, payload }) return { ok: true, value: { accepted: true } } - }, { authority: 'trusted-host' }) + }) const route = routes.find(candidate => candidate.path === '/rpc') expect(route).toBeDefined() @@ -236,7 +270,10 @@ describe('connection node half', () => { payload: { args: { agentId: 'agent-1' } }, } const result = fakeResponse() - await route!.handler(fakePost({ host: '127.0.0.1:3080' }, '/rpc/goals/create', request), result.response) + await route!.handler(fakePost({ + host: '127.0.0.1:3080', + cookie: await browserCookie(connection, '127.0.0.1:3080'), + }, '/rpc/goals/create', request), result.response) expect(result.state.status).toBe(200) expect(JSON.parse(String(result.state.body))).toEqual({ type: 'server-response', @@ -248,9 +285,8 @@ describe('connection node half', () => { payload: { args: { agentId: 'agent-1' } }, }]) - expect(() => connection.rpc.handle('/rpc', async () => ({ ok: true, value: null }), { - authority: 'trusted-host', - })).toThrow(/duplicate route/) + expect(() => connection.rpc.handle('/rpc', async () => ({ ok: true, value: null }))) + .toThrow(/duplicate route/) await remove() expect(routes.map(candidate => candidate.path)).toEqual([API_PATH]) await fiber.dispose() @@ -260,6 +296,7 @@ describe('connection node half', () => { it('dispatches claimed /api endpoints before the API Proxy fallback and withdraws the claim', async () => { const ctx = new Context() const routes: WebRoute[] = [] + await ctx.plugin(MemoryCredentials) ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) ctx.provide('apiProxy', {} as unknown as ApiProxy) const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] }) @@ -273,19 +310,16 @@ describe('connection node half', () => { calls.push({ endpoint, payload }) return { ok: true, value: { accepted: true } } }, - { authority: 'trusted-host' }, ) expect(() => connection.rpc.intercept( '/api', () => true, async () => ({ ok: true, value: null }), - { authority: 'trusted-host' }, )).toThrow('already has an interceptor') expect(() => connection.rpc.intercept( '/rpc' as '/api', () => true, async () => ({ ok: true, value: null }), - { authority: 'trusted-host' }, )).toThrow('invalid shared RPC channel') const route = routes.find(candidate => candidate.path === API_PATH)! const request: ClientRequest = { @@ -296,7 +330,10 @@ describe('connection node half', () => { } const claimed = fakeResponse() - await route.handler(fakePost({ host: '127.0.0.1:3080' }, '/api/goals/create', request), claimed.response) + const loopbackCookie = await browserCookie(connection, '127.0.0.1:3080') + await route.handler(fakePost({ + host: '127.0.0.1:3080', cookie: loopbackCookie, + }, '/api/goals/create', request), claimed.response) expect(JSON.parse(String(claimed.state.body))).toEqual({ type: 'server-response', rpcId: 'rpc-shared', @@ -313,31 +350,38 @@ describe('connection node half', () => { expect(calls).toHaveLength(1) const unclaimed = fakeResponse() - await route.handler(fakeRequest({ host: '127.0.0.1:3080' }, '/api/session.list'), unclaimed.response) + await route.handler(fakeRequest({ + host: '127.0.0.1:3080', cookie: loopbackCookie, + }, '/api/session.list'), unclaimed.response) expect(unclaimed.state.status).toBe(404) await remove() const withdrawn = fakeResponse() - await route.handler(fakePost({ host: '127.0.0.1:3080' }, '/api/goals/create', request), withdrawn.response) + await route.handler(fakePost({ + host: '127.0.0.1:3080', cookie: loopbackCookie, + }, '/api/goals/create', request), withdrawn.response) expect(withdrawn.state.status).toBe(404) expect(calls).toHaveLength(1) - const removeLoopback = connection.rpc.intercept( + const removeAuthenticated = connection.rpc.intercept( '/api', endpoint => endpoint === 'goals/create', async () => ({ ok: true, value: null }), - { authority: 'loopback' }, ) - const loopbackOnly = fakeResponse() - await route.handler(fakePost({ host: 'harness.example' }, '/api/goals/create', request), loopbackOnly.response) - expect(loopbackOnly.state.status).toBe(403) - await removeLoopback() + const declared = fakeResponse() + await route.handler(fakePost({ + host: 'harness.example', + cookie: await browserCookie(connection, 'harness.example'), + }, '/api/goals/create', request), declared.response) + expect(declared.state.status).toBe(200) + await removeAuthenticated() await fiber.dispose() }) it('applies the configured trust fence and JSON envelope checks to generic channels', async () => { const ctx = new Context() const routes: WebRoute[] = [] + await ctx.plugin(MemoryCredentials) ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] }) await fiber.await() @@ -345,17 +389,23 @@ describe('connection node half', () => { const remove = connection.rpc.handle('/rpc', async (endpoint) => { if (endpoint === 'fail') throw new Error('handler broke') return { ok: true, value: null } - }, { - authority: 'trusted-host', }) const route = routes.find(candidate => candidate.path === '/rpc')! + const harnessHeaders = { + host: 'harness.example', + cookie: await browserCookie(connection, 'harness.example'), + } const denied = fakeResponse() await route.handler(fakePost({ host: 'other.example' }, '/rpc/goals/create', {}), denied.response) expect(denied.state).toMatchObject({ status: 403, body: 'forbidden' }) + const unauthenticated = fakeResponse() + await route.handler(fakePost({ host: 'harness.example' }, '/rpc/goals/create', {}), unauthenticated.response) + expect(unauthenticated.state).toMatchObject({ status: 401, body: 'unauthorized' }) + const methodMismatch = fakeResponse() - await route.handler(fakePost({ host: 'harness.example' }, '/rpc/goals/create', { + await route.handler(fakePost(harnessHeaders, '/rpc/goals/create', { type: 'client-request', rpcId: 'rpc-bad', method: 'other', payload: {}, }), methodMismatch.response) expect(JSON.parse(String(methodMismatch.state.body))).toMatchObject({ @@ -364,12 +414,12 @@ describe('connection node half', () => { }) for (const [request, status] of [ - [fakeRequest({ host: 'harness.example' }, '/rpc/goals/create'), 404], - [fakePost({ host: 'harness.example' }, '/outside/goals/create', {}), 404], - [fakePost({ host: 'harness.example' }, '/rpc/goals//create', {}), 404], - [fakeRawPost({ host: 'harness.example' }, '/rpc/goals/create', '{}'), 415], - [fakeRawPost({ host: 'harness.example', 'content-type': 'text/plain' }, '/rpc/goals/create', '{}'), 415], - [fakeRawPost({ host: 'harness.example', 'content-type': 'application/json; charset=utf-8' }, '/rpc/goals/create', '{'), 400], + [fakeRequest(harnessHeaders, '/rpc/goals/create'), 404], + [fakePost(harnessHeaders, '/outside/goals/create', {}), 404], + [fakePost(harnessHeaders, '/rpc/goals//create', {}), 404], + [fakeRawPost(harnessHeaders, '/rpc/goals/create', '{}'), 415], + [fakeRawPost({ ...harnessHeaders, 'content-type': 'text/plain' }, '/rpc/goals/create', '{}'), 415], + [fakeRawPost({ ...harnessHeaders, 'content-type': 'application/json; charset=utf-8' }, '/rpc/goals/create', '{'), 400], ] as const) { const response = fakeResponse() await route.handler(request, response.response) @@ -382,7 +432,7 @@ describe('connection node half', () => { [null, 'invalid-request'], ] as const) { const response = fakeResponse() - await route.handler(fakePost({ host: 'harness.example' }, '/rpc/goals/create', body), response.response) + await route.handler(fakePost(harnessHeaders, '/rpc/goals/create', body), response.response) expect(JSON.parse(String(response.state.body))).toMatchObject({ rpcId, result: { ok: false, error: { code: 'bad-request' } }, @@ -390,28 +440,15 @@ describe('connection node half', () => { } const failed = fakeResponse() - await route.handler(fakePost({ host: 'harness.example' }, '/rpc/fail', { + await route.handler(fakePost(harnessHeaders, '/rpc/fail', { type: 'client-request', rpcId: 'rpc-fail', method: 'fail', payload: {}, }), failed.response) expect(failed.state).toMatchObject({ status: 500, body: 'handler failure: Error: handler broke' }) - expect(() => connection.rpc.handle('/api', async () => ({ ok: true, value: null }), { - authority: 'loopback', - })).toThrow('invalid or reserved RPC channel') - expect(() => connection.rpc.handle('api3', async () => ({ ok: true, value: null }), { - authority: 'loopback', - })).toThrow('invalid or reserved RPC channel') - - const removeLoopback = connection.rpc.handle('/loopback', async () => ({ ok: true, value: null }), { - authority: 'loopback', - }) - const loopbackRoute = routes.find(candidate => candidate.path === '/loopback')! - const publicResponse = fakeResponse() - await loopbackRoute.handler(fakePost({ host: 'harness.example' }, '/loopback/read', { - type: 'client-request', rpcId: 'rpc-public', method: 'read', payload: {}, - }), publicResponse.response) - expect(publicResponse.state.status).toBe(403) - await removeLoopback() + expect(() => connection.rpc.handle('/api', async () => ({ ok: true, value: null }))) + .toThrow('invalid or reserved RPC channel') + expect(() => connection.rpc.handle('api3', async () => ({ ok: true, value: null }))) + .toThrow('invalid or reserved RPC channel') await remove() await fiber.dispose() }) @@ -437,10 +474,16 @@ describe('connection node half over a real HTTP server', () => { } /** One real request; `host` spoofs the authority the way a LAN client's browser would send it. */ - function call(port: number, method: string, host: string): Promise { + function call(port: number, method: string, host: string, cookie?: string): Promise { return new Promise((resolve, reject) => { const request = httpRequest( - { host: '127.0.0.1', port, path: `${API_PATH}/${method}`, method: 'GET', headers: { host } }, + { + host: '127.0.0.1', + port, + path: `${API_PATH}/${method}`, + method: 'GET', + headers: { host, ...cookie === undefined ? {} : { cookie } }, + }, (response) => { response.resume() response.on('end', () => { resolve(response.statusCode ?? 0) }) @@ -451,40 +494,37 @@ describe('connection node half over a real HTTP server', () => { }) } - it('answers a declared LAN authority with 403 on every configuration method, over real HTTP', async () => { - // The fence's input is a real IncomingMessage parsed by Node from the - // wire, not a hand-assembled object: the Host header a LAN browser sends - // is exactly what decides loopback-only here, so the boundary is asserted - // against the parse the server actually performs. - const { routes, dispose } = await mounted({ trustedHosts: ['harness.example'] }) + it('requires authentication uniformly over a real HTTP request', async () => { + // A real IncomingMessage pins the exploit boundary: a client-controlled + // Host naming loopback passes the rebinding fence but never authenticates. + const { routes, connection, dispose } = await mounted({ trustedHosts: ['harness.example'] }) const { port, close } = await serve(routes) try { - // Reads are as privileged as writes: describe returns the exposed - // configuration, and credentials.describe probes arbitrary env-var names. - for (const method of [ + const methods = [ 'settings.describe', 'settings.openDocument', 'settings.update', 'settings.replace', 'settings.mutate', 'credentials.describe', 'credentials.set', 'credentials.unset', 'host.pickDirectory', 'host.openPath', - // Carries a draft credential and turns the host into a fetcher for a - // URL the caller picked: an anonymous LAN caller must not reach it. 'llm.discoverModels', 'agentPreset.read', 'agentPreset.copy', 'agentPreset.openDocument', 'agentPreset.remove', - ]) { - expect([method, await call(port, method, 'harness.example')]).toEqual([method, 403]) + 'llm.providers', 'llm.models', 'agentPreset.list', 'agentPreset.select', + ] + for (const method of methods) { + expect([method, await call(port, method, 'localhost')]).toEqual([method, 401]) + expect([method, await call(port, method, 'harness.example')]).toEqual([method, 401]) } - // The model catalog stays reachable for the same authority: a LAN - // client's model picker needs it, and it carries no key or endpoint - // state (404 is the empty proxy's carrier answer — the fence passed). - // `agentPreset.list` joins the model catalog for the same reason: ids and - // trust only, and a LAN client's preset picker needs it. `select` is - // reachable too: `session.create` already takes an `agentPreset`, and the - // deployment's own default already carries bash, so pinning the switch - // would be a fence beside an open gate. - for (const method of ['llm.providers', 'llm.models', 'agentPreset.list', 'agentPreset.select']) { - expect([method, await call(port, method, 'harness.example')]).toEqual([method, 404]) + expect(await call(port, 'settings.describe', 'other.example')).toBe(403) + + const declaredCookie = await browserCookie(connection, 'harness.example') + for (const method of methods) { + expect([method, await call(port, method, 'harness.example', declaredCookie)]).toEqual([method, 404]) } - // Loopback reaches everything, configuration included. - expect(await call(port, 'settings.describe', `127.0.0.1:${String(port)}`)).toBe(404) + const loopbackAuthority = `127.0.0.1:${String(port)}` + expect(await call( + port, + 'settings.describe', + loopbackAuthority, + await browserCookie(connection, loopbackAuthority), + )).toBe(404) } finally { await close() await dispose() diff --git a/packages/client/connection/tsconfig.host.json b/packages/client/connection/tsconfig.host.json index ed5305797d..ad9bacc704 100644 --- a/packages/client/connection/tsconfig.host.json +++ b/packages/client/connection/tsconfig.host.json @@ -8,6 +8,7 @@ "files": [ "src/api-path.ts", "src/api-request-trust.ts", + "src/browser-auth.ts", "src/http-bridge.ts", "src/index.ts", "src/invariant.ts", @@ -19,6 +20,9 @@ { "path": "../../attachment/attachment" }, + { + "path": "../../credentials/credentials" + }, { "path": "../../host/apiproxy" }, diff --git a/packages/client/locale/README.i18n.yaml b/packages/client/locale/README.i18n.yaml index 096e4ab66a..dca2ac21ab 100644 --- a/packages/client/locale/README.i18n.yaml +++ b/packages/client/locale/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/locale/README.md -README.md: 4f54a9a2c5aa9d39ee3c93a4d8f2c6deb538b792 -README.zh.md: d4c4833b2334c1b21f31e9b6f4d5116bbbb8591d +README.md: 1fa0262e7c1e8aa50f12fd2b7533d97ea4737199 +README.zh.md: 45cf657d5f8455fe128f378c2a2b77d919a441da diff --git a/packages/client/locale/README.md b/packages/client/locale/README.md index 4f54a9a2c5..1fa0262e7c 100644 --- a/packages/client/locale/README.md +++ b/packages/client/locale/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Locale plugin: LocaleRuntime — the `zh`/`en` preference stored as `locale.preference` in `$DSH_HOME/settings.yaml`; when that explicit Host value is absent, a fresh browser starts provisionally in the language `navigator` asks for (primary-subtag matching, with `en` when it asks for no language this app ships). The Host read runs after plugin activation so an unavailable settings service cannot block the page; its result replaces the provisional browser value live. Remote browsers retain only a process-local selection because the settings API is loopback-only. `locale/change` fires on switches, and the plugin points `` at the active locale (`zh-CN`/`en`) on activation and on every switch. The service also owns the ns×locale dictionary registry (typed `register(ns, {zh, en})` checked against `LocaleNamespaceMap`, `bind(ns)`→`TranslateNS`; lookup chain ns → common → en → key), implements the slot system's `LocaleFace`, and installs itself through `ctx.slots.installLocale`, backing the framework-injected `t` standard seat (`Translate`/`TranslateNS` are ui-slots types; import them from there — this package only re-exports for dictionary owners' convenience). Product-authored Client UI text must enter through these typed dictionaries or an already-localized primitive prop; `verify-client-ui-i18n` enforces that source ownership ([decision](../../../.agents/notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.md)). The [Host-backed preferences decision](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md) owns the persistence boundary. +Locale plugin: LocaleRuntime — the `zh`/`en` preference stored as `locale.preference` in `$DSH_HOME/settings.yaml`; when that explicit Host value is absent, a fresh browser starts provisionally in the language `navigator` asks for (primary-subtag matching, with `en` when it asks for no language this app ships). The Host read runs after plugin activation so an unavailable settings service cannot block the page; its result replaces the provisional browser value live. The Client keeps Host settings persistence disabled on non-loopback pages, so their locale selection remains process-local even though Connection authenticates every API method. `locale/change` fires on switches, and the plugin points `` at the active locale (`zh-CN`/`en`) on activation and on every switch. The service also owns the ns×locale dictionary registry (typed `register(ns, {zh, en})` checked against `LocaleNamespaceMap`, `bind(ns)`→`TranslateNS`; lookup chain ns → common → en → key), implements the slot system's `LocaleFace`, and installs itself through `ctx.slots.installLocale`, backing the framework-injected `t` standard seat (`Translate`/`TranslateNS` are ui-slots types; import them from there — this package only re-exports for dictionary owners' convenience). Product-authored Client UI text must enter through these typed dictionaries or an already-localized primitive prop; `verify-client-ui-i18n` enforces that source ownership ([decision](../../../.agents/notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.md)). The [Host-backed preferences decision](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md) owns the persistence boundary. ## Model Experience diff --git a/packages/client/locale/README.zh.md b/packages/client/locale/README.zh.md index d4c4833b23..45cf657d5f 100644 --- a/packages/client/locale/README.zh.md +++ b/packages/client/locale/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -locale 插件:LocaleRuntime——`zh`/`en` 偏好以 `locale.preference` 存储在 `$DSH_HOME/settings.yaml` 中;若没有显式 Host 值,全新浏览器会暂时使用 `navigator` 请求的语言(按主子标签匹配;若其请求的语言本应用都不提供,则使用 `en`)。Host 读取在插件激活后执行,因此 settings 服务不可用不会阻塞页面;读取结果会实时替换浏览器暂定值。settings API 仅限回环请求,因此远程浏览器的选择仅保留在进程内。`locale/change` 仅在切换语言时触发;插件会在激活时以及每次切换时把 `` 指向当前 locale(`zh-CN`/`en`)。该服务还拥有 ns×locale 字典注册表(类型化 `register(ns, {zh, en})` 按 `LocaleNamespaceMap` 校验,`bind(ns)`→`TranslateNS`;查找链 ns → common → en → key),实现 slot 系统的 `LocaleFace`,并经 `ctx.slots.installLocale` 自行安装,支撑框架注入的 `t` 标准席位(`Translate`/`TranslateNS` 是 ui-slots 的类型;请从那里导入——本包的再导出仅为字典所有者提供便利)。产品编写的 Client UI 文本必须经这些 typed 字典或已本地化原子组件 prop 进入展示;`verify-client-ui-i18n` 会强制这项源码归属([决策](../../../.agents/notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.zh.md))。该持久化边界由[Host settings 支撑的偏好决策](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md)拥有。 +locale 插件:LocaleRuntime——`zh`/`en` 偏好以 `locale.preference` 存储在 `$DSH_HOME/settings.yaml` 中;若没有显式 Host 值,全新浏览器会暂时使用 `navigator` 请求的语言(按主子标签匹配;若其请求的语言本应用都不提供,则使用 `en`)。Host 读取在插件激活后执行,因此 settings 服务不可用不会阻塞页面;读取结果会实时替换浏览器暂定值。Client 在非 loopback 页面禁用 Host settings 持久化,因此这些页面的 locale 选择仍只保留在进程内,尽管 Connection 会认证每个 API 方法。`locale/change` 仅在切换语言时触发;插件会在激活时以及每次切换时把 `` 指向当前 locale(`zh-CN`/`en`)。该服务还拥有 ns×locale 字典注册表(类型化 `register(ns, {zh, en})` 按 `LocaleNamespaceMap` 校验,`bind(ns)`→`TranslateNS`;查找链 ns → common → en → key),实现 slot 系统的 `LocaleFace`,并经 `ctx.slots.installLocale` 自行安装,支撑框架注入的 `t` 标准席位(`Translate`/`TranslateNS` 是 ui-slots 的类型;请从那里导入——本包的再导出仅为字典所有者提供便利)。产品编写的 Client UI 文本必须经这些 typed 字典或已本地化原子组件 prop 进入展示;`verify-client-ui-i18n` 会强制这项源码归属([决策](../../../.agents/notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.zh.md))。该持久化边界由[Host settings 支撑的偏好决策](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md)拥有。 ## 模型体验 diff --git a/packages/client/ui-agent-preset/README.i18n.yaml b/packages/client/ui-agent-preset/README.i18n.yaml index 15b1810f04..64d8176b13 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-agent-preset/README.md -README.md: 35b667a1f02cfb56567c71350c117194e08aad6b -README.zh.md: 03420776bd3af6d0c7b6be7a9f88c1db8933901c +README.md: b7cd57fed5ea08e272c97df5bc9e96d481ff6a3a +README.zh.md: 4f828c3eec977a57ea34b20ee21ef23c0c7fc922 diff --git a/packages/client/ui-agent-preset/README.md b/packages/client/ui-agent-preset/README.md index 35b667a1f0..b7cd57fed5 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -50,7 +50,7 @@ A roster row carrying `broken` (the host's shape check found the composition mis Setting the default writes the `agent-presets` settings namespace, which the host exposes to configuration clients ([`dsh-apiproxy`](../../host/apiproxy/README.md) keeps an explicit allowlist — a namespace outside it makes a picker move and then silently forget). -`agentPreset.read`, `copy`, `openDocument`, and `remove` are loopback-pinned ([`dsh-client-connection`](../connection/README.md)): a composition names the plugins a session runs, so reading one is reconnaissance, and the rest manage the roster and drive the host desktop. `agentPreset.list` is not — it carries ids, trust, and the two path-free capability flags, and a LAN client's picker needs it. +[`dsh-client-connection`](../connection/README.md) authenticates `agentPreset.read`, `copy`, `openDocument`, `remove`, `list`, and every other Host API method with the same browser session. A composition still names the plugins a session runs, so reading one is reconnaissance, while copy/remove/openDocument manage the roster and drive the host desktop. ## When the surfaces are absent diff --git a/packages/client/ui-agent-preset/README.zh.md b/packages/client/ui-agent-preset/README.zh.md index 03420776bd..4f828c3eec 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -50,7 +50,7 @@ preset 自行发布描述,长度不限,而网格让每一行卡片等高— 设置默认值写入的是 `agent-presets` settings 命名空间,宿主需将其暴露给配置客户端([`dsh-apiproxy`](../../host/apiproxy/README.zh.md) 维护一份显式白名单——不在其中的命名空间会让选择器动一下然后悄悄忘记)。 -`agentPreset.read`、`copy`、`openDocument` 与 `remove` 被固定在环回地址(见 [`dsh-client-connection`](../connection/README.zh.md)):组装指明了一个会话所运行的插件,因此读取它是侦察,其余几个则管理名单并驱动宿主桌面。`agentPreset.list` 不在其中——它携带 id、信任级别与两个不含路径的能力标志,而局域网客户端的选择器需要它。 +[`dsh-client-connection`](../connection/README.zh.md) 用同一浏览器会话认证 `agentPreset.read`、`copy`、`openDocument`、`remove`、`list` 及其他所有 Host API 方法。组装仍指明一个会话所运行的插件,因此读取它是侦察,而 copy/remove/openDocument 管理名单并驱动宿主桌面。 ## 何时不显示这些表层 diff --git a/packages/client/ui-agent-preset/src/client/settings-store.ts b/packages/client/ui-agent-preset/src/client/settings-store.ts index d0a89f358b..8c7e7444f1 100644 --- a/packages/client/ui-agent-preset/src/client/settings-store.ts +++ b/packages/client/ui-agent-preset/src/client/settings-store.ts @@ -168,7 +168,7 @@ export interface AgentPresetSettingsState { error: string | null /** * Whether this browser may persist the choice at all. `settings.describe` is - * loopback-only and reports a read-only provider as `writable: false`; the + * enabled Host settings path reports a read-only provider as `writable: false`; the * row then shows the current default and disables the control rather than * offering a write the gateway will refuse. */ diff --git a/packages/client/ui-agent-preset/tests/settings-store.client.spec.ts b/packages/client/ui-agent-preset/tests/settings-store.client.spec.ts index 9d7baa26d1..6d66b4ee6d 100644 --- a/packages/client/ui-agent-preset/tests/settings-store.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/settings-store.client.spec.ts @@ -42,7 +42,7 @@ function fakeApi( : { rpcId: 'r', result: { ok: false as const, error: { code: 'internal', message: options.failList, details: {} } } }), }, settings: { - // Loopback-only in production; a read-only provider answers writable:false + // Host persistence is enabled in production only on the selected client path; a read-only provider answers writable:false // and the row disables its control instead of offering a refused write. describe: () => Promise.resolve({ rpcId: 'r', @@ -75,7 +75,7 @@ describe('the agent-preset settings controller', () => { await controller.load() - // `settings.describe` is loopback-only and reports a read-only provider; + // The enabled `settings.describe` path reports a read-only provider; // offering a control whose write answers `settings-rejected` would promise // a switch the host refuses. expect(controller.store.getSnapshot().writable).toBe(false) diff --git a/packages/client/ui-permission-presets/src/client/settings-store.ts b/packages/client/ui-permission-presets/src/client/settings-store.ts index 2f78d7c4b3..2015cfe0b9 100644 --- a/packages/client/ui-permission-presets/src/client/settings-store.ts +++ b/packages/client/ui-permission-presets/src/client/settings-store.ts @@ -168,7 +168,7 @@ export class PermissionPresetSettingsController { if (this.disposed || this.saving) return const mirrored = this.describeFace.getSnapshot() if (mirrored.status === 'unavailable') { - // The terminal non-loopback state: settings RPCs are loopback-only, so + // The terminal non-loopback state: this client keeps Host persistence disabled, so // the row hides itself exactly like an unserved namespace. this.store.update((state) => { state.status = 'unavailable' diff --git a/packages/client/ui-settings-general/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index 77b5c4e2d3..e3ddfd3faf 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings-general/README.md -README.md: c59b77617cfd5848553ba340e97bafe37b7b2a2f -README.zh.md: ea4896284b677a7b430cceb949b53aa6e3a5a242 +README.md: b625f4259869de1449ff18cceeac7f0c6f7c7f0d +README.zh.md: 9381bec1cc0b2a33dd4e8afac20ff6edcfc38dd9 diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md index c59b77617c..b625f42598 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -6,7 +6,7 @@ Settings shell, ownerless copy, and durable product-onboarding namespace. It occ The shell ships no onboarding copy of its own — all text arrives from registrants. Nav labels may be locale-following thunks, so the nav projection resolves them through `resolveSlotLabel` and re-renders on the section ledger bump or the locale revision (an optional `ctx.get('locale')` read; no hard locale dependency). The onboarding ledger projects in ascending order and mounts exactly one step at a time. Visible steps own their dialog chrome and app-root `inert` lifecycle; a mounted step still resolving private facts renders null, so nothing paints or blocks while it decides. The active registrant receives its id, `complete()`, and an `openSection(id)` callback; completing or skipping transfers ownership to the next entry. Registrants own durable completion, capability readiness, copy, mutations, and their visible wrapper, so independently registered flows cannot stack and the shell does not become a second configuration fact source. -A loopback browser loads the provider's `hasDocument` capability through `settings.describe` and renders **Open configuration file** only when the Host confirms that a provider-owned local document can be prepared. The action sends the pathless, loopback-only `settings.openDocument` request; the Host resolves the provider path again, materializes an absent document, and hands it to a native text editor (`open -t` on macOS, bypassing a browser file association; the desktop file association on Linux and Windows; Windows association after `wslpath -w` translation on WSL). Open failures keep the action available and render a localized error. Reopening the dialog or reconnecting refreshes availability after a transient read failure or Host topology change. Remote browsers never register the action and never issue the privileged settings read. +On a loopback page, the Client loads the provider's `hasDocument` capability through `settings.describe` and renders **Open configuration file** only when the Host confirms that a provider-owned local document can be prepared. The action sends the pathless, browser-authenticated `settings.openDocument` request; the Host resolves the provider path again, materializes an absent document, and hands it to a native text editor (`open -t` on macOS, bypassing a browser file association; the desktop file association on Linux and Windows; Windows association after `wslpath -w` translation on WSL). Open failures keep the action available and render a localized error. Reopening the dialog or reconnecting refreshes availability after a transient read failure or Host topology change. Non-loopback pages retain the Client policy that withholds this native action and its settings read. The Host half registers `ui-onboarding` in the user-settings seam. The welcome step contributed by `ui-settings-models` reads and writes its `welcomeNoticeVersion` through the existing public settings boundary; the shell itself remains policy-free. diff --git a/packages/client/ui-settings-general/README.zh.md b/packages/client/ui-settings-general/README.zh.md index ea4896284b..9381bec1cc 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -6,7 +6,7 @@ 外壳不自带引导文案:所有文本都来自注册方。导航 label 可以是跟随语言的 thunk,因此导航投影经 `resolveSlotLabel` 解析,并在分区账本更新或 locale revision 变化时重新渲染(`ctx.get('locale')` 可选读取,无硬 locale 依赖)。首次使用引导记录按升序投影,每次只挂载一个步骤;可见步骤自行持有弹窗框架和应用根节点 `inert` 生命周期。已挂载但仍在判定私有事实的步骤渲染 null,因此判定期间不绘制也不阻塞任何内容。当前注册方会收到该条目的 id、`complete()` 和 `openSection(id)` 回调;完成或跳过当前步骤后,所有权转交给下一项。持久化完成状态、能力就绪状态、文案、变更操作以及可见包装均由注册方持有,因此独立注册的流程无法堆叠,外壳也不会成为第二个配置事实来源。 -回环浏览器通过 `settings.describe` 加载提供方的 `hasDocument` 能力,且只有在 Host 确认可准备好一份由提供方持有的本地文档时才渲染**打开配置文件**。该操作发送无路径参数且仅限回环访问的 `settings.openDocument` 请求;Host 会再次解析提供方路径、在文档缺失时将其创建出来,并交给原生文本编辑器(macOS 上使用 `open -t`,绕过浏览器文件关联;Linux 和 Windows 上使用桌面文件关联;WSL 上经 `wslpath -w` 转换后使用 Windows 文件关联)。打开失败时该操作仍可使用,并渲染本地化错误。临时读取失败或 Host 拓扑变化后,重新打开对话框或重新连接会刷新可用性。远程浏览器从不注册该操作,也从不发起这项特权设置读取。 +在 loopback 页面上,Client 通过 `settings.describe` 加载提供方的 `hasDocument` 能力,且只有在 Host 确认可准备好一份由提供方持有的本地文档时才渲染**打开配置文件**。该操作发送无路径参数且经浏览器认证的 `settings.openDocument` 请求;Host 会再次解析提供方路径、在文档缺失时将其创建出来,并交给原生文本编辑器(macOS 上使用 `open -t`,绕过浏览器文件关联;Linux 和 Windows 上使用桌面文件关联;WSL 上经 `wslpath -w` 转换后使用 Windows 文件关联)。打开失败时该操作仍可使用,并渲染本地化错误。临时读取失败或 Host 拓扑变化后,重新打开对话框或重新连接会刷新可用性。非 loopback 页面保留 Client 策略,不提供该原生操作及其 settings 读取。 宿主端在用户设置 seam 中注册 `ui-onboarding`。`ui-settings-models` 提供的欢迎步骤通过既有公开 settings 边界读写其中的 `welcomeNoticeVersion`;外壳本身仍不持有产品策略。 diff --git a/packages/client/ui-settings-general/tests/apply.client.spec.ts b/packages/client/ui-settings-general/tests/apply.client.spec.ts index c91b608509..d26af3c58a 100644 --- a/packages/client/ui-settings-general/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-general/tests/apply.client.spec.ts @@ -168,7 +168,7 @@ describe('ui-settings-general apply', () => { await vi.waitFor(() => { expect(b.settingsDescribe).toHaveBeenCalledTimes(2) }) }) - it('withholds the loopback-only document action off-loopback', async () => { + it('withholds the Host document action off-loopback', async () => { const b = await bench(false) declare(b.slots) const fiber = b.ctx.plugin({ inject: [...inject], apply }) diff --git a/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts b/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts index 52d2771b0b..efcb2aefdb 100644 --- a/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts +++ b/packages/client/ui-settings-models/tests/welcome-store.client.spec.ts @@ -49,7 +49,7 @@ function buildWelcome( } describe('WelcomeNoticeStore', () => { - it('acknowledges in memory without calling loopback-only settings APIs', async () => { + it('acknowledges in memory while Host settings persistence is disabled', async () => { const describeCall = vi.fn() const mutate = vi.fn() const { controller } = buildWelcome({ describe: describeCall, mutate }, 'memory') diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index c4188a0eaf..98fc9433d0 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings/README.md -README.md: 990469573309b3a92b5eeb8bc41d89b226dbd0d4 -README.zh.md: a0ce9d5cf6d4633cec9fbf466083c7a11a947e8e +README.md: 7e4f3e20ad84e05ee8ec17e37d6922c6d7cf9fce +README.zh.md: cc1c0c6bd94cf770a39d6833ef6efc5d2bd227df diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index 9904695733..7e4f3e20ad 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -15,5 +15,5 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work -- **Remote browsers get no durable settings** — the settings RPCs are loopback-only, so a scope bound in a non-loopback browser starts `unavailable` and never crosses the wire; every row it backs is inert there. +- **Non-loopback pages get no durable settings** — this Client keeps Host persistence disabled there, so a scope starts `unavailable` and never crosses the wire; every row it backs is inert even though Connection authentication covers the API. - **One field per write** — `set` sends a single `set` op, so a row that must move two fields together has no transaction and publishes two revisions. diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index a0ce9d5cf6..cc1c0c6bd9 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -15,5 +15,5 @@ ## 已知限制与暂缓事项 -- **远程浏览器没有持久化设置**:设置 RPC 仅限 loopback,因此在非 loopback 浏览器中绑定的 scope 以 `unavailable` 起步且从不跨线路,它支撑的每一行在那里都是无效的。 +- **非 loopback 页面没有持久化设置**:本 Client 在那里禁用 Host 持久化,因此 scope 以 `unavailable` 起步且从不跨线路;尽管 Connection 认证覆盖 API,它支撑的每一行仍在那里无效。 - **每次写入仅一个字段**:`set` 只发送单个 `set` op,因此需要同时改动两个字段的行没有事务可用,会发布两个 revision。 diff --git a/packages/client/ui-settings/src/client/settings-mirror.ts b/packages/client/ui-settings/src/client/settings-mirror.ts index 81b190e034..bd4aedfc16 100644 --- a/packages/client/ui-settings/src/client/settings-mirror.ts +++ b/packages/client/ui-settings/src/client/settings-mirror.ts @@ -79,7 +79,7 @@ export class SettingsDescribeMirror implements SettingsDescribeFace { /** * @param api - settings wire face. - * @param persistence - remote browsers stay process-local because settings RPCs are loopback-only. + * @param persistence - client-selected Host persistence; non-loopback pages may remain process-local. */ constructor( private readonly api: SettingsFace, diff --git a/packages/client/ui-settings/src/client/settings-scope.ts b/packages/client/ui-settings/src/client/settings-scope.ts index a49b8ba707..1b06940577 100644 --- a/packages/client/ui-settings/src/client/settings-scope.ts +++ b/packages/client/ui-settings/src/client/settings-scope.ts @@ -57,7 +57,7 @@ export class SettingsScopeController implements SettingsScope { * @param api - settings wire face (writes only; reads ride the mirror). * @param spec - namespace identity and optional narrowing decoder. * @param mirror - the shared describe mirror this scope derives from. - * @param persistence - remote browsers remain process-local because settings RPCs are loopback-only. + * @param persistence - client-selected Host persistence; non-loopback pages may remain process-local. * @param schema - settings-owned schema operations. */ constructor( diff --git a/packages/client/ui-theme/README.i18n.yaml b/packages/client/ui-theme/README.i18n.yaml index 9d080a036f..cdc4c96fa1 100644 --- a/packages/client/ui-theme/README.i18n.yaml +++ b/packages/client/ui-theme/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-theme/README.md -README.md: a9f0eb428789bc117e2fcbbdd2366066e0b994cc -README.zh.md: 1447536c3e12a415c3ca241e4fe04a636ecaa6fd +README.md: 0c9bdf3ee3d99aee1e05453e8f455c1309deb284 +README.zh.md: 033bf7867ac19c664e6303377cae545876ade6f1 diff --git a/packages/client/ui-theme/README.md b/packages/client/ui-theme/README.md index a9f0eb4287..0c9bdf3ee3 100644 --- a/packages/client/ui-theme/README.md +++ b/packages/client/ui-theme/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Theme plugin: ThemeRuntime over the --dsw-* token base stylesheets (static scale + alias semantic layers). The service owns the live theme preference (`light`/`dark`/`system`), resolves `system` through `prefers-color-scheme`, and publishes immutable `ThemeSnapshot`s on the `theme/change` event; it never touches the DOM — ui-layout's presenter applies the resolved snapshot (`html { color-scheme }`, `body[data-ds-dark-theme]`, and inline alias tokens). A loopback browser provides the service immediately with `system`, then loads `ui-theme.preference` in the background and writes each built-in selection through the Host settings API, whose local provider stores it in `$DSH_HOME/settings.yaml` by default; pushed settings changes and reconnects refetch it, rapid selections are serialized in gesture order with namespace revisions, and a rejected latest write reloads the durable value. A remote browser cannot access the privileged settings API, so its selection remains process-local. Third-party registered theme ids remain an in-process extension and do not cross the built-in settings schema; removing one never overwrites the last durable built-in preference. The [Host-backed preferences decision](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md) owns the persistence boundary. +Theme plugin: ThemeRuntime over the --dsw-* token base stylesheets (static scale + alias semantic layers). The service owns the live theme preference (`light`/`dark`/`system`), resolves `system` through `prefers-color-scheme`, and publishes immutable `ThemeSnapshot`s on the `theme/change` event; it never touches the DOM — ui-layout's presenter applies the resolved snapshot (`html { color-scheme }`, `body[data-ds-dark-theme]`, and inline alias tokens). A loopback browser provides the service immediately with `system`, then loads `ui-theme.preference` in the background and writes each built-in selection through the Host settings API, whose local provider stores it in `$DSH_HOME/settings.yaml` by default; pushed settings changes and reconnects refetch it, rapid selections are serialized in gesture order with namespace revisions, and a rejected latest write reloads the durable value. The Client keeps Host settings persistence disabled on non-loopback pages, so their selections remain process-local even though Connection authentication applies to every API method. Third-party registered theme ids remain an in-process extension and do not cross the built-in settings schema; removing one never overwrites the last durable built-in preference. The [Host-backed preferences decision](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md) owns the persistence boundary. When the host composition includes an HTTP server, the host half injects a synchronous bootstrap immediately after the opening `` tag. Each index response embeds the registered Host setting for `ui-theme.preference`, or `system` when no settings provider is present; the browser resolves `system` from the OS scheme, then sets `color-scheme` and `body[data-ds-dark-theme]` before the shell loading page renders. Compositions without an HTTP server remain unaffected, and ThemeRuntime and ui-layout remain authoritative for client state and subsequent DOM updates after the plugin tree activates. diff --git a/packages/client/ui-theme/README.zh.md b/packages/client/ui-theme/README.zh.md index 1447536c3e..033bf7867a 100644 --- a/packages/client/ui-theme/README.zh.md +++ b/packages/client/ui-theme/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -主题插件:基于 --dsw-* token 基础样式表(静态尺度 + 别名语义层)的 ThemeRuntime。该服务拥有实时主题偏好(`light`/`dark`/`system`),将 `system` 通过 `prefers-color-scheme` 解析为实际主题,并发布不可变的 `ThemeSnapshot`,通过 `theme/change` 事件通知变化;它绝不接触 DOM:ui-layout 的呈现器会应用解析后的快照(`html { color-scheme }`、`body[data-ds-dark-theme]`,以及主题的别名 token 内联变量)。来自回环地址的浏览器会先以 `system` 立即提供该服务,随后在后台加载 `ui-theme.preference`,并将每次内置主题选择通过 Host settings API 写入;其本地提供方默认将设置存入 `$DSH_HOME/settings.yaml`。收到推送的 settings 变更时或重连后,浏览器都会重新拉取该设置;连续快速选择会按操作顺序携带 namespace revision 串行写入,最新写入被拒时则重新加载持久化值。远程浏览器无法访问特权 settings API,因此它的选择仅保留在进程内。已注册的第三方主题 id 仍是进程内扩展,不会跨越内置 settings schema;移除其中任意一个都绝不会覆盖最后一个持久化的内置偏好。该持久化边界由[Host settings 支撑的偏好决策](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md)拥有。 +主题插件:基于 --dsw-* token 基础样式表(静态尺度 + 别名语义层)的 ThemeRuntime。该服务拥有实时主题偏好(`light`/`dark`/`system`),将 `system` 通过 `prefers-color-scheme` 解析为实际主题,并发布不可变的 `ThemeSnapshot`,通过 `theme/change` 事件通知变化;它绝不接触 DOM:ui-layout 的呈现器会应用解析后的快照(`html { color-scheme }`、`body[data-ds-dark-theme]`,以及主题的别名 token 内联变量)。来自回环地址的浏览器会先以 `system` 立即提供该服务,随后在后台加载 `ui-theme.preference`,并将每次内置主题选择通过 Host settings API 写入;其本地提供方默认将设置存入 `$DSH_HOME/settings.yaml`。收到推送的 settings 变更时或重连后,浏览器都会重新拉取该设置;连续快速选择会按操作顺序携带 namespace revision 串行写入,最新写入被拒时则重新加载持久化值。Client 在非 loopback 页面禁用 Host settings 持久化,因此这些页面的选择仍只保留在进程内,尽管 Connection 会认证每个 API 方法。已注册的第三方主题 id 仍是进程内扩展,不会跨越内置 settings schema;移除其中任意一个都绝不会覆盖最后一个持久化的内置偏好。该持久化边界由[Host settings 支撑的偏好决策](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.zh.md)拥有。 当主机组合包含 HTTP 服务器时,主机侧紧接 `` 起始标签注入同步引导代码。每份 index 响应会嵌入已注册的 Host 设置 `ui-theme.preference`,没有 settings provider 时则嵌入 `system`;浏览器按操作系统配色解析 `system`,随后在外壳加载页面渲染前设置 `color-scheme` 和 `body[data-ds-dark-theme]`。不含 HTTP 服务器的组合不受影响,插件树激活后,ThemeRuntime 与 ui-layout 仍分别是客户端状态和后续 DOM 更新的权威来源。 diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index a369fe508f..c07785d98f 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md -README.md: 4cf11c7ffe55484fd2c27e597931f22f8f861a14 -README.zh.md: 934a00f36ab764f13336e26aea5aa7a274de17e5 +README.md: 69826d76b437ea482655d91a930310185079414c +README.zh.md: c7f5d5b579e20236fe7a9f79ed1db8417b641c64 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 4cf11c7ffe..69826d76b4 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -50,15 +50,15 @@ A stale continuation discards every partial result, deduplication entry, and cur Directory picking delegates to the composed `ctx.directoryPicker` backend ([the directory-picker seam](../directory-picker/README.md)); a method called outside the composed capability's kind fails with `directory-picker-unavailable` (the client needs no advertisement — the composed picker package's own client half renders the matching interaction). Under `native`, `host.pickDirectory` opens one native chooser and returns its selected path (`null` on cancel); this user-paced method does not use the default 30-second unary timeout, while caller/connection aborts still propagate to the native process. Under `browse`, `host.listDirectory` returns one name-sorted directory level with breadcrumb ancestry, a `home` anchor, and host-owned `hidden` flags (absent path = home directory), and `host.createDirectory` creates one validated child segment; the backend's typed failures map 1:1 onto the `directory-unreadable`/`directory-exists`/`directory-create-failed` codes. The browser carrier's prefix-wide trust fence (dsh-client-connection) covers all of these like every other `/api` request. -`host.openPath` opens a filesystem path with the operating system's default application (`open` on macOS, `Invoke-Item` on Windows, and `xdg-open` on desktop Linux). For `.html`, `.htm`, `.xhtml`, and `.svg`, macOS and desktop Linux prefer a named default browser and fall back to that application handoff when none can be named. WSL translates every Linux path through `wslpath -w` and hands the resulting Windows/UNC path to Windows `Invoke-Item`, including browser-renderable documents, instead of assuming a Linux desktop association. `host.describe.home` is the host account home directory. The Web client uses it to display POSIX home-rooted paths as `~`; Windows values are still reported and are not abbreviated. `host.describe.canOpenPath` advertises whether that handoff can reach a user-visible desktop: explicit gateway `nativeOpen` wins, an injected opener is usable by definition, and platform detection otherwise accepts macOS, Windows, WSL, or Linux with a display while rejecting headless/container Linux. The browser carrier applies the same loopback, same-origin restriction as `host.pickDirectory`; clients combine both facts before presenting a native action. +`host.openPath` opens a filesystem path with the operating system's default application (`open` on macOS, `Invoke-Item` on Windows, and `xdg-open` on desktop Linux). For `.html`, `.htm`, `.xhtml`, and `.svg`, macOS and desktop Linux prefer a named default browser and fall back to that application handoff when none can be named. WSL translates every Linux path through `wslpath -w` and hands the resulting Windows/UNC path to Windows `Invoke-Item`, including browser-renderable documents, instead of assuming a Linux desktop association. `host.describe.home` is the host account home directory. The Web client uses it to display POSIX home-rooted paths as `~`; Windows values are still reported and are not abbreviated. `host.describe.canOpenPath` advertises whether that handoff can reach a user-visible desktop: explicit gateway `nativeOpen` wins, an injected opener is usable by definition, and platform detection otherwise accepts macOS, Windows, WSL, or Linux with a display while rejecting headless/container Linux. The browser carrier applies the same Host/Origin checks and signed-cookie authentication as every Host API method; clients combine the capability facts before presenting a native action. The `agentPreset.list` domain exposes the deployment's preset roster so a browser can offer a choice when starting a session; each row carries its `trust` (a `user` preset is exactly as privileged as the plugins it names), whether it is the current default, and — when the preset cannot compose a session — a `broken` reason, because a damaged directory still occupies its id and a surface must be able to show and delete it rather than offer it and fail the session start. A deployment composing no presets answers with an empty roster rather than an error, because sharing the host composition is a valid deployment. `agentPreset.select` recomposes one session's agent from a different preset, and is allowed only while the session is blank: once a turn has run, that history was produced under the preset's tools and swapping them would strand logged tool calls, so the attempt answers `agent-preset-locked`. The agent and the session survive — only the composition is swapped, and a failed swap restores the previous one. -`agentPreset.read`, `copy`, `openDocument`, and `remove` manage the compositions themselves. `read` reports the text with its `trust`, for the read-only viewer. Authoring is copy-only: `copy` takes `{ from, agentPreset, name? }` — two ids the Host resolves against its own roots plus an optional display name — and copies the source's whole directory, so no composition text crosses the wire and a copy is exactly as loadable as its source; an uncontainable or already-taken id answers `agent-preset-invalid`, and `remove` refuses a shipped preset as `agent-preset-read-only`. `openDocument` hands one locally authored preset's DIRECTORY to the platform opener — the request carries an id, never a path, so no browser payload can select an arbitrary filesystem target; where the deployment has no native opener the reply is `{ opened: false, path }` for the surface to show as text, a shipped preset is refused like `remove`, and the gateway's `nativeOpen` config pins the capability where platform detection (`canOpenNativePath`) would mislead. These four are loopback-pinned in [`dsh-client-connection`](../../client/connection/README.md): a composition names the plugins a session runs, so reading one is reconnaissance, and copy/remove/openDocument manage the roster and drive the host desktop. `list` and `select` stay ordinary — the roster carries ids and trust and every preset picker needs it, and choosing a preset grants nothing `session.create`'s own `agentPreset` did not, over a default that already carries bash. `list` reports two path-free capability flags: `authorable`, whether the deployment configures a root a new preset could be copied to, and `hasDocument`, whether `openDocument` would open natively rather than answer a path. +`agentPreset.read`, `copy`, `openDocument`, and `remove` manage the compositions themselves. `read` reports the text with its `trust`, for the read-only viewer. Authoring is copy-only: `copy` takes `{ from, agentPreset, name? }` — two ids the Host resolves against its own roots plus an optional display name — and copies the source's whole directory, so no composition text crosses the wire and a copy is exactly as loadable as its source; an uncontainable or already-taken id answers `agent-preset-invalid`, and `remove` refuses a shipped preset as `agent-preset-read-only`. `openDocument` hands one locally authored preset's DIRECTORY to the platform opener — the request carries an id, never a path, so no browser payload can select an arbitrary filesystem target; where the deployment has no native opener the reply is `{ opened: false, path }` for the surface to show as text, a shipped preset is refused like `remove`, and the gateway's `nativeOpen` config pins the capability where platform detection (`canOpenNativePath`) would mislead. [`dsh-client-connection`](../../client/connection/README.md) authenticates these methods with `list`, `select`, and the complete Host API. A composition still names the plugins a session runs, so reading one is reconnaissance and copy/remove/openDocument manage the roster and drive the host desktop. `list` reports two path-free capability flags: `authorable`, whether the deployment configures a root a new preset could be copied to, and `hasDocument`, whether `openDocument` would open natively rather than answer a path. The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `skill.list` serves the composer's menu: it returns every user-invocable skill with its `modelInvocable` flag, so menus can mark user-only (`disable-model-invocation`) entries whose only invocation path is the slash gesture. Listing is the skill domain's only RPC — invocation itself is an ordinary `session.prompt` whose whitespace-bounded `/name` tokens `dsh-tool-skill` recognizes at the pre-step boundary and answers with injected `` context, so every entry point (Web, TUI, and ACP) shares one deterministic path—including for hand-typed text—with no dedicated invocation wire. `command.execute` runs a slash-command line host-side with pure admission semantics: the response reports whether the line resolved to a handler plus the minted lifecycle `commandId` when it did (correlating the acknowledgment with the flow node), while the outcome rides the durably logged `command/run`/`command/done` lifecycle pair broadcast on the mux stream. Command handlers may legitimately outlast the 30-second transport health deadline, so `command.execute` carries only caller/connection cancellation; that signal cancels the running handler. `commands/change` rides the forwarded-event frame as the registry-wide catalog invalidation signal: clients refetch `command.list` instead of diffing. Forwarded `agent-preset/selected` is its per-session counterpart, emitted from the logged selection commit: recomposing a blank session's agent re-parents its scope without registering anything, so both catalogs that session's composition decides (`command.list`, `skill.list`) go stale with no registry change to announce it. -The `settings.*`, `credentials.*`, and `llm.*` domains are the configuration-page wire. The settings domain serves every registered namespace: a plugin distributed outside this repository becomes browser-configurable by registering its section, with no change here, and this proxy adds no boundary of its own — a name no registration answers folds into the seam's own `settings-rejected`. Which surface renders a namespace is the browser's decision (the plugin configuration page keys its cards on the namespace), never this proxy's. `settings.describe` returns each namespace's serialized schemastery schema, redacted layered values (resolved/`base`/`user` — a field's presence in `user` marks it user-overridden), the `secrets` slot list, the section's `revision`, and the boolean `hasDocument` capability flag. The browser receives no Host path: pathless `settings.openDocument` asks the provider to materialize its document and then hands the Host-resolved result to the native opener, so no browser payload can select any filesystem target. `settings.update`/`settings.replace` write the user layer; `settings.mutate` applies path ops (`set`/`unset`) against the section as stored, which is the removal path for a client holding the redacted view — rebuilding a section from it and replacing wholesale would delete the secrets the wire never returned. Any write may carry `expectedRevision`; a stale one answers `settings-conflict` with both revisions rather than overwriting the writer that landed first, and every other seam refusal folds into `settings-rejected`. Secret-role values never ride any response in any layer; a secret crosses the wire in exactly one direction — inside an `update`/`mutate` payload or `credentials.set`. `credentials.describe` returns value-free views (`configured`/`source`/`writable`), and `credentials.set`/`credentials.unset` map a shadowed-reference refusal onto `credential-rejected`. `llm.providers` merges the configurable-provider directory with live routes (dormant entries carry `active: false`; undeclared live routes append with no settings address) and `llm.models` is the session-independent catalog. `llm.discoverModels` interrogates a provider endpoint the page is still drafting: `settingsNs` selects the adapter family that knows how to read the listing, and the endpoint, protocol, and key come from the form rather than from storage. It writes nothing — the reply is candidates, and only a later `settings.mutate` decides what a route serves — so its `apiKey` is the third payload on which a secret may ride, alongside `settings.update`/`mutate` and `credentials.set`. The host never stores or returns it; like the other two it does ride the client's outgoing envelope, which `subscribeEnvelopes()` observers can see, and redacting that tap is a configuration-plane-wide change rather than this method's to make alone. Every refusal (an unserved namespace, a protocol with no readable listing, an unreachable endpoint, a rejected credential) folds into `model-discovery-failed`, whose message is the adapter's own text and whose details name the endpoint asked but never the credential offered. Invalidations keep every surface converged without polling. `settings/document-updated` and `credentials/reference-updated` ride the verbatim forwarded-event frame (see below), so a raw settings change whose resolved value is unchanged still reaches clients, and a credential invalidation still carries reference names only, never values. `llm/adapters-updated` is forwarded beside `settings/document-updated`; concrete model consumers subscribe to both owner events directly because topology commits and settings documents can independently change their directories. The browser carrier restricts the whole configuration plane, reads and native actions included (`settings.describe`/`openDocument`/`update`/`replace`/`mutate`, `credentials.describe`/`set`/`unset`), to loopback same-origin requests — the `host.pickDirectory` privileged set. A composition without a settings or credential provider answers those domains with an actionable `internal` error naming the missing plugin. +The `settings.*`, `credentials.*`, and `llm.*` domains are the configuration-page wire. The settings domain serves every registered namespace: a plugin distributed outside this repository becomes browser-configurable by registering its section, with no change here, and this proxy adds no boundary of its own — a name no registration answers folds into the seam's own `settings-rejected`. Which surface renders a namespace is the browser's decision (the plugin configuration page keys its cards on the namespace), never this proxy's. `settings.describe` returns each namespace's serialized schemastery schema, redacted layered values (resolved/`base`/`user` — a field's presence in `user` marks it user-overridden), the `secrets` slot list, the section's `revision`, and the boolean `hasDocument` capability flag. The browser receives no Host path: pathless `settings.openDocument` asks the provider to materialize its document and then hands the Host-resolved result to the native opener, so no browser payload can select any filesystem target. `settings.update`/`settings.replace` write the user layer; `settings.mutate` applies path ops (`set`/`unset`) against the section as stored, which is the removal path for a client holding the redacted view — rebuilding a section from it and replacing wholesale would delete the secrets the wire never returned. Any write may carry `expectedRevision`; a stale one answers `settings-conflict` with both revisions rather than overwriting the writer that landed first, and every other seam refusal folds into `settings-rejected`. Secret-role values never ride any response in any layer; a secret crosses the wire in exactly one direction — inside an `update`/`mutate` payload or `credentials.set`. `credentials.describe` returns value-free views (`configured`/`source`/`writable`), and `credentials.set`/`credentials.unset` map a shadowed-reference refusal onto `credential-rejected`. `llm.providers` merges the configurable-provider directory with live routes (dormant entries carry `active: false`; undeclared live routes append with no settings address) and `llm.models` is the session-independent catalog. `llm.discoverModels` interrogates a provider endpoint the page is still drafting: `settingsNs` selects the adapter family that knows how to read the listing, and the endpoint, protocol, and key come from the form rather than from storage. It writes nothing — the reply is candidates, and only a later `settings.mutate` decides what a route serves — so its `apiKey` is the third payload on which a secret may ride, alongside `settings.update`/`mutate` and `credentials.set`. The host never stores or returns it; like the other two it does ride the client's outgoing envelope, which `subscribeEnvelopes()` observers can see, and redacting that tap is a configuration-plane-wide change rather than this method's to make alone. Every refusal (an unserved namespace, a protocol with no readable listing, an unreachable endpoint, a rejected credential) folds into `model-discovery-failed`, whose message is the adapter's own text and whose details name the endpoint asked but never the credential offered. Invalidations keep every surface converged without polling. `settings/document-updated` and `credentials/reference-updated` ride the verbatim forwarded-event frame (see below), so a raw settings change whose resolved value is unchanged still reaches clients, and a credential invalidation still carries reference names only, never values. `llm/adapters-updated` is forwarded beside `settings/document-updated`; concrete model consumers subscribe to both owner events directly because topology commits and settings documents can independently change their directories. Connection authenticates the whole configuration plane, reads and native actions included, with the same browser session as every Host API method. A composition without a settings or credential provider answers those domains with an actionable `internal` error naming the missing plugin. ## Carrier layer (`/client` + root) diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 934a00f36a..c7f5d5b579 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -50,15 +50,15 @@ Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.cr 目录选择委托给组合的 `ctx.directoryPicker` 后端([目录选择 seam](../directory-picker/README.zh.md));调用组合能力 kind 之外的方法会以 `directory-picker-unavailable` 失败(客户端不需要广播——组合的选择器包自己的 client half 渲染匹配的交互)。在 `native` 下,`host.pickDirectory` 打开一个原生选择器并返回选中路径(取消为 `null`);该方法需等待用户完成操作,不使用默认的 30 秒一元调用超时,而调用方与连接的中止仍会传播至原生进程。在 `browse` 下,`host.listDirectory` 返回一个按名称排序的目录层级,携带面包屑祖先链、`home` 锚点与宿主判定的 `hidden` 标志(不带路径即家目录),`host.createDirectory` 创建一个经校验的子段;后端的类型化失败 1:1 映射为 `directory-unreadable`/`directory-exists`/`directory-create-failed` 错误码。浏览器载体的前缀级信任栅栏(dsh-client-connection)像覆盖其他所有 `/api` 请求一样覆盖上述全部方法。 -`host.openPath` 会用操作系统的默认应用打开一个文件系统路径(macOS 为 `open`,Windows 为 `Invoke-Item`,桌面 Linux 为 `xdg-open`)。对于 `.html`、`.htm`、`.xhtml` 与 `.svg`,macOS 和桌面 Linux 会优先使用能够确定的默认浏览器;无法确定时回退到上述应用交接。WSL 会通过 `wslpath -w` 转换每个 Linux 路径,并将所得 Windows/UNC 路径交给 Windows `Invoke-Item`,浏览器可渲染的文档也不例外,而非假定存在 Linux 桌面文件关联。`host.describe.home` 是宿主账户的家目录。Web 客户端用它把 POSIX 家目录路径显示为 `~`;Windows 值仍会上报,但不会缩写。`host.describe.canOpenPath` 会宣告这次交接能否抵达用户可见的桌面:网关显式配置的 `nativeOpen` 优先,注入的 opener 按定义可用,否则平台检测接受 macOS、Windows、WSL 或带 display 的 Linux,并拒绝 headless/容器 Linux。浏览器载体对其施加与 `host.pickDirectory` 相同的回环、同源限制;客户端会组合这两个事实后再呈现原生操作。 +`host.openPath` 会用操作系统的默认应用打开一个文件系统路径(macOS 为 `open`,Windows 为 `Invoke-Item`,桌面 Linux 为 `xdg-open`)。对于 `.html`、`.htm`、`.xhtml` 与 `.svg`,macOS 和桌面 Linux 会优先使用能够确定的默认浏览器;无法确定时回退到上述应用交接。WSL 会通过 `wslpath -w` 转换每个 Linux 路径,并将所得 Windows/UNC 路径交给 Windows `Invoke-Item`,浏览器可渲染的文档也不例外,而非假定存在 Linux 桌面文件关联。`host.describe.home` 是宿主账户的家目录。Web 客户端用它把 POSIX 家目录路径显示为 `~`;Windows 值仍会上报,但不会缩写。`host.describe.canOpenPath` 会宣告这次交接能否抵达用户可见的桌面:网关显式配置的 `nativeOpen` 优先,注入的 opener 按定义可用,否则平台检测接受 macOS、Windows、WSL 或带 display 的 Linux,并拒绝 headless/容器 Linux。浏览器载体对其施加与每个 Host API 方法相同的 Host/Origin 校验和签名 cookie 认证;客户端会组合能力事实后再呈现原生操作。 `agentPreset.list` 领域向浏览器暴露部署的 preset 名单,使其在开启会话时能够提供选择;每一行携带它的 `trust`(`user` preset 的权限恰好等于它所引用的插件)、它是否为当前默认值,以及——当该 preset 无法组装会话时——一条 `broken` 原因:损坏的目录仍占着它的 id,界面必须能展示并删除它,而不是把它端出来然后在会话启动时失败。未组装任何 preset 的部署返回空名单而非错误,因为共用宿主组装本身就是一种有效部署。`agentPreset.select` 用另一个 preset 重组某个会话的 agent,且仅在会话空白时允许:一旦跑过任何轮次,那段历史就是在该 preset 的工具下产生的,替换会留下无法执行的已记录的工具调用,此时返回 `agent-preset-locked`。agent 与会话都不销毁——只替换组装,且替换失败会恢复原来的组装。 -`agentPreset.read`、`copy`、`openDocument` 与 `remove` 负责管理组装本身。`read` 返回文本连同它的 `trust`,供只读查看器使用。创作只有复制一种写入:`copy` 接收 `{ from, agentPreset, name? }`——两个由 Host 对照自身根目录解析的 id 加一个可选显示名——并整目录复制来源,因此组装文本不经过传输层,副本与其来源同等可加载;不可约束或已被占用的 id 回答 `agent-preset-invalid`,`remove` 对随附 preset 回答 `agent-preset-read-only`。`openDocument` 把一个本地创作 preset 的**目录**交给平台打开器——请求只携带 id、绝不携带路径,因此没有任何浏览器载荷能选中任意文件系统目标;部署没有原生打开器时回答 `{ opened: false, path }` 供界面以文本展示,随附 preset 与 `remove` 一样被拒绝,而网关的 `nativeOpen` 配置可在平台探测(`canOpenNativePath`)失真处钉死该能力。这四个方法在 [`dsh-client-connection`](../../client/connection/README.zh.md) 中被固定在环回地址:组装指明了一个会话所运行的插件,因此读取它是侦察,而 copy/remove/openDocument 管理名单并驱动宿主桌面。`list` 与 `select` 保持为普通方法——名单只携带 id 与信任级别,每个 preset 选择器都需要它;而选择一个 preset 并不比 `session.create` 自带的 `agentPreset` 多给任何能力,何况默认 preset 本就带着 bash。`list` 报告两个不含路径的能力标志:`authorable`,即部署是否配置了可供复制新 preset 的根目录;`hasDocument`,即 `openDocument` 会原生打开、还是回答一个路径。 +`agentPreset.read`、`copy`、`openDocument` 与 `remove` 负责管理组装本身。`read` 返回文本连同它的 `trust`,供只读查看器使用。创作只有复制一种写入:`copy` 接收 `{ from, agentPreset, name? }`——两个由 Host 对照自身根目录解析的 id 加一个可选显示名——并整目录复制来源,因此组装文本不经过传输层,副本与其来源同等可加载;不可约束或已被占用的 id 回答 `agent-preset-invalid`,`remove` 对随附 preset 回答 `agent-preset-read-only`。`openDocument` 把一个本地创作 preset 的**目录**交给平台打开器——请求只携带 id、绝不携带路径,因此没有任何浏览器载荷能选中任意文件系统目标;部署没有原生打开器时回答 `{ opened: false, path }` 供界面以文本展示,随附 preset 与 `remove` 一样被拒绝,而网关的 `nativeOpen` 配置可在平台探测(`canOpenNativePath`)失真处钉死该能力。[`dsh-client-connection`](../../client/connection/README.zh.md) 用与 `list`、`select` 及完整 Host API 相同的浏览器会话认证这些方法。组装仍指明一个会话所运行的插件,因此读取它是侦察,而 copy/remove/openDocument 管理名单并驱动宿主桌面。`list` 报告两个不含路径的能力标志:`authorable`,即部署是否配置了可供复制新 preset 的根目录;`hasDocument`,即 `openDocument` 会原生打开、还是回答一个路径。 `command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和 skill(技能)目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`skill.list` 服务于 composer 的菜单:它返回每一个用户可调用的 skill 及其 `modelInvocable` 标志,让菜单能够标出仅限用户(`disable-model-invocation`)的条目——斜杠手势是这类条目唯一的调用路径。列表是 skill 领域唯一的 RPC——调用本身就是一次普通的 `session.prompt`,`dsh-tool-skill` 会在 pre-step 边界识别其中以空白为界的 `/name` token,并以注入的 `` 上下文作答,因此所有入口(Web、TUI 与 ACP(Agent Client Protocol))共享同一条确定性路径,手动键入的文本也走该路径,且没有专设的调用协议。`command.execute` 在宿主侧运行一条斜杠命令行,语义为纯准入:响应报告该行是否解析到处理器,并在解析到时回带铸造的生命周期 `commandId`(将本次确认与流节点关联);结局经由持久落账并在 mux 流广播的 `command/run`/`command/done` 生命周期事件对承载。命令处理器运行超过 30 秒的传输健康时限仍属正常,因此 `command.execute` 仅携带调用方/连接取消信号;该信号可取消正在运行的处理器。`commands/change` 搭乘转发事件帧作为注册表级目录失效信号:客户端重新拉取 `command.list` 而不是做差分。转发的 `agent-preset/selected` 是它按会话粒度的对应物,由落账的选择提交点发出:重组空会话的 agent 只是重新挂接其 scope,不产生任何注册,因此该会话组成所决定的两份目录(`command.list`、`skill.list`)都会失效,却没有任何注册表变化来宣告它。 -`settings.*`、`credentials.*` 与 `llm.*` 领域是配置页协议。settings 领域服务于每一个已注册 namespace:在本仓库之外分发的插件只要注册自己的分节即可变得可从浏览器配置,无需改动这里;本代理也不再自设边界——没有任何注册应答的名字会折叠为 seam 自己的 `settings-rejected`。由哪个界面渲染某个 namespace 是浏览器的决定(插件配置页按 namespace 为其卡片编键),从不由本代理决定。`settings.describe` 为每个 namespace 提供其序列化 schemastery schema、脱敏后的分层值(resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表、该分节的 `revision`,以及布尔型 `hasDocument` 能力标志。浏览器不会收到 Host 路径:无路径参数的 `settings.openDocument` 会请求提供方准备文档,再把由 Host 解析出的结果交给原生打开器,因此任何浏览器载荷都无法选择任意文件系统目标。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op(`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;陈旧的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应;secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable`),`credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected`。`llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。`llm.discoverModels` 询问页面尚在起草的提供方端点:`settingsNs` 选出懂得读取该列表的适配器家族,端点、协议与密钥则来自表单而非存储。它什么都不写——回复是候选,只有随后的 `settings.mutate` 才决定路由服务什么——因此其 `apiKey` 是 secret 可以搭乘的第三个载荷(另两个是 `settings.update`/`mutate` 与 `credentials.set`),且绝不被存储或回显。host 从不存储或回传它;与另两者一样,它确实会搭乘客户端的出站信封,`subscribeEnvelopes()` 的观察者能看到——为该 tap 做脱敏是整个配置面的改动,而非本方法一家的事。每一种拒绝(无人服务的 namespace、没有可读列表的协议、不可达端点、被拒凭据)都折叠为 `model-discovery-failed`,其消息是适配器自己的文本,details 点名被询问的端点,绝不点名所提供的凭据。失效通知让每个面无需轮询即保持收敛。`settings/document-updated` 与 `credentials/reference-updated` 搭乘原样转发事件帧(见下),因此解析值未变的原始设置变更同样能到达客户端,凭据失效通知也仍然只带引用名、绝不带值。`llm/adapters-updated` 与 `settings/document-updated` 一并原样转发;具体模型消费方直接订阅这两个 owner 事件,因为拓扑提交和设置文档都能独立改变其目录。浏览器载体把整个配置面(含读取与原生操作:`settings.describe`/`openDocument`/`update`/`replace`/`mutate` 与 `credentials.describe`/`set`/`unset`)限制为仅接受来自回环地址的同源请求——即 `host.pickDirectory` 所在的特权集合。未装 settings 或凭据提供方的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。 +`settings.*`、`credentials.*` 与 `llm.*` 领域是配置页协议。settings 领域服务于每一个已注册 namespace:在本仓库之外分发的插件只要注册自己的分节即可变得可从浏览器配置,无需改动这里;本代理也不再自设边界——没有任何注册应答的名字会折叠为 seam 自己的 `settings-rejected`。由哪个界面渲染某个 namespace 是浏览器的决定(插件配置页按 namespace 为其卡片编键),从不由本代理决定。`settings.describe` 为每个 namespace 提供其序列化 schemastery schema、脱敏后的分层值(resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表、该分节的 `revision`,以及布尔型 `hasDocument` 能力标志。浏览器不会收到 Host 路径:无路径参数的 `settings.openDocument` 会请求提供方准备文档,再把由 Host 解析出的结果交给原生打开器,因此任何浏览器载荷都无法选择任意文件系统目标。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op(`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;陈旧的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应;secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable`),`credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected`。`llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。`llm.discoverModels` 询问页面尚在起草的提供方端点:`settingsNs` 选出懂得读取该列表的适配器家族,端点、协议与密钥则来自表单而非存储。它什么都不写——回复是候选,只有随后的 `settings.mutate` 才决定路由服务什么——因此其 `apiKey` 是 secret 可以搭乘的第三个载荷(另两个是 `settings.update`/`mutate` 与 `credentials.set`),且绝不被存储或回显。host 从不存储或回传它;与另两者一样,它确实会搭乘客户端的出站信封,`subscribeEnvelopes()` 的观察者能看到——为该 tap 做脱敏是整个配置面的改动,而非本方法一家的事。每一种拒绝(无人服务的 namespace、没有可读列表的协议、不可达端点、被拒凭据)都折叠为 `model-discovery-failed`,其消息是适配器自己的文本,details 点名被询问的端点,绝不点名所提供的凭据。失效通知让每个面无需轮询即保持收敛。`settings/document-updated` 与 `credentials/reference-updated` 搭乘原样转发事件帧(见下),因此解析值未变的原始设置变更同样能到达客户端,凭据失效通知也仍然只带引用名、绝不带值。`llm/adapters-updated` 与 `settings/document-updated` 一并原样转发;具体模型消费方直接订阅这两个 owner 事件,因为拓扑提交和设置文档都能独立改变其目录。Connection 用与每个 Host API 方法相同的浏览器会话认证整个配置面,包括读取与原生操作。未装 settings 或凭据提供方的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。 ## 载体层(`/client` + 根路径) diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index a236782544..1a8835383a 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -745,10 +745,9 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro } }, - // Authoring is privileged (see PRIVILEGED_METHODS in dsh-client-connection): - // a composition names the plugins a session runs, so reading one is + // A composition names the plugins a session runs, so reading one is // reconnaissance, and copy/remove/openDocument manage the roster and - // drive the host desktop. + // drive the host desktop. Connection authenticates the complete API. async read(request) { const { agentPreset } = request.payload const presets = ctx.get('agentPresets') diff --git a/packages/host/apiproxy/src/api/agent-presets.ts b/packages/host/apiproxy/src/api/agent-presets.ts index fe33062df6..3918de5894 100644 --- a/packages/host/apiproxy/src/api/agent-presets.ts +++ b/packages/host/apiproxy/src/api/agent-presets.ts @@ -2,11 +2,11 @@ * agent-presets domain contract: the roster a browser offers when starting a * session, plus the authoring calls behind it. * - * `list` is ordinary: it carries ids and trust, and every preset picker needs - * it. The authoring calls are privileged and loopback-pinned — a composition - * names the plugins a session runs, so reading one is reconnaissance, and - * although authoring is copy-only (no caller supplies composition text or a - * path), copying and deleting still rearrange what the deployment offers. + * A composition names the plugins a session runs, so reading one is + * reconnaissance; although authoring is copy-only (no caller supplies + * composition text or a path), copying and deleting still rearrange what the + * deployment offers. Connection authenticates these calls with the complete + * Host API rather than assigning a separate method tier. */ import type { SessionId } from '@deepseek-ai/dsh-session/types' diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index 5e45fcf3a5..e700b86db3 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -88,8 +88,8 @@ export interface HostApi { /** * Open a filesystem path with the operating system's default application * (Finder / Explorer / xdg-open hand-off). The browser carrier's - * prefix-wide trust fence covers this privileged method like every other - * `/api` request. + * prefix-wide trust and authentication checks cover this method like every + * other `/api` request. */ openPath( request: RpcRequest<{ path: string }>, diff --git a/packages/host/apiproxy/src/api/settings.ts b/packages/host/apiproxy/src/api/settings.ts index 5bbc6d56d9..ec7017eef7 100644 --- a/packages/host/apiproxy/src/api/settings.ts +++ b/packages/host/apiproxy/src/api/settings.ts @@ -55,8 +55,8 @@ export interface SettingsApi { * Describe every registered namespace: redacted layered values plus the * serialized schema a client renders its form from. `hasDocument` reports * whether a file-backed provider owns a local document without exposing its - * Host path. This method is loopback-only; `writable: false` (read-only - * provider) tells the client to disable every write control. + * Host path. Connection requires the browser session used by every Host API + * method; `writable: false` tells the client to disable every write control. */ describe(request: RpcRequest<{}>): Promise { it('serves every registered namespace, including one this repository never named', async () => { // Registering IS the exposure: a plugin distributed outside this // repository configures itself from the browser without a change here. - // The plane stays loopback-only and secret-redacted, and which surface - // renders a namespace is the browser's decision, not this proxy's. + // The plane stays browser-authenticated and secret-redacted, and which + // surface renders a namespace is the browser's decision, not this proxy's. const ctx = await harness() ctx.settings.register(NS, AdapterConfig) ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() })) diff --git a/packages/host/frontend-static/README.i18n.yaml b/packages/host/frontend-static/README.i18n.yaml index 771455e06a..f21081f544 100644 --- a/packages/host/frontend-static/README.i18n.yaml +++ b/packages/host/frontend-static/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/frontend-static/README.md -README.md: e4f3765a0471566dfb2f6780b1072d3e79788dc5 -README.zh.md: 7672478480f07b760634fef0c8640fcbdc0e6e7e +README.md: c541791e667dc07995a91263aa219afb84ee488a +README.zh.md: 76aeaff93db4eb3eb4b098e865acee46776f85c6 diff --git a/packages/host/frontend-static/README.md b/packages/host/frontend-static/README.md index e4f3765a04..c541791e66 100644 --- a/packages/host/frontend-static/README.md +++ b/packages/host/frontend-static/README.md @@ -4,6 +4,8 @@ English | [中文](README.zh.md) SPA dist server for the Web shell: a function plugin (config `{distIndex}`) that claims the [webserver](../webserver/README.md)'s single fallback seat and serves the built frontend directory with explicit index entry points. While `distIndex` is readable, the dist root and configured index path render `index.html` with HTTP 200; other existing files are served directly. An absent or non-file target inside the dist root, including a missing configured index, returns an empty 404; traversal outside the dist root returns 403, unknown extensions ship as `application/octet-stream`, and non-GET/HEAD without a matching named route returns 405. Every successful index response is rendered through the webserver's `renderIndex` — structured injection rows first, then the raw index taps — which is how the boot manifest reaches the page. `distIndex` is an assembly fact of the composing application: [`dsh-web-app`](../../bundle/web-app/README.md) resolves it through the frontend package's exports and mounts this plugin; a deployment never hardcodes it. +Root and configured-index responses require `ctx.connection.authorizeIndex` before reading the HTML bytes. A valid process token receives a 303 redirect plus the persistent browser cookie; an existing valid cookie serves the index; every other index request receives the Connection-owned 401 response. Non-index files remain public static assets. Connection owns all token, cookie, expiry, and signing-record semantics; this package only places that decision before the HTML read. + The fallback seat is single-owner (a second claim throws) and effect-scoped: disposing the plugin's fiber releases the seat, after which the unclaimed webserver answers 404. ## Model Experience diff --git a/packages/host/frontend-static/README.zh.md b/packages/host/frontend-static/README.zh.md index 7672478480..76aeaff93d 100644 --- a/packages/host/frontend-static/README.zh.md +++ b/packages/host/frontend-static/README.zh.md @@ -4,6 +4,8 @@ Web 壳的 SPA dist 服务器:一个函数插件(配置为 `{distIndex}`),占据 [webserver](../webserver/README.zh.md) 的唯一回退席位,并通过显式 index 入口服务已构建的前端目录。`distIndex` 可读时,dist 根目录和配置的 index 路径以 HTTP 200 渲染 `index.html`;其他现有文件直接提供。dist 根目录内缺失或不是文件的目标——包括缺失的配置 index——返回空的 404;越出 dist 根目录的遍历返回 403,未知扩展名按 `application/octet-stream` 提供,GET/HEAD 之外的方法在没有匹配的具名路由时返回 405。每个成功的 index 响应都经 webserver 的 `renderIndex` 渲染——先结构化注入行、后原始 index 转换器——启动 manifest(元数据清单)就是经这条路径送达页面的。`distIndex` 是组合应用的组装事实:[`dsh-web-app`](../../bundle/web-app/README.zh.md) 通过前端包的 exports 解析它并挂载本插件;部署绝不硬编码它。 +根路径与配置 index 响应在读取 HTML 字节前必须通过 `ctx.connection.authorizeIndex`。有效进程令牌得到带持久浏览器 cookie 的 303 重定向;既有有效 cookie 允许提供 index;其他 index 请求都得到 Connection 持有的 401 响应。非 index 文件保持公开静态资源。令牌、cookie、有效期和签名记录的全部语义归 Connection;本包只把这项判定放在 HTML 读取之前。 + 回退席位只有单一所有者(第二次占据会抛错),并受 effect 作用域约束:dispose(资源释放)插件的 fiber 会释放席位,此后无人占据的 webserver 回答 404。 ## 模型体验 diff --git a/packages/host/frontend-static/package.json b/packages/host/frontend-static/package.json index 2fcc012873..067548dca2 100644 --- a/packages/host/frontend-static/package.json +++ b/packages/host/frontend-static/package.json @@ -34,6 +34,7 @@ "peerDependencies": { "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/cordis": "workspace:^" }, "dependencies": { @@ -41,6 +42,8 @@ }, "devDependencies": { "@deepseek-ai/cordis-plugin-loader": "workspace:^", + "@deepseek-ai/dsh-client-connection": "workspace:^", + "@deepseek-ai/dsh-credentials-local": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/cordis": "workspace:^" diff --git a/packages/host/frontend-static/src/index.ts b/packages/host/frontend-static/src/index.ts index 1227299362..6855a21190 100644 --- a/packages/host/frontend-static/src/index.ts +++ b/packages/host/frontend-static/src/index.ts @@ -4,8 +4,9 @@ * entry points. A readable index renders at the dist root and configured index * path; missing paths return 404, traversal outside the dist root is 403, * unknown extensions ship as octet-stream, and non-GET/HEAD is 405. Every - * index response runs through the webserver's index render (structured - * injection rows, then raw taps). The dist location is workspace knowledge of + * index response first passes Connection's browser authentication, then the + * webserver's index render (structured injection rows, then raw taps). + * Non-index assets stay public. The dist location is workspace knowledge of * the composing application, so `distIndex` is typically supplied through a * `!!js` expression, never hardcoded by a deployment. * @module @deepseek-ai/dsh-host-frontend-static @@ -16,13 +17,14 @@ import { readFile } from 'node:fs/promises' import { dirname, extname, join, normalize, resolve, sep } from 'node:path' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-client-connection' import type {} from '@deepseek-ai/dsh-host-webserver' /** Stable Cordis plugin name. */ export const name = 'frontend-static' -/** Service required before the fallback seat can be claimed. */ -export const inject = ['webServer'] +/** Services required before the authenticated fallback seat can be claimed. */ +export const inject = ['webServer', 'connection'] /** Plugin config: the dist anchor. */ export interface Config { @@ -62,11 +64,13 @@ const STATIC_MISS_CODES: ReadonlySet = new Set([ * @param res - the node:http response to write. * @param distRoot - absolute dist root directory (resolved by the caller). * @param distIndex - absolute path of index.html inside distRoot. + * @param authorizeIndex - authenticates an index response before its bytes are read. * @param renderIndex - produces the index.html body (structured injection * rendering) for the dist root and configured index path. */ export async function serveStatic( pathname: string, res: ServerResponse, distRoot: string, distIndex: string, + authorizeIndex: () => Promise, renderIndex: () => Promise, ): Promise { const target = resolve(normalize(join(distRoot, pathname))) @@ -82,6 +86,7 @@ export async function serveStatic( let type: string try { if (target === distRoot || target === distIndex) { + if (!await authorizeIndex()) return body = await renderIndex() type = HTML_MIME } else { @@ -126,6 +131,13 @@ export function apply(ctx: Context, config: Config): void { } /* v8 ignore next -- node:http always sets url on server requests */ const rawPath = new URL(req.url ?? '/', 'http://x').pathname - await serveStatic(decodeURIComponent(rawPath), res, distRoot, distIndex, renderIndex) + await serveStatic( + decodeURIComponent(rawPath), + res, + distRoot, + distIndex, + () => ctx.connection.authorizeIndex(req, res), + renderIndex, + ) }), 'frontend-static: fallback seat') } diff --git a/packages/host/frontend-static/tests/frontend-static.spec.ts b/packages/host/frontend-static/tests/frontend-static.spec.ts index 93989857b9..a503777254 100644 --- a/packages/host/frontend-static/tests/frontend-static.spec.ts +++ b/packages/host/frontend-static/tests/frontend-static.spec.ts @@ -14,6 +14,8 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' +import * as Connection from '@deepseek-ai/dsh-client-connection' +import LocalCredentials from '@deepseek-ai/dsh-credentials-local' import HttpServer from '@deepseek-ai/dsh-host-webserver' import * as FrontendStatic from '../src/index.ts' @@ -27,7 +29,7 @@ afterEach(async () => { root = undefined }) -/** Write a dist fixture and a two-row cordis.yml, then boot it through the real Loader. */ +/** Write a dist fixture and the authenticated Web rows, then boot them through the real Loader. */ async function loadComposition(): Promise { root = await mkdtemp(join(tmpdir(), 'dsh-frontend-static-')) const dist = join(root, 'dist') @@ -40,10 +42,15 @@ async function loadComposition(): Promise { await mkdir(join(dist, 'empty')) const configPath = join(root, 'cordis.yml') await writeFile(configPath, [ + "- name: '@deepseek-ai/dsh-credentials-local'", + ' config:', + ` path: '${join(root, '.credentials.yaml')}'`, + ' watch: false', "- name: '@deepseek-ai/dsh-host-webserver'", ' config:', " host: '127.0.0.1'", ' port: 0', + "- name: '@deepseek-ai/dsh-client-connection'", '- id: frontend', " name: '@deepseek-ai/dsh-host-frontend-static'", ' config:', @@ -56,7 +63,9 @@ async function loadComposition(): Promise { await context.plugin(Loader) context.loader.builtins.include = Include const modules = new Map([ + ['@deepseek-ai/dsh-credentials-local', LocalCredentials], ['@deepseek-ai/dsh-host-webserver', HttpServer], + ['@deepseek-ai/dsh-client-connection', Connection], ['@deepseek-ai/dsh-host-frontend-static', FrontendStatic], ]) context.loader.internal = { @@ -95,6 +104,24 @@ describe('real Loader composition', () => { expect(unloaded).toEqual([]) const server = loaded.webServer const port = server.port + const launchUrl = loaded.connection.authenticatedUrl(`http://127.0.0.1:${String(port)}`) + const exchange = await fetch(launchUrl, { redirect: 'manual' }) + expect(exchange.status).toBe(303) + expect(exchange.headers.get('location')).toBe('/') + const setCookie = exchange.headers.get('set-cookie') + if (setCookie === null) throw new Error('authenticated frontend did not set a cookie') + const cookie = setCookie.split(';', 1)[0]! + const authenticated = (init?: RequestInit): RequestInit => { + const headers = new Headers(init?.headers) + headers.set('cookie', cookie) + return { ...init, headers } + } + + expect(await request(port, '/')).toMatchObject({ + status: 401, + type: 'text/plain; charset=utf-8', + body: 'dsh web authentication required; reopen the URL printed by dsh web.\n', + }) // Real assets with their MIME types; a live rebuild is served on the next read. expect(await request(port, '/app.js')).toMatchObject({ status: 200, type: 'text/javascript; charset=utf-8', body: 'export {}' }) @@ -117,33 +144,33 @@ describe('real Loader composition', () => { // Only the root and index path render index.html through registered taps. const untap = server.tapIndex(html => html.replace('', '')) for (const path of ['/', '/index.html', '/?fixture']) { - const got = await request(port, path) + const got = await request(port, path, authenticated()) expect(got.status).toBe(200) expect(got.type).toBe('text/html; charset=utf-8') expect(got.body).toContain('__T__') expect(got.body).toContain('shell') } - expect(await request(port, '/', { method: 'HEAD' })).toEqual({ + expect(await request(port, '/', authenticated({ method: 'HEAD' }))).toEqual({ status: 200, type: 'text/html; charset=utf-8', body: '', }) untap() - expect((await request(port, '/')).body).not.toContain('__T__') + expect((await request(port, '/', authenticated())).body).not.toContain('__T__') // A missing configured index follows the same empty-404 contract for both // of its public entry paths and for both supported methods. await rm(join(root!, 'dist', 'index.html')) for (const path of ['/', '/index.html']) { - const get = await request(port, path) - const head = await request(port, path, { method: 'HEAD' }) + const get = await request(port, path, authenticated()) + const head = await request(port, path, authenticated({ method: 'HEAD' })) expect(get).toEqual({ status: 404, type: null, body: '' }) expect(head).toEqual(get) } // Ordinary unknown paths and static-resource misses are empty 404s for // both GET and HEAD; neither class can be mistaken for the HTML shell. - const ordinaryMisses = ['/no/such/route', '/api/no/such/route', '/empty', '/app.js/child'] + const ordinaryMisses = ['/no/such/route', '/empty', '/app.js/child'] const assetMisses = [ '/missing.js', '/missing.css', @@ -158,6 +185,11 @@ describe('real Loader composition', () => { expect(get).toEqual({ status: 404, type: null, body: '' }) expect(head).toEqual(get) } + expect(await request(port, '/api/no/such/route', authenticated())).toEqual({ + status: 404, + type: 'text/plain;charset=UTF-8', + body: 'not found', + }) // Traversal outside the dist root is 403, non-GET/HEAD is 405, and a // malformed filesystem target still reaches the webserver's 400 guard. diff --git a/packages/host/frontend-static/tsconfig.json b/packages/host/frontend-static/tsconfig.json index 6c09296ed9..5eda998b9b 100644 --- a/packages/host/frontend-static/tsconfig.json +++ b/packages/host/frontend-static/tsconfig.json @@ -17,6 +17,9 @@ { "path": "../../../vendor/schemastery" }, + { + "path": "../../client/connection/tsconfig.host.json" + }, { "path": "../webserver" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6e95ecdff6..86359634bb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -454,9 +454,15 @@ importers: '@types/js-yaml': specifier: ^4.0.9 version: 4.0.9 + '@types/ws': + specifier: 8.18.1 + version: 8.18.1 execa: specifier: ^10.0.0 version: 10.0.0 + ws: + specifier: 8.21.0 + version: 8.21.0 apps/web: devDependencies: @@ -499,6 +505,9 @@ importers: '@types/react-dom': specifier: ~18.3.0 version: 18.3.7(@types/react@18.3.31) + '@types/ws': + specifier: 8.18.1 + version: 8.18.1 '@vitejs/plugin-react': specifier: ^4.0.0 version: 4.7.0(vite@6.4.3(@types/node@22.20.0)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.22.4)(yaml@2.9.0)) @@ -526,6 +535,9 @@ importers: vitest: specifier: ^4.1.8 version: 4.1.8(@opentelemetry/api@1.9.1)(@types/node@22.20.0)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1(@noble/hashes@2.3.0))(vite@6.4.3(@types/node@22.20.0)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.22.4)(yaml@2.9.0)) + ws: + specifier: 8.21.0 + version: 8.21.0 native/landlock-run: devDependencies: @@ -1579,6 +1591,9 @@ importers: '@deepseek-ai/dsh-attachment': specifier: workspace:^ version: link:../../attachment/attachment + '@deepseek-ai/dsh-credentials': + specifier: workspace:^ + version: link:../../credentials/credentials '@deepseek-ai/dsh-commands': specifier: workspace:^ version: link:../../interaction/commands @@ -5692,6 +5707,12 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:^ version: link:../../../vendor/loader + '@deepseek-ai/dsh-client-connection': + specifier: workspace:^ + version: link:../../client/connection + '@deepseek-ai/dsh-credentials-local': + specifier: workspace:^ + version: link:../../credentials/credentials-local '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../webserver From ce031ddd1696d95b4602292f0a7caa589a7dd776 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Tue, 25 Aug 2026 02:07:56 +0800 Subject: [PATCH 24/31] fix(web): cover authenticated host runtimes --- ...-24-browser-token-authentication.i18n.yaml | 4 +- ...2026-08-24-browser-token-authentication.md | 4 +- ...6-08-24-browser-token-authentication.zh.md | 4 +- apps/web/tests/access-confirmation.e2e.ts | 2 +- apps/web/tests/agent-preset-authoring.e2e.ts | 4 +- apps/web/tests/agent-preset-selection.e2e.ts | 12 +++--- apps/web/tests/approval-composer.e2e.ts | 2 +- apps/web/tests/background-job-list.e2e.ts | 2 +- apps/web/tests/bash-abort-row.e2e.ts | 2 +- .../tests/chat-continuous-conversation.e2e.ts | 2 +- apps/web/tests/chat-long-interactions.e2e.ts | 2 +- apps/web/tests/chat-scroll-contract.e2e.ts | 2 +- apps/web/tests/code-mode-round.e2e.ts | 2 +- apps/web/tests/cold-blank-session.e2e.ts | 2 +- apps/web/tests/complex-history.perf.ts | 4 +- apps/web/tests/composer-draft-scroll.e2e.ts | 2 +- apps/web/tests/composer-tab-geometry.e2e.ts | 2 +- .../tests/conversation-column-overflow.e2e.ts | 2 +- apps/web/tests/cordis-tool-round.e2e.ts | 2 +- apps/web/tests/declared-reasoning.e2e.ts | 2 +- apps/web/tests/default-model.e2e.ts | 2 +- .../tests/details-session-lifecycle.e2e.ts | 2 +- apps/web/tests/feedback-command.e2e.ts | 2 +- apps/web/tests/github-ready-review.e2e.ts | 2 +- apps/web/tests/goal-bar.e2e.ts | 2 + .../tests/goal-command-presentation.e2e.ts | 2 +- apps/web/tests/goal-multi-turn-actions.e2e.ts | 2 +- apps/web/tests/lifecycle-chrome.e2e.ts | 4 +- apps/web/tests/live-interactions.e2e.ts | 2 +- apps/web/tests/markdown-cjk-strong.e2e.ts | 2 +- apps/web/tests/markdown-images.e2e.ts | 2 +- .../tests/markdown-inline-code-links.e2e.ts | 2 +- apps/web/tests/markdown-wide-table.e2e.ts | 4 +- apps/web/tests/math-rendering.e2e.ts | 2 +- apps/web/tests/message-actions.e2e.ts | 2 +- apps/web/tests/message-feedback-layout.e2e.ts | 2 +- .../message-feedback-protocol.snapshot.ts | 2 +- apps/web/tests/message-feedback.e2e.ts | 2 +- apps/web/tests/models-settings.e2e.ts | 2 +- apps/web/tests/navigation-panes.e2e.ts | 4 +- .../tests/onboarding-deepseek-config.e2e.ts | 2 +- .../tests/onboarding-usable-provider.e2e.ts | 2 +- .../tests/permission-policy-context.e2e.ts | 2 +- apps/web/tests/plan-control-row.e2e.ts | 2 +- apps/web/tests/plan-review.e2e.ts | 2 +- apps/web/tests/plugin-config.e2e.ts | 2 +- apps/web/tests/produced-file-mentions.e2e.ts | 2 +- apps/web/tests/produced-files.e2e.ts | 2 +- apps/web/tests/pwsh-terminal.e2e.ts | 2 +- apps/web/tests/question-composer.e2e.ts | 2 +- apps/web/tests/queue-actions.e2e.ts | 4 +- apps/web/tests/rail-search-expand.e2e.ts | 2 +- apps/web/tests/reference-composer.e2e.ts | 2 +- apps/web/tests/remote-welcome.e2e.ts | 2 +- apps/web/tests/replay-round-trip.e2e.ts | 2 +- apps/web/tests/scaffold.ts | 26 ++++++++++++- apps/web/tests/schedule-after.e2e.ts | 2 +- apps/web/tests/seeded-history.e2e.ts | 6 ++- apps/web/tests/settings-chrome.e2e.ts | 12 +++--- apps/web/tests/sidebar-scrollbar.e2e.ts | 2 +- .../tests/sidebar-subagent-activity.e2e.ts | 2 +- apps/web/tests/skill-invocation-policy.e2e.ts | 2 +- apps/web/tests/skill-tool-row.e2e.ts | 2 +- apps/web/tests/skill-user-invoke.e2e.ts | 2 +- apps/web/tests/startup-auto-selection.e2e.ts | 2 +- apps/web/tests/startup-rpc-budget.e2e.ts | 2 +- apps/web/tests/stats-paged-history.e2e.ts | 2 +- apps/web/tests/steering.e2e.ts | 8 ++-- apps/web/tests/subagent-conversation.e2e.ts | 2 +- apps/web/tests/subagent-interrupt-ui.e2e.ts | 2 +- apps/web/tests/subagent-interrupt.e2e.ts | 16 ++++---- .../tests/trajectory-virtualization.e2e.ts | 2 +- apps/web/tests/turn-tail-actions.e2e.ts | 2 +- apps/web/tests/web-search-round.e2e.ts | 2 +- apps/web/tests/workflow-run.e2e.ts | 2 +- apps/web/tests/workspace-management.e2e.ts | 2 +- docs/module-graph.i18n.yaml | 4 +- docs/module-graph.md | 10 +++-- docs/module-graph.zh.md | 10 +++-- packages/api/remotes/tests/built-lib.e2e.ts | 33 ++++++++++++++++- .../bundle/web-app/tests/browser-open.spec.ts | 27 +++++++++++++- packages/bundle/web-app/tests/web-app.spec.ts | 1 + .../client/connection/src/browser-auth.ts | 37 ++++++++++++++----- .../tests/api-request-trust.host.spec.ts | 7 ++++ .../tests/browser-auth.host.spec.ts | 13 +++++-- .../webworker-runtime/src/transport/tunnel.ts | 25 ++++++------- .../webworker-runtime/src/worker-host.ts | 6 +-- .../tests/transport/tunnel-server.spec.ts | 36 ++++++++++++++++++ 88 files changed, 303 insertions(+), 144 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml index e8c68740aa..0691ce60ab 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md -2026-08-24-browser-token-authentication.md: fb55a35018b7c8df45213f9b9e59dccc3512c0ab -2026-08-24-browser-token-authentication.zh.md: 6cd77117395ff753d36d39da0ec247e064bdb393 +2026-08-24-browser-token-authentication.md: 515990b81f3c92b7f3c422dcc40acfed1e5996ac +2026-08-24-browser-token-authentication.zh.md: 8066e2c3f62245779c6a03b5160c41e4bbc94ba5 diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md index fb55a35018..515990b81f 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -18,11 +18,13 @@ The cookie is a signed, authority-bound bearer. Its deterministic name and signe The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection reads the record for each verification, so deletion or replacement revokes every existing cookie without restarting the process. A missing record is recreated only by a valid process-token exchange. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. +The in-page Web Worker preview exposes no network socket. Its page-owned `postMessage` tunnel enters the real route first, then retries a 401 or 403 through the worker-local fetch handler. This keeps Connection interceptors while limiting the authentication bypass to the page that created the Host worker. + The shipped CLI continues to reject `--host 0.0.0.0`. Authentication does not imply supported network deployment, TLS, forwarding-header interpretation, or proxy configuration. ## Verification -Unit coverage pins token comparison, cookie attributes, HMAC and payload validation, authority and lifetime checks, persistent-secret reuse, record deletion, and invalid durable records. Host transport suites pin uniform 401/403 behavior for API Proxy, generic RPC, Typert Remote HTTP, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `host.describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. +Unit coverage pins token comparison, cookie attributes, HMAC and payload validation, authority and lifetime checks, persistent-secret reuse, record deletion, and invalid durable records. Host transport suites pin uniform 401/403 behavior for API Proxy, generic RPC, Typert Remote HTTP, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `host.describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md index 6cd7711739..8066e2c3f6 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -18,11 +18,13 @@ cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payloa HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 每次校验都读取记录,因此删除或替换记录无需重启进程即可撤销全部既有 cookie。缺失记录只能由有效进程令牌交换重新创建。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 +页内 Web Worker preview 不暴露网络 socket。其由页面持有的 `postMessage` tunnel 先进入真实 route,收到 401 或 403 后再经 worker 本地 fetch handler 重试。这样既保留 Connection interceptor,又把认证绕过限制在创建 Host worker 的页面内。 + 随附 CLI 继续拒绝 `--host 0.0.0.0`。认证不代表支持网络部署、TLS、转发 header 解释或代理配置。 ## 验证 -单元覆盖固定令牌比较、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、持久密钥复用、记录删除及无效持久记录。Host 传输套件固定 API Proxy、通用 RPC、Typert Remote HTTP 和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `host.describe`,观测新的进程令牌,并在重启后复用旧 cookie。 +单元覆盖固定令牌比较、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、持久密钥复用、记录删除及无效持久记录。Host 传输套件固定 API Proxy、通用 RPC、Typert Remote HTTP 和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `host.describe`,观测新的进程令牌,并在重启后复用旧 cookie。 ## 曾考虑的替代方案 diff --git a/apps/web/tests/access-confirmation.e2e.ts b/apps/web/tests/access-confirmation.e2e.ts index 87578885ce..26aa2d3d3d 100644 --- a/apps/web/tests/access-confirmation.e2e.ts +++ b/apps/web/tests/access-confirmation.e2e.ts @@ -35,7 +35,7 @@ describe('web e2e: Full access confirmation', () => { // callback. page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspaceZh(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/agent-preset-authoring.e2e.ts b/apps/web/tests/agent-preset-authoring.e2e.ts index d338b43b55..72b8317fe4 100644 --- a/apps/web/tests/agent-preset-authoring.e2e.ts +++ b/apps/web/tests/agent-preset-authoring.e2e.ts @@ -69,7 +69,7 @@ describe('web e2e: agent-preset authoring is a host-side copy', () => { // The scenario asserts the shipped Chinese copy, so the browser asks for it. page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) @@ -257,7 +257,7 @@ describe('web e2e: agent-preset authoring is a host-side copy', () => { await dialog.waitFor({ state: 'detached', timeout: 10_000 }) await page.getByRole('button', { name: '创造模式' }).waitFor({ timeout: 10_000 }) await expect.poll(async () => { - const response = await fetch(`${scaffold.baseUrl}/api/session/list`, { + const response = await scaffold.hostFetch('/api/session/list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ diff --git a/apps/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index ea7ee009d5..a1f198ca93 100644 --- a/apps/web/tests/agent-preset-selection.e2e.ts +++ b/apps/web/tests/agent-preset-selection.e2e.ts @@ -137,11 +137,11 @@ async function seedSubagent(scaffold: WebScaffold, parentId: SessionId): Promise * produced. Addressed by id rather than by scanning the serialized list: the * seeded session records `minimal` too, so a substring match over the whole * list answers before the switch has landed. - * @param baseUrl - the scaffold's origin. + * @param scaffold - authenticated Web Host scaffold. * @returns the live session's preset, or undefined before it is listed. */ -async function livePreset(baseUrl: string): Promise { - const response = await fetch(`${baseUrl}/api/session/list`, { +async function livePreset(scaffold: WebScaffold): Promise { + const response = await scaffold.hostFetch('/api/session/list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ @@ -190,7 +190,7 @@ describe('web e2e: agent-preset selection', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) @@ -234,7 +234,7 @@ describe('web e2e: agent-preset selection', () => { // The chip stages; the blank session the workspace connect produced is // what the stage lands on. The host's own answer is what comes back. - await expect.poll(() => livePreset(scaffold.baseUrl), { timeout: 15_000 }).toBe('minimal') + await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('minimal') }) it('re-reads the slash catalog through the composition the switch installed', async () => { @@ -264,7 +264,7 @@ describe('web e2e: agent-preset selection', () => { // instead of leaving the session reading the narrower composition. await page.getByRole('button', { name: 'Minimal mode' }).click() await page.getByRole('menuitem', { name: /^Standard mode/ }).first().click() - await expect.poll(() => livePreset(scaffold.baseUrl), { timeout: 15_000 }).toBe('standard') + await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('standard') await composer.fill('/') await expect.poll(() => menuOptions(page), { timeout: 15_000 }) diff --git a/apps/web/tests/approval-composer.e2e.ts b/apps/web/tests/approval-composer.e2e.ts index 0bbc3fa210..d8fe3935c8 100644 --- a/apps/web/tests/approval-composer.e2e.ts +++ b/apps/web/tests/approval-composer.e2e.ts @@ -43,7 +43,7 @@ describe('web e2e: approval takeover keeps its actions reachable', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/background-job-list.e2e.ts b/apps/web/tests/background-job-list.e2e.ts index fcf02290fd..cad3d05aa0 100644 --- a/apps/web/tests/background-job-list.e2e.ts +++ b/apps/web/tests/background-job-list.e2e.ts @@ -56,7 +56,7 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) const groupRow = page.locator('[role="treeitem"]').first() diff --git a/apps/web/tests/bash-abort-row.e2e.ts b/apps/web/tests/bash-abort-row.e2e.ts index dcd4f93cf9..63d8d729e0 100644 --- a/apps/web/tests/bash-abort-row.e2e.ts +++ b/apps/web/tests/bash-abort-row.e2e.ts @@ -34,7 +34,7 @@ describe.skipIf(MODE === 'record')('web e2e: cancelled Bash row disclosure', () browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) const groupRow = page.locator('[role="treeitem"]').first() diff --git a/apps/web/tests/chat-continuous-conversation.e2e.ts b/apps/web/tests/chat-continuous-conversation.e2e.ts index cd15f2e054..8130e70308 100644 --- a/apps/web/tests/chat-continuous-conversation.e2e.ts +++ b/apps/web/tests/chat-continuous-conversation.e2e.ts @@ -197,7 +197,7 @@ describe('web e2e: continuous conversation grown through the composer', () => { page.on('console', (message) => { if (message.type() === 'warning') consoleWarnings.push(message.text()) }) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd, 'continuous-chat-e2e') }, 120_000) diff --git a/apps/web/tests/chat-long-interactions.e2e.ts b/apps/web/tests/chat-long-interactions.e2e.ts index 03198a23a8..c7d6c7de50 100644 --- a/apps/web/tests/chat-long-interactions.e2e.ts +++ b/apps/web/tests/chat-long-interactions.e2e.ts @@ -155,7 +155,7 @@ describe('web e2e: long Chat interaction contract', () => { browser = await chromium.launch() page = await newEnglishPage(browser, 900) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await openSeed(page) }, 120_000) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index 7c70741296..287e3a61f8 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -166,7 +166,7 @@ async function launchScrollWorld(options: ScrollWorldOptions): Promise { events.push(event) }) page = await newEnglishPage(browser, 900) const tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // Session-list bootstrap can replace the controlled search state. Wait // for the seeded baseline before openSeed starts the lazy content query diff --git a/apps/web/tests/code-mode-round.e2e.ts b/apps/web/tests/code-mode-round.e2e.ts index fcdbb721a6..58210a6437 100644 --- a/apps/web/tests/code-mode-round.e2e.ts +++ b/apps/web/tests/code-mode-round.e2e.ts @@ -38,7 +38,7 @@ describe('web e2e: Code Mode round renders nested sub-calls', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/cold-blank-session.e2e.ts b/apps/web/tests/cold-blank-session.e2e.ts index 87eaf848db..b9e64960d3 100644 --- a/apps/web/tests/cold-blank-session.e2e.ts +++ b/apps/web/tests/cold-blank-session.e2e.ts @@ -39,7 +39,7 @@ describe('web e2e: cold blank Session visibility', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/complex-history.perf.ts b/apps/web/tests/complex-history.perf.ts index eeb9931473..0913d82e90 100644 --- a/apps/web/tests/complex-history.perf.ts +++ b/apps/web/tests/complex-history.perf.ts @@ -907,7 +907,7 @@ async function openPerformancePage( world: PerformanceWorld, expectedSessions: number, ): Promise { - await world.page.goto(world.scaffold.baseUrl, { waitUntil: 'load' }) + await world.page.goto(world.scaffold.authenticatedUrl, { waitUntil: 'load' }) await world.page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) const group = world.page.getByRole('treeitem').first() await expect.poll(() => group.textContent(), { timeout: 30_000 }) @@ -1389,7 +1389,7 @@ describe('manual web performance: complex workspace and history', () => { }) let testFailure: unknown try { - await world.page.goto(world.scaffold.baseUrl, { waitUntil: 'load' }) + await world.page.goto(world.scaffold.authenticatedUrl, { waitUntil: 'load' }) await world.page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(world.page, world.scaffold.workspaceCwd, 'continuous-conversation-perf') const cdp = await world.page.context().newCDPSession(world.page) diff --git a/apps/web/tests/composer-draft-scroll.e2e.ts b/apps/web/tests/composer-draft-scroll.e2e.ts index dd6ae8085e..04b13e206e 100644 --- a/apps/web/tests/composer-draft-scroll.e2e.ts +++ b/apps/web/tests/composer-draft-scroll.e2e.ts @@ -195,7 +195,7 @@ describe('web e2e: composer draft scrolling', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd, 'composer-draft-scroll') await page.locator('textarea:enabled').first().fill(DRAFT) diff --git a/apps/web/tests/composer-tab-geometry.e2e.ts b/apps/web/tests/composer-tab-geometry.e2e.ts index 99b746d97b..a4905b86e0 100644 --- a/apps/web/tests/composer-tab-geometry.e2e.ts +++ b/apps/web/tests/composer-tab-geometry.e2e.ts @@ -248,7 +248,7 @@ describe('web e2e: input card position across view tabs', () => { browser = await chromium.launch({ ignoreDefaultArgs: ['--hide-scrollbars'] }) page = await newEnglishPage(browser, WIDE_VIEWPORT.height) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await openSeededSession(page) await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor({ timeout: 30_000 }) diff --git a/apps/web/tests/conversation-column-overflow.e2e.ts b/apps/web/tests/conversation-column-overflow.e2e.ts index c9805a4df8..460acf9163 100644 --- a/apps/web/tests/conversation-column-overflow.e2e.ts +++ b/apps/web/tests/conversation-column-overflow.e2e.ts @@ -208,7 +208,7 @@ describe('web e2e: the conversation column scrolls on one axis', () => { browser = await chromium.launch() page = await newEnglishPage(browser, 900) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[data-conversation-scroll] [class*="heroGlow"]', { timeout: 30_000 }) }, 180_000) diff --git a/apps/web/tests/cordis-tool-round.e2e.ts b/apps/web/tests/cordis-tool-round.e2e.ts index e6e3fe6f5e..6dfebd0e98 100644 --- a/apps/web/tests/cordis-tool-round.e2e.ts +++ b/apps/web/tests/cordis-tool-round.e2e.ts @@ -91,7 +91,7 @@ describe('web e2e: Cordis tools use their owned cards', () => { }) }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/declared-reasoning.e2e.ts b/apps/web/tests/declared-reasoning.e2e.ts index 8d35d0d1ea..2310e392e0 100644 --- a/apps/web/tests/declared-reasoning.e2e.ts +++ b/apps/web/tests/declared-reasoning.e2e.ts @@ -51,7 +51,7 @@ describe.skipIf(MODE === 'record')('web e2e: declared reasoning efforts reach th browser = await chromium.launch() page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspaceZh(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index 34a9fab2f9..d095448a79 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -81,7 +81,7 @@ describe('web e2e: the composer model switch is the default for later sessions', browser = await chromium.launch() page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // The composer's seats only exist once a workspace is connected: without // one the input is the locked placeholder and no session scope is open. diff --git a/apps/web/tests/details-session-lifecycle.e2e.ts b/apps/web/tests/details-session-lifecycle.e2e.ts index 9ff90d2dca..d53338e1a1 100644 --- a/apps/web/tests/details-session-lifecycle.e2e.ts +++ b/apps/web/tests/details-session-lifecycle.e2e.ts @@ -78,7 +78,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await appFrame(page).waitFor({ timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/feedback-command.e2e.ts b/apps/web/tests/feedback-command.e2e.ts index f017d9289d..242b28188c 100644 --- a/apps/web/tests/feedback-command.e2e.ts +++ b/apps/web/tests/feedback-command.e2e.ts @@ -45,7 +45,7 @@ describe('web e2e: /feedback command acknowledgement', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // Fresh world: connecting a workspace births the blank session whose // live composer accepts the slash line. diff --git a/apps/web/tests/github-ready-review.e2e.ts b/apps/web/tests/github-ready-review.e2e.ts index af3af1c0f2..4d473ddf13 100644 --- a/apps/web/tests/github-ready-review.e2e.ts +++ b/apps/web/tests/github-ready-review.e2e.ts @@ -98,7 +98,7 @@ describe.skipIf(MODE === 'record')('web e2e: GitHub ready-for-review', () => { page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: 'en-US' }) await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'en') }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 60_000) diff --git a/apps/web/tests/goal-bar.e2e.ts b/apps/web/tests/goal-bar.e2e.ts index a775143da6..631367886b 100644 --- a/apps/web/tests/goal-bar.e2e.ts +++ b/apps/web/tests/goal-bar.e2e.ts @@ -30,6 +30,8 @@ describe('web e2e: goal bar clear convergence', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) + const login = await page.context().request.get(scaffold.authenticatedUrl, { maxRedirects: 0 }) + expect(login.status()).toBe(303) await page.goto(`${scaffold.baseUrl}?fixture`, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/goal-command-presentation.e2e.ts b/apps/web/tests/goal-command-presentation.e2e.ts index 537ab8095b..605c45e1bb 100644 --- a/apps/web/tests/goal-command-presentation.e2e.ts +++ b/apps/web/tests/goal-command-presentation.e2e.ts @@ -33,7 +33,7 @@ describe('web e2e: /goal human transcript presentation', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/goal-multi-turn-actions.e2e.ts b/apps/web/tests/goal-multi-turn-actions.e2e.ts index f73c100827..346593529b 100644 --- a/apps/web/tests/goal-multi-turn-actions.e2e.ts +++ b/apps/web/tests/goal-multi-turn-actions.e2e.ts @@ -117,7 +117,7 @@ describe('web e2e: Goal keeps one assistant action row per completed turn', () = browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) } diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index 35bea3b085..e1b62632aa 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -53,7 +53,7 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // Fresh world: connect a Workspace so the composer scenarios start live. await connectFreshWorkspace(page, scaffold.workspaceCwd) @@ -103,7 +103,7 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () const activePage = await newEnglishPage(browser) const activeTripwire = watchConsole(activePage) try { - await activePage.goto(activeScaffold.baseUrl, { waitUntil: 'load' }) + await activePage.goto(activeScaffold.authenticatedUrl, { waitUntil: 'load' }) await activePage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(activePage, activeScaffold.workspaceCwd) const input = activePage.locator('textarea').first() diff --git a/apps/web/tests/live-interactions.e2e.ts b/apps/web/tests/live-interactions.e2e.ts index ced590a45d..553b1565cf 100644 --- a/apps/web/tests/live-interactions.e2e.ts +++ b/apps/web/tests/live-interactions.e2e.ts @@ -104,7 +104,7 @@ describe('web e2e: live-turn interactions (cancel / error / retry)', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // Fresh world: connect a Workspace so the composer scenarios start live. await connectFreshWorkspace(page, scaffold.workspaceCwd) diff --git a/apps/web/tests/markdown-cjk-strong.e2e.ts b/apps/web/tests/markdown-cjk-strong.e2e.ts index 83963ea36e..b99f7f90d4 100644 --- a/apps/web/tests/markdown-cjk-strong.e2e.ts +++ b/apps/web/tests/markdown-cjk-strong.e2e.ts @@ -96,7 +96,7 @@ describe('web e2e: CJK-adjacent Markdown strong emphasis', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/markdown-images.e2e.ts b/apps/web/tests/markdown-images.e2e.ts index 57e5910813..54783b48a5 100644 --- a/apps/web/tests/markdown-images.e2e.ts +++ b/apps/web/tests/markdown-images.e2e.ts @@ -153,7 +153,7 @@ describe('web e2e: remote Markdown image rendering', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/markdown-inline-code-links.e2e.ts b/apps/web/tests/markdown-inline-code-links.e2e.ts index e216e5b6d0..be3e30a380 100644 --- a/apps/web/tests/markdown-inline-code-links.e2e.ts +++ b/apps/web/tests/markdown-inline-code-links.e2e.ts @@ -95,7 +95,7 @@ describe('web e2e: Markdown inline-code links', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/markdown-wide-table.e2e.ts b/apps/web/tests/markdown-wide-table.e2e.ts index 901a425f43..77e583bf45 100644 --- a/apps/web/tests/markdown-wide-table.e2e.ts +++ b/apps/web/tests/markdown-wide-table.e2e.ts @@ -253,7 +253,7 @@ describe('web e2e: markdown tables fill the column, wide ones break out and scro browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) const groupRow = page.locator('[role="treeitem"]').first() await groupRow.waitFor({ timeout: 15_000 }) @@ -423,7 +423,7 @@ describe('web e2e: markdown tables fill the column, wide ones break out and scro const hidpiTripwire = watchConsole(hidpiPage) try { onTestFailed(() => saveFailureShot(hidpiPage, 'web-e2e-markdown-wide-table-hidpi')) - await hidpiPage.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await hidpiPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await hidpiPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) const groupRow = hidpiPage.locator('[role="treeitem"]').first() await groupRow.waitFor({ timeout: 15_000 }) diff --git a/apps/web/tests/math-rendering.e2e.ts b/apps/web/tests/math-rendering.e2e.ts index 08f4ca2705..c5e3e22a60 100644 --- a/apps/web/tests/math-rendering.e2e.ts +++ b/apps/web/tests/math-rendering.e2e.ts @@ -97,7 +97,7 @@ describe('web e2e: settled Markdown math rendering', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/message-actions.e2e.ts b/apps/web/tests/message-actions.e2e.ts index 58e54965fb..de849baea3 100644 --- a/apps/web/tests/message-actions.e2e.ts +++ b/apps/web/tests/message-actions.e2e.ts @@ -87,7 +87,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/message-feedback-layout.e2e.ts b/apps/web/tests/message-feedback-layout.e2e.ts index ed03d14f8d..5ab5cb0102 100644 --- a/apps/web/tests/message-feedback-layout.e2e.ts +++ b/apps/web/tests/message-feedback-layout.e2e.ts @@ -207,7 +207,7 @@ describe('web e2e: the feedback note editor floats above the column', () => { browser = await chromium.launch() page = await newEnglishPage(browser, 900) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 180_000) diff --git a/apps/web/tests/message-feedback-protocol.snapshot.ts b/apps/web/tests/message-feedback-protocol.snapshot.ts index 02cebabcc0..e9dfa197b3 100644 --- a/apps/web/tests/message-feedback-protocol.snapshot.ts +++ b/apps/web/tests/message-feedback-protocol.snapshot.ts @@ -65,7 +65,7 @@ describe('message feedback Host Remote protocol', () => { const exchanges: ProtocolExchange[] = [] const invoke = async (rpcId: string, endpoint: string, request: unknown): Promise => { const payload = { args: { request } } - const response = await fetch(`${scaffold.baseUrl}/api/${endpoint}`, { + const response = await scaffold.hostFetch(`/api/${endpoint}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ diff --git a/apps/web/tests/message-feedback.e2e.ts b/apps/web/tests/message-feedback.e2e.ts index f6c3262c5f..02e4b62951 100644 --- a/apps/web/tests/message-feedback.e2e.ts +++ b/apps/web/tests/message-feedback.e2e.ts @@ -32,7 +32,7 @@ describe('web e2e: durable per-message feedback', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index f727c619f9..e802b981bf 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -47,7 +47,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { // The scenario asserts the shipped Chinese copy, so the browser asks for it. page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index 1da479e432..6ba5df86c9 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -114,7 +114,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { // Workspace stream settles through the user-visible Ungrouped barrier. const sessionBaseline = baselineResponse(page) const [, sessionResponse] = await Promise.all([ - page.goto(scaffold.baseUrl, { waitUntil: 'load' }), + page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }), sessionBaseline, ]) await assertBaselineSucceeded(sessionResponse, 'session.list') @@ -327,7 +327,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { }) const observerSessionBaseline = baselineResponse(observer) const [, observerSessionResponse] = await Promise.all([ - observer.goto(scaffold.baseUrl, { waitUntil: 'load' }), + observer.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }), observerSessionBaseline, ]) await assertBaselineSucceeded(observerSessionResponse, 'observer session.list') diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 59b7e3c987..82079543d3 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -38,7 +38,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) page.on('console', message => browserConsole.push(message.text())) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/onboarding-usable-provider.e2e.ts b/apps/web/tests/onboarding-usable-provider.e2e.ts index a1d97993b7..d16ed51822 100644 --- a/apps/web/tests/onboarding-usable-provider.e2e.ts +++ b/apps/web/tests/onboarding-usable-provider.e2e.ts @@ -33,7 +33,7 @@ describe.skipIf(MODE === 'record')('web e2e: another usable provider ends first- // The scenario asserts the shipped Chinese copy, so the browser asks for it. page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/permission-policy-context.e2e.ts b/apps/web/tests/permission-policy-context.e2e.ts index 06817d7df5..5ff6141af8 100644 --- a/apps/web/tests/permission-policy-context.e2e.ts +++ b/apps/web/tests/permission-policy-context.e2e.ts @@ -77,7 +77,7 @@ describe('web e2e: current sandbox policy reaches the model before tools', () => browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/plan-control-row.e2e.ts b/apps/web/tests/plan-control-row.e2e.ts index 49a3ce06dc..dd55656d61 100644 --- a/apps/web/tests/plan-control-row.e2e.ts +++ b/apps/web/tests/plan-control-row.e2e.ts @@ -64,7 +64,7 @@ describe('web e2e: plan chip click area at the narrow viewport', () => { browser = await chromium.launch() page = await newEnglishPage(browser, VIEWPORT.height) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) await page.setViewportSize(VIEWPORT) diff --git a/apps/web/tests/plan-review.e2e.ts b/apps/web/tests/plan-review.e2e.ts index 5c4082747f..8b4dc3afd4 100644 --- a/apps/web/tests/plan-review.e2e.ts +++ b/apps/web/tests/plan-review.e2e.ts @@ -53,7 +53,7 @@ describe('web e2e: plan review takeover round trip', () => { // golden pins one language. page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/plugin-config.e2e.ts b/apps/web/tests/plugin-config.e2e.ts index 1877d71e7c..0235f687de 100644 --- a/apps/web/tests/plugin-config.e2e.ts +++ b/apps/web/tests/plugin-config.e2e.ts @@ -33,7 +33,7 @@ describe('web e2e: plugin configuration section', () => { // derives from it, as the rest of the settings surface does. page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/produced-file-mentions.e2e.ts b/apps/web/tests/produced-file-mentions.e2e.ts index badd9b845e..f89cfe53b3 100644 --- a/apps/web/tests/produced-file-mentions.e2e.ts +++ b/apps/web/tests/produced-file-mentions.e2e.ts @@ -127,7 +127,7 @@ describe('web e2e: inline-code mentions of produced files', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/produced-files.e2e.ts b/apps/web/tests/produced-files.e2e.ts index 2dcc92f65e..3c6ebbf526 100644 --- a/apps/web/tests/produced-files.e2e.ts +++ b/apps/web/tests/produced-files.e2e.ts @@ -118,7 +118,7 @@ describe('web e2e: a finished turn ends with the files it produced', () => { // the assertion itself narrows the conversation after navigation. await page.setViewportSize({ width: 1280, height: 900 }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/pwsh-terminal.e2e.ts b/apps/web/tests/pwsh-terminal.e2e.ts index 4f56a422a9..85ce829904 100644 --- a/apps/web/tests/pwsh-terminal.e2e.ts +++ b/apps/web/tests/pwsh-terminal.e2e.ts @@ -55,7 +55,7 @@ describe.skipIf(MODE === 'record' || !HAS_PWSH)('web e2e: pwsh calls use the bas await seedSession(scaffold, fixture, SEED_ID) browser = await chromium.launch() page = await newEnglishPage(browser) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/question-composer.e2e.ts b/apps/web/tests/question-composer.e2e.ts index f0325a9e63..b63815975a 100644 --- a/apps/web/tests/question-composer.e2e.ts +++ b/apps/web/tests/question-composer.e2e.ts @@ -75,7 +75,7 @@ describe('web e2e: resident question composer round trip', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // Fresh world: connect a Workspace so the composer scenarios start live. await connectFreshWorkspace(page, scaffold.workspaceCwd) diff --git a/apps/web/tests/queue-actions.e2e.ts b/apps/web/tests/queue-actions.e2e.ts index 3dfeee4f4a..d026aa1110 100644 --- a/apps/web/tests/queue-actions.e2e.ts +++ b/apps/web/tests/queue-actions.e2e.ts @@ -81,7 +81,7 @@ describe('web e2e: queue row actions', () => { browser = await chromium.launch() page = await newEnglishPage(browser) const tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) onTestFailed(() => saveFailureShot(page, 'web-e2e-queue-actions')) @@ -191,7 +191,7 @@ describe('web e2e: queue row actions', () => { browser = await chromium.launch() page = await newEnglishPage(browser) const tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) onTestFailed(() => saveFailureShot(page, 'web-e2e-context-layout')) diff --git a/apps/web/tests/rail-search-expand.e2e.ts b/apps/web/tests/rail-search-expand.e2e.ts index 74f7cb12c9..bf520f3ebb 100644 --- a/apps/web/tests/rail-search-expand.e2e.ts +++ b/apps/web/tests/rail-search-expand.e2e.ts @@ -30,7 +30,7 @@ describe('web e2e: rail search click survives its own document-level bubble', () browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/reference-composer.e2e.ts b/apps/web/tests/reference-composer.e2e.ts index c6d8bfb60f..1e052462f5 100644 --- a/apps/web/tests/reference-composer.e2e.ts +++ b/apps/web/tests/reference-composer.e2e.ts @@ -147,7 +147,7 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) await writeFile(join(scaffold.workspaceCwd, 'workspace', 'reference.txt'), 'reference fixture\n') diff --git a/apps/web/tests/remote-welcome.e2e.ts b/apps/web/tests/remote-welcome.e2e.ts index 256afaeede..b7b013dc2d 100644 --- a/apps/web/tests/remote-welcome.e2e.ts +++ b/apps/web/tests/remote-welcome.e2e.ts @@ -29,7 +29,7 @@ describe.skipIf(MODE === 'record')('web e2e: remote welcome notice', () => { locale: ZH_BROWSER_LOCALE, }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('#root', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index fa1ee79079..30644607f5 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -50,7 +50,7 @@ describe('web e2e: fresh round trip through the real assembly', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // Fresh world: connect a Workspace so the composer scenarios start live. await connectFreshWorkspace(page, scaffold.workspaceCwd) diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index a4e1adc07b..bde659deec 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -205,6 +205,8 @@ export interface WebScaffold { mode: WebSnapshotMode /** Browser-facing origin for the bound test server. */ baseUrl: string + /** Process-token URL that establishes this scaffold's browser session. */ + authenticatedUrl: string /** Settled root context (the in-process readiness barrier; headless event subscription is its sanctioned use). */ ctx: Context /** Temp project directory sessions run in (shell/fs tool cwd). */ @@ -213,6 +215,8 @@ export interface WebScaffold { persistenceRoot: string /** Isolated harness home the settings/credentials rows write ($DSH_HOME double). */ harnessHome: string + /** Send a browser-equivalent Host request with this scaffold's authenticated cookie. */ + hostFetch(path: string, init?: RequestInit): Promise /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */ whenTurnSettled(timeoutMs?: number): Promise /** @@ -559,6 +563,9 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise { + const headers = new Headers(init.headers) + headers.set('cookie', cookieHeader) + return fetch(new URL(path, baseUrl), { ...init, headers }) + }, // Barrier stack: the in-process turn/end identifies the session, its // explicit flush makes the transcript durable, and the caller's browser // settled-poll comes last because host completion strictly precedes render. diff --git a/apps/web/tests/schedule-after.e2e.ts b/apps/web/tests/schedule-after.e2e.ts index 65192533c5..9b0b407464 100644 --- a/apps/web/tests/schedule-after.e2e.ts +++ b/apps/web/tests/schedule-after.e2e.ts @@ -235,7 +235,7 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { }) await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'en') }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) expect(await page.evaluate(() => Intl.DateTimeFormat().resolvedOptions().timeZone)) diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index ad4af3b3da..07d5810185 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -208,7 +208,7 @@ describe('web e2e: seeded history renders through cold resume', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) @@ -288,6 +288,10 @@ describe('web e2e: seeded history renders through cold resume', () => { // only — the prompt and full tool output must stay on screen. expect(await page.getByText(PROMPT, { exact: true }).count()).toBe(1) + await expect.poll( + () => scaffold.ctx.agents.get(SessionId(SEED_ID)) !== undefined, + { timeout: 10_000 }, + ).toBe(true) const agent = scaffold.ctx.agents.get(SessionId(SEED_ID)) if (agent === undefined) throw new Error('seeded session did not attach an agent') agent.session.append('user/message', createUserMessage({ diff --git a/apps/web/tests/settings-chrome.e2e.ts b/apps/web/tests/settings-chrome.e2e.ts index 35de5ac4f2..27521b8a57 100644 --- a/apps/web/tests/settings-chrome.e2e.ts +++ b/apps/web/tests/settings-chrome.e2e.ts @@ -42,7 +42,7 @@ describe('web e2e: settings modal and General preferences', () => { // the client derives from it (the English default has its own spec below). page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) @@ -314,7 +314,7 @@ describe('web e2e: settings modal and General preferences', () => { try { expect(second.baseUrl).not.toBe(scaffold.baseUrl) await secondPage.emulateMedia({ colorScheme: 'light' }) - await secondPage.goto(second.baseUrl, { waitUntil: 'load' }) + await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' }) await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await expect.poll(async () => (await readState(secondPage)).attr, { timeout: 5_000 }).toBe(true) const secondState = await readState(secondPage) @@ -372,7 +372,7 @@ describe('web e2e: settings modal and General preferences', () => { const secondTripwire = watchConsole(secondPage) try { expect(second.baseUrl).not.toBe(scaffold.baseUrl) - await secondPage.goto(second.baseUrl, { waitUntil: 'load' }) + await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' }) await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await secondPage.getByRole('button', { name: '设置', exact: true }).click() await secondPage.getByRole('dialog', { name: '设置' }) @@ -438,7 +438,7 @@ describe('web e2e: settings modal and General preferences', () => { const secondTripwire = watchConsole(secondPage) try { expect(second.baseUrl).not.toBe(scaffold.baseUrl) - await secondPage.goto(second.baseUrl, { waitUntil: 'load' }) + await secondPage.goto(second.authenticatedUrl, { waitUntil: 'load' }) await secondPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await secondPage.getByRole('button', { name: 'Settings', exact: true }).click() await secondPage.getByRole('dialog', { name: 'Settings' }) @@ -472,7 +472,7 @@ describe('web e2e: settings modal and General preferences', () => { const enTripwire = watchConsole(enPage) onTestFailed(() => saveFailureShot(enPage, 'web-e2e-settings-browser-language')) try { - await enPage.goto(fresh.baseUrl, { waitUntil: 'load' }) + await enPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' }) await enPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) expect(await enPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull() await enPage.getByRole('button', { name: 'Settings', exact: true }).click() @@ -498,7 +498,7 @@ describe('web e2e: settings modal and General preferences', () => { const frTripwire = watchConsole(frPage) onTestFailed(() => saveFailureShot(frPage, 'web-e2e-settings-unshipped-language')) try { - await frPage.goto(fresh.baseUrl, { waitUntil: 'load' }) + await frPage.goto(fresh.authenticatedUrl, { waitUntil: 'load' }) await frPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) expect(await frPage.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull() await frPage.getByRole('button', { name: 'Settings', exact: true }).click() diff --git a/apps/web/tests/sidebar-scrollbar.e2e.ts b/apps/web/tests/sidebar-scrollbar.e2e.ts index 3c2761e72d..899bf57e19 100644 --- a/apps/web/tests/sidebar-scrollbar.e2e.ts +++ b/apps/web/tests/sidebar-scrollbar.e2e.ts @@ -292,7 +292,7 @@ describe('web e2e: sidebar session list scrollbar (reserved gutter / themed thum // the list with room to spare. page = await newEnglishPage(browser, 800) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await expandSeededSessions(page) // Every assertion about a thumb colour needs a drawn thumb, and the column diff --git a/apps/web/tests/sidebar-subagent-activity.e2e.ts b/apps/web/tests/sidebar-subagent-activity.e2e.ts index ed087f0b8f..43fbd22f05 100644 --- a/apps/web/tests/sidebar-subagent-activity.e2e.ts +++ b/apps/web/tests/sidebar-subagent-activity.e2e.ts @@ -111,7 +111,7 @@ describe('web e2e: sidebar subagent activity', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) const workspace = await scaffold.ctx.workspaceRegistry.resolveByPath(cwd) diff --git a/apps/web/tests/skill-invocation-policy.e2e.ts b/apps/web/tests/skill-invocation-policy.e2e.ts index a938ed65d8..de0a838417 100644 --- a/apps/web/tests/skill-invocation-policy.e2e.ts +++ b/apps/web/tests/skill-invocation-policy.e2e.ts @@ -83,7 +83,7 @@ describe('web e2e: skill invocation policy through the real host', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/skill-tool-row.e2e.ts b/apps/web/tests/skill-tool-row.e2e.ts index 6e41ba9035..25914d5fa0 100644 --- a/apps/web/tests/skill-tool-row.e2e.ts +++ b/apps/web/tests/skill-tool-row.e2e.ts @@ -33,7 +33,7 @@ describe.skipIf(MODE === 'record')('web e2e: dedicated Skill tool row', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) const groupRow = page.locator('[role="treeitem"]').first() diff --git a/apps/web/tests/skill-user-invoke.e2e.ts b/apps/web/tests/skill-user-invoke.e2e.ts index 767146d2b9..04c7d6880c 100644 --- a/apps/web/tests/skill-user-invoke.e2e.ts +++ b/apps/web/tests/skill-user-invoke.e2e.ts @@ -79,7 +79,7 @@ describe.skipIf(MODE === 'record')('web e2e: user-explicit skill invocation thro browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/startup-auto-selection.e2e.ts b/apps/web/tests/startup-auto-selection.e2e.ts index d85343d7f9..7cfc3e68b2 100644 --- a/apps/web/tests/startup-auto-selection.e2e.ts +++ b/apps/web/tests/startup-auto-selection.e2e.ts @@ -29,7 +29,7 @@ describe('web e2e: startup auto-selection', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 180_000) diff --git a/apps/web/tests/startup-rpc-budget.e2e.ts b/apps/web/tests/startup-rpc-budget.e2e.ts index b9e06fcb3b..59faec6512 100644 --- a/apps/web/tests/startup-rpc-budget.e2e.ts +++ b/apps/web/tests/startup-rpc-budget.e2e.ts @@ -33,7 +33,7 @@ describe('startup RPC budget', () => { const url = new URL(request.url()) if (url.pathname.startsWith('/api/')) calls.push(url.pathname.slice('/api/'.length)) }) - await page.goto(scaffold.baseUrl) + await page.goto(scaffold.authenticatedUrl) // Boot settles when the workspace picker is interactive; the trailing wait // absorbs the first-connection reset wave the budget must include. await page.getByRole('textbox', { name: 'Choose workspace' }).waitFor({ timeout: 30_000 }) diff --git a/apps/web/tests/stats-paged-history.e2e.ts b/apps/web/tests/stats-paged-history.e2e.ts index 845b9a3593..1e6682489d 100644 --- a/apps/web/tests/stats-paged-history.e2e.ts +++ b/apps/web/tests/stats-paged-history.e2e.ts @@ -83,7 +83,7 @@ describe('web e2e: whole-session stats survive history paging', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/apps/web/tests/steering.e2e.ts b/apps/web/tests/steering.e2e.ts index 111b49f705..30a4afb832 100644 --- a/apps/web/tests/steering.e2e.ts +++ b/apps/web/tests/steering.e2e.ts @@ -78,7 +78,7 @@ describe('web e2e: mid-turn steering lands durably and visibly', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // Fresh world: connect a Workspace so the composer scenarios start live. await connectFreshWorkspace(page, scaffold.workspaceCwd) @@ -191,7 +191,7 @@ describe('web e2e: composer shortcut steers directly', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) @@ -248,7 +248,7 @@ describe('web e2e: composer shortcut follows the swapped busy behavior', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) @@ -314,7 +314,7 @@ describe('web e2e: empty-draft Cmd+Enter steers the whole queue', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) await page.getByText('Standard mode', { exact: true }).waitFor({ timeout: 10_000 }) diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 0be7e1f05e..a786b2c6cf 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -88,7 +88,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = if (path.startsWith('/api/')) apiCalls.push(path) }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) diff --git a/apps/web/tests/subagent-interrupt-ui.e2e.ts b/apps/web/tests/subagent-interrupt-ui.e2e.ts index aa985f6601..e9ef24ca4f 100644 --- a/apps/web/tests/subagent-interrupt-ui.e2e.ts +++ b/apps/web/tests/subagent-interrupt-ui.e2e.ts @@ -134,7 +134,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co if (path.startsWith('/api/')) apiCalls.push(path) }) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) diff --git a/apps/web/tests/subagent-interrupt.e2e.ts b/apps/web/tests/subagent-interrupt.e2e.ts index b3b9a53037..6edb81e404 100644 --- a/apps/web/tests/subagent-interrupt.e2e.ts +++ b/apps/web/tests/subagent-interrupt.e2e.ts @@ -23,8 +23,8 @@ const WAKING = 'And add one concrete example.' type RpcResult = { ok: true; value: T } | { ok: false; error: { code: string; message: string } } /** POST one API Proxy unary RPC through the real HTTP carrier and unwrap its result. */ -async function rpc(baseUrl: string, method: string, payload: unknown): Promise> { - const response = await fetch(`${baseUrl}/api/${method}`, { +async function rpc(scaffold: WebScaffold, method: string, payload: unknown): Promise> { + const response = await scaffold.hostFetch(`/api/${method}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ @@ -39,9 +39,9 @@ async function rpc(baseUrl: string, method: string, payload: unknown): Promis } /** POST one generated Session Remote unary through the API Gateway carrier. */ -async function sessionRemote(baseUrl: string, method: string, request: unknown): Promise> { +async function sessionRemote(scaffold: WebScaffold, method: string, request: unknown): Promise> { const endpoint = `session/${method}` - const response = await fetch(`${baseUrl}/api/${endpoint}`, { + const response = await scaffold.hostFetch(`/api/${endpoint}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ @@ -108,7 +108,7 @@ describe.skipIf(MODE === 'record')('web e2e: subagent.interrupt over the real co }) // A live parent Agent through the real API; no workspace or browser. - const created = await sessionRemote<{ sessionId: string }>(scaffold.baseUrl, 'create', { + const created = await sessionRemote<{ sessionId: string }>(scaffold, 'create', { cwd: scaffold.workspaceCwd, }) if (!created.ok) throw new Error(`session.create failed: ${created.error.code}`) @@ -138,7 +138,7 @@ describe.skipIf(MODE === 'record')('web e2e: subagent.interrupt over the real co it('parks a queued follow-up on interrupt and resumes it FIFO on a waking send', async () => { // Queue the follow-up while the turn is still open, then interrupt. - const queued = await rpc<{ messageId: string }>(scaffold.baseUrl, 'subagent.prompt', { + const queued = await rpc<{ messageId: string }>(scaffold, 'subagent.prompt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable', @@ -147,7 +147,7 @@ describe.skipIf(MODE === 'record')('web e2e: subagent.interrupt over the real co expect(queued).toMatchObject({ ok: true }) const settled = scaffold.whenTurnSettled() - const interrupted = await rpc<{ accepted: true }>(scaffold.baseUrl, 'subagent.interrupt', { + const interrupted = await rpc<{ accepted: true }>(scaffold, 'subagent.interrupt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable', @@ -169,7 +169,7 @@ describe.skipIf(MODE === 'record')('web e2e: subagent.interrupt over the real co // Only an explicit waking send resumes the parked queue, FIFO, then the // child runs both turns to completion and settles. - const waking = await rpc<{ messageId: string }>(scaffold.baseUrl, 'subagent.prompt', { + const waking = await rpc<{ messageId: string }>(scaffold, 'subagent.prompt', { parentSessionId: parentId, childSessionId: childId, mode: 'continuable', diff --git a/apps/web/tests/trajectory-virtualization.e2e.ts b/apps/web/tests/trajectory-virtualization.e2e.ts index 6629bb0b5d..e0f2b5bb66 100644 --- a/apps/web/tests/trajectory-virtualization.e2e.ts +++ b/apps/web/tests/trajectory-virtualization.e2e.ts @@ -196,7 +196,7 @@ describe('web e2e: Trajectory virtualization over tail-paged history', () => { browser = await chromium.launch() page = await newEnglishPage(browser, 900) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) // The compact layout dropped group session counts; the seeded baseline is // the Ungrouped bucket once cold summaries load. diff --git a/apps/web/tests/turn-tail-actions.e2e.ts b/apps/web/tests/turn-tail-actions.e2e.ts index ce848fa96b..b2ea2baf88 100644 --- a/apps/web/tests/turn-tail-actions.e2e.ts +++ b/apps/web/tests/turn-tail-actions.e2e.ts @@ -80,7 +80,7 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) } diff --git a/apps/web/tests/web-search-round.e2e.ts b/apps/web/tests/web-search-round.e2e.ts index 3299b1b163..7237670f0b 100644 --- a/apps/web/tests/web-search-round.e2e.ts +++ b/apps/web/tests/web-search-round.e2e.ts @@ -160,7 +160,7 @@ describe('web e2e: shipped default web search', () => { browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/workflow-run.e2e.ts b/apps/web/tests/workflow-run.e2e.ts index cf5999b626..f3d9e2c8b3 100644 --- a/apps/web/tests/workflow-run.e2e.ts +++ b/apps/web/tests/workflow-run.e2e.ts @@ -59,7 +59,7 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () = browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) diff --git a/apps/web/tests/workspace-management.e2e.ts b/apps/web/tests/workspace-management.e2e.ts index 2dbd8cd1f4..a8345c45d3 100644 --- a/apps/web/tests/workspace-management.e2e.ts +++ b/apps/web/tests/workspace-management.e2e.ts @@ -124,7 +124,7 @@ describe('web e2e: workspace management (create / rename / flat view / hover aff browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index d23a564580..e32509f544 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/module-graph.md -module-graph.md: 3fce90069441b683f449b4b16def95d8d9acc323 -module-graph.zh.md: f7431bd5a417ff6c5de4efe22a1d711611b1ffee +module-graph.md: cc8eaf8b49dc95568d34a4d57e9cbff8d30656c1 +module-graph.zh.md: 73ba9081455a265194aae943fb96efc0ec95d38f diff --git a/docs/module-graph.md b/docs/module-graph.md index 3fce900694..cc8eaf8b49 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -399,8 +399,6 @@ flowchart TD pkg_subprocess_e2b --> pkg_invariants pkg_subprocess_e2b --> pkg_subprocess pkg_subprocess_e2b --> pkg_timeout - pkg_host_frontend_static --> pkg_host_webserver - pkg_host_frontend_static --> pkg_invariants pkg_host_plugin_inventory --> pkg_brand pkg_host_plugin_inventory --> pkg_invariants pkg_host_plugin_inventory --> pkg_typert_protocol @@ -1076,6 +1074,7 @@ flowchart TD pkg_tool_session_query --> pkg_tools pkg_client_connection --> pkg_attachment pkg_client_connection --> pkg_commands + pkg_client_connection --> pkg_credentials pkg_client_connection --> pkg_host_apiproxy pkg_client_connection --> pkg_host_webserver pkg_client_connection --> pkg_invariants @@ -1195,6 +1194,9 @@ flowchart TD pkg_experimental_agent_team --> pkg_session pkg_experimental_agent_team --> pkg_session_persistence pkg_experimental_agent_team --> pkg_subagent + pkg_host_frontend_static --> pkg_client_connection + pkg_host_frontend_static --> pkg_host_webserver + pkg_host_frontend_static --> pkg_invariants pkg_sdk_protocol --> pkg_invariants pkg_sdk_protocol --> pkg_llm pkg_sdk_protocol --> pkg_session @@ -1696,7 +1698,6 @@ flowchart TD | [`client-modules`](../packages/client/modules) | `client` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`credentials`](../packages/credentials/credentials) | `credentials` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`subprocess-e2b`](../packages/e2b/subprocess-e2b) | `e2b` | [`e2b`](../packages/e2b/e2b), [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | -| [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`typert-protocol`](../packages/typert/protocol) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`settings`](../packages/settings/settings) | `settings` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) | @@ -1829,7 +1830,7 @@ flowchart TD | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`tool-session-query`](../packages/session-query/tool-session-query) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | -| [`client-connection`](../packages/client/connection) | `client` | [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`host-apiproxy`](../packages/host/apiproxy), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tool-todo`](../packages/todo/tool-todo) | +| [`client-connection`](../packages/client/connection) | `client` | [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`host-apiproxy`](../packages/host/apiproxy), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tool-todo`](../packages/todo/tool-todo) | | [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`typert-protocol`](../packages/typert/protocol) | | [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs-local`](../packages/jobs/jobs-local), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`shell-env`](../packages/shell/shell-env), [`skill`](../packages/skill/skill), [`skill-filesystem`](../packages/skill/skill-filesystem), [`system-prompt`](../packages/core/system-prompt), [`tool-bash`](../packages/shell/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-skill`](../packages/skill/tool-skill), [`tools`](../packages/core/tools) | @@ -1845,6 +1846,7 @@ flowchart TD | [`hooks-claude-code`](../packages/hooks/hooks-claude-code) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`api-gateway`](../packages/api/gateway) | `api` | [`brand`](../packages/util/brand), [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants), [`typert-registry`](../packages/typert/registry) | | [`experimental-agent-team`](../packages/experimental/agent-team) | `experimental` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`subagent`](../packages/subagent/subagent) | +| [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`tool-ralph`](../packages/workflow/tool-ralph) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`workflow-worker-thread`](../packages/workflow/workflow-worker-thread) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index f7431bd5a4..73ba908145 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -401,8 +401,6 @@ flowchart TD pkg_subprocess_e2b --> pkg_invariants pkg_subprocess_e2b --> pkg_subprocess pkg_subprocess_e2b --> pkg_timeout - pkg_host_frontend_static --> pkg_host_webserver - pkg_host_frontend_static --> pkg_invariants pkg_host_plugin_inventory --> pkg_brand pkg_host_plugin_inventory --> pkg_invariants pkg_host_plugin_inventory --> pkg_typert_protocol @@ -1078,6 +1076,7 @@ flowchart TD pkg_tool_session_query --> pkg_tools pkg_client_connection --> pkg_attachment pkg_client_connection --> pkg_commands + pkg_client_connection --> pkg_credentials pkg_client_connection --> pkg_host_apiproxy pkg_client_connection --> pkg_host_webserver pkg_client_connection --> pkg_invariants @@ -1197,6 +1196,9 @@ flowchart TD pkg_experimental_agent_team --> pkg_session pkg_experimental_agent_team --> pkg_session_persistence pkg_experimental_agent_team --> pkg_subagent + pkg_host_frontend_static --> pkg_client_connection + pkg_host_frontend_static --> pkg_host_webserver + pkg_host_frontend_static --> pkg_invariants pkg_sdk_protocol --> pkg_invariants pkg_sdk_protocol --> pkg_llm pkg_sdk_protocol --> pkg_session @@ -1698,7 +1700,6 @@ flowchart TD | [`client-modules`](../packages/client/modules) | `client` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`credentials`](../packages/credentials/credentials) | `credentials` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`subprocess-e2b`](../packages/e2b/subprocess-e2b) | `e2b` | [`e2b`](../packages/e2b/e2b), [`invariants`](../packages/runtime-diagnostics/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | -| [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`typert-protocol`](../packages/typert/protocol) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`settings`](../packages/settings/settings) | `settings` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) | @@ -1831,7 +1832,7 @@ flowchart TD | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`tool-session-query`](../packages/session-query/tool-session-query) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | -| [`client-connection`](../packages/client/connection) | `client` | [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`host-apiproxy`](../packages/host/apiproxy), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tool-todo`](../packages/todo/tool-todo) | +| [`client-connection`](../packages/client/connection) | `client` | [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`host-apiproxy`](../packages/host/apiproxy), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tool-todo`](../packages/todo/tool-todo) | | [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`typert-protocol`](../packages/typert/protocol) | | [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs-local`](../packages/jobs/jobs-local), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`shell-env`](../packages/shell/shell-env), [`skill`](../packages/skill/skill), [`skill-filesystem`](../packages/skill/skill-filesystem), [`system-prompt`](../packages/core/system-prompt), [`tool-bash`](../packages/shell/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-skill`](../packages/skill/tool-skill), [`tools`](../packages/core/tools) | @@ -1847,6 +1848,7 @@ flowchart TD | [`hooks-claude-code`](../packages/hooks/hooks-claude-code) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`api-gateway`](../packages/api/gateway) | `api` | [`brand`](../packages/util/brand), [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants), [`typert-registry`](../packages/typert/registry) | | [`experimental-agent-team`](../packages/experimental/agent-team) | `experimental` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`subagent`](../packages/subagent/subagent) | +| [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`tool-ralph`](../packages/workflow/tool-ralph) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`workflow-worker-thread`](../packages/workflow/workflow-worker-thread) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | diff --git a/packages/api/remotes/tests/built-lib.e2e.ts b/packages/api/remotes/tests/built-lib.e2e.ts index 232cf9b2f6..92c5c7c621 100644 --- a/packages/api/remotes/tests/built-lib.e2e.ts +++ b/packages/api/remotes/tests/built-lib.e2e.ts @@ -58,6 +58,7 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { const { Session, SessionId } = await import(urls.session) const routes = [] + const credentialRecords = new Map() const host = new Context() host.provide('webServer', { register(route) { @@ -67,6 +68,15 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { tapIndex() { return () => {} }, port: 0, }) + host.provide('credentials', { + readRecord(key) { return Promise.resolve(credentialRecords.get(key)) }, + async modifyRecord(key, mutate) { + const current = credentialRecords.get(key) + const next = await mutate(current) + if (next !== undefined) credentialRecords.set(key, next) + return next ?? current + }, + }) await host.plugin({ inject: connectionHost.inject, apply: connectionHost.apply }) await host.plugin(TypertRegistry) await host.plugin(AgentRegistry) @@ -101,11 +111,32 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { if (routes.length !== 1 || routes[0].path !== '/api') { throw new Error('Connection did not register exactly one /api route') } - const server = createServer((request, response) => { void routes[0].handler(request, response) }) + const server = createServer((request, response) => { + if ((request.url ?? '/').startsWith('/?')) { + void host.connection.authorizeIndex(request, response).then(authorized => { + if (authorized) { + response.writeHead(200, { 'content-type': 'text/html' }) + response.end('shell') + } + }) + return + } + void routes[0].handler(request, response) + }) await new Promise(resolveListen => server.listen(0, '127.0.0.1', resolveListen)) const address = server.address() if (address === null || typeof address === 'string') throw new Error('HTTP server has no TCP address') const origin = 'http://127.0.0.1:' + String(address.port) + const login = await fetch(host.connection.authenticatedUrl(origin), { redirect: 'manual' }) + const setCookie = login.headers.get('set-cookie') + if (login.status !== 303 || setCookie === null) throw new Error('browser token exchange failed') + const cookie = setCookie.split(';', 1)[0] + const hostFetch = globalThis.fetch + globalThis.fetch = (input, init = {}) => { + const headers = new Headers(init.headers) + headers.set('cookie', cookie) + return hostFetch(input, { ...init, headers }) + } const handoffs = new Map() globalThis.window = { diff --git a/packages/bundle/web-app/tests/browser-open.spec.ts b/packages/bundle/web-app/tests/browser-open.spec.ts index 0e2e22649d..5c1560c445 100644 --- a/packages/bundle/web-app/tests/browser-open.spec.ts +++ b/packages/bundle/web-app/tests/browser-open.spec.ts @@ -29,6 +29,7 @@ afterEach(async () => { vi.unstubAllEnvs() Reflect.deleteProperty(globalThis, '__dshWebAppApply') Reflect.deleteProperty(globalThis, '__dshWebServer') + Reflect.deleteProperty(globalThis, '__dshConnection') }) describe('web app browser startup', () => { @@ -42,8 +43,14 @@ describe('web app browser startup', () => { internals.resolveDistIndex = () => index const webserverModule = join(root, 'webserver.mjs') + const connectionModule = join(root, 'connection.mjs') const webAppModule = join(root, 'web-app.mjs') writeFileSync(webserverModule, 'export default globalThis.__dshWebServer\n') + writeFileSync(connectionModule, [ + "export const inject = ['webServer']", + "export const apply = ctx => ctx.provide('connection', globalThis.__dshConnection)", + '', + ].join('\n')) writeFileSync(webAppModule, [ "export const name = 'fixture-web-app'", "export const inject = ['webServer']", @@ -57,6 +64,8 @@ describe('web app browser startup', () => { ' config:', ' host: 127.0.0.1', ' port: 0', + '- id: connection', + ` name: ${pathToFileURL(connectionModule).href}`, '- id: web-app', ` name: ${pathToFileURL(webAppModule).href}`, ' config:', @@ -70,9 +79,25 @@ describe('web app browser startup', () => { const globals = globalThis as unknown as { __dshWebAppApply: typeof apply __dshWebServer: typeof WebServer + __dshConnection: { + authenticatedUrl(baseUrl: string): string + authorizeIndex(): Promise + requestRejection(): Promise + rpc: object + } } globals.__dshWebAppApply = apply globals.__dshWebServer = WebServer + globals.__dshConnection = { + authenticatedUrl: (baseUrl) => { + const url = new URL(baseUrl) + url.searchParams.set('token', 'fixture-token') + return url.href + }, + authorizeIndex: () => Promise.resolve(true), + requestRejection: () => Promise.resolve(undefined), + rpc: {}, + } let openedUrl: string | undefined let openedStatus: number | undefined @@ -95,7 +120,7 @@ describe('web app browser startup', () => { await ctx.loader.await() await opened - expect(openedUrl).toBe(`http://127.0.0.1:${String(ctx.webServer.port)}`) + expect(openedUrl).toBe(`http://127.0.0.1:${String(ctx.webServer.port)}/?token=fixture-token`) expect(openedStatus).toBe(200) }) }) diff --git a/packages/bundle/web-app/tests/web-app.spec.ts b/packages/bundle/web-app/tests/web-app.spec.ts index 90f7063bf7..4376147e47 100644 --- a/packages/bundle/web-app/tests/web-app.spec.ts +++ b/packages/bundle/web-app/tests/web-app.spec.ts @@ -286,6 +286,7 @@ describe('web-app runtime glue', () => { const tornSettlement = new Promise((resolve) => { releaseTorn = resolve }) provideLoader(torn, () => tornSettlement) apply(torn, new Config({ openBrowser: true, printUrl: true, surfaceContext: true, trustedHosts: [] })) + await new Promise(resolve => setTimeout(resolve, 0)) await child.dispose() // the webServer service goes away releaseTorn!() await new Promise(resolve => setTimeout(resolve, 0)) diff --git a/packages/client/connection/src/browser-auth.ts b/packages/client/connection/src/browser-auth.ts index 7c57622bb2..1f2bd8768a 100644 --- a/packages/client/connection/src/browser-auth.ts +++ b/packages/client/connection/src/browser-auth.ts @@ -16,6 +16,7 @@ const TOKEN_QUERY = 'token' const COOKIE_PREFIX = 'dsh-auth-' const COOKIE_PAYLOAD_VERSION = 1 const STORED_SECRET_VERSION = 1 +const BASE64URL_PATTERN = /^[A-Za-z0-9_-]*$/ interface StoredSecretPayload { readonly version: typeof STORED_SECRET_VERSION @@ -33,6 +34,20 @@ function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } +function encodeBase64Url(value: Uint8Array): string { + return Buffer.from(value).toString('base64') + .replaceAll('+', '-') + .replaceAll('/', '_') + .replace(/=+$/u, '') +} + +function decodeBase64Url(value: string): Buffer | undefined { + if (!BASE64URL_PATTERN.test(value) || value.length % 4 === 1) return undefined + const padding = '='.repeat((4 - value.length % 4) % 4) + const decoded = Buffer.from(value.replaceAll('-', '+').replaceAll('_', '/') + padding, 'base64') + return encodeBase64Url(decoded) === value ? decoded : undefined +} + function header( headers: ConnectionTrustRequest['headers'], name: string, @@ -55,8 +70,8 @@ function requestAuthority(headers: ConnectionTrustRequest['headers']): string | function canonicalSecret(value: unknown): Buffer | undefined { if (typeof value !== 'string') return undefined - const decoded = Buffer.from(value, 'base64url') - if (decoded.byteLength !== SECRET_BYTES || decoded.toString('base64url') !== value) return undefined + const decoded = decodeBase64Url(value) + if (decoded === undefined || decoded.byteLength !== SECRET_BYTES) return undefined return decoded } @@ -80,7 +95,7 @@ function tokenMatches(actual: string, expected: string): boolean { } function cookieName(authority: string): string { - return COOKIE_PREFIX + createHash('sha256').update(authority).digest('base64url') + return COOKIE_PREFIX + encodeBase64Url(createHash('sha256').update(authority).digest()) } /** Read the exact generated cookie without implementing general Cookie decoding. */ @@ -103,8 +118,8 @@ function signature(secret: Buffer, body: string): Buffer { } function encodeCookie(payload: BrowserCookiePayload, secret: Buffer): string { - const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url') - return `v1.${body}.${signature(secret, body).toString('base64url')}` + const body = encodeBase64Url(Buffer.from(JSON.stringify(payload), 'utf8')) + return `v1.${body}.${encodeBase64Url(signature(secret, body))}` } function decodeCookie(value: string, secret: Buffer): BrowserCookiePayload | undefined { @@ -113,14 +128,16 @@ function decodeCookie(value: string, secret: Buffer): BrowserCookiePayload | und if (parts.length !== 3 || version !== 'v1' || body === undefined || encodedSignature === undefined) { return undefined } - const actualSignature = Buffer.from(encodedSignature, 'base64url') - if (actualSignature.toString('base64url') !== encodedSignature) return undefined + const actualSignature = decodeBase64Url(encodedSignature) + if (actualSignature === undefined) return undefined const expectedSignature = signature(secret, body) if (actualSignature.byteLength !== expectedSignature.byteLength || !timingSafeEqual(actualSignature, expectedSignature)) return undefined let decoded: unknown try { - decoded = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) + const bodyBytes = decodeBase64Url(body) + if (bodyBytes === undefined) return undefined + decoded = JSON.parse(bodyBytes.toString('utf8')) } catch { return undefined } @@ -139,7 +156,7 @@ function decodeCookie(value: string, secret: Buffer): BrowserCookiePayload | und * process restart. */ export class BrowserAuth { - private readonly launchToken = randomBytes(SECRET_BYTES).toString('base64url') + private readonly launchToken = encodeBase64Url(randomBytes(SECRET_BYTES)) private readonly maxAgeMilliseconds: number private constructor( @@ -248,7 +265,7 @@ export class BrowserAuth { private async ensureSecret(): Promise { const generated: StoredSecretPayload = { version: STORED_SECRET_VERSION, - secret: randomBytes(SECRET_BYTES).toString('base64url'), + secret: encodeBase64Url(randomBytes(SECRET_BYTES)), } const record = await this.credentials.modifyRecord(AUTH_RECORD_KEY, (current) => { if (current !== undefined) { diff --git a/packages/client/connection/tests/api-request-trust.host.spec.ts b/packages/client/connection/tests/api-request-trust.host.spec.ts index f145230a8b..359a461e94 100644 --- a/packages/client/connection/tests/api-request-trust.host.spec.ts +++ b/packages/client/connection/tests/api-request-trust.host.spec.ts @@ -68,6 +68,13 @@ describe('isTrustedApiRequest', () => { expect(isTrustedApiRequest(request({ host: 'localhost:3080', 'sec-fetch-site': 'same-origin' }), [])).toBe(true) }) + it('reads Fetch Headers while preserving absent browser markers', () => { + expect(isTrustedApiRequest({ headers: new Headers({ host: '127.0.0.1:3080' }) }, [])).toBe(true) + expect(isTrustedApiRequest({ + headers: new Headers({ host: '127.0.0.1:3080', origin: 'http://evil.example' }), + }, [])).toBe(false) + }) + it('assertTrustedAuthority accepts bare authorities and throws on anything more', () => { for (const entry of ['harness.internal', 'harness.internal:3080', 'HARNESS.internal:80', '10.0.0.9', '[::1]:3080']) { expect(() => { assertTrustedAuthority(entry) }).not.toThrow() diff --git a/packages/client/connection/tests/browser-auth.host.spec.ts b/packages/client/connection/tests/browser-auth.host.spec.ts index 21ce8f592b..6a62d6401c 100644 --- a/packages/client/connection/tests/browser-auth.host.spec.ts +++ b/packages/client/connection/tests/browser-auth.host.spec.ts @@ -31,15 +31,19 @@ class RecordCredentials { } function signedCookie(store: RecordCredentials, name: string, payload: unknown): string { + const body = typeof payload === 'string' + ? Buffer.from(payload, 'utf8').toString('base64url') + : Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url') + return signedBodyCookie(store, name, body) +} + +function signedBodyCookie(store: RecordCredentials, name: string, body: string): string { const record = store.record if (record?.kind !== 'grant' || typeof record.payload !== 'object' || record.payload === null) { throw new Error('test credential store has no signing secret') } const secret: unknown = Reflect.get(record.payload, 'secret') if (typeof secret !== 'string') throw new Error('test credential record has no string secret') - const body = typeof payload === 'string' - ? Buffer.from(payload, 'utf8').toString('base64url') - : Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url') const signature = createHmac('sha256', Buffer.from(secret, 'base64url')).update(body).digest('base64url') return `${name}=v1.${body}.${signature}` } @@ -169,6 +173,9 @@ describe('BrowserAuth', () => { expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=broken` }))).toBe(false) expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=${value.slice(0, -1)}x` }))).toBe(false) expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=%` }))).toBe(false) + expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { + cookie: signedBodyCookie(store, name, 'a'), + }))).toBe(false) expect(await auth.isAuthenticated({ headers: {} })).toBe(false) expect(await auth.isAuthenticated({ headers: { host: 'bad host', cookie } })).toBe(false) expect(await auth.isAuthenticated({ headers: { host: '127.0.0.1:3080' } })).toBe(false) diff --git a/packages/experimental/webworker-runtime/src/transport/tunnel.ts b/packages/experimental/webworker-runtime/src/transport/tunnel.ts index b181e89687..dc6608f975 100644 --- a/packages/experimental/webworker-runtime/src/transport/tunnel.ts +++ b/packages/experimental/webworker-runtime/src/transport/tunnel.ts @@ -4,11 +4,9 @@ * * - `GET /__boot__` answers from tunnel glue, never from the host API surface, * because the page needs the boot payload before its Cordis tree exists. - * - Privileged `/api` methods take that same direct entry: the browser strips the - * `host` header from the WHATWG `Request` the route lane rebuilds, so the - * privileged fence would answer 403 for every one of them. The method set is - * not restated here — an unexpected 403 from the route lane is retried on the - * direct lane, which keeps the split honest without a copied list. + * - Privileged `/api` methods take that same direct entry. The method set is not + * restated here: a 401 or 403 from the route lane is retried on the direct + * lane because the page owns the worker and needs no network authentication. * - Everything else is fed into the real webserver route table through the * request listener the app's fake `node:http` captured, keeping the trust * fences, byte limits, and status semantics intact. @@ -88,7 +86,7 @@ export interface TunnelPort { export interface TunnelSeams { /** * Direct entry to the API fetch handler for privileged methods and any unary - * call the route lane refused with 403. + * call the route lane refused with 401 or 403. */ readonly directFetch: (request: Request) => Promise /** Boot payload for `GET /__boot__`: the structured index injection table. */ @@ -118,12 +116,12 @@ export interface TunnelServerOptions { readonly requestListener: () => Promise /** * Methods that skip the route lane outright. Supply the host's own privileged - * set when it is reachable; omitting it leaves the 403 retry as the mechanism. + * set when it is reachable; omitting it leaves the 401/403 retry as the mechanism. */ readonly privilegedMethods?: ReadonlySet /** * Escape hatch for the unary `/api` lane. `route` (default) keeps every fence - * and byte limit with a 403 retry on the direct lane; `direct` sends every + * and byte limit with a 401/403 retry on the direct lane; `direct` sends every * unary `/api` call straight to the fetch handler. */ readonly unaryApiLane?: 'route' | 'direct' @@ -135,7 +133,7 @@ interface InFlight { type QueuedFrame = TunnelRequestFrame | TunnelStreamOpenFrame -/** Recorded response frames, so a 403 from the route lane can be discarded. */ +/** Recorded response frames, so a route-lane authentication refusal can be discarded. */ class BufferedSink { private readonly calls: Array<() => void> = [] private target: ResponseSink | undefined @@ -228,7 +226,7 @@ export class TunnelServer { */ serve(seams: TunnelSeams): void { this.seams = seams - console.info(`webworker tunnel: serving (unary /api lane=${this.unaryApiLane}${this.unaryApiLane === 'route' ? ' with 403 retry' : ''}, privileged set=${this.privilegedMethods === undefined ? 'none' : String(this.privilegedMethods.size)}, queued=${String(this.queue.length)})`) + console.info(`webworker tunnel: serving (unary /api lane=${this.unaryApiLane}${this.unaryApiLane === 'route' ? ' with 401/403 retry' : ''}, privileged set=${this.privilegedMethods === undefined ? 'none' : String(this.privilegedMethods.size)}, queued=${String(this.queue.length)})`) for (const frame of this.queue.splice(0)) this.dispatchFrame(frame) } @@ -380,7 +378,7 @@ export class TunnelServer { /** * Unary `/api`: keep the route lane's fences, but fall back to the direct lane - * when the privileged fence refuses a request the page is entitled to make. + * when network authentication or trust rejects the worker-owning page. */ private async serveApi( original: TunnelRequestFrame, @@ -405,9 +403,8 @@ export class TunnelServer { if (outcome === 'aborted' || exchange.aborted) return // The decision happens at the first frame, before anything reaches the page: // the route lane streams its answers, so a refusal can carry a body too. - if (outcome.status === 403) { - // The privileged fence read a Request the browser stripped `host` from. - console.debug(`webworker tunnel: route lane refused ${method} with 403; answering on the direct lane`) + if (outcome.status === 401 || outcome.status === 403) { + console.debug(`webworker tunnel: route lane refused ${method} with ${String(outcome.status)}; answering on the direct lane`) await this.serveDirect(original, sink) return } diff --git a/packages/experimental/webworker-runtime/src/worker-host.ts b/packages/experimental/webworker-runtime/src/worker-host.ts index bbbf6a3900..27ffb27214 100644 --- a/packages/experimental/webworker-runtime/src/worker-host.ts +++ b/packages/experimental/webworker-runtime/src/worker-host.ts @@ -356,9 +356,9 @@ function requireLoweredImage(vfs: MemoryVfs, path: string): void { * endpoints (`/api//`) are served by an interceptor the gateway * registers on the Connection service, and answer 404 from the core routes. The * Connection service composes both halves in `createSharedFetchHandler`, whose - * fallback — not the composition — carries the privileged fence, so composing it - * here keeps every interceptor while leaving out the fence the direct lane exists - * to bypass. + * fallback — not the composition — carries network authentication and trust, so + * composing it here keeps every interceptor while leaving out the fences the + * worker-local direct lane exists to bypass. * @param ctx - Booted host context. * @param core - Fetch handler over the API surface. * @returns Handler covering interceptors and the core surface. diff --git a/packages/experimental/webworker-runtime/tests/transport/tunnel-server.spec.ts b/packages/experimental/webworker-runtime/tests/transport/tunnel-server.spec.ts index f9107e1037..0a32e77753 100644 --- a/packages/experimental/webworker-runtime/tests/transport/tunnel-server.spec.ts +++ b/packages/experimental/webworker-runtime/tests/transport/tunnel-server.spec.ts @@ -24,6 +24,42 @@ function seams(openStream: TunnelSeams['openStream']): TunnelSeams { } } +describe('worker tunnel unary authentication', () => { + it.each([401, 403])('retries a route-lane HTTP %s through the worker-local direct lane', async (status) => { + const frames: TunnelOutboundFrame[] = [] + const directFetch = vi.fn(async () => new Response('direct answer', { + status: 200, + headers: { 'content-type': 'text/plain' }, + })) + const server = new TunnelServer({ + port: { postMessage: (frame) => { frames.push(frame) } }, + requestListener: () => Promise.resolve((_req, response) => { + const res = response as { + writeHead(status: number, headers: Record): void + end(body: string): void + } + res.writeHead(status, { 'content-type': 'text/plain' }) + res.end('network request rejected') + }), + }) + server.serve({ + ...seams(async () => (async function *(): AsyncGenerator { yield undefined })()), + directFetch, + }) + + server.handleMessage({ + t: 'req', id: status, method: 'POST', url: 'http://localhost/api/session/list', headers: {}, + }) + + await vi.waitFor(() => { expect(frames).toHaveLength(1) }) + const [frame] = frames + expect(frame).toMatchObject({ t: 'res', id: status, status: 200 }) + if (frame?.t !== 'res' || frame.body === undefined) throw new Error('direct retry did not return one body') + expect(new TextDecoder().decode(frame.body)).toBe('direct answer') + expect(directFetch).toHaveBeenCalledOnce() + }) +}) + describe('worker tunnel logical streams', () => { it('drains a pre-boot open through the worker-local Gateway seam', async () => { const { server, frames } = harness() From 3b3b493a9607a2cbbebd3b01b89c8b328d15edeb Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Tue, 25 Aug 2026 02:21:42 +0800 Subject: [PATCH 25/31] fix(web): retain launch token across reloads --- ...-24-browser-token-authentication.i18n.yaml | 4 +- ...2026-08-24-browser-token-authentication.md | 6 +-- ...6-08-24-browser-token-authentication.zh.md | 6 +-- docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- packages/bundle/web-app/src/index.ts | 3 ++ packages/bundle/web-app/tests/web-app.spec.ts | 18 +++++++ .../client/connection/src/browser-auth.ts | 31 ++++++++++-- packages/client/connection/src/index.ts | 2 +- .../tests/browser-auth.host.spec.ts | 50 +++++++++++++++---- 11 files changed, 101 insertions(+), 27 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml index 0691ce60ab..126c669ced 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md -2026-08-24-browser-token-authentication.md: 515990b81f3c92b7f3c422dcc40acfed1e5996ac -2026-08-24-browser-token-authentication.zh.md: 8066e2c3f62245779c6a03b5160c41e4bbc94ba5 +2026-08-24-browser-token-authentication.md: 69f24c148a1054f99447f1f9f2a6d2e5540c83db +2026-08-24-browser-token-authentication.zh.md: e9b96af21e913c1c3e482940c9f65d0d37506c81 diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md index 515990b81f..69f24c148a 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -12,11 +12,11 @@ The Web Host runs tool-capable Sessions with the current operating-system user's `dsh-client-connection` authenticates the complete Host API before dispatch. Every API Proxy method, Remote unary call, generic Connection channel, and Remote WebSocket stream requires the same browser session; endpoint ownership and method names do not alter authority. The existing Host/Origin checks run first and retain their DNS-rebinding and cross-site-request role, returning 403 when they fail. A trusted Host without a valid browser session receives 401. The browser-trust rules remain owned by the [carrier-level browser trust decision](2026-07-28-api-browser-trust-boundary.md). -Each Connection process generates a random launch token. `dsh-web-app` prints and opens the normal root URL with that token in the query. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `/`; the token is not accepted on API paths or in an Authorization header. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public. +Each Host process generates a random launch token, retained by the root application context across Connection hot reloads. `dsh-web-app` prints and opens the normal root URL with that token in the query once per process. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `/`; the token is not accepted on API paths or in an Authorization header. An obsolete token paired with a valid cookie redirects to clean `/`. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public. The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. It omits `Secure` because the shipped server uses loopback HTTP. There is no logout operation or reverse-proxy-specific handling. -The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection reads the record for each verification, so deletion or replacement revokes every existing cookie without restarting the process. A missing record is recreated only by a valid process-token exchange. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. +The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection reads the record for each verification, so deletion or replacement revokes every existing cookie without restarting the process. A missing record is created when Connection starts; after runtime deletion, the next valid process-token exchange or process start recreates it. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. The in-page Web Worker preview exposes no network socket. Its page-owned `postMessage` tunnel enters the real route first, then retries a 401 or 403 through the worker-local fetch handler. This keeps Connection interceptors while limiting the authentication bypass to the page that created the Host worker. @@ -24,7 +24,7 @@ The shipped CLI continues to reject `--host 0.0.0.0`. Authentication does not im ## Verification -Unit coverage pins token comparison, cookie attributes, HMAC and payload validation, authority and lifetime checks, persistent-secret reuse, record deletion, and invalid durable records. Host transport suites pin uniform 401/403 behavior for API Proxy, generic RPC, Typert Remote HTTP, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `host.describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. +Unit coverage pins process-token retention across Connection reloads, cookie attributes, HMAC and payload validation, authority and lifetime checks, persistent-secret reuse, record deletion, invalid durable records, and cleanup of obsolete token URLs backed by valid cookies. Host transport suites pin uniform 401/403 behavior for API Proxy, generic RPC, Typert Remote HTTP, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `host.describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md index 8066e2c3f6..e9b96af21e 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -12,11 +12,11 @@ Web Host 以当前操作系统用户的权限运行具有工具能力的 Session `dsh-client-connection` 在分发前认证完整 Host API。每个 API Proxy 方法、Remote 一元调用、通用 Connection channel 和 Remote WebSocket stream 都要求同一个浏览器会话;endpoint 所有权与方法名称不改变 authority。既有 Host/Origin 校验先执行,继续负责 DNS rebinding 和跨站请求防御,失败时返回 403。Host 可信但没有有效浏览器会话时返回 401。浏览器信任规则仍由[载体级浏览器信任决策](2026-07-28-api-browser-trust-boundary.zh.md)持有。 -每个 Connection 进程生成随机启动令牌。`dsh-web-app` 打印并打开 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `/`;API 路径和 Authorization header 都不接受该令牌。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。 +每个 Host 进程生成随机启动令牌,并由应用根 context 跨 Connection 热重载保留。`dsh-web-app` 每个进程只打印并打开一次 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `/`;API 路径和 Authorization header 都不接受该令牌。过时令牌如果同时带有有效 cookie,会重定向到干净的 `/`。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。 cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。随附服务器使用 loopback HTTP,因此不设置 `Secure`。这里没有 logout 操作或反向代理专用处理。 -HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 每次校验都读取记录,因此删除或替换记录无需重启进程即可撤销全部既有 cookie。缺失记录只能由有效进程令牌交换重新创建。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 +HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 每次校验都读取记录,因此删除或替换记录无需重启进程即可撤销全部既有 cookie。缺失记录在 Connection 启动时创建;运行期删除后,由下一次有效进程令牌交换或进程启动重新创建。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 页内 Web Worker preview 不暴露网络 socket。其由页面持有的 `postMessage` tunnel 先进入真实 route,收到 401 或 403 后再经 worker 本地 fetch handler 重试。这样既保留 Connection interceptor,又把认证绕过限制在创建 Host worker 的页面内。 @@ -24,7 +24,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` ## 验证 -单元覆盖固定令牌比较、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、持久密钥复用、记录删除及无效持久记录。Host 传输套件固定 API Proxy、通用 RPC、Typert Remote HTTP 和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `host.describe`,观测新的进程令牌,并在重启后复用旧 cookie。 +单元覆盖 Connection 重载时保留进程令牌、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、持久密钥复用、记录删除、无效持久记录,以及用有效 cookie 清理过时令牌 URL。Host 传输套件固定 API Proxy、通用 RPC、Typert Remote HTTP 和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `host.describe`,观测新的进程令牌,并在重启后复用旧 cookie。 ## 曾考虑的替代方案 diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 15b0eabc28..222437150c 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: a4eeb7ffbe09253d7f0f979cd8dc681b4ae038ac -config-catalog.zh.md: 8490829a7881e6503fdf7b7652c679e5d3cc0f3c +config-catalog.md: aaeb30309288b2864c510cf7ebf6674988c568d1 +config-catalog.zh.md: ec649715bc74f2eb11c366b2eeca5026afdcdd6f diff --git a/docs/config-catalog.md b/docs/config-catalog.md index a4eeb7ffbe..aaeb303092 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -3143,7 +3143,7 @@ export interface Config { } ``` -Source: [`packages/bundle/web-app/src/index.ts:44`](../packages/bundle/web-app/src/index.ts) +Source: [`packages/bundle/web-app/src/index.ts:45`](../packages/bundle/web-app/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 8490829a78..ec649715bc 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -3145,7 +3145,7 @@ export interface Config { } ``` -来源:[`packages/bundle/web-app/src/index.ts:44`](../packages/bundle/web-app/src/index.ts) +来源:[`packages/bundle/web-app/src/index.ts:45`](../packages/bundle/web-app/src/index.ts) diff --git a/packages/bundle/web-app/src/index.ts b/packages/bundle/web-app/src/index.ts index 5ec4ae7072..d0b2635f8e 100644 --- a/packages/bundle/web-app/src/index.ts +++ b/packages/bundle/web-app/src/index.ts @@ -33,6 +33,7 @@ export const name = 'web-app' /** This dsh installation's root, from either this package's source or built entry. */ const SOURCE_ROOT = fileURLToPath(new URL('../../../..', import.meta.url)) +const ANNOUNCED_ROOTS = new WeakSet() /** Runtime service that releases Web rows after bind-dependent values resolve. */ const WEB_RUNTIME_SERVICE = 'webRuntime' @@ -266,6 +267,7 @@ export function apply(ctx: Context, config: Config): void { // route owner are still mounting. Await Loader settlement first; a // hand-built tree without a Loader is already the complete tree. const announceReady = (): void => { + if (ANNOUNCED_ROOTS.has(connectionCtx.root)) return const webUrl = localWebUrl(connectionCtx) const authenticatedUrl = connectionCtx.connection.authenticatedUrl(webUrl) // Reuse the exact LAN snapshot provided to the /api trust fence. @@ -274,6 +276,7 @@ export function apply(ctx: Context, config: Config): void { const lanUrl = lanCandidate === undefined ? undefined : connectionCtx.connection.authenticatedUrl(`http://${lanCandidate}:${String(port)}`) + ANNOUNCED_ROOTS.add(connectionCtx.root) if (config.printUrl) { console.log(`dsh web: ${authenticatedUrl}${lanUrl === undefined ? '' : ` (LAN: ${lanUrl})`}`) } diff --git a/packages/bundle/web-app/tests/web-app.spec.ts b/packages/bundle/web-app/tests/web-app.spec.ts index 4376147e47..6a6f8c8c15 100644 --- a/packages/bundle/web-app/tests/web-app.spec.ts +++ b/packages/bundle/web-app/tests/web-app.spec.ts @@ -216,6 +216,24 @@ describe('web-app runtime glue', () => { await ctx.fiber.dispose() }) + it('does not publish readiness again when Connection reloads', async () => { + stageDist() + const ctx = new Context() + ctx.provide('webServer', fakeHttpServer().server) + const first = ctx.plugin((connectionCtx: Context) => { provideConnection(connectionCtx) }) + await first + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + apply(ctx, new Config({ openBrowser: false, printUrl: true, surfaceContext: true, trustedHosts: [] })) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(log).toHaveBeenCalledTimes(1) + + await first.dispose() + await ctx.plugin((connectionCtx: Context) => { provideConnection(connectionCtx) }) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(log).toHaveBeenCalledTimes(1) + await ctx.fiber.dispose() + }) + it.each([ ['SSH_CONNECTION', '10.0.0.2 55000 10.0.0.9 22'], ['SSH_TTY', '/dev/pts/3'], diff --git a/packages/client/connection/src/browser-auth.ts b/packages/client/connection/src/browser-auth.ts index 1f2bd8768a..3316b746bc 100644 --- a/packages/client/connection/src/browser-auth.ts +++ b/packages/client/connection/src/browser-auth.ts @@ -17,6 +17,7 @@ const COOKIE_PREFIX = 'dsh-auth-' const COOKIE_PAYLOAD_VERSION = 1 const STORED_SECRET_VERSION = 1 const BASE64URL_PATTERN = /^[A-Za-z0-9_-]*$/ +const PROCESS_LAUNCH_TOKENS = new WeakMap() interface StoredSecretPayload { readonly version: typeof STORED_SECRET_VERSION @@ -48,6 +49,14 @@ function decodeBase64Url(value: string): Buffer | undefined { return encodeBase64Url(decoded) === value ? decoded : undefined } +function processLaunchToken(owner: object): string { + const existing = PROCESS_LAUNCH_TOKENS.get(owner) + if (existing !== undefined) return existing + const created = encodeBase64Url(randomBytes(SECRET_BYTES)) + PROCESS_LAUNCH_TOKENS.set(owner, created) + return created +} + function header( headers: ConnectionTrustRequest['headers'], name: string, @@ -156,13 +165,15 @@ function decodeCookie(value: string, secret: Buffer): BrowserCookiePayload | und * process restart. */ export class BrowserAuth { - private readonly launchToken = encodeBase64Url(randomBytes(SECRET_BYTES)) + private readonly launchToken: string private readonly maxAgeMilliseconds: number private constructor( + processOwner: object, private readonly credentials: CredentialProvider, maxAgeDays: number, ) { + this.launchToken = processLaunchToken(processOwner) this.maxAgeMilliseconds = maxAgeDays * DAY_MILLISECONDS if (!Number.isSafeInteger(this.maxAgeMilliseconds) || !Number.isSafeInteger(Date.now() + this.maxAgeMilliseconds)) { @@ -173,12 +184,17 @@ export class BrowserAuth { /** * Initialize browser authentication and create its durable signing secret * when this Harness home has none. + * @param processOwner - root application context retaining one token across Connection reloads. * @param credentials - persistent credential provider for the Web profile. * @param maxAgeDays - positive absolute browser-cookie lifetime in days. * @returns initialized authentication owner with a fresh process token. */ - static async create(credentials: CredentialProvider, maxAgeDays: number): Promise { - const auth = new BrowserAuth(credentials, maxAgeDays) + static async create( + processOwner: object, + credentials: CredentialProvider, + maxAgeDays: number, + ): Promise { + const auth = new BrowserAuth(processOwner, credentials, maxAgeDays) await auth.ensureSecret() return auth } @@ -232,6 +248,15 @@ export class BrowserAuth { res.end() return false } + if (req.method === 'GET' && url.pathname === '/' && await this.isAuthenticated(req)) { + res.writeHead(303, { + 'cache-control': 'no-store', + 'location': '/', + 'referrer-policy': 'no-referrer', + }) + res.end() + return false + } this.writeUnauthorized(req, res) return false } diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index 0d43a322a3..ff4d3ba1c1 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -93,7 +93,7 @@ export async function apply(ctx: Context, config?: ConnectionConfig): Promise { + return BrowserAuth.create(processOwner, credentials(store), maxAgeDays) +} + function request(url: string, authority = '127.0.0.1:3080', init?: { cookie?: string method?: string @@ -108,7 +116,8 @@ afterEach(() => { describe('BrowserAuth', () => { it('mints one process token and a persistent authority-bound cookie', async () => { const store = new RecordCredentials() - const first = await BrowserAuth.create(credentials(store), 30) + const processOwner = {} + const first = await createAuth(store, 30, processOwner) const login = await exchange(first) expect(login.state).toMatchObject({ @@ -129,14 +138,33 @@ describe('BrowserAuth', () => { expect(await first.isAuthenticated(request('/', 'localhost:3080', { cookie: login.cookie }))).toBe(false) expect(await first.isAuthenticated(request('/', '127.0.0.1:3081', { cookie: login.cookie }))).toBe(false) - const restarted = await BrowserAuth.create(credentials(store), 30) + const reloaded = await createAuth(store, 30, processOwner) + expect(reloaded.authenticatedUrl('http://127.0.0.1:3080')).toBe(login.launchUrl) + expect(await reloaded.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) + + const restarted = await createAuth(store) expect(new URL(restarted.authenticatedUrl('http://127.0.0.1:3080')).searchParams.get('token')) .not.toBe(new URL(login.launchUrl).searchParams.get('token')) expect(await restarted.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) + const staleUrl = new URL(login.launchUrl) + const redirected = response() + expect(await restarted.authorizeIndex(request( + `${staleUrl.pathname}${staleUrl.search}`, + '127.0.0.1:3080', + { cookie: login.cookie }, + ), redirected.value)).toBe(false) + expect(redirected.state).toEqual({ + status: 303, + headers: { + 'cache-control': 'no-store', + 'location': '/', + 'referrer-policy': 'no-referrer', + }, + }) }) it('accepts the cookie for index serving and gives every unauthenticated request one response', async () => { - const auth = await BrowserAuth.create(credentials(new RecordCredentials()), 30) + const auth = await createAuth(new RecordCredentials()) const { cookie } = await exchange(auth) const allowed = response() expect(await auth.authorizeIndex(request('/index.html', '127.0.0.1:3080', { cookie }), allowed.value)).toBe(true) @@ -166,7 +194,7 @@ describe('BrowserAuth', () => { vi.useFakeTimers() vi.setSystemTime(new Date('2026-08-24T00:00:00.000Z')) const store = new RecordCredentials() - const auth = await BrowserAuth.create(credentials(store), 30) + const auth = await createAuth(store) const { cookie } = await exchange(auth) const [name, value] = cookie.split('=') as [string, string] @@ -194,7 +222,7 @@ describe('BrowserAuth', () => { }))).toBe(false) } - const shorter = await BrowserAuth.create(credentials(store), 1) + const shorter = await createAuth(store, 1) expect(await shorter.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) vi.setSystemTime(new Date('2026-09-24T00:00:00.000Z')) expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) @@ -204,7 +232,7 @@ describe('BrowserAuth', () => { it('revokes on record deletion and creates a new secret on the next token exchange', async () => { const store = new RecordCredentials() - const auth = await BrowserAuth.create(credentials(store), 30) + const auth = await createAuth(store) const first = await exchange(auth) await store.deleteRecord() expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: first.cookie }))).toBe(false) @@ -218,21 +246,21 @@ describe('BrowserAuth', () => { it('fails loud on an invalid owner record instead of replacing it', async () => { const unsupported = new RecordCredentials() unsupported.record = { kind: 'api-key', key: 'not-a-cookie-secret' } - await expect(BrowserAuth.create(credentials(unsupported), 30)).rejects.toThrow(/unsupported format/u) + await expect(createAuth(unsupported)).rejects.toThrow(/unsupported format/u) const malformed = new RecordCredentials() malformed.record = { kind: 'grant', payload: { version: 1, secret: 'short' } } - await expect(BrowserAuth.create(credentials(malformed), 30)).rejects.toThrow(/invalid secret/u) + await expect(createAuth(malformed)).rejects.toThrow(/invalid secret/u) const nonString = new RecordCredentials() nonString.record = { kind: 'grant', payload: { version: 1, secret: 42 } } - await expect(BrowserAuth.create(credentials(nonString), 30)).rejects.toThrow(/invalid secret/u) + await expect(createAuth(nonString)).rejects.toThrow(/invalid secret/u) const discarded = new RecordCredentials() discarded.discardWrites = true - await expect(BrowserAuth.create(credentials(discarded), 30)).rejects.toThrow(/was not created/u) + await expect(createAuth(discarded)).rejects.toThrow(/was not created/u) - await expect(BrowserAuth.create(credentials(new RecordCredentials()), Number.MAX_SAFE_INTEGER)) + await expect(createAuth(new RecordCredentials(), Number.MAX_SAFE_INTEGER)) .rejects.toThrow(/safe timestamp range/u) }) }) From 5595d593d123e17390bc357b7e7ebb02b9b0110a Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Tue, 25 Aug 2026 02:35:02 +0800 Subject: [PATCH 26/31] docs(web): state authentication contracts directly --- .../2026-07-28-api-browser-trust-boundary.i18n.yaml | 4 ++-- .../architecture/2026-07-28-api-browser-trust-boundary.md | 2 +- .../architecture/2026-07-28-api-browser-trust-boundary.zh.md | 2 +- .../2026-08-24-browser-token-authentication.i18n.yaml | 4 ++-- .../architecture/2026-08-24-browser-token-authentication.md | 2 +- .../2026-08-24-browser-token-authentication.zh.md | 2 +- .../2026-08-08-copy-only-preset-authoring.i18n.yaml | 2 +- .../2026-08-08-copy-only-preset-authoring.zh.md | 2 +- packages/client/connection/README.i18n.yaml | 2 +- packages/client/connection/README.zh.md | 2 +- packages/client/connection/src/browser-auth.ts | 2 +- packages/host/apiproxy/README.i18n.yaml | 2 +- packages/host/apiproxy/README.zh.md | 2 +- 13 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml index f2e1a2ed33..5d8fa99508 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md -2026-07-28-api-browser-trust-boundary.md: 2997b0f2affaac59be9cd58108bc20086442f6db -2026-07-28-api-browser-trust-boundary.zh.md: ff952ede9adc53c9d590ad2ba24a32b448172f82 +2026-07-28-api-browser-trust-boundary.md: 4401dc8e361281b1239eb84319fc5353948bc217 +2026-07-28-api-browser-trust-boundary.zh.md: c1db2632a6019585ab6a948bcb0f4f2ef853b8a7 diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md index 2997b0f2af..4401dc8e36 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md @@ -15,7 +15,7 @@ Enforce browser trust once, at the carrier, for the entire `/api` prefix — two - **Media-type fence (dsh-host-apiproxy)**: every `/api` POST must declare `application/json`, else 415 before parsing. Cross-site "simple" requests thereby stop existing: any cross-site attempt is forced into a CORS preflight this server never answers. - **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: every request must present a `Host` that is loopback or matches a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense). Deliberately no shortcut for unmarked requests: over plain HTTP a browser attaches neither `Origin` nor Fetch-Metadata to reads (EventSource, images, navigations — those headers go only to trustworthy destinations), so an unmarked request may be a rebound browser read whose response the page can read, and Host is the one header rebinding cannot forge; non-browser clients pass via loopback, the derived LAN IP literals, or a declared authority. An attached `Origin` must equal the Host authority; `sec-fetch-site: cross-site` is refused outright. A `trustedHosts` entry that is not a bare, canonical authority fails the plugin load — WHATWG parsing would otherwise quietly authorize the hostname inside a typo or broaden an exact-port grant. `host.pickDirectory` loses its bespoke guard and rides the same fence. -Reachability remains the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and this fence remains a confused-deputy defense rather than identity. Connection applies the separate [browser token authentication](2026-08-24-browser-token-authentication.md) after the fence. The old guard's loopback-socket check was dropped rather than generalized: with binding expressing reachability and `trustedHosts` naming accepted authorities, the socket address adds nothing the Host/Origin checks need. +Reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and this fence is a confused-deputy defense rather than identity. Connection applies the separate [browser token authentication](2026-08-24-browser-token-authentication.md) after the fence. The fence does not inspect peer socket addresses: binding expresses reachability, `trustedHosts` names accepted authorities, and the socket address adds nothing the Host/Origin checks need. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md index ff952ede9a..c1db2632a6 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md @@ -15,7 +15,7 @@ Web GUI 宿主以纯 loopback HTTP 提供 `/api`(默认 `127.0.0.1:3080`;CLI - **媒体类型栅栏(dsh-host-apiproxy)**:每个 `/api` POST 必须声明 `application/json`,否则在解析前以 415 拒绝。跨站「简单请求」由此不复存在:任何跨站尝试都被逼进一次本服务器从不应答的 CORS 预检。 - **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:每个请求的 `Host` 都必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御)。刻意不为无标记请求开捷径:明文 HTTP 下浏览器的读取(EventSource、图片、导航——这些头只发给可信目标)既不带 `Origin` 也不带 Fetch-Metadata,因此无标记请求可能是被重绑页面发起且响应可被读走的读取,而 Host 是重绑唯一伪造不了的请求头;非浏览器客户端经由回环地址、推导的 LAN IP 字面量或已声明的权威通过。若带 `Origin` 则必须与 Host 权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不是单纯规范化 authority 的 `trustedHosts` 条目会导致插件加载失败——否则 WHATWG 解析会悄悄授权笔误里的 hostname,或放大精确端口授权。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 -可达性仍由 webserver 的绑定配置(`host: 127.0.0.1 | 0.0.0.0`)控制,这道栅栏仍是混淆代理人防御,而不是身份。Connection 在栅栏之后应用独立的[浏览器令牌认证](2026-08-24-browser-token-authentication.zh.md)。旧守卫的回环 socket 检查被放弃而非泛化:绑定表达可达性、`trustedHosts` 点名接受的 authority 之后,socket 地址提供不了 Host/Origin 校验需要的额外信息。 +可达性由 webserver 的绑定配置(`host: 127.0.0.1 | 0.0.0.0`)控制,这道栅栏是混淆代理人防御,而不是身份。Connection 在栅栏之后应用独立的[浏览器令牌认证](2026-08-24-browser-token-authentication.zh.md)。栅栏不检查对端 socket 地址:绑定表达可达性,`trustedHosts` 点名接受的 authority,socket 地址提供不了 Host/Origin 校验需要的额外信息。 ## 曾考虑的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml index 126c669ced..8fec25a1a2 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md -2026-08-24-browser-token-authentication.md: 69f24c148a1054f99447f1f9f2a6d2e5540c83db -2026-08-24-browser-token-authentication.zh.md: e9b96af21e913c1c3e482940c9f65d0d37506c81 +2026-08-24-browser-token-authentication.md: d04e655a9e4f25623e45f7c85922352db602da36 +2026-08-24-browser-token-authentication.zh.md: ff66630e9fbb77f7cba2c0af16693af724a85c70 diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md index 69f24c148a..d04e655a9e 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -40,7 +40,7 @@ Unit coverage pins process-token retention across Connection reloads, cookie att ## Consequences -Possession of the browser cookie authorizes the complete tool-capable Host API, matching the authority the Web application already exposes after Session creation. `Host` no longer grants a higher method tier, and a method migration between API Proxy and Typert Remote cannot change its caller set. +Possession of the browser cookie authorizes the complete tool-capable Host API, matching the authority the Web application exposes after Session creation. `Host` does not grant a higher method tier, and a method migration between API Proxy and Typert Remote cannot change its caller set. The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime; deletion or rotation of the record is the global revocation mechanism. Omitting `Secure` preserves loopback HTTP and permits plaintext transmission if an operator makes the same cookie authority reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it. diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md index e9b96af21e..ff66630e9f 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -40,7 +40,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` ## 后果 -持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后本就暴露的 authority 一致。`Host` 不再授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。 +持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后暴露的 authority 一致。`Host` 不授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。 持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期;删除或轮换记录是全局撤销机制。不设置 `Secure` 保留 loopback HTTP,但如果操作者让同一 cookie authority 经未加密网络可达,cookie 会以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。 diff --git a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.i18n.yaml b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.i18n.yaml index df36182179..d98333c159 100644 --- a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.i18n.yaml +++ b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.i18n.yaml @@ -3,4 +3,4 @@ # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.md 2026-08-08-copy-only-preset-authoring.md: bfe0d49755abf47314a7b4cf56c738537fca3963 -2026-08-08-copy-only-preset-authoring.zh.md: fc2d9ac5c6ace45c46fc920e1f7f28aca508ba9c +2026-08-08-copy-only-preset-authoring.zh.md: 71e83d5e17c56e53ce4f4678b5a22baaed02be31 diff --git a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.zh.md b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.zh.md index fc2d9ac5c6..71e83d5e17 100644 --- a/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.zh.md +++ b/.agents/notes/implemented/simplification/2026-08-08-copy-only-preset-authoring.zh.md @@ -14,7 +14,7 @@ agent-preset 设置页带着一个网页 YAML 编辑器:`agentPreset.write` ## 后果 -- 创作两个方向都不再有组装文本或路径跨越浏览器传输层;`entryListSchema`/`!!js` 的顾虑随 `assertComposition` 本身(已删除)一并消解。创作操作现为 `read`/`copy`/`openDocument`/`remove`——没有一个接收文件系统目标,且 Connection 用完整 Host API 的同一会话认证它们。 +- 创作两个方向都没有组装文本或路径跨越浏览器传输层;`entryListSchema`/`!!js` 的顾虑随 `assertComposition` 本身(已删除)一并消解。创作操作是 `read`/`copy`/`openDocument`/`remove`——没有一个接收文件系统目标,且 Connection 用完整 Host API 的同一会话认证它们。 - 编辑器移除后,手改 `agent.cordis.yml` 成为唯一的组装编辑方式,因此常驻挂载层增加了以 stamp 为键的代际:`ensureStanding` 比对文件的 mtime+大小,为后续会话开启下一代际([常驻挂载 note](../architecture/2026-08-08-per-preset-standing-mounts.zh.md),已就地更新)。没有它,改过的文件要等进程重启才生效。 - 副本是完整快照,会随随附来源升级而漂移——接受;preset 层没有 patch 语义(那是 bundle 层 `cordis.patch.yml` 的能力),随附集合自己也为「一个文件读完整份组装」付了同样的代价(`cordis`/`code` 就是 `standard` 的完整副本)。 - `read` 去掉了 `writable`(没有编辑器可门控),内置目录绝不被打开(`openDocument` 与 `remove` 一样拒绝非 `user` 信任):安装目录会被升级覆盖,把编辑器指向它等于招揽会被升级悄悄丢弃的编辑。 diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index 83d376368b..9e2f611ae3 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -3,4 +3,4 @@ # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/connection/README.md README.md: 293e9f9d6b158e325325f4f741a244031b1d2e02 -README.zh.md: e3cea191ab1c9745a1920b5cfd13fcd8d8b77692 +README.zh.md: 1acc4e1748b8067bd18a626dfddfabc2cdcc242d diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index e3cea191ab..1acc4e1748 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -8,7 +8,7 @@ ## 浏览器认证与请求信任 -每个 Host RPC 方法和 WebSocket stream 都要求同一个浏览器会话,不再存在按方法区分的 loopback 层。每个进程生成一个随机启动令牌。`dsh-web-app` 打印并打开带 `?token=...` 的普通根 URL;`frontend-static` 把根路径和 index 请求交给 `ctx.connection.authorizeIndex`,后者只在 `GET /` 接受该令牌,写入绑定 authority 的签名 cookie,再重定向到干净的 `/`。缺失、过期、畸形或 authority 不匹配的 cookie 会在 RPC 分发前得到 401。静态资源保持公开。HTTP 载体不在根路径交换之外接受 query token,也不接受 Authorization header token。 +每个 Host RPC 方法和 WebSocket stream 都要求同一个浏览器会话,不存在按方法区分的 loopback 层。每个进程生成一个随机启动令牌。`dsh-web-app` 打印并打开带 `?token=...` 的普通根 URL;`frontend-static` 把根路径和 index 请求交给 `ctx.connection.authorizeIndex`,后者只在 `GET /` 接受该令牌,写入绑定 authority 的签名 cookie,再重定向到干净的 `/`。缺失、过期、畸形或 authority 不匹配的 cookie 会在 RPC 分发前得到 401。静态资源保持公开。HTTP 载体不在根路径交换之外接受 query token,也不接受 Authorization header token。 cookie 签名密钥是 `ctx.credentials` 中由 `client-connection/browser-session` 拥有的 grant 记录。本地提供方把它持久化到 `$DSH_HOME/.credentials.yaml`;`BrowserAuth` 每次校验都读取当前记录,因此删除或轮换记录无需重启进程即可撤销 cookie。cookie 携带绝对签发与过期区间,`cookieMaxAgeDays` 默认设为 30 天,并在确定性名称与签名 payload 中同时绑定规范化 hostname 和 port。它是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`;随附服务器使用 loopback HTTP,因此刻意不设置 `Secure`。 diff --git a/packages/client/connection/src/browser-auth.ts b/packages/client/connection/src/browser-auth.ts index 3316b746bc..77194e16f0 100644 --- a/packages/client/connection/src/browser-auth.ts +++ b/packages/client/connection/src/browser-auth.ts @@ -187,7 +187,7 @@ export class BrowserAuth { * @param processOwner - root application context retaining one token across Connection reloads. * @param credentials - persistent credential provider for the Web profile. * @param maxAgeDays - positive absolute browser-cookie lifetime in days. - * @returns initialized authentication owner with a fresh process token. + * @returns initialized authentication owner with the process owner's launch token. */ static async create( processOwner: object, diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index c07785d98f..103060ad44 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -3,4 +3,4 @@ # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md README.md: 69826d76b437ea482655d91a930310185079414c -README.zh.md: c7f5d5b579e20236fe7a9f79ed1db8417b641c64 +README.zh.md: 26d132a9a8e48c0833e6145b139226d765cb9709 diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index c7f5d5b579..26d132a9a8 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -58,7 +58,7 @@ Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.cr `command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和 skill(技能)目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`skill.list` 服务于 composer 的菜单:它返回每一个用户可调用的 skill 及其 `modelInvocable` 标志,让菜单能够标出仅限用户(`disable-model-invocation`)的条目——斜杠手势是这类条目唯一的调用路径。列表是 skill 领域唯一的 RPC——调用本身就是一次普通的 `session.prompt`,`dsh-tool-skill` 会在 pre-step 边界识别其中以空白为界的 `/name` token,并以注入的 `` 上下文作答,因此所有入口(Web、TUI 与 ACP(Agent Client Protocol))共享同一条确定性路径,手动键入的文本也走该路径,且没有专设的调用协议。`command.execute` 在宿主侧运行一条斜杠命令行,语义为纯准入:响应报告该行是否解析到处理器,并在解析到时回带铸造的生命周期 `commandId`(将本次确认与流节点关联);结局经由持久落账并在 mux 流广播的 `command/run`/`command/done` 生命周期事件对承载。命令处理器运行超过 30 秒的传输健康时限仍属正常,因此 `command.execute` 仅携带调用方/连接取消信号;该信号可取消正在运行的处理器。`commands/change` 搭乘转发事件帧作为注册表级目录失效信号:客户端重新拉取 `command.list` 而不是做差分。转发的 `agent-preset/selected` 是它按会话粒度的对应物,由落账的选择提交点发出:重组空会话的 agent 只是重新挂接其 scope,不产生任何注册,因此该会话组成所决定的两份目录(`command.list`、`skill.list`)都会失效,却没有任何注册表变化来宣告它。 -`settings.*`、`credentials.*` 与 `llm.*` 领域是配置页协议。settings 领域服务于每一个已注册 namespace:在本仓库之外分发的插件只要注册自己的分节即可变得可从浏览器配置,无需改动这里;本代理也不再自设边界——没有任何注册应答的名字会折叠为 seam 自己的 `settings-rejected`。由哪个界面渲染某个 namespace 是浏览器的决定(插件配置页按 namespace 为其卡片编键),从不由本代理决定。`settings.describe` 为每个 namespace 提供其序列化 schemastery schema、脱敏后的分层值(resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表、该分节的 `revision`,以及布尔型 `hasDocument` 能力标志。浏览器不会收到 Host 路径:无路径参数的 `settings.openDocument` 会请求提供方准备文档,再把由 Host 解析出的结果交给原生打开器,因此任何浏览器载荷都无法选择任意文件系统目标。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op(`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;陈旧的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应;secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable`),`credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected`。`llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。`llm.discoverModels` 询问页面尚在起草的提供方端点:`settingsNs` 选出懂得读取该列表的适配器家族,端点、协议与密钥则来自表单而非存储。它什么都不写——回复是候选,只有随后的 `settings.mutate` 才决定路由服务什么——因此其 `apiKey` 是 secret 可以搭乘的第三个载荷(另两个是 `settings.update`/`mutate` 与 `credentials.set`),且绝不被存储或回显。host 从不存储或回传它;与另两者一样,它确实会搭乘客户端的出站信封,`subscribeEnvelopes()` 的观察者能看到——为该 tap 做脱敏是整个配置面的改动,而非本方法一家的事。每一种拒绝(无人服务的 namespace、没有可读列表的协议、不可达端点、被拒凭据)都折叠为 `model-discovery-failed`,其消息是适配器自己的文本,details 点名被询问的端点,绝不点名所提供的凭据。失效通知让每个面无需轮询即保持收敛。`settings/document-updated` 与 `credentials/reference-updated` 搭乘原样转发事件帧(见下),因此解析值未变的原始设置变更同样能到达客户端,凭据失效通知也仍然只带引用名、绝不带值。`llm/adapters-updated` 与 `settings/document-updated` 一并原样转发;具体模型消费方直接订阅这两个 owner 事件,因为拓扑提交和设置文档都能独立改变其目录。Connection 用与每个 Host API 方法相同的浏览器会话认证整个配置面,包括读取与原生操作。未装 settings 或凭据提供方的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。 +`settings.*`、`credentials.*` 与 `llm.*` 领域是配置页协议。settings 领域服务于每一个已注册 namespace:在本仓库之外分发的插件只要注册自己的分节即可变得可从浏览器配置,无需改动这里;本代理不自设边界——没有任何注册应答的名字会折叠为 seam 自己的 `settings-rejected`。由哪个界面渲染某个 namespace 是浏览器的决定(插件配置页按 namespace 为其卡片编键),从不由本代理决定。`settings.describe` 为每个 namespace 提供其序列化 schemastery schema、脱敏后的分层值(resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表、该分节的 `revision`,以及布尔型 `hasDocument` 能力标志。浏览器不会收到 Host 路径:无路径参数的 `settings.openDocument` 会请求提供方准备文档,再把由 Host 解析出的结果交给原生打开器,因此任何浏览器载荷都无法选择任意文件系统目标。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op(`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;陈旧的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应;secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable`),`credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected`。`llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。`llm.discoverModels` 询问页面尚在起草的提供方端点:`settingsNs` 选出懂得读取该列表的适配器家族,端点、协议与密钥则来自表单而非存储。它什么都不写——回复是候选,只有随后的 `settings.mutate` 才决定路由服务什么——因此其 `apiKey` 是 secret 可以搭乘的第三个载荷(另两个是 `settings.update`/`mutate` 与 `credentials.set`),且绝不被存储或回显。host 从不存储或回传它;与另两者一样,它确实会搭乘客户端的出站信封,`subscribeEnvelopes()` 的观察者能看到——为该 tap 做脱敏是整个配置面的改动,而非本方法一家的事。每一种拒绝(无人服务的 namespace、没有可读列表的协议、不可达端点、被拒凭据)都折叠为 `model-discovery-failed`,其消息是适配器自己的文本,details 点名被询问的端点,绝不点名所提供的凭据。失效通知让每个面无需轮询即保持收敛。`settings/document-updated` 与 `credentials/reference-updated` 搭乘原样转发事件帧(见下),因此解析值未变的原始设置变更同样能到达客户端,凭据失效通知也仍然只带引用名、绝不带值。`llm/adapters-updated` 与 `settings/document-updated` 一并原样转发;具体模型消费方直接订阅这两个 owner 事件,因为拓扑提交和设置文档都能独立改变其目录。Connection 用与每个 Host API 方法相同的浏览器会话认证整个配置面,包括读取与原生操作。未装 settings 或凭据提供方的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。 ## 载体层(`/client` + 根路径) From 9c964848cd54d6e9a7d5f01f1745936673cd1910 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Tue, 25 Aug 2026 13:15:34 +0800 Subject: [PATCH 27/31] fix(web): keep browser authentication synchronous --- ...-24-browser-token-authentication.i18n.yaml | 4 +- ...2026-08-24-browser-token-authentication.md | 8 +- ...6-08-24-browser-token-authentication.zh.md | 8 +- packages/api/gateway/src/index.ts | 4 +- .../gateway/tests/gateway-stream.host.spec.ts | 44 +++++------ .../api/gateway/tests/gateway.host.spec.ts | 10 +-- packages/api/remotes/tests/built-lib.e2e.ts | 10 +-- .../bundle/web-app/tests/browser-open.spec.ts | 8 +- packages/bundle/web-app/tests/web-app.spec.ts | 4 +- packages/client/connection/README.i18n.yaml | 4 +- packages/client/connection/README.md | 4 +- packages/client/connection/README.zh.md | 4 +- .../client/connection/src/browser-auth.ts | 65 +++++++-------- packages/client/connection/src/index.ts | 2 +- packages/client/connection/src/rpc-host.ts | 8 +- packages/client/connection/src/rpc.ts | 4 +- .../tests/browser-auth.host.spec.ts | 79 +++++++++++-------- .../connection/tests/node-half.host.spec.ts | 32 ++++---- packages/host/frontend-static/src/index.ts | 4 +- 19 files changed, 154 insertions(+), 152 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml index 8fec25a1a2..6756a4d842 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md -2026-08-24-browser-token-authentication.md: d04e655a9e4f25623e45f7c85922352db602da36 -2026-08-24-browser-token-authentication.zh.md: ff66630e9fbb77f7cba2c0af16693af724a85c70 +2026-08-24-browser-token-authentication.md: c75f561d9529296ff668791c29453e522f309cc3 +2026-08-24-browser-token-authentication.zh.md: d4a5059619fefda9d9060e9879d10c0a2197f8f3 diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md index d04e655a9e..c75f561d95 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -16,7 +16,7 @@ Each Host process generates a random launch token, retained by the root applicat The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. It omits `Secure` because the shipped server uses loopback HTTP. There is no logout operation or reverse-proxy-specific handling. -The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection reads the record for each verification, so deletion or replacement revokes every existing cookie without restarting the process. A missing record is created when Connection starts; after runtime deletion, the next valid process-token exchange or process start recreates it. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. +The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection loads or creates the record during activation and retains the secret for synchronous request verification. An active Connection continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. The in-page Web Worker preview exposes no network socket. Its page-owned `postMessage` tunnel enters the real route first, then retries a 401 or 403 through the worker-local fetch handler. This keeps Connection interceptors while limiting the authentication bypass to the page that created the Host worker. @@ -24,7 +24,7 @@ The shipped CLI continues to reject `--host 0.0.0.0`. Authentication does not im ## Verification -Unit coverage pins process-token retention across Connection reloads, cookie attributes, HMAC and payload validation, authority and lifetime checks, persistent-secret reuse, record deletion, invalid durable records, and cleanup of obsolete token URLs backed by valid cookies. Host transport suites pin uniform 401/403 behavior for API Proxy, generic RPC, Typert Remote HTTP, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `host.describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. +Unit coverage pins process-token retention across Connection reloads, one secret load per activation, synchronous verification without credential-provider reads, cookie attributes, HMAC and payload validation, authority and lifetime checks, record deletion taking effect on the next activation, invalid durable records, and cleanup of obsolete token URLs backed by valid cookies. Host transport suites pin uniform 401/403 behavior for API Proxy, generic RPC, Typert Remote HTTP, and WebSocket upgrade paths. The frontend real-composition test boots credentials, Connection, webserver, and static serving through Loader and proves token exchange before index reads while static assets remain public. Packed-worker tests prove portable cookie encoding and worker-local retry for both authentication and trust rejection. A real-CLI test starts `dsh web` twice on one port with a temporary `DSH_HOME`, proves that forged `Host: localhost` is unauthenticated, calls `host.describe` with the exchanged cookie, observes a new process token, and reuses the old cookie after restart. ## Alternatives considered @@ -36,12 +36,12 @@ Unit coverage pins process-token retention across Connection reloads, cookie att **Rotate the signing secret on every restart.** This prevents an existing browser from reconnecting after an ordinary DSH restart. Persisting only the signing secret keeps that workflow while process-token rotation limits the startup URL to one process lifetime. -**Add logout, TLS-proxy, and forwarding-header configuration.** None is required by the loopback Web application or the reported authentication gap. Adding them would define deployment contracts without current consumers. Browser site-data controls and credential-record deletion provide the two revocation operations this decision needs. +**Add logout, TLS-proxy, and forwarding-header configuration.** None is required by the loopback Web application or the reported authentication gap. Adding them would define deployment contracts without current consumers. Browser site-data controls revoke one browser session; deleting the credential record and restarting the process revokes all sessions. ## Consequences Possession of the browser cookie authorizes the complete tool-capable Host API, matching the authority the Web application exposes after Session creation. `Host` does not grant a higher method tier, and a method migration between API Proxy and Typert Remote cannot change its caller set. -The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime; deletion or rotation of the record is the global revocation mechanism. Omitting `Secure` preserves loopback HTTP and permits plaintext transmission if an operator makes the same cookie authority reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it. +The persistent secret makes cookies survive restarts but gives a stolen cookie up to the configured absolute lifetime. Deleting the record and restarting the process is the global revocation mechanism; the active Connection intentionally avoids credential-provider work on each request. Omitting `Secure` preserves loopback HTTP and permits plaintext transmission if an operator makes the same cookie authority reachable over an unencrypted network. The startup URL contains a process credential and must be treated as sensitive output; runtime diagnostics do not repeat it. The decision partially supersedes the authentication deferral and unauthenticated non-loopback consequences in the [browser trust note](2026-07-28-api-browser-trust-boundary.md). That note remains active authority for media-type, Host, Origin, Fetch-Metadata, and configured-authority validation. No active Agent Note is archived: the overlap is partial and both security rules retain future decision value. diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md index ff66630e9f..d4a5059619 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -16,7 +16,7 @@ Web Host 以当前操作系统用户的权限运行具有工具能力的 Session cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。随附服务器使用 loopback HTTP,因此不设置 `Secure`。这里没有 logout 操作或反向代理专用处理。 -HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 每次校验都读取记录,因此删除或替换记录无需重启进程即可撤销全部既有 cookie。缺失记录在 Connection 启动时创建;运行期删除后,由下一次有效进程令牌交换或进程启动重新创建。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 +HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Connection 继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 页内 Web Worker preview 不暴露网络 socket。其由页面持有的 `postMessage` tunnel 先进入真实 route,收到 401 或 403 后再经 worker 本地 fetch handler 重试。这样既保留 Connection interceptor,又把认证绕过限制在创建 Host worker 的页面内。 @@ -24,7 +24,7 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` ## 验证 -单元覆盖 Connection 重载时保留进程令牌、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、持久密钥复用、记录删除、无效持久记录,以及用有效 cookie 清理过时令牌 URL。Host 传输套件固定 API Proxy、通用 RPC、Typert Remote HTTP 和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `host.describe`,观测新的进程令牌,并在重启后复用旧 cookie。 +单元覆盖 Connection 重载时保留进程令牌、每次激活只加载一次密钥、无需读取凭据提供方的同步校验、cookie 属性、HMAC 与 payload 校验、authority 与有效期校验、记录删除在下一次激活时生效、无效持久记录,以及用有效 cookie 清理过时令牌 URL。Host 传输套件固定 API Proxy、通用 RPC、Typert Remote HTTP 和 WebSocket upgrade 路径上一致的 401/403 行为。frontend 真实组合测试经 Loader 启动 credentials、Connection、webserver 与静态服务,证明读取 index 前完成令牌交换,同时静态资产仍公开。打包 worker 测试证明 cookie 编码可移植,并覆盖认证与信任拒绝后的 worker 本地重试。真实 CLI 测试在临时 `DSH_HOME` 上用同一端口两次启动 `dsh web`,证明伪造 `Host: localhost` 仍未认证,以交换所得 cookie 调用 `host.describe`,观测新的进程令牌,并在重启后复用旧 cookie。 ## 曾考虑的替代方案 @@ -36,12 +36,12 @@ HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` **每次重启都轮换签名密钥。** 这会阻止既有浏览器在普通 DSH 重启后重连。只持久化签名密钥既保留该工作流,又由进程令牌轮换把启动 URL 限定在一个进程生命周期。 -**增加 logout、TLS 代理和转发 header 配置。** loopback Web 应用与已报告认证缺口都不需要这些能力;加入它们会在没有当前 consumer 时定义部署约定。浏览器站点数据控制与凭据记录删除已经提供本决策所需的两种撤销操作。 +**增加 logout、TLS 代理和转发 header 配置。** loopback Web 应用与已报告认证缺口都不需要这些能力;加入它们会在没有当前 consumer 时定义部署约定。浏览器站点数据控制会撤销单个浏览器会话;删除凭据记录并重启进程会撤销全部会话。 ## 后果 持有浏览器 cookie 就能调用完整的工具型 Host API,这与 Web 应用在创建 Session 后暴露的 authority 一致。`Host` 不授予更高的方法层级,方法在 API Proxy 与 Typert Remote 之间迁移也不会改变调用者集合。 -持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期;删除或轮换记录是全局撤销机制。不设置 `Secure` 保留 loopback HTTP,但如果操作者让同一 cookie authority 经未加密网络可达,cookie 会以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。 +持久密钥使 cookie 跨重启生效,也让被盗 cookie 最多保有配置的绝对有效期。删除记录并重启进程是全局撤销机制;当前 Connection 刻意避免在每个请求上访问凭据提供方。不设置 `Secure` 保留 loopback HTTP,但如果操作者让同一 cookie authority 经未加密网络可达,cookie 会以明文传输。启动 URL 含进程凭据,必须视为敏感输出;运行时诊断不会重复它。 本决策部分取代[浏览器信任说明](2026-07-28-api-browser-trust-boundary.zh.md)中的认证延期与未认证非 loopback 后果。该说明仍是媒体类型、Host、Origin、Fetch-Metadata 和配置 authority 校验的有效权威。没有 active Agent Note 被归档:重叠只发生在局部,两条安全规则都保有未来决策价值。 diff --git a/packages/api/gateway/src/index.ts b/packages/api/gateway/src/index.ts index edc3f8697e..86a71d834a 100644 --- a/packages/api/gateway/src/index.ts +++ b/packages/api/gateway/src/index.ts @@ -192,8 +192,8 @@ export class TypertGatewayService extends Service implements TypertGateway { webCtx.effect(() => { const route: WebUpgradeRoute = { path: REMOTE_STREAM_MUX_PATH, - handler: async (req, socket, head) => { - const rejection = await webCtx.connection.requestRejection(req) + handler: (req, socket, head) => { + const rejection = webCtx.connection.requestRejection(req) if (rejection !== undefined) { rejectRemoteStreamUpgrade(socket, rejection) return diff --git a/packages/api/gateway/tests/gateway-stream.host.spec.ts b/packages/api/gateway/tests/gateway-stream.host.spec.ts index 273d5f9b99..01fcc81b0f 100644 --- a/packages/api/gateway/tests/gateway-stream.host.spec.ts +++ b/packages/api/gateway/tests/gateway-stream.host.spec.ts @@ -33,31 +33,29 @@ vi.mock('node:crypto', async (importOriginal) => { }) const randomUuid = vi.mocked(randomUUID) -const browserCookies = new WeakMap>() +const browserCookies = new WeakMap() type AgentWireId = TypertContextWire const agentId = (value: string): AgentWireId => value as AgentWireId /** Exchange this test Host's process token for its WebSocket/HTTP Cookie header. */ -function browserCookie(ctx: Context): Promise { +function browserCookie(ctx: Context): string { const existing = browserCookies.get(ctx) if (existing !== undefined) return existing - const exchange = (async () => { - const origin = `http://127.0.0.1:${String(ctx.webServer.port)}` - const target = new URL(ctx.connection.authenticatedUrl(origin)) - let setCookie: string | undefined - await ctx.connection.authorizeIndex({ - method: 'GET', - url: `${target.pathname}${target.search}`, - headers: { host: target.host }, - }, { - writeHead(_status, headers) { setCookie = headers?.['set-cookie'] }, - end() {}, - }) - if (setCookie === undefined) throw new Error('gateway stream fixture did not receive a browser cookie') - return setCookie.split(';', 1)[0]! - })() - browserCookies.set(ctx, exchange) - return exchange + const origin = `http://127.0.0.1:${String(ctx.webServer.port)}` + const target = new URL(ctx.connection.authenticatedUrl(origin)) + let setCookie: string | undefined + ctx.connection.authorizeIndex({ + method: 'GET', + url: `${target.pathname}${target.search}`, + headers: { host: target.host }, + }, { + writeHead(_status, headers) { setCookie = headers?.['set-cookie'] }, + end() {}, + }) + if (setCookie === undefined) throw new Error('gateway stream fixture did not receive a browser cookie') + const cookie = setCookie.split(';', 1)[0]! + browserCookies.set(ctx, cookie) + return cookie } class FeedService extends Service { @@ -285,7 +283,7 @@ describe('Typert Remote streams', () => { it('multiplexes independent streams over one WebSocket and propagates cancellation', async () => { const { ctx, service } = await setup(true) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: await browserCookie(ctx) }, + headers: { cookie: browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -369,7 +367,7 @@ describe('Typert Remote streams', () => { .toThrow('forwarded Remote event source is already registered') const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: await browserCookie(ctx) }, + headers: { cookie: browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -891,7 +889,7 @@ describe('Typert Remote streams', () => { it('validates the internal Remote event request and reports an absent source', async () => { const { ctx } = await setup(true) const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, { - headers: { cookie: await browserCookie(ctx) }, + headers: { cookie: browserCookie(ctx) }, }) await once(socket, 'open') const frames: Record[] = [] @@ -1039,7 +1037,7 @@ interface RemoteEventTestClient { async function openEventClient(ctx: Context, streamId: string): Promise { const origin = `http://127.0.0.1:${String(ctx.webServer.port)}` - const cookie = await browserCookie(ctx) + const cookie = browserCookie(ctx) const socket = new WebSocket(`${origin.replace('http:', 'ws:')}/api/remote.mux`, { headers: { cookie }, }) diff --git a/packages/api/gateway/tests/gateway.host.spec.ts b/packages/api/gateway/tests/gateway.host.spec.ts index 36f23a62df..0798765e98 100644 --- a/packages/api/gateway/tests/gateway.host.spec.ts +++ b/packages/api/gateway/tests/gateway.host.spec.ts @@ -134,8 +134,8 @@ class FakeConnectionService extends Service { } } - requestRejection(): Promise { - return Promise.resolve(undefined) + requestRejection(): undefined { + return undefined } } @@ -171,10 +171,10 @@ async function serveRoute(route: WebRoute): Promise<{ readonly origin: string; c } /** Exchange a Connection launch token without mounting the frontend fallback. */ -async function browserCookie(connection: HostConnectionHandle, origin: string): Promise { +function browserCookie(connection: HostConnectionHandle, origin: string): string { const target = new URL(connection.authenticatedUrl(origin)) let setCookie: string | undefined - await connection.authorizeIndex({ + connection.authorizeIndex({ method: 'GET', url: `${target.pathname}${target.search}`, headers: { host: target.host }, @@ -1182,7 +1182,7 @@ describe('TypertGatewayService', () => { let strictActive = true expect(routes).toHaveLength(1) const server = await serveRoute(routes[0]!) - const cookie = await browserCookie(ctx.connection, server.origin) + const cookie = browserCookie(ctx.connection, server.origin) try { const response = await fetch(`${server.origin}/api/goals/create`, { diff --git a/packages/api/remotes/tests/built-lib.e2e.ts b/packages/api/remotes/tests/built-lib.e2e.ts index 92c5c7c621..ef7b4ae0ed 100644 --- a/packages/api/remotes/tests/built-lib.e2e.ts +++ b/packages/api/remotes/tests/built-lib.e2e.ts @@ -113,12 +113,10 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { } const server = createServer((request, response) => { if ((request.url ?? '/').startsWith('/?')) { - void host.connection.authorizeIndex(request, response).then(authorized => { - if (authorized) { - response.writeHead(200, { 'content-type': 'text/html' }) - response.end('shell') - } - }) + if (host.connection.authorizeIndex(request, response)) { + response.writeHead(200, { 'content-type': 'text/html' }) + response.end('shell') + } return } void routes[0].handler(request, response) diff --git a/packages/bundle/web-app/tests/browser-open.spec.ts b/packages/bundle/web-app/tests/browser-open.spec.ts index 5c1560c445..c9bc0c31cf 100644 --- a/packages/bundle/web-app/tests/browser-open.spec.ts +++ b/packages/bundle/web-app/tests/browser-open.spec.ts @@ -81,8 +81,8 @@ describe('web app browser startup', () => { __dshWebServer: typeof WebServer __dshConnection: { authenticatedUrl(baseUrl: string): string - authorizeIndex(): Promise - requestRejection(): Promise + authorizeIndex(): boolean + requestRejection(): undefined rpc: object } } @@ -94,8 +94,8 @@ describe('web app browser startup', () => { url.searchParams.set('token', 'fixture-token') return url.href }, - authorizeIndex: () => Promise.resolve(true), - requestRejection: () => Promise.resolve(undefined), + authorizeIndex: () => true, + requestRejection: () => undefined, rpc: {}, } diff --git a/packages/bundle/web-app/tests/web-app.spec.ts b/packages/bundle/web-app/tests/web-app.spec.ts index 6a6f8c8c15..40e47132ca 100644 --- a/packages/bundle/web-app/tests/web-app.spec.ts +++ b/packages/bundle/web-app/tests/web-app.spec.ts @@ -92,8 +92,8 @@ function provideConnection(ctx: Context): void { url.searchParams.set('token', 'test-token') return url.href }, - authorizeIndex: () => Promise.resolve(true), - requestRejection: () => Promise.resolve(undefined), + authorizeIndex: () => true, + requestRejection: () => undefined, rpc: {}, } as never) } diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index 9e2f611ae3..34c03db722 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/connection/README.md -README.md: 293e9f9d6b158e325325f4f741a244031b1d2e02 -README.zh.md: 1acc4e1748b8067bd18a626dfddfabc2cdcc242d +README.md: 4aa85765b009bd9231687976b43bc923ba41177a +README.zh.md: da784c1ce2d966fe8f650d9ebb3b9c6313271829 diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index 293e9f9d6b..4aa85765b0 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -10,7 +10,7 @@ The browser uses HTTP POST for API Proxy and generic Remote unary calls. API Gat Every Host RPC method and WebSocket stream requires one browser session; there is no method-specific loopback tier. Each process mints a random launch token. `dsh-web-app` prints and opens the ordinary root URL with `?token=...`; `frontend-static` delegates root and index requests to `ctx.connection.authorizeIndex`, which accepts that token only on `GET /`, writes an authority-bound signed cookie, and redirects to clean `/`. A missing, expired, malformed, or wrong-authority cookie returns 401 before RPC dispatch. Static assets remain public. The HTTP carrier accepts no query token outside the root exchange and no Authorization-header token. -The cookie signing secret is the owner-scoped `client-connection/browser-session` grant record in `ctx.credentials`. The local provider persists it in `$DSH_HOME/.credentials.yaml`; `BrowserAuth` reads the current record for every verification, so deletion or rotation revokes cookies without restarting the process. Cookies carry an absolute issue/expiry interval, defaulting to 30 days through `cookieMaxAgeDays`, and bind the normalized hostname plus port in both their deterministic name and signed payload. They are host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`; they deliberately omit `Secure` because the shipped server uses loopback HTTP. +The cookie signing secret is the owner-scoped `client-connection/browser-session` grant record in `ctx.credentials`. The local provider persists it in `$DSH_HOME/.credentials.yaml`; `BrowserAuth` loads or creates the record during Connection activation and retains the secret in memory, so request authentication is synchronous. Deleting or replacing the record takes effect on the next Connection activation. Cookies carry an absolute issue/expiry interval, defaulting to 30 days through `cookieMaxAgeDays`, and bind the normalized hostname plus port in both their deterministic name and signed payload. They are host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`; they deliberately omit `Secure` because the shipped server uses loopback HTTP. Before authentication, every request still passes `src/api-request-trust.ts`. Its `Host` must be loopback or match a `trustedHosts` entry: exact on `host:port`, any port on port-less entries, both sides WHATWG-normalized. An attached `Origin` must equal that Host and `sec-fetch-site: cross-site` is refused. Malformed configured authorities fail plugin load. These checks defend DNS rebinding and cross-site browser requests; they never establish identity. A failed Host/Origin check returns 403, while a trusted but unauthenticated request returns 401. `dsh web --host 0.0.0.0` remains unsupported. Decision records: [browser request trust](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md) and [browser token authentication](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md). @@ -32,4 +32,4 @@ None; this package neither assembles nor sends a provider request. - **The `/api` bridge buffers each request body in memory** — `maxRequestBodyBytes` (default 300 MiB, sized for the default 200 MiB aggregate image limit after base64 expansion plus envelope headroom) is therefore also the per-request resident bound; a streaming body path would be needed to lower it without shrinking the image limits. - **The browser cookie is not marked `Secure`** — loopback HTTP is the shipped transport, so deployments that make the same authority reachable over plaintext networking can expose the bearer cookie in transit. -- **There is no logout operation** — clearing the browser cookie ends one browser session; deleting the owner credential record revokes every session and the next launch-token exchange creates a new signing secret. +- **There is no logout operation** — clearing the browser cookie ends one browser session; deleting the owner credential record and restarting `dsh` revokes every session, and the next Connection activation creates a new signing secret. diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index 1acc4e1748..da784c1ce2 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -10,7 +10,7 @@ 每个 Host RPC 方法和 WebSocket stream 都要求同一个浏览器会话,不存在按方法区分的 loopback 层。每个进程生成一个随机启动令牌。`dsh-web-app` 打印并打开带 `?token=...` 的普通根 URL;`frontend-static` 把根路径和 index 请求交给 `ctx.connection.authorizeIndex`,后者只在 `GET /` 接受该令牌,写入绑定 authority 的签名 cookie,再重定向到干净的 `/`。缺失、过期、畸形或 authority 不匹配的 cookie 会在 RPC 分发前得到 401。静态资源保持公开。HTTP 载体不在根路径交换之外接受 query token,也不接受 Authorization header token。 -cookie 签名密钥是 `ctx.credentials` 中由 `client-connection/browser-session` 拥有的 grant 记录。本地提供方把它持久化到 `$DSH_HOME/.credentials.yaml`;`BrowserAuth` 每次校验都读取当前记录,因此删除或轮换记录无需重启进程即可撤销 cookie。cookie 携带绝对签发与过期区间,`cookieMaxAgeDays` 默认设为 30 天,并在确定性名称与签名 payload 中同时绑定规范化 hostname 和 port。它是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`;随附服务器使用 loopback HTTP,因此刻意不设置 `Secure`。 +cookie 签名密钥是 `ctx.credentials` 中由 `client-connection/browser-session` 拥有的 grant 记录。本地提供方把它持久化到 `$DSH_HOME/.credentials.yaml`;`BrowserAuth` 在 Connection 激活期间加载或创建该记录,并把密钥留在内存中,因此请求认证同步执行。删除或替换该记录会在下一次 Connection 激活时生效。cookie 携带绝对签发与过期区间,`cookieMaxAgeDays` 默认设为 30 天,并在确定性名称与签名 payload 中同时绑定规范化 hostname 和 port。它是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`;随附服务器使用 loopback HTTP,因此刻意不设置 `Secure`。 认证之前,每个请求仍经过 `src/api-request-trust.ts`。其 `Host` 必须是 loopback,或与 `trustedHosts` 条目匹配:带端口的 `host:port` 精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化。若附带 `Origin`,它必须等于该 Host;`sec-fetch-site: cross-site` 一律拒绝。畸形配置 authority 会让插件加载失败。这些检查防御 DNS rebinding 与跨站浏览器请求,绝不建立身份。Host/Origin 校验失败返回 403;Host 可信但未认证的请求返回 401。`dsh web --host 0.0.0.0` 仍不受支持。决策记录:[浏览器请求信任](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md)与[浏览器令牌认证](../../../.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md)。 @@ -32,4 +32,4 @@ API Gateway Client 把内部 `$events` logical stream 注册为唯一 generation - **`/api` 桥把每个请求体整体缓冲在内存里**:`maxRequestBodyBytes`(默认 300 MiB,按默认 200 MiB 图片总量上限经 base64 膨胀加信封余量得出)因此同时是单请求的驻留内存上界;要降低它而不缩小图片限额,需要流式请求体路径。 - **浏览器 cookie 不带 `Secure`**:随附载体是 loopback HTTP;若部署把同一 authority 经明文网络暴露,bearer cookie 可能在传输中泄露。 -- **没有 logout 操作**:清除浏览器 cookie 会结束单个浏览器会话;删除 owner 凭据记录会撤销全部会话,下一次启动令牌交换会创建新的签名密钥。 +- **没有 logout 操作**:清除浏览器 cookie 会结束单个浏览器会话;删除 owner 凭据记录并重启 `dsh` 会撤销全部会话,下一次 Connection 激活会创建新的签名密钥。 diff --git a/packages/client/connection/src/browser-auth.ts b/packages/client/connection/src/browser-auth.ts index 77194e16f0..10353d9a06 100644 --- a/packages/client/connection/src/browser-auth.ts +++ b/packages/client/connection/src/browser-auth.ts @@ -158,11 +158,29 @@ function decodeCookie(value: string, secret: Buffer): BrowserCookiePayload | und return decoded as unknown as BrowserCookiePayload } +async function initializeSecret(credentials: CredentialProvider): Promise { + const generated: StoredSecretPayload = { + version: STORED_SECRET_VERSION, + secret: encodeBase64Url(randomBytes(SECRET_BYTES)), + } + const record = await credentials.modifyRecord(AUTH_RECORD_KEY, (current) => { + if (current !== undefined) { + storedSecret(current) + return Promise.resolve(undefined) + } + return Promise.resolve({ kind: 'grant', payload: generated }) + }) + const secret = storedSecret(record) + if (secret === undefined) { + throw new Error('client-connection: browser-session credential record was not created') + } + return secret +} + /** * Process launch-token exchange and persistent signed-cookie verification. - * The credential provider owns the signing secret; this object reads it for - * each operation so deletion or rotation revokes existing cookies without a - * process restart. + * Connection loads the credential provider's signing secret during activation + * and retains it for synchronous request authentication. */ export class BrowserAuth { private readonly launchToken: string @@ -170,7 +188,7 @@ export class BrowserAuth { private constructor( processOwner: object, - private readonly credentials: CredentialProvider, + private readonly secret: Buffer, maxAgeDays: number, ) { this.launchToken = processLaunchToken(processOwner) @@ -194,9 +212,7 @@ export class BrowserAuth { credentials: CredentialProvider, maxAgeDays: number, ): Promise { - const auth = new BrowserAuth(processOwner, credentials, maxAgeDays) - await auth.ensureSecret() - return auth + return new BrowserAuth(processOwner, await initializeSecret(credentials), maxAgeDays) } /** @@ -221,7 +237,7 @@ export class BrowserAuth { * @param res - response owned when this method returns false. * @returns true only when the caller may serve index.html. */ - async authorizeIndex(req: ConnectionIndexRequest, res: ConnectionIndexResponse): Promise { + authorizeIndex(req: ConnectionIndexRequest, res: ConnectionIndexResponse): boolean { /* v8 ignore next -- node:http always supplies url on server requests. */ const url = new URL(req.url ?? '/', 'http://dsh.invalid') const tokens = url.searchParams.getAll(TOKEN_QUERY) @@ -236,7 +252,7 @@ export class BrowserAuth { authority, issuedAt, expiresAt, - }, await this.ensureSecret()) + }, this.secret) res.writeHead(303, { 'cache-control': 'no-store', 'location': '/', @@ -248,7 +264,7 @@ export class BrowserAuth { res.end() return false } - if (req.method === 'GET' && url.pathname === '/' && await this.isAuthenticated(req)) { + if (req.method === 'GET' && url.pathname === '/' && this.isAuthenticated(req)) { res.writeHead(303, { 'cache-control': 'no-store', 'location': '/', @@ -260,7 +276,7 @@ export class BrowserAuth { this.writeUnauthorized(req, res) return false } - if (await this.isAuthenticated(req)) return true + if (this.isAuthenticated(req)) return true this.writeUnauthorized(req, res) return false } @@ -268,17 +284,15 @@ export class BrowserAuth { /** * Verify the authority-bound browser cookie on a Host request. * @param request - request headers carrying Host and Cookie. - * @returns true only for an unexpired cookie signed by the current durable secret. + * @returns true only for an unexpired cookie signed by this activation's loaded secret. */ - async isAuthenticated(request: ConnectionTrustRequest): Promise { + isAuthenticated(request: ConnectionTrustRequest): boolean { const authority = requestAuthority(request.headers) const rawCookie = header(request.headers, 'cookie') if (authority === undefined || rawCookie === undefined) return false const value = cookieValue(rawCookie, cookieName(authority)) if (value === undefined) return false - const secret = storedSecret(await this.credentials.readRecord(AUTH_RECORD_KEY)) - if (secret === undefined) return false - const payload = decodeCookie(value, secret) + const payload = decodeCookie(value, this.secret) if (payload === undefined || payload.authority !== authority) return false const now = Date.now() return payload.issuedAt <= now @@ -287,25 +301,6 @@ export class BrowserAuth { && payload.expiresAt - payload.issuedAt <= this.maxAgeMilliseconds } - private async ensureSecret(): Promise { - const generated: StoredSecretPayload = { - version: STORED_SECRET_VERSION, - secret: encodeBase64Url(randomBytes(SECRET_BYTES)), - } - const record = await this.credentials.modifyRecord(AUTH_RECORD_KEY, (current) => { - if (current !== undefined) { - storedSecret(current) - return Promise.resolve(undefined) - } - return Promise.resolve({ kind: 'grant', payload: generated }) - }) - const secret = storedSecret(record) - if (secret === undefined) { - throw new Error('client-connection: browser-session credential record was not created') - } - return secret - } - private writeUnauthorized(req: ConnectionIndexRequest, res: ConnectionIndexResponse): void { res.writeHead(401, { 'cache-control': 'no-store', diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index ff4d3ba1c1..c7203f38d8 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -106,7 +106,7 @@ export async function apply(ctx: Context, config?: ConnectionConfig): Promise { - const rejection = await connection.requestRejection(req) + const rejection = connection.requestRejection(req) if (rejection !== undefined) { res.writeHead(rejection) res.end(rejection === 401 ? 'unauthorized' : 'forbidden') diff --git a/packages/client/connection/src/rpc-host.ts b/packages/client/connection/src/rpc-host.ts index 5c079e092a..4f1e78341b 100644 --- a/packages/client/connection/src/rpc-host.ts +++ b/packages/client/connection/src/rpc-host.ts @@ -77,13 +77,13 @@ export class HostConnectionService extends Service implements HostConnectionHand } /** Apply the configured Host/Origin fence, then browser authentication. */ - async requestRejection(request: ConnectionTrustRequest): Promise { + requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection { if (!isTrustedApiRequest(request, this.trustedHosts)) return 403 - return await this.browserAuth.isAuthenticated(request) ? undefined : 401 + return this.browserAuth.isAuthenticated(request) ? undefined : 401 } /** Authenticate an index request through the process-token exchange or cookie. */ - authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): Promise { + authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): boolean { return this.browserAuth.authorizeIndex(request, response) } @@ -125,7 +125,7 @@ export class HostConnectionService extends Service implements HostConnectionHand kind: 'prefix', path: channel, handler: async (req, res) => { - const rejection = await this.requestRejection(req) + const rejection = this.requestRejection(req) if (rejection !== undefined) { res.writeHead(rejection) res.end(rejection === 401 ? 'unauthorized' : 'forbidden') diff --git a/packages/client/connection/src/rpc.ts b/packages/client/connection/src/rpc.ts index d05e2f0b81..1f879963af 100644 --- a/packages/client/connection/src/rpc.ts +++ b/packages/client/connection/src/rpc.ts @@ -81,7 +81,7 @@ export interface HostConnectionHandle { * @param request - request headers from the HTTP or upgrade request. * @returns rejection status, or undefined when the route may accept the request. */ - requestRejection(request: ConnectionTrustRequest): Promise + requestRejection(request: ConnectionTrustRequest): ConnectionRequestRejection /** * Authenticate one frontend index request, owning a token redirect or 401. @@ -89,7 +89,7 @@ export interface HostConnectionHandle { * @param response - response owned when the result is false. * @returns true only when the frontend may serve index.html. */ - authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): Promise + authorizeIndex(request: ConnectionIndexRequest, response: ConnectionIndexResponse): boolean /** * Add the fresh process token to an ordinary Web application URL. diff --git a/packages/client/connection/tests/browser-auth.host.spec.ts b/packages/client/connection/tests/browser-auth.host.spec.ts index 8b899ff7c9..885b726b69 100644 --- a/packages/client/connection/tests/browser-auth.host.spec.ts +++ b/packages/client/connection/tests/browser-auth.host.spec.ts @@ -9,8 +9,11 @@ import type { ConnectionIndexRequest, ConnectionIndexResponse } from '../src/rpc class RecordCredentials { record: CredentialRecord | undefined discardWrites = false + reads = 0 + modifies = 0 readRecord(): Promise { + this.reads += 1 return Promise.resolve(this.record) } @@ -18,6 +21,7 @@ class RecordCredentials { _key: unknown, mutate: (current: CredentialRecord | undefined) => Promise, ): Promise { + this.modifies += 1 const next = await mutate(this.record) if (this.discardWrites) return undefined if (next !== undefined) this.record = next @@ -96,14 +100,14 @@ function request(url: string, authority = '127.0.0.1:3080', init?: { } } -async function exchange( +function exchange( auth: BrowserAuth, authority = '127.0.0.1:3080', -): Promise<{ cookie: string; launchUrl: string; state: ResponseState }> { +): { cookie: string; launchUrl: string; state: ResponseState } { const launchUrl = auth.authenticatedUrl(`http://${authority}`) const target = new URL(launchUrl) const res = response() - expect(await auth.authorizeIndex(request(`${target.pathname}${target.search}`, authority), res.value)).toBe(false) + expect(auth.authorizeIndex(request(`${target.pathname}${target.search}`, authority), res.value)).toBe(false) const setCookie = res.state.headers?.['set-cookie'] if (setCookie === undefined) throw new Error('token exchange did not set a cookie') return { cookie: setCookie.split(';', 1)[0]!, launchUrl, state: res.state } @@ -118,7 +122,7 @@ describe('BrowserAuth', () => { const store = new RecordCredentials() const processOwner = {} const first = await createAuth(store, 30, processOwner) - const login = await exchange(first) + const login = exchange(first) expect(login.state).toMatchObject({ status: 303, @@ -130,25 +134,25 @@ describe('BrowserAuth', () => { }) expect(login.state.headers?.['set-cookie']).toMatch(/; Max-Age=2592000; Path=\/; Expires=.*; HttpOnly; SameSite=Strict$/u) expect(login.state.headers?.['set-cookie']).not.toContain('Secure') - expect(await first.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) - expect(await first.isAuthenticated({ + expect(first.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) + expect(first.isAuthenticated({ headers: new Headers({ host: '127.0.0.1:3080', cookie: login.cookie }), })).toBe(true) - expect(await first.isAuthenticated({ headers: new Headers() })).toBe(false) - expect(await first.isAuthenticated(request('/', 'localhost:3080', { cookie: login.cookie }))).toBe(false) - expect(await first.isAuthenticated(request('/', '127.0.0.1:3081', { cookie: login.cookie }))).toBe(false) + expect(first.isAuthenticated({ headers: new Headers() })).toBe(false) + expect(first.isAuthenticated(request('/', 'localhost:3080', { cookie: login.cookie }))).toBe(false) + expect(first.isAuthenticated(request('/', '127.0.0.1:3081', { cookie: login.cookie }))).toBe(false) const reloaded = await createAuth(store, 30, processOwner) expect(reloaded.authenticatedUrl('http://127.0.0.1:3080')).toBe(login.launchUrl) - expect(await reloaded.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) + expect(reloaded.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) const restarted = await createAuth(store) expect(new URL(restarted.authenticatedUrl('http://127.0.0.1:3080')).searchParams.get('token')) .not.toBe(new URL(login.launchUrl).searchParams.get('token')) - expect(await restarted.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) + expect(restarted.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: login.cookie }))).toBe(true) const staleUrl = new URL(login.launchUrl) const redirected = response() - expect(await restarted.authorizeIndex(request( + expect(restarted.authorizeIndex(request( `${staleUrl.pathname}${staleUrl.search}`, '127.0.0.1:3080', { cookie: login.cookie }, @@ -165,9 +169,9 @@ describe('BrowserAuth', () => { it('accepts the cookie for index serving and gives every unauthenticated request one response', async () => { const auth = await createAuth(new RecordCredentials()) - const { cookie } = await exchange(auth) + const { cookie } = exchange(auth) const allowed = response() - expect(await auth.authorizeIndex(request('/index.html', '127.0.0.1:3080', { cookie }), allowed.value)).toBe(true) + expect(auth.authorizeIndex(request('/index.html', '127.0.0.1:3080', { cookie }), allowed.value)).toBe(true) expect(allowed.state).toEqual({}) for (const candidate of [ @@ -178,7 +182,7 @@ describe('BrowserAuth', () => { request(auth.authenticatedUrl('http://127.0.0.1:3080'), '127.0.0.1:3080', { method: 'HEAD' }), ]) { const denied = response() - expect(await auth.authorizeIndex(candidate, denied.value)).toBe(false) + expect(auth.authorizeIndex(candidate, denied.value)).toBe(false) expect(denied.state.status).toBe(401) expect(denied.state.headers).toEqual({ 'cache-control': 'no-store', @@ -195,18 +199,18 @@ describe('BrowserAuth', () => { vi.setSystemTime(new Date('2026-08-24T00:00:00.000Z')) const store = new RecordCredentials() const auth = await createAuth(store) - const { cookie } = await exchange(auth) + const { cookie } = exchange(auth) const [name, value] = cookie.split('=') as [string, string] - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=broken` }))).toBe(false) - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=${value.slice(0, -1)}x` }))).toBe(false) - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=%` }))).toBe(false) - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=broken` }))).toBe(false) + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=${value.slice(0, -1)}x` }))).toBe(false) + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: `${name}=%` }))).toBe(false) + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: signedBodyCookie(store, name, 'a'), }))).toBe(false) - expect(await auth.isAuthenticated({ headers: {} })).toBe(false) - expect(await auth.isAuthenticated({ headers: { host: 'bad host', cookie } })).toBe(false) - expect(await auth.isAuthenticated({ headers: { host: '127.0.0.1:3080' } })).toBe(false) + expect(auth.isAuthenticated({ headers: {} })).toBe(false) + expect(auth.isAuthenticated({ headers: { host: 'bad host', cookie } })).toBe(false) + expect(auth.isAuthenticated({ headers: { host: '127.0.0.1:3080' } })).toBe(false) const invalidPayloads: unknown[] = [ 'not json', @@ -217,30 +221,37 @@ describe('BrowserAuth', () => { { version: 1, authority: '127.0.0.1:3080', issuedAt: Date.now(), expiresAt: 'later' }, ] for (const payload of invalidPayloads) { - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: signedCookie(store, name, payload), }))).toBe(false) } const shorter = await createAuth(store, 1) - expect(await shorter.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) + expect(shorter.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) vi.setSystemTime(new Date('2026-09-24T00:00:00.000Z')) - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) vi.setSystemTime(new Date('2026-08-23T00:00:00.000Z')) - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie }))).toBe(false) }) - it('revokes on record deletion and creates a new secret on the next token exchange', async () => { + it('loads one secret per activation and replaces it after deletion on the next activation', async () => { const store = new RecordCredentials() const auth = await createAuth(store) - const first = await exchange(auth) - await store.deleteRecord() - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: first.cookie }))).toBe(false) + const first = exchange(auth) + expect(store).toMatchObject({ reads: 0, modifies: 1 }) - const second = await exchange(auth) + await store.deleteRecord() + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: first.cookie }))).toBe(true) + const sameActivation = exchange(auth) + expect(auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: sameActivation.cookie }))).toBe(true) + expect(store).toMatchObject({ reads: 0, modifies: 1 }) + + const reactivated = await createAuth(store) + const second = exchange(reactivated) expect(second.cookie).not.toBe(first.cookie) - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: first.cookie }))).toBe(false) - expect(await auth.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: second.cookie }))).toBe(true) + expect(reactivated.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: first.cookie }))).toBe(false) + expect(reactivated.isAuthenticated(request('/', '127.0.0.1:3080', { cookie: second.cookie }))).toBe(true) + expect(store).toMatchObject({ reads: 0, modifies: 2 }) }) it('fails loud on an invalid owner record instead of replacing it', async () => { diff --git a/packages/client/connection/tests/node-half.host.spec.ts b/packages/client/connection/tests/node-half.host.spec.ts index a175a7f005..6442b83145 100644 --- a/packages/client/connection/tests/node-half.host.spec.ts +++ b/packages/client/connection/tests/node-half.host.spec.ts @@ -106,10 +106,10 @@ async function mounted(config?: { trustedHosts?: string[] }): Promise<{ } /** Exchange a service's process token for one authority-bound Cookie header. */ -async function browserCookie(connection: HostConnectionHandle, authority: string): Promise { +function browserCookie(connection: HostConnectionHandle, authority: string): string { const url = new URL(connection.authenticatedUrl(`http://${authority}`)) const exchanged = fakeResponse() - await connection.authorizeIndex( + connection.authorizeIndex( fakeRequest({ host: authority }, `${url.pathname}${url.search}`), exchanged.response, ) @@ -184,7 +184,7 @@ describe('connection node half', () => { expect([method, denied.state.status, denied.state.body]).toEqual([method, 401, 'unauthorized']) } - const cookie = await browserCookie(connection, 'harness.example') + const cookie = browserCookie(connection, 'harness.example') for (const method of methods) { const allowed = fakeResponse() await routes[0]!.handler( @@ -207,7 +207,7 @@ describe('connection node half', () => { const loopback = fakeResponse() await routes[0]!.handler(fakeRequest({ host: '127.0.0.1:3080', - cookie: await browserCookie(connection, '127.0.0.1:3080'), + cookie: browserCookie(connection, '127.0.0.1:3080'), }), loopback.response) expect(loopback.state.status).toBe(404) // An all-interfaces composition derives port-less LAN IP literals, which @@ -215,7 +215,7 @@ describe('connection node half', () => { const lan = fakeResponse() await routes[0]!.handler(fakeRequest({ host: '192.168.1.5:3080', - cookie: await browserCookie(connection, '192.168.1.5:3080'), + cookie: browserCookie(connection, '192.168.1.5:3080'), }), lan.response) expect(lan.state.status).toBe(404) // Declared public authority, same-origin browser shape. @@ -224,7 +224,7 @@ describe('connection node half', () => { host: 'harness.example:3080', origin: 'http://harness.example:3080', 'sec-fetch-site': 'same-origin', - cookie: await browserCookie(connection, 'harness.example:3080'), + cookie: browserCookie(connection, 'harness.example:3080'), }), declared.response) expect(declared.state.status).toBe(404) await dispose() @@ -235,11 +235,11 @@ describe('connection node half', () => { const loopback = fakeRequest({ host: '127.0.0.1:3080' }) const declared = fakeRequest({ host: 'harness.example' }) - expect(await connection.requestRejection(loopback)).toBe(401) - expect(await connection.requestRejection(declared)).toBe(401) - expect(await connection.requestRejection(fakeRequest({ + expect(connection.requestRejection(loopback)).toBe(401) + expect(connection.requestRejection(declared)).toBe(401) + expect(connection.requestRejection(fakeRequest({ host: 'harness.example', - cookie: await browserCookie(connection, 'harness.example'), + cookie: browserCookie(connection, 'harness.example'), }))).toBeUndefined() await dispose() }) @@ -272,7 +272,7 @@ describe('connection node half', () => { const result = fakeResponse() await route!.handler(fakePost({ host: '127.0.0.1:3080', - cookie: await browserCookie(connection, '127.0.0.1:3080'), + cookie: browserCookie(connection, '127.0.0.1:3080'), }, '/rpc/goals/create', request), result.response) expect(result.state.status).toBe(200) expect(JSON.parse(String(result.state.body))).toEqual({ @@ -330,7 +330,7 @@ describe('connection node half', () => { } const claimed = fakeResponse() - const loopbackCookie = await browserCookie(connection, '127.0.0.1:3080') + const loopbackCookie = browserCookie(connection, '127.0.0.1:3080') await route.handler(fakePost({ host: '127.0.0.1:3080', cookie: loopbackCookie, }, '/api/goals/create', request), claimed.response) @@ -371,7 +371,7 @@ describe('connection node half', () => { const declared = fakeResponse() await route.handler(fakePost({ host: 'harness.example', - cookie: await browserCookie(connection, 'harness.example'), + cookie: browserCookie(connection, 'harness.example'), }, '/api/goals/create', request), declared.response) expect(declared.state.status).toBe(200) await removeAuthenticated() @@ -393,7 +393,7 @@ describe('connection node half', () => { const route = routes.find(candidate => candidate.path === '/rpc')! const harnessHeaders = { host: 'harness.example', - cookie: await browserCookie(connection, 'harness.example'), + cookie: browserCookie(connection, 'harness.example'), } const denied = fakeResponse() @@ -514,7 +514,7 @@ describe('connection node half over a real HTTP server', () => { } expect(await call(port, 'settings.describe', 'other.example')).toBe(403) - const declaredCookie = await browserCookie(connection, 'harness.example') + const declaredCookie = browserCookie(connection, 'harness.example') for (const method of methods) { expect([method, await call(port, method, 'harness.example', declaredCookie)]).toEqual([method, 404]) } @@ -523,7 +523,7 @@ describe('connection node half over a real HTTP server', () => { port, 'settings.describe', loopbackAuthority, - await browserCookie(connection, loopbackAuthority), + browserCookie(connection, loopbackAuthority), )).toBe(404) } finally { await close() diff --git a/packages/host/frontend-static/src/index.ts b/packages/host/frontend-static/src/index.ts index 6855a21190..3d218f31e6 100644 --- a/packages/host/frontend-static/src/index.ts +++ b/packages/host/frontend-static/src/index.ts @@ -70,7 +70,7 @@ const STATIC_MISS_CODES: ReadonlySet = new Set([ */ export async function serveStatic( pathname: string, res: ServerResponse, distRoot: string, distIndex: string, - authorizeIndex: () => Promise, + authorizeIndex: () => boolean, renderIndex: () => Promise, ): Promise { const target = resolve(normalize(join(distRoot, pathname))) @@ -86,7 +86,7 @@ export async function serveStatic( let type: string try { if (target === distRoot || target === distIndex) { - if (!await authorizeIndex()) return + if (!authorizeIndex()) return body = await renderIndex() type = HTML_MIME } else { From b43d0934f7d4b76ca207b7470176f6f36505239c Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Tue, 25 Aug 2026 13:17:11 +0800 Subject: [PATCH 28/31] test(web): keep credential fixtures package-local --- .../api/gateway/tests/browser-credentials.ts | 17 +++++++++ .../gateway/tests/gateway-stream.host.spec.ts | 4 +-- .../api/gateway/tests/gateway.host.spec.ts | 4 +-- .../tests/browser-auth.host.spec.ts | 31 ++-------------- .../connection/tests/browser-credentials.ts | 36 +++++++++++++++++++ .../connection/tests/node-half.host.spec.ts | 12 +++---- 6 files changed, 65 insertions(+), 39 deletions(-) create mode 100644 packages/api/gateway/tests/browser-credentials.ts create mode 100644 packages/client/connection/tests/browser-credentials.ts diff --git a/packages/api/gateway/tests/browser-credentials.ts b/packages/api/gateway/tests/browser-credentials.ts new file mode 100644 index 0000000000..8661983ea8 --- /dev/null +++ b/packages/api/gateway/tests/browser-credentials.ts @@ -0,0 +1,17 @@ +import type { Context } from '@deepseek-ai/cordis' + +/** Provide an in-memory credential-record owner for a mounted Connection plugin. */ +export function provideBrowserCredentials(ctx: Context): void { + const records = new Map() + ctx.provide('credentials', { + async modifyRecord( + key: unknown, + mutate: (current: unknown) => Promise, + ): Promise { + const current = records.get(key) + const next = await mutate(current) + if (next !== undefined) records.set(key, next) + return next ?? current + }, + } as never) +} diff --git a/packages/api/gateway/tests/gateway-stream.host.spec.ts b/packages/api/gateway/tests/gateway-stream.host.spec.ts index 01fcc81b0f..d7289783d3 100644 --- a/packages/api/gateway/tests/gateway-stream.host.spec.ts +++ b/packages/api/gateway/tests/gateway-stream.host.spec.ts @@ -14,7 +14,7 @@ import { TypertRemoteFailure, } from '@deepseek-ai/dsh-typert-protocol' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' -import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts' +import { provideBrowserCredentials } from './browser-credentials.ts' import TypertGatewayService, { TypertGatewayError, type TypertRemoteEventDispatch, @@ -969,7 +969,7 @@ async function setup(transport: boolean): Promise<{ readonly ctx: Context; reado roots.push(ctx) if (transport) { await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }) - await ctx.plugin(MemoryCredentials) + provideBrowserCredentials(ctx) } await ctx.plugin(TypertRegistry) await ctx.plugin(TypertGatewayService) diff --git a/packages/api/gateway/tests/gateway.host.spec.ts b/packages/api/gateway/tests/gateway.host.spec.ts index 0798765e98..c0455bba10 100644 --- a/packages/api/gateway/tests/gateway.host.spec.ts +++ b/packages/api/gateway/tests/gateway.host.spec.ts @@ -18,7 +18,7 @@ import { } from '@deepseek-ai/dsh-typert-protocol' import TypertRegistry, { type TypertContribution } from '@deepseek-ai/dsh-typert-registry' import TypertGatewayService, { TypertGatewayError } from '@deepseek-ai/dsh-api-gateway' -import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts' +import { provideBrowserCredentials } from './browser-credentials.ts' interface FixtureAgent { readonly id: string @@ -1168,7 +1168,7 @@ describe('TypertGatewayService', () => { it('dispatches claimed invocations through /api and leaves unclaimed endpoints to its fallback', async () => { const ctx = new Context().extend({ fixtureScope: 'http-caller' }) const routes: WebRoute[] = [] - await ctx.plugin(MemoryCredentials) + provideBrowserCredentials(ctx) ctx.provide('webServer', fakeHttpServer(routes) as WebServer) const connectionFiber = ctx.plugin({ inject: [...connectionInject], apply: applyConnection }) await connectionFiber diff --git a/packages/client/connection/tests/browser-auth.host.spec.ts b/packages/client/connection/tests/browser-auth.host.spec.ts index 885b726b69..3f06672ff1 100644 --- a/packages/client/connection/tests/browser-auth.host.spec.ts +++ b/packages/client/connection/tests/browser-auth.host.spec.ts @@ -2,37 +2,10 @@ import { createHmac } from 'node:crypto' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { CredentialProvider, CredentialRecord } from '@deepseek-ai/dsh-credentials' +import type { CredentialProvider } from '@deepseek-ai/dsh-credentials' import { BrowserAuth } from '../src/browser-auth.ts' import type { ConnectionIndexRequest, ConnectionIndexResponse } from '../src/rpc.ts' - -class RecordCredentials { - record: CredentialRecord | undefined - discardWrites = false - reads = 0 - modifies = 0 - - readRecord(): Promise { - this.reads += 1 - return Promise.resolve(this.record) - } - - async modifyRecord( - _key: unknown, - mutate: (current: CredentialRecord | undefined) => Promise, - ): Promise { - this.modifies += 1 - const next = await mutate(this.record) - if (this.discardWrites) return undefined - if (next !== undefined) this.record = next - return this.record - } - - deleteRecord(): Promise { - this.record = undefined - return Promise.resolve() - } -} +import { RecordCredentials } from './browser-credentials.ts' function signedCookie(store: RecordCredentials, name: string, payload: unknown): string { const body = typeof payload === 'string' diff --git a/packages/client/connection/tests/browser-credentials.ts b/packages/client/connection/tests/browser-credentials.ts new file mode 100644 index 0000000000..3739101648 --- /dev/null +++ b/packages/client/connection/tests/browser-credentials.ts @@ -0,0 +1,36 @@ +import type { Context } from '@deepseek-ai/cordis' +import type { CredentialProvider, CredentialRecord } from '@deepseek-ai/dsh-credentials' + +/** Mutable credential-record double for Connection authentication tests. */ +export class RecordCredentials { + record: CredentialRecord | undefined + discardWrites = false + reads = 0 + modifies = 0 + + readRecord(): Promise { + this.reads += 1 + return Promise.resolve(this.record) + } + + async modifyRecord( + _key: unknown, + mutate: (current: CredentialRecord | undefined) => Promise, + ): Promise { + this.modifies += 1 + const next = await mutate(this.record) + if (this.discardWrites) return undefined + if (next !== undefined) this.record = next + return this.record + } + + deleteRecord(): Promise { + this.record = undefined + return Promise.resolve() + } +} + +/** Provide the record operations Connection needs during authentication setup. */ +export function provideBrowserCredentials(ctx: Context): void { + ctx.provide('credentials', new RecordCredentials() as unknown as CredentialProvider) +} diff --git a/packages/client/connection/tests/node-half.host.spec.ts b/packages/client/connection/tests/node-half.host.spec.ts index 6442b83145..75691394ed 100644 --- a/packages/client/connection/tests/node-half.host.spec.ts +++ b/packages/client/connection/tests/node-half.host.spec.ts @@ -12,7 +12,7 @@ import { RpcId, type ClientRequest } from '@deepseek-ai/dsh-host-apiproxy/api' import type { WebServer, WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver' import { API_PATH, apply, inject, type HostConnectionHandle } from '../src/index.ts' import { DEFAULT_MAX_REQUEST_BODY_BYTES } from '../src/http-bridge.ts' -import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts' +import { provideBrowserCredentials } from './browser-credentials.ts' /** Structural webServer fake recording both route registries. */ function fakeHttpServer( @@ -92,7 +92,7 @@ async function mounted(config?: { trustedHosts?: string[] }): Promise<{ const ctx = new Context() const routes: WebRoute[] = [] const upgrades: WebUpgradeRoute[] = [] - await ctx.plugin(MemoryCredentials) + provideBrowserCredentials(ctx) ctx.provide('webServer', fakeHttpServer(routes, upgrades) as WebServer) ctx.provide('apiProxy', {} as unknown as ApiProxy) const fiber = ctx.plugin({ inject: [...inject], apply }, config) @@ -141,7 +141,7 @@ describe('connection node half', () => { const routes: WebRoute[] = [] const upgrades: WebUpgradeRoute[] = [] const ctx = new Context() - await ctx.plugin(MemoryCredentials) + provideBrowserCredentials(ctx) ctx.provide('webServer', fakeHttpServer(routes, upgrades) as WebServer) ctx.provide('apiProxy', {} as unknown as ApiProxy) const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.internal/path'] }) @@ -247,7 +247,7 @@ describe('connection node half', () => { it('provides a disposable dedicated RPC channel without requiring apiProxy', async () => { const ctx = new Context() const routes: WebRoute[] = [] - await ctx.plugin(MemoryCredentials) + provideBrowserCredentials(ctx) ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() @@ -296,7 +296,7 @@ describe('connection node half', () => { it('dispatches claimed /api endpoints before the API Proxy fallback and withdraws the claim', async () => { const ctx = new Context() const routes: WebRoute[] = [] - await ctx.plugin(MemoryCredentials) + provideBrowserCredentials(ctx) ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) ctx.provide('apiProxy', {} as unknown as ApiProxy) const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] }) @@ -381,7 +381,7 @@ describe('connection node half', () => { it('applies the configured trust fence and JSON envelope checks to generic channels', async () => { const ctx = new Context() const routes: WebRoute[] = [] - await ctx.plugin(MemoryCredentials) + provideBrowserCredentials(ctx) ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer) const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] }) await fiber.await() From 4de11c022964e47b9ef7abb52f8c6c8e2c3062e0 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Tue, 25 Aug 2026 14:11:38 +0800 Subject: [PATCH 29/31] test(web): authenticate streaming fence scaffold --- apps/web/tests/streaming-fence-highlight.e2e.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/tests/streaming-fence-highlight.e2e.ts b/apps/web/tests/streaming-fence-highlight.e2e.ts index 594d51c949..411b37075c 100644 --- a/apps/web/tests/streaming-fence-highlight.e2e.ts +++ b/apps/web/tests/streaming-fence-highlight.e2e.ts @@ -98,7 +98,7 @@ describe.skipIf(MODE === 'record')('web e2e: streaming code-fence highlighting', browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) - await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) }, 120_000) From 61b65d3147437b18220171d7d091841100208450 Mon Sep 17 00:00:00 2001 From: 07akioni <07akioni2@gmail.com> Date: Tue, 25 Aug 2026 11:50:49 +0800 Subject: [PATCH 30/31] fix(web): show system prompts in chat Render reconstructable system prompts at each request-series boundary, preserve series declarations through pre-step wrappers, and keep the presentation and replay snapshots aligned across clients. --- ...6-07-05-reconstructable-requests.i18n.yaml | 4 +- .../2026-07-05-reconstructable-requests.md | 9 +- .../2026-07-05-reconstructable-requests.zh.md | 9 +- ...lient-conversation-node-assembly.i18n.yaml | 4 +- ...08-09-client-conversation-node-assembly.md | 4 + ...09-client-conversation-node-assembly.zh.md | 4 + ...17-web-system-prompt-opaque-body.i18n.yaml | 6 + ...026-08-17-web-system-prompt-opaque-body.md | 29 + ...-08-17-web-system-prompt-opaque-body.zh.md | 29 + ...plify-session-log-representation.i18n.yaml | 4 +- ...-12-simplify-session-log-representation.md | 2 +- ...-simplify-session-log-representation.zh.md | 2 +- .../goal-round-driver/session.expected.jsonl | 6 +- .../goal-wrapup/session.expected.jsonl | 7 +- .../tests/chat-continuous-conversation.e2e.ts | 5 + .../conversation.expected.md | 4 + .../expected/skill-user-invoke/ui.expected.md | 4 + .../expected/steer-all/mid-steer.expected.md | 4 + .../expected/steer-all/settled.expected.md | 4 + apps/web/tests/goal-multi-turn-actions.e2e.ts | 5 + apps/web/tests/replay-round-trip.e2e.ts | 19 + .../mid-stream.expected.md | 4 + docs/agent-lifecycle.i18n.yaml | 4 +- docs/agent-lifecycle.md | 2 +- docs/agent-lifecycle.zh.md | 2 +- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 4 +- docs/architecture.zh.md | 4 +- docs/event-producer-consumer.i18n.yaml | 4 +- docs/event-producer-consumer.md | 24 +- docs/event-producer-consumer.zh.md | 24 +- docs/persistence-catalog.i18n.yaml | 4 +- docs/persistence-catalog.md | 33 +- docs/persistence-catalog.zh.md | 7 +- docs/subsystems/core.i18n.yaml | 4 +- docs/subsystems/core.md | 7 +- docs/subsystems/core.zh.md | 7 +- docs/subsystems/session.i18n.yaml | 4 +- docs/subsystems/session.md | 9 +- docs/subsystems/session.zh.md | 9 +- packages/api/session-controller/src/agent.ts | 12 +- .../tests/session-models.host.spec.ts | 29 +- packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 4 + packages/client/ui-chat/README.zh.md | 4 + .../ui-chat/src/client/chat/ChatView.tsx | 20 +- .../chat/ContextInjectionRow.module.css | 3 +- .../src/client/chat/ContextInjectionRow.tsx | 4 +- .../src/client/chat/SystemPromptRow.tsx | 47 + .../client/chat/register-node-renderers.ts | 3 + .../chat-snapshot-builder.ts | 2 + .../src/client/conversation-nodes/register.ts | 2 + .../conversation-nodes/request-prompt.ts | 87 ++ packages/client/ui-chat/src/client/index.ts | 1 + packages/client/ui-chat/src/client/locale.ts | 2 + .../ui-chat/tests/chat-view.client.spec.tsx | 33 + ...nversation-node-definitions.client.spec.ts | 232 +++ .../tests/system-prompt-row.client.spec.tsx | 44 + .../src/client/contract/request-inspection.ts | 56 + .../src/client/conversation/assembly.ts | 19 + .../ui-conversation/src/client/index.ts | 3 +- .../tests/request-inspection.client.spec.ts | 86 + .../client/ui-primitives/src/icons/index.tsx | 16 + .../ui-primitives/tests/icons.client.spec.tsx | 4 +- .../trajectory-request-header-definition.ts | 100 +- .../src/client/trajectory-snapshot-builder.ts | 46 +- .../conversation-definitions.client.spec.ts | 3 +- .../tests/snapshot-builder.client.spec.ts | 59 + .../context/agent-instructions/src/index.ts | 2 +- .../context/session-reference/src/index.ts | 2 +- packages/context/time-context/src/index.ts | 2 +- packages/context/tmux-context/src/index.ts | 2 +- packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 2 +- packages/core/agent-loop/README.zh.md | 2 +- packages/core/agent-loop/src/agent.ts | 37 +- packages/core/agent-loop/tests/loop.spec.ts | 3 +- .../agent-loop/tests/request-error.spec.ts | 2 + .../tests/request-reconstruction.spec.ts | 144 +- packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 2 +- packages/core/agent/README.zh.md | 2 +- packages/core/agent/src/runtime-types.ts | 7 +- packages/core/session/README.i18n.yaml | 4 +- packages/core/session/README.md | 2 +- packages/core/session/README.zh.md | 2 +- packages/core/session/src/types.ts | 13 +- .../src/client/slot-catalog.ts | 3 +- .../extensions/tool-cordis/src/api-catalog.ts | 6 +- packages/extensions/tool-cordis/src/index.ts | 2 +- .../goal/goal-round-driver/README.i18n.yaml | 4 +- packages/goal/goal-round-driver/README.md | 2 +- packages/goal/goal-round-driver/README.zh.md | 2 +- packages/goal/goal-round-driver/src/index.ts | 2 +- .../tests/goal-round-driver.spec.ts | 4 + packages/hooks/hooks-claude-code/src/index.ts | 2 +- packages/hooks/hooks-codex/src/index.ts | 2 +- packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 2 +- packages/host/apiproxy/README.zh.md | 2 +- packages/skill/tool-skill/src/index.ts | 8 +- .../session-snapshot/src/suite.ts | 108 +- .../fixtures/suite/pin-turn/behavior.json | 3 +- .../fixtures/suite/pin-turn/session.jsonl | 1 + scripts/gen-doc-graphs.ts | 2 +- .../session/agent-instructions/session.jsonl | 7 +- .../session/agent-instructions/snapshot.yml | 2 +- .../system-prompt.expected.md | 33 + .../tool-schemas.expected.json | 1392 +++++++++++++++++ .../session/compaction-recovery/session.jsonl | 3 +- .../session/compaction-recovery/snapshot.yml | 3 +- .../system-prompt.expected.md | 63 + .../tool-schemas.expected.json | 1392 +++++++++++++++++ snapshots/session/headless.snapshot.ts | 8 +- .../session-sandbox-root/session.jsonl | 6 +- snapshots/web/bash-abort-row/ui.expected.md | 4 + snapshots/web/code-mode-round/ui.expected.md | 4 + .../web/cordis-tool-round/ui.expected.md | 4 + .../web/feedback-command/ack.expected.md | 4 + snapshots/web/fresh-round-trip/ui.expected.md | 4 + .../web/goal-multi-turn-actions/session.jsonl | 39 +- .../goal-multi-turn-actions/ui.expected.md | 8 + .../web/lifecycle-chrome/reloaded.expected.md | 4 + .../web/live-interactions/cancel.expected.md | 4 + .../live-interactions/error-auth.expected.md | 4 + .../web/live-interactions/loading.expected.md | 4 + .../retry-exhausted.expected.md | 4 + .../web/live-interactions/retry.expected.md | 4 + .../running-draft.expected.md | 4 + snapshots/web/message-actions/ui.expected.md | 4 + .../web/plan-review/approved.expected.md | 11 +- .../question-composer/answered.expected.md | 4 + .../web/queue-actions/collapsed.expected.md | 4 + .../web/queue-actions/editing.expected.md | 4 + .../web/queue-actions/layout.expected.md | 4 + .../web/queue-actions/preserved.expected.md | 4 + snapshots/web/queue-actions/ui.expected.md | 4 + .../seeded-history/command-row.expected.md | 4 + .../seeded-history/feedback-row.expected.md | 4 + snapshots/web/seeded-history/ui.expected.md | 4 + snapshots/web/skill-tool-row/ui.expected.md | 4 + snapshots/web/steering/mid-steer.expected.md | 4 + snapshots/web/steering/settled.expected.md | 4 + .../web/subagent-conversation/ui.expected.md | 11 +- .../offline-composer.expected.md | 4 + .../web/turn-tail-actions/running.expected.md | 4 + .../web/turn-tail-actions/settled.expected.md | 4 + snapshots/web/web-search-round/ui.expected.md | 4 + snapshots/web/workflow-run/ui.expected.md | 4 + 149 files changed, 4445 insertions(+), 299 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.md create mode 100644 .agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.zh.md create mode 100644 packages/client/ui-chat/src/client/chat/SystemPromptRow.tsx create mode 100644 packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts create mode 100644 packages/client/ui-chat/tests/system-prompt-row.client.spec.tsx create mode 100644 packages/client/ui-conversation/tests/request-inspection.client.spec.ts create mode 100644 snapshots/session/agent-instructions/tool-schemas.expected.json create mode 100644 snapshots/session/compaction-recovery/system-prompt.expected.md create mode 100644 snapshots/session/compaction-recovery/tool-schemas.expected.json diff --git a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.i18n.yaml index 23c4ea4142..a9d00bc3b9 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md -2026-07-05-reconstructable-requests.md: 3f49ba71a6b98a84b05530c900e902b0cf9f6449 -2026-07-05-reconstructable-requests.zh.md: 7b8a9df65b60f975bc3ae60b2c1b0c3a8cc22e95 +2026-07-05-reconstructable-requests.md: 3786de02d06c0b6c094297ae89ac3f84053e408d +2026-07-05-reconstructable-requests.zh.md: 851045aca7dababd0da859f3b04b721c65382fc3 diff --git a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md index 3f49ba71a6..3786de02d0 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md @@ -22,9 +22,9 @@ Prefix-cache stability is corollary #1, not the headline: an append-only log pro **Messages.** `Session.deriveMessages()` is cached: each surface entry is projected exactly once, when first seen, through the public per-event function `deriveEventMessage(event)`; a surface rewrite (a compaction `replace` — `SurfaceManager.replaceGeneration`) rebuilds. Callers get a fresh array per call over shared, deep-frozen messages: mutating logged history through a projection is unrepresentable (it throws), replacing the old clone-per-call isolation. External reconstructors fold the same public function over a log prefix, so no two paths can disagree. -`EpochHeader` records the request's non-history state: call config, rendered system prompt, and tool schemas, with empty values canonicalized to absence. `request/header` always writes a full snapshot: the first loop instance uses reason `initial`, later instances use `resume`, and an in-instance change uses `change`. `foldRequestHeader` selects the latest snapshot. Legacy `request/header-delta` events and the removed `fallback` reason are rejected when appended or loaded. +`EpochHeader` records the request's non-history state: call config, rendered system prompt, and tool schemas, with empty values canonicalized to absence. Adapter-supplied effort and token defaults retain their `adapterDefaults` provenance; a Web model selection restored from the log omits an adapter-owned effort so the next resolution cannot reclassify the same effective config as an explicit selection and a false change. `request/header` always writes a full snapshot: the first loop instance uses reason `initial`, later instances use `resume`, an in-instance change uses `change`, and an unchanged envelope beginning an explicitly declared message series or following a surface replacement uses `series`. A `change` snapshot carries `startsSeries: true` when the changed request also starts a series, preserving the two independent facts without a duplicate header. Ordinary append-only later Turns, further same-series Steps, and retries inherit the latest snapshot. `foldRequestHeader` selects the latest snapshot. Legacy `request/header-delta` events and the removed `fallback` reason are rejected when appended or loaded. -Each proposed step first claims its inbox batch and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start` and records the final message batch as `user/message` events. The step then assembles the system prompt and tools, while `agent/request` may replace only the frozen call-config seed. The loop records the owed full header snapshot, builds `GenerateOptions` from derived messages and that header, and deep-freezes it while leaving `AbortSignal` live. The first call config starts from explicit `AgentOptions`, preserving fork overrides and resume reconfiguration; later calls start from the folded header. +Each proposed step first claims its inbox batch and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. The step then assembles the system prompt and tools, while `agent/request` may replace only the frozen call-config seed. The loop records the owed initial, resume, change, or series full snapshot, builds `GenerateOptions` from derived messages and that header, and deep-freezes it while leaving `AbortSignal` live. The first call config starts from explicit `AgentOptions`, preserving fork overrides and resume reconfiguration; later calls start from the folded header. **The open step is the reconstruction boundary.** Its entered `user/message` batch and any newly written `request/header` precede request dispatch. Injection after the atomic claim joins a later request, while a listener that must affect this request returns messages through `agent/pre-step`. Header reconstruction selects the step's `request/header`, or carries the prior snapshot when no new header is written. @@ -42,6 +42,7 @@ Like MiniCode, the conversation advances append-only and resets only when model- - **Detect-and-report** (compare consecutive requests, warn on divergence): catches violations after the fact; a violating request is still constructible and ships. Rejected for interface-level unrepresentability. - **Event-driven assembly** (re-render only on change signals): a missed-signal bug class — a tool registered mid-session emits `tools/change`, not `system-prompt/change`, and a third-party provider may emit nothing. Per-step render + value compare is robust with zero signal discipline. - **A custom header-delta codec** (system line edits, name-keyed tool edits, whole config/prefix replacements): reduced repeated bytes but duplicated the representation and its diff/apply/fallback machinery. Full snapshots retain one replay representation. +- **A lightweight series marker referencing the previous header**: reduced repeated prompt and tool bytes, but a window beginning at that marker could not render or reconstruct the request without fetching its predecessor. A self-contained full snapshot preserves one representation for persistence, partial history, and snapshot pinning. - **Narrative changed-field lists on header snapshots**: derivable by comparing consecutive snapshots. The `reason` remains because an instance boundary is not derivable from the snapshot values. ## Consequences @@ -52,5 +53,5 @@ Like MiniCode, the conversation advances append-only and resets only when model- - `agent/pre-step` is the current-request message channel; direct inbox mutation is the eventual later-request channel. - Tool-result trimming needs no new mechanism: a logged single-entry surface replace (`start === end`) carrying a trimmed `tool/result` under the same `callId` — compaction-family, replay-correct, cache-bust batched by the same pressure logic. - Unreadable referenced attachment objects still fail model requests; [automatic attachment quarantine](../../proposed/bug-fix/2026-08-20-attachment-read-quarantine.md) records the proposed recovery without weakening byte-exact reconstruction. -- Session logs grow one `request/header` snapshot per loop instance plus snapshots on real changes. This is larger than a delta codec but small beside chunk-heavy logs and retains one replay representation. `SESSION_FORMAT_VERSION` stays `0`; legacy delta events are rejected rather than migrated. -- Snapshot expected outputs changed once (every transcript gains its header events); the fs-writing fixtures are stored in the normalized authored form with cwd-relative tool arguments, because replay only round-trips cwd-independent argument paths. +- Session logs grow one `request/header` snapshot per loop instance, real change, and later model-message series. Repeating the full system prompt and tool catalog is larger than a delta codec but small beside chunk-heavy logs and retains one self-contained replay representation. `SESSION_FORMAT_VERSION` stays `0`; legacy delta events are rejected rather than migrated. +- Snapshot fixtures include each repeated series header. Keyless refresh owns those deterministic log changes, while the snapshot harness pins prompt and tool sidecars only for the initial and actual change revisions and reuses the current revision for `series` snapshots. Filesystem-writing fixtures remain in normalized authored form with cwd-relative tool arguments because replay only round-trips cwd-independent argument paths. diff --git a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md index 7b8a9df65b..851045aca7 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md @@ -22,9 +22,9 @@ Status: implemented **消息。** `Session.deriveMessages()` 带缓存:每个 surface 条目在首次出现时通过公开的逐事件函数 `deriveEventMessage(event)` 精确投影一次;surface 重写(压缩的 `replace`,即 `SurfaceManager.replaceGeneration`)触发重建。调用方每次获得一个新数组,底层是共享的深度冻结消息:通过投影变异已记录的历史是不可表达的(会抛异常),取代了旧的逐次调用克隆隔离。外部重建器对日志前缀折叠同一个公开函数,因此不可能有两条路径产生分歧。 -`EpochHeader` 记录请求的非历史状态:调用配置、渲染后的系统提示词和工具 schema,空值规范化为缺失。`request/header` 始终写入完整快照:首个循环实例使用 reason `initial`,后续实例使用 `resume`,实例内变更使用 `change`。`foldRequestHeader` 选择最新快照。旧的 `request/header-delta` 事件和已移除的 `fallback` reason 在追加或加载时都会被拒绝。 +`EpochHeader` 记录请求的非历史状态:调用配置、渲染后的系统提示词和工具 schema,空值规范化为缺失。适配器提供的推理强度与 token 默认值会保留其 `adapterDefaults` 来源信息;Web 从日志恢复模型选择时会省略适配器持有的推理强度,因此下一次解析不会把相同的有效配置重新归类为显式选择并产生虚假变更。`request/header` 始终写入完整快照:首个循环实例使用 reason `initial`,后续实例使用 `resume`,实例内变更使用 `change`,内容未变的封装显式开启消息序列或跟随表层替换时使用 `series`。如果发生变化的请求同时开启序列,`change` 快照会携带 `startsSeries: true`,无需重复 header 即可保留这两个独立事实。普通的仅追加后续 Turn、同一序列内后续的 Step 与重试沿用最新快照。`foldRequestHeader` 选择最新快照。旧的 `request/header-delta` 事件和已移除的 `fallback` reason 在追加或加载时都会被拒绝。 -每个拟议步骤先领取其 inbox 批次,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,并把最终消息批次记录为 `user/message` 事件。随后步骤组装系统提示词与工具,`agent/request` 只能替换冻结的调用配置种子。循环记录所需的完整 header 快照,从派生消息与该 header 构建 `GenerateOptions`,对其深度冻结但保持 `AbortSignal` 活跃。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 +每个拟议步骤先领取其 inbox 批次,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。随后步骤组装系统提示词与工具,`agent/request` 只能替换冻结的调用配置种子。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息与该 header 构建 `GenerateOptions`,对其深度冻结但保持 `AbortSignal` 活跃。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 **已打开步骤是重建边界。** 进入步骤的 `user/message` 批次与任何新写入的 `request/header` 都位于请求分派之前。原子领取后发生的注入加入后续请求;必须影响本次请求的监听器则通过 `agent/pre-step` 返回消息。header 重建选择该步骤的 `request/header`,或在无新 header 写入时沿用前一个快照。 @@ -42,6 +42,7 @@ Status: implemented - **检测并报告**(比较连续请求,发散时告警):事后捕获违规;违规请求仍可构造并发出。因违规必须在接口层面不可表达而否决。 - **事件驱动组装**(仅在变更信号时重新渲染):存在漏信号的 bug 类别——会话中途注册的工具发出 `tools/change` 而非 `system-prompt/change`,第三方提供方可能什么都不发。逐步骤渲染加值比较在零信号纪律下即可稳健工作。 - **自定义 header-delta 编解码器**(系统行编辑、按名称键控的工具编辑、完整配置/前缀替换):减少了重复字节,却复制了表示及其 diff/apply/fallback 机制。完整快照只保留一种回放表示。 +- **引用前一个 header 的轻量 series 标记**:减少重复的提示词与工具字节,但从该标记开始的窗口若不再读取前序,就无法渲染或重建请求。自包含的完整快照让持久化、局部历史和快照固定共用一种表示。 - **Header 快照上的叙事性变更字段列表**:可以通过比较连续快照推导。`reason` 仍保留,因为实例边界无法从快照值推导。 ## 后果 @@ -52,5 +53,5 @@ Status: implemented - `agent/pre-step` 是当前请求的消息通道;直接修改 inbox 则是最终进入后续请求的通道。 - 工具结果裁剪无需新机制:一个已记录的单条目 surface replace(`start === end`),携带同一 `callId` 下裁剪后的 `tool/result`——属压缩家族,回放正确,缓存失效由相同的压力逻辑批量处理。 - 无法读取的被引用附件对象仍会让模型请求失败;[附件自动隔离](../../proposed/bug-fix/2026-08-20-attachment-read-quarantine.zh.md)记录了不削弱字节精确重建的拟议恢复方案。 -- 会话日志每个循环实例增长一个 `request/header` 快照,并在真正变更时增加快照。它比 delta 编解码器更大,但相对分片密集型日志仍然很小,并只保留一种回放表示。`SESSION_FORMAT_VERSION` 保持 `0`;旧的 delta 事件被拒绝而非迁移。 -- 快照预期输出变更一次(每个 transcript(文本记录)增加其 header 事件);写入文件系统的 fixture(测试前置数据)以规范化的撰写形式存储,工具参数使用 cwd 相对路径,因为回放只对 cwd 无关的参数路径做往返。 +- 会话日志会为每个循环实例、真实变更和后续模型消息序列增加一个 `request/header` 快照。重复完整系统提示词与工具目录比 delta 编解码器更大,但相对分片密集型日志仍然很小,并保留一种自包含的回放表示。`SESSION_FORMAT_VERSION` 保持 `0`;旧的 delta 事件被拒绝而非迁移。 +- 快照 fixture 包含每个重复的 series header。无密钥 refresh 负责这些确定性日志变化;快照 harness 只为 initial 与真实 change 修订固定提示词和工具 sidecar,并让 `series` 快照复用当前修订。写入文件系统的 fixture 继续以规范化的撰写形式存储,工具参数使用 cwd 相对路径,因为回放只对 cwd 无关的参数路径做往返。 \ No newline at end of file diff --git a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.i18n.yaml index e7aa813ad5..eea93dc866 100644 --- a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md -2026-08-09-client-conversation-node-assembly.md: e6c0e790a361265870a04ee63301b9f11940c648 -2026-08-09-client-conversation-node-assembly.zh.md: 702ddba0019e125d3976727f841db775276b3b77 +2026-08-09-client-conversation-node-assembly.md: ea2505d4a72f483a9df6fcd78d7e5c9a96b02f5c +2026-08-09-client-conversation-node-assembly.zh.md: b87f127d753cadf2805ed5cd948fc58ad01830aa diff --git a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md index e6c0e790a3..ea2505d4a7 100644 --- a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md +++ b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md @@ -260,6 +260,7 @@ Page size, the number of history loads, and RAF coalescing affect only when evid | Next-turn Inbox / `inbox-next-turn` | Splice Event seq | Each `agent/inbox/spliced` targeting next-turn | None | Apply the current splice to the pending/claimed instantaneous state from `reader.previous(ownKind)` | | Next-step Inbox / `inbox-next-step` | Splice Event seq | Each `agent/inbox/spliced` targeting next-step | None | Build the same per-instruction instantaneous state; Message reads its claimed set | | Message / `input-message` | Message ID | Append-surface `user/message` | None | Use source for a context message, or read the nearest next-step Inbox to distinguish user from steering | +| Request Prompt / `request-prompt` | Header Event seq | Each `request/header` | None | Read the preceding Request Prompt through Reader, retain the full prompt state, and classify system/tool changes | | Assistant / `assistant-step` | `turn:step` | `step/start` | `assistant/chunk`, final `assistant/message`, and same-step Retry | Aggregate blocks, usage, first-token time, final evidence, and retry-hidden state, then publish same-key Step data | | Tool / `tool-call` | Root call ID | Root `tool/call` | Root result and Code Dispatch start/result | Aggregate the root, children, and parent Map; Dispatch Events route exactly through `rootCallId` | | Command / `command` | Command ID | `command/run` | `command/done` and compact lifecycle/checkpoint Events carrying a source command ID | Aggregate command outcome and manual-compaction evidence | @@ -276,6 +277,7 @@ Page size, the number of history loads, and RAF coalescing affect only when evid |---|---|---|---| | Inbox | `none` | No Node | Recompute instantaneous states along the Reader chain when prepend supplies earlier splices | | Message | Immediate by default | `user`, `steering`, or `context` | Window-gap repair can reclassify the same message key | +| Request Prompt | Immediate by default | One `system-prompt` for every header carrying a non-empty system field | A step's first header anchors before its request messages; a later same-step series anchors after its surface rewrite; prepend of the preceding header can correct a partial-window anchor | | Assistant | RAF for chunks, immediate for final, none for pure usage/finish | Same-key `assistant-step` with running/settled/interrupted status | Matches support fallback without `step/start`; Location close produces interruption presentation | | Tool | Immediate by default | One recursive `tool-call` root containing all `subCalls` | A result-only history window supports fallback; running→settled retains its key | | Command | Immediate by default | Ordinary `command` or integrated `manual-compaction` | Checkpoint arrival may change the anchor without changing the Context key | @@ -288,6 +290,8 @@ Page size, the number of history loads, and RAF coalescing affect only when evid Inbox demonstrates that every Event can be a start-only instantaneous-state Context; not every business requires a start/update pair. Reader links each state to the prior same-kind Context instead of inventing a lifecycle ID for the entire Inbox. +Request Prompt demonstrates shared pure interpretation without shared target State: Chat and Trajectory call `inspectRequestPrompt()` from their own Definitions. The function canonicalizes the full header and classifies model-visible system/tool differences; each target then chooses its own output. Chat materializes every header carrying a non-empty system field, including `series` snapshots that repeat an unchanged header for an explicitly declared series or a post-replacement request, while Trajectory retains the complete request fact and its change classification. Ordinary append-only later Turns do not write another unchanged header. The first header in a Step follows the provider envelope rather than the header Event position: step one uses the owning Turn start and later steps use their Step start, placing the system field before the request's user-role messages; a later header in the same Step stays at its own Event after the surface rewrite that began the new series. When the preceding header is outside a partial window, a non-`initial` header stays at its own Event until prepend supplies that predecessor. Every header is a full snapshot, so a first loaded `resume`, `change`, or `series` header can render its system field without fabricating a comparison to unloaded history. + Retry, Assistant, and Turn Tail demonstrate independent claims on one Event. Each Definition updates only its own State and produces its own atomic Chat Node. Assistant, Turn Tail, and Deliverables demonstrate layered Location data composition. Assistant writes `assistant-step` data for each Step; Turn Tail derives `turn-tail` data from those Step values; Deliverables independently maintains `deliverables` data for the same Turn. Consumers read only declaration-merged keys, do not scan another business's Nodes, and cannot obtain the provider's Context State. diff --git a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.zh.md b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.zh.md index 702ddba001..b87f127d75 100644 --- a/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.zh.md @@ -260,6 +260,7 @@ Chat `order` 的结构性变化仍可能重排当前可见 key;纯 data 更新 | Next-turn Inbox / `inbox-next-turn` | splice Event seq | 每条目标为 next-turn 的 `agent/inbox/spliced` | 无 | 从 `reader.previous(ownKind)` 的 pending/claimed 瞬间态应用当前 splice | | Next-step Inbox / `inbox-next-step` | splice Event seq | 每条目标为 next-step 的 `agent/inbox/spliced` | 无 | 同样形成逐指令瞬间态,claimed 集合供 Message 读取 | | Message / `input-message` | message ID | append-surface `user/message` | 无 | 根据 source 生成 context message,或读取最近 next-step Inbox 判断 user/steering | +| Request Prompt / `request-prompt` | header Event seq | 每条 `request/header` | 无 | 通过 Reader 读取前一条 Request Prompt,保留完整 prompt 状态,并判定 system/tool 变化 | | Assistant / `assistant-step` | `turn:step` | `step/start` | `assistant/chunk`、final `assistant/message`、同 step Retry | 聚合 blocks、usage、首 token 时间、final 和 retry 隐藏状态,并发布同 key Step data | | Tool / `tool-call` | root call ID | root `tool/call` | root result、Code Dispatch start/result | 聚合 root、children 和 parent Map;Dispatch Event 用 `rootCallId` 精确路由 | | Command / `command` | command ID | `command/run` | `command/done`、带 source command ID 的 compact lifecycle/checkpoint | 聚合 command outcome 和手动压缩证据 | @@ -276,6 +277,7 @@ Chat `order` 的结构性变化仍可能重排当前可见 key;纯 data 更新 |---|---|---|---| | Inbox | `none` | 不生成 Node | prepend 补前序 splice 时沿 Reader 链重算瞬间态 | | Message | 默认 immediate | `user`、`steering` 或 `context` | window gap 修复可让同一 message key 重新分类 | +| Request Prompt | 默认 immediate | 每条带非空 system 字段的 header 都生成一个 `system-prompt` | Step 首条 header 锚定在请求消息之前;同 step 后续序列锚定在表层改写之后;prepend 补入前序 header 后可纠正部分窗口的锚点 | | Assistant | chunk 为 RAF,final immediate,纯 usage/finish 为 none | 同 key `assistant-step`,状态为 running/settled/interrupted | 缺 `step/start` 可先用 Matches fallback;Location close 生成中断表现 | | Tool | 默认 immediate | 一个递归 `tool-call` root,包含全部 `subCalls` | result-only 历史窗口可 fallback;running→settled 保持 key | | Command | 默认 immediate | 普通 `command` 或集成 `manual-compaction` | checkpoint 到达可改变 anchor,但不改变 Context key | @@ -288,6 +290,8 @@ Chat `order` 的结构性变化仍可能重排当前可见 key;纯 data 更新 Inbox 展示了“每条 Event 都是一个 start-only 瞬间态 Context”,不是所有业务都需要 start/update 配对。它通过 Reader 与前一个同 kind Context 形成连续 fold,而非给整个 Inbox 人工制造生命周期 ID。 +Request Prompt 展示了如何在不共享 target State 的前提下共用纯解释逻辑:Chat 与 Trajectory 各自在自己的 Definition 中调用 `inspectRequestPrompt()`。该函数规范化完整 header,并判定面向模型的 system/tool 差异;随后每个 target 自行选择产物。Chat 会物化每条带非空 system 字段的 header,包括为显式声明的序列或表层替换后的请求重复未变 header 的 `series` 快照;Trajectory 则保留完整请求事实及其变化分类。普通的仅追加后续 Turn 不会再次写入未变 header。一个 Step 中的首条 header 遵循提供方信封,而不是 header Event 位置:step one 使用所属 Turn start,后续 step 使用各自的 Step start,把 system 字段放到该请求的 user-role 消息之前;同一 Step 的后续 header 保留在开启新序列的表层改写之后。部分窗口未包含前序 header 时,非 `initial` header 会保留在自身 Event,直到 prepend 补入该前序 header。每条 header 都是完整快照,因此已加载窗口中的首条 `resume`、`change` 或 `series` header 无需凭空构造与未加载历史的比较,也能渲染其 system 字段。 + Retry、Assistant 和 Turn Tail 展示了同一 Event 被多个 Definition 独立认领。每个 Definition 只更新自己的 State,最终分别生成原子 Chat Node。 Assistant、Turn Tail 和 Deliverables 展示了 Location data 的分层组合。Assistant 负责写好每个 Step 的 `assistant-step` data;Turn Tail 从这些 Step values 计算 `turn-tail` data;Deliverables 独立维护同一 Turn 的 `deliverables` data。消费者只读取声明合并后的 key,不扫描其他业务 Node,也不取得提供方的 Context State。 diff --git a/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.i18n.yaml b/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.i18n.yaml new file mode 100644 index 0000000000..3af8585b6e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.md +2026-08-17-web-system-prompt-opaque-body.md: 9b1992dd8eb1062a3b35666b332178985aa91653 +2026-08-17-web-system-prompt-opaque-body.zh.md: 6f2fbba9d3f286e8c3073197a144d347f732cbc1 diff --git a/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.md b/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.md new file mode 100644 index 0000000000..9b1992dd8e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.md @@ -0,0 +1,29 @@ +# Agent Note: System prompt expands into the opaque context body + +Status: implemented + +English | [中文](2026-08-17-web-system-prompt-opaque-body.zh.md) + +## Problem + +The Chat `System prompt` row shares `DisclosureRow` chrome with context injection and needs an expanded body for the request's system field. Rendering that field as Markdown would restyle it — headings, emphasis, lists — so a reader would see a rendered document the model never received. Context injection already solves the same job with a 141px code-block scrollport and `
` text that keeps the bytes and line breaks the model read, so the row needs that presentation, not a second one.
+
+## Decision
+
+`SystemPromptRow` mounts the same expanded body as an opaque context injection. It reuses `ContextInjectionRow.module.css` for the 141px Figma 10:2482 scrollport and renders the durable `request/header` system string through `OpaqueBody` as one text block, so the disclosure shows model-facing text with its real line breaks and the same 20_000-character display bound. The row stays collapsed by default and still has no streaming path. It does not grow a producer label, form marker, or source-field list: the system field is one joined string on the header, not a sourced `user/message`.
+
+## Alternatives considered
+
+**Render settled Markdown in a card-styled body.** The chrome could match, but Markdown rewrites what the model read. A heading or bold span is a different document from the request bytes.
+
+**Split the joined system string into snapshot sections.** The durable header stores only the assembled text. Inventing section boundaries in the client would attribute prose the log does not name, and a resumed or foreign header could not reconstruct them.
+
+**Render through `ContextInjectionRow` itself.** That row is for sourced user-role messages: it titles a role, shows a producer, and chooses a form body. The system field is a different durable fact and has none of those fields.
+
+## Consequences
+
+The two disclosures now share one expanded-body chrome and one text presentation, so a later change to the 141px scrollport or the opaque bound applies to both. The cost is that a long system prompt scrolls inside 141px instead of 360px, and Markdown markup in the prompt stays visible as characters.
+
+## Testing
+
+`packages/client/ui-chat/tests/system-prompt-row.client.spec.tsx` expands and collapses the row and pins the opaque `[data-context-text]` bytes, including Markdown markers that must not become a heading. `apps/web/tests/replay-round-trip.e2e.ts` still opens the assembled disclosure and reads the persona line from that body.
diff --git a/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.zh.md b/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.zh.md
new file mode 100644
index 0000000000..6f2fbba9d3
--- /dev/null
+++ b/.agents/notes/implemented/feature/2026-08-17-web-system-prompt-opaque-body.zh.md
@@ -0,0 +1,29 @@
+# Agent Note: System prompt expands into the opaque context body
+
+Status: implemented
+
+[English](2026-08-17-web-system-prompt-opaque-body.md) | 中文
+
+## Problem
+
+Chat 的 `系统提示词` 行和上下文注入共用 `DisclosureRow` 外壳,其展开内容区需要呈现请求的 system 字段。如果把该字段渲染成 Markdown——标题、强调、列表——读者看到的将是模型从未收到的排版文档。上下文注入已经用 141px 代码块滚动区和保留模型所见字节与换行的 `
` 文本解决了同一件事,因此该行需要复用这一呈现,而不是再造一套。
+
+## Decision
+
+`SystemPromptRow` 展开后挂载与不透明上下文注入相同的内容区。它复用 `ContextInjectionRow.module.css` 的 Figma 10:2482 的 141px 滚动区,并把持久 `request/header` 的 system 字符串作为一块文本交给 `OpaqueBody`,因此展开后看到的是带真实换行的模型可见文本,以及相同的 20_000 字符显示上限。该行默认折叠,仍然没有流式路径。它不增加生产者标签、form 标记或 source 字段列表:system 字段是 header 上的一段拼接字符串,不是带 source 的 `user/message`。
+
+## Alternatives considered
+
+**在卡片式内容区里渲染结算后的 Markdown。** 外壳可以对齐,但 Markdown 会改写模型读到的内容。标题或加粗是另一份文档,不是请求里的字节。
+
+**把拼接后的 system 字符串拆成 snapshot 分段。** 持久 header 只保存组装后的文本。客户端臆造分段边界会把日志未命名的正文归到某个子系统,恢复或外来 header 也无法重建这些分段。
+
+**直接走 `ContextInjectionRow`。** 那一行面向带 source 的 user-role 消息:它标角色、显示生产者,并按 form 选内容区。system 字段是另一件持久事实,没有这些字段。
+
+## Consequences
+
+两处展开现在共用同一套内容区外壳和同一套文本展示,因此之后改 141px 滚动区或不透明显示上限会同时作用到两边。代价是较长的系统提示词在 141px 而不是 360px 内滚动,提示词里的 Markdown 标记会以字符形式可见。
+
+## Testing
+
+`packages/client/ui-chat/tests/system-prompt-row.client.spec.tsx` 会展开并折叠该行,并钉住不透明 `[data-context-text]` 字节,包括不得变成标题的 Markdown 标记。`apps/web/tests/replay-round-trip.e2e.ts` 仍会打开组装后的展开行,并从该内容区读出 persona 行。
diff --git a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.i18n.yaml
index 48800b1c08..68511a8efe 100644
--- a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.i18n.yaml
+++ b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md
-2026-07-12-simplify-session-log-representation.md: 3efb531d3c0822d7444d1270eac4da2617c12447
-2026-07-12-simplify-session-log-representation.zh.md: 8c05ac6512a8aa8e7fefc56ba410bc81dc3be277
+2026-07-12-simplify-session-log-representation.md: a0c86b66af78b4c94991d38656f03609297e2314
+2026-07-12-simplify-session-log-representation.zh.md: ceaf90236a47c141e3a4bb2cc78d415b3b9ac2ba
diff --git a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md
index 3efb531d3c..a0c86b66af 100644
--- a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md
+++ b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.md
@@ -18,7 +18,7 @@ The implementation retains append and replacement `sourceEventSeqs`, the `tool/c
 
 `SurfaceManager.nodes` is a `readonly number[]` of event sequences; the public `SurfaceNode` shape, node links, and seq-to-node map are removed. The internal replace-generation signal remains. The complete `foldSurface()` read used by session-query returns the same number-array representation plus replacement metadata without making the incremental manager retain history. Tool-pairing balance and compaction use event sequences and surface positions; the compact-owned per-cut balance cache does not depend on node links.
 
-Request headers use canonical full snapshots only. Initial and resume anchors remain full snapshots even when unchanged; an in-instance change appends another full `request/header` with reason `change`. The delta event, codec types, diff/apply helpers, and codec-only `fallback` reason are removed. Request reconstruction selects the latest snapshot.
+Request headers use canonical full snapshots only. Initial and resume anchors remain full snapshots even when unchanged; an in-instance change appends another full `request/header` with reason `change`; and an unchanged envelope beginning an explicitly declared message series or following a surface replacement appends a full snapshot with reason `series`. Ordinary append-only later Turns, further Steps, and retries in that model-message series inherit the latest snapshot. The delta event, codec types, diff/apply helpers, and codec-only `fallback` reason are removed. Request reconstruction selects the latest snapshot.
 
 `SESSION_FORMAT_VERSION` remains pinned at `0`, so seed, append, and persistence-load validation explicitly reject old v0 `request/header-delta` events and full snapshots carrying the removed `fallback` reason. There is no compatibility fold or migration. JSONL and SQLite tests pin this fail-loud boundary, and the ACP snapshot harness represents legitimate mid-session changes as full pinned headers and full readable prompts.
 
diff --git a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.zh.md b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.zh.md
index 8c05ac6512..ceaf90236a 100644
--- a/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.zh.md
+++ b/.agents/notes/implemented/simplification/2026-07-12-simplify-session-log-representation.zh.md
@@ -18,7 +18,7 @@ Status: implemented
 
 `SurfaceManager.nodes` 是由事件序号组成的 `readonly number[]`;公共 `SurfaceNode` 形状、node 链接和 seq-to-node map 均已移除。内部替换 generation 信号保留。session-query 使用的完整 `foldSurface()` 读取会返回相同的数字数组表示和替换元数据,而无需让增量 manager 保留历史。工具配对 balance 和压缩(compaction)使用事件序号与 surface 位置;由 compact 拥有的每个切点的 balance cache 不依赖 node 链接。
 
-请求头只使用规范的完整快照。初始与恢复锚点即使没有变化也仍是完整快照;实例内变化会追加另一个完整 `request/header`,reason 为 `change`。delta 事件、codec 类型、diff/apply 辅助函数,以及仅供 codec 使用的 `fallback` reason 均已移除。请求重建选择最新快照。
+请求头只使用规范的完整快照。初始与恢复锚点即使没有变化也仍是完整快照;实例内变化会追加另一个完整 `request/header`,reason 为 `change`;未变的信封显式开启消息序列或跟随 surface 替换时,会追加 reason 为 `series` 的完整快照。普通的仅追加后续 Turn、同一模型消息序列内的后续 Step 与重试沿用最新快照。delta 事件、codec 类型、diff/apply 辅助函数,以及仅供 codec 使用的 `fallback` reason 均已移除。请求重建选择最新快照。
 
 `SESSION_FORMAT_VERSION` 仍固定为 `0`,因此 seed、追加和持久化加载验证会显式拒绝旧 v0 `request/header-delta` 事件,以及携带已删除 `fallback` reason 的完整快照。不存在兼容性 fold 或迁移。JSONL 与 SQLite 测试固定了这一失败即报错的边界;ACP(Agent Client Protocol)快照 harness 则把合法的会话中途变更表示为固定的完整请求头和完整可读提示词。
 
diff --git a/apps/cli/tests/profiles/acp/tests/goal-expected/goal-round-driver/session.expected.jsonl b/apps/cli/tests/profiles/acp/tests/goal-expected/goal-round-driver/session.expected.jsonl
index 3804ea77b3..390b157a76 100644
--- a/apps/cli/tests/profiles/acp/tests/goal-expected/goal-round-driver/session.expected.jsonl
+++ b/apps/cli/tests/profiles/acp/tests/goal-expected/goal-round-driver/session.expected.jsonl
@@ -45,12 +45,13 @@
 {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
 {"type":"step/start","data":{"turn":2,"step":1}}
 {"type":"user/message","data":{"content":[{"type":"text","text":"\nObjective: \"Finish the ACP goal-round-driver snapshot proof\"\nRound: 1/2\n\nContinue working toward the objective in this same session. Treat the current workspace, tool results, and durable session state as authoritative; inspect them instead of assuming earlier narration is still current. Make concrete progress and verify the result. Before claiming completion, gather evidence that the whole objective is achieved, read the current goal, and mark it complete. If work remains, leave the goal active for the next round. Follow the configured goal-tool policy before reporting a blocker.\n"}],"source":{"kind":"goal","goalId":"goal-{{sessionId}}","revision":1,"round":1},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
+{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"series"}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"text-delta","index":0,"text":"GOAL ROUND ONE"}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"GOAL ROUND ONE"}}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":40,"outputTokens":3}}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
-{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"GOAL ROUND ONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":40,"outputTokens":3}},"sourceEventSeqs":[46,47,48,49,50],"surfaceOp":"append"}
+{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"GOAL ROUND ONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":40,"outputTokens":3}},"sourceEventSeqs":[47,48,49,50,51],"surfaceOp":"append"}
 {"type":"step/end","data":{"turn":2,"step":1}}
 {"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}}
 {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"\nObjective: \"Finish the ACP goal-round-driver snapshot proof\"\nRound: 2/2\n\nContinue working toward the objective in this same session. Treat the current workspace, tool results, and durable session state as authoritative; inspect them instead of assuming earlier narration is still current. Make concrete progress and verify the result. Before claiming completion, gather evidence that the whole objective is achieved, read the current goal, and mark it complete. If work remains, leave the goal active for the next round. Follow the configured goal-tool policy before reporting a blocker.\n"}],"source":{"kind":"goal","goalId":"goal-{{sessionId}}","revision":1,"round":2},"role":"user","id":"{{sessionId}}"}]}}
@@ -58,9 +59,10 @@
 {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
 {"type":"step/start","data":{"turn":3,"step":1}}
 {"type":"user/message","data":{"content":[{"type":"text","text":"\nObjective: \"Finish the ACP goal-round-driver snapshot proof\"\nRound: 2/2\n\nContinue working toward the objective in this same session. Treat the current workspace, tool results, and durable session state as authoritative; inspect them instead of assuming earlier narration is still current. Make concrete progress and verify the result. Before claiming completion, gather evidence that the whole objective is achieved, read the current goal, and mark it complete. If work remains, leave the goal active for the next round. Follow the configured goal-tool policy before reporting a blocker.\n"}],"source":{"kind":"goal","goalId":"goal-{{sessionId}}","revision":1,"round":2},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
+{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"series"}}
 {"type":"assistant/chunk","data":{"turn":3,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
 {"type":"assistant/chunk","data":{"turn":3,"step":1,"chunk":{"type":"text-delta","index":0,"text":"partial"}}}
-{"type":"assistant/message","data":{"turn":3,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"partial"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"interrupted":true},"sourceEventSeqs":[59,60],"surfaceOp":"append"}
+{"type":"assistant/message","data":{"turn":3,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"partial"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"interrupted":true},"sourceEventSeqs":[61,62],"surfaceOp":"append"}
 {"type":"step/end","data":{"turn":3,"step":1}}
 {"type":"turn/end","data":{"turn":3,"reason":{"kind":"aborted","reason":{"kind":"user"}}}}
 {"type":"goal/change","data":{"kind":"goal/change","version":1,"operation":"pause","goal":{"id":"goal-{{sessionId}}","revision":2,"objective":"Finish the ACP goal-round-driver snapshot proof","phase":"paused","maxGoalRounds":2},"roundsStarted":2,"createdAt":0,"updatedAt":0}}
diff --git a/apps/cli/tests/profiles/acp/tests/goal-expected/goal-wrapup/session.expected.jsonl b/apps/cli/tests/profiles/acp/tests/goal-expected/goal-wrapup/session.expected.jsonl
index 71d23de033..b724c08ef5 100644
--- a/apps/cli/tests/profiles/acp/tests/goal-expected/goal-wrapup/session.expected.jsonl
+++ b/apps/cli/tests/profiles/acp/tests/goal-expected/goal-wrapup/session.expected.jsonl
@@ -35,15 +35,16 @@
 {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
 {"type":"step/start","data":{"turn":2,"step":1}}
 {"type":"user/message","data":{"content":[{"type":"text","text":"\nObjective: \"Finish the ACP goal wrap-up snapshot proof\"\nRound: 1/2\n\nContinue working toward the objective in this same session. Treat the current workspace, tool results, and durable session state as authoritative; inspect them instead of assuming earlier narration is still current. Make concrete progress and verify the result. Before claiming completion, gather evidence that the whole objective is achieved, read the current goal, and mark it complete. If work remains, leave the goal active for the next round. Follow the configured goal-tool policy before reporting a blocker.\n"}],"source":{"kind":"goal","goalId":"goal-{{sessionId}}","revision":1,"round":1},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
+{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"series"}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_goal_complete","name":"update_goal","argumentsDelta":"{\"goal_id\":\"goal-{{sessionId}}\",\"revision\":1,\"action\":\"complete\"}"}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_goal_complete","name":"update_goal","arguments":"{\"goal_id\":\"goal-{{sessionId}}\",\"revision\":1,\"action\":\"complete\"}"}}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":40,"outputTokens":9}}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
-{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_goal_complete","name":"update_goal","arguments":"{\"goal_id\":\"goal-{{sessionId}}\",\"revision\":1,\"action\":\"complete\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":40,"outputTokens":9}},"sourceEventSeqs":[36,37,38,39,40],"surfaceOp":"append"}
+{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_goal_complete","name":"update_goal","arguments":"{\"goal_id\":\"goal-{{sessionId}}\",\"revision\":1,\"action\":\"complete\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":40,"outputTokens":9}},"sourceEventSeqs":[37,38,39,40,41],"surfaceOp":"append"}
 {"type":"tool/call","data":{"turn":2,"step":1,"callId":"call_goal_complete","name":"update_goal","arguments":"{\"goal_id\":\"goal-{{sessionId}}\",\"revision\":1,\"action\":\"complete\"}"}}
 {"type":"goal/change","data":{"kind":"goal/change","version":1,"operation":"complete","goal":{"id":"goal-{{sessionId}}","revision":2,"objective":"Finish the ACP goal wrap-up snapshot proof","phase":"complete","maxGoalRounds":2},"roundsStarted":1,"createdAt":0,"updatedAt":0}}
-{"type":"tool/result","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool","callId":"call_goal_complete"},"content":[{"type":"tool-result","toolCallId":"call_goal_complete","content":[{"type":"text","text":"{\"goal\":{\"id\":\"goal-{{sessionId}}\",\"revision\":2,\"objective\":\"Finish the ACP goal wrap-up snapshot proof\",\"phase\":\"complete\",\"roundsStarted\":1,\"maxGoalRounds\":2},\"activation\":\"disarmed\"}"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[42],"surfaceOp":"append"}
+{"type":"tool/result","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool","callId":"call_goal_complete"},"content":[{"type":"tool-result","toolCallId":"call_goal_complete","content":[{"type":"text","text":"{\"goal\":{\"id\":\"goal-{{sessionId}}\",\"revision\":2,\"objective\":\"Finish the ACP goal wrap-up snapshot proof\",\"phase\":\"complete\",\"roundsStarted\":1,\"maxGoalRounds\":2},\"activation\":\"disarmed\"}"}],"isError":false}],"role":"user","id":"{{sessionId}}"}},"sourceEventSeqs":[43],"surfaceOp":"append"}
 {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nObjective: \"Finish the ACP goal wrap-up snapshot proof\"\nThe goal is marked complete and this autonomous run is ending. Write the closing message to the user now: state the outcome, summarize what was done and how it was verified, and point to the concrete results (files, commits, or other artifacts). Report only what earlier rounds and tool results in this session actually establish; when a detail is not in the session, say so instead of inventing it. Note anything the user should review or do next. Address the user directly. Do not call any more tools in this run; further work waits for the user's next instruction.\n"}],"source":{"kind":"plugin","plugin":"tool-goal","form":"notice","summary":"complete: Finish the ACP goal wrap-up snapshot proof"},"role":"user","id":"{{sessionId}}"}]}}
 {"type":"step/end","data":{"turn":2,"step":1}}
 {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}}
@@ -54,6 +55,6 @@
 {"type":"assistant/chunk","data":{"turn":2,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"GOAL WRAP-UP: the snapshot objective is achieved and this closing message reaches the user."}}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":52,"outputTokens":14}}}}
 {"type":"assistant/chunk","data":{"turn":2,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
-{"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"GOAL WRAP-UP: the snapshot objective is achieved and this closing message reaches the user."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":52,"outputTokens":14}},"sourceEventSeqs":[50,51,52,53,54],"surfaceOp":"append"}
+{"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"GOAL WRAP-UP: the snapshot objective is achieved and this closing message reaches the user."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":52,"outputTokens":14}},"sourceEventSeqs":[51,52,53,54,55],"surfaceOp":"append"}
 {"type":"step/end","data":{"turn":2,"step":2}}
 {"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}}
diff --git a/apps/web/tests/chat-continuous-conversation.e2e.ts b/apps/web/tests/chat-continuous-conversation.e2e.ts
index 8130e70308..e18af7c791 100644
--- a/apps/web/tests/chat-continuous-conversation.e2e.ts
+++ b/apps/web/tests/chat-continuous-conversation.e2e.ts
@@ -330,6 +330,11 @@ describe('web e2e: continuous conversation grown through the composer', () => {
     expect(scaffold.ctx.agents.get(sessionId)?.session.events.filter(event => (
       event.type === 'turn/end' && event.data.reason.kind === 'completed'
     ))).toHaveLength(TURN_COUNT)
+    expect(sessionEvents.flatMap(event =>
+      event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial'])
+    await expect.poll(() => page.getByRole('button', { name: 'System prompt' }).count(), {
+      timeout: 10_000,
+    }).toBe(1)
     expect(specs.at(-1)?.prompt.length).toBeGreaterThan(4_000)
     expect(sessionEvents.filter(event => (
       event.type === 'assistant/chunk' && event.data.turn === TURN_COUNT
diff --git a/apps/web/tests/expected/github-ready-review/conversation.expected.md b/apps/web/tests/expected/github-ready-review/conversation.expected.md
index 0f4902439c..738a1b11a3 100644
--- a/apps/web/tests/expected/github-ready-review/conversation.expected.md
+++ b/apps/web/tests/expected/github-ready-review/conversation.expected.md
@@ -20,6 +20,10 @@
   - tablist:
     - tab "Chat" [selected]
     - tab "Trajectory"
+- button "System prompt":
+  - img
+  - img
+  - text: System prompt
 - button "Context injection webhook github webhook handled by review-pr-when-ready":
   - img
   - img
diff --git a/apps/web/tests/expected/skill-user-invoke/ui.expected.md b/apps/web/tests/expected/skill-user-invoke/ui.expected.md
index 0aa6eeb091..b06b3aae82 100644
--- a/apps/web/tests/expected/skill-user-invoke/ui.expected.md
+++ b/apps/web/tests/expected/skill-user-invoke/ui.expected.md
@@ -9,6 +9,10 @@
   - tablist:
     - tab "Chat" [selected]
     - tab "Trajectory"
+- button "System prompt":
+  - img
+  - img
+  - text: System prompt
 - text: /user-invoke-demo and confirm the fixture wiring {{clock}}
 - button "Copy":
   - img
diff --git a/apps/web/tests/expected/steer-all/mid-steer.expected.md b/apps/web/tests/expected/steer-all/mid-steer.expected.md
index 7084523979..c201520e8d 100644
--- a/apps/web/tests/expected/steer-all/mid-steer.expected.md
+++ b/apps/web/tests/expected/steer-all/mid-steer.expected.md
@@ -9,6 +9,10 @@
   - tablist:
     - tab "Chat" [selected]
     - tab "Trajectory"
+- button "System prompt":
+  - img
+  - img
+  - text: System prompt
 - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}}
 - button "Copy":
   - img
diff --git a/apps/web/tests/expected/steer-all/settled.expected.md b/apps/web/tests/expected/steer-all/settled.expected.md
index 96da765b9b..885143a0f6 100644
--- a/apps/web/tests/expected/steer-all/settled.expected.md
+++ b/apps/web/tests/expected/steer-all/settled.expected.md
@@ -9,6 +9,10 @@
   - tablist:
     - tab "Chat" [selected]
     - tab "Trajectory"
+- button "System prompt":
+  - img
+  - img
+  - text: System prompt
 - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}}
 - button "Copy":
   - img
diff --git a/apps/web/tests/goal-multi-turn-actions.e2e.ts b/apps/web/tests/goal-multi-turn-actions.e2e.ts
index 346593529b..54af9f2da9 100644
--- a/apps/web/tests/goal-multi-turn-actions.e2e.ts
+++ b/apps/web/tests/goal-multi-turn-actions.e2e.ts
@@ -151,6 +151,11 @@ describe('web e2e: Goal keeps one assistant action row per completed turn', () =
     expect(sessionEvents.flatMap(event => event.type === 'turn/end' ? [event.data.turn] : []))
       .toEqual([1, 2])
     expect(goalRounds(sessionEvents)).toEqual([1, 2])
+    expect(sessionEvents.flatMap(event =>
+      event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial', 'series'])
+    await expect.poll(() => page.getByRole('button', { name: 'System prompt' }).count(), {
+      timeout: 15_000,
+    }).toBe(2)
     const branchButtons = page.getByRole('button', { name: 'Branch into a new conversation' })
     await expect.poll(() => branchButtons.count(), { timeout: 15_000 }).toBe(2)
     expect(await branchButtons.evaluateAll(buttons => buttons.map(button => button.getAttribute('aria-disabled'))))
diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts
index 30644607f5..6325e202b2 100644
--- a/apps/web/tests/replay-round-trip.e2e.ts
+++ b/apps/web/tests/replay-round-trip.e2e.ts
@@ -150,6 +150,25 @@ describe('web e2e: fresh round trip through the real assembly', () => {
     await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
   })
 
+  it.skipIf(MODE === 'record')('renders the system prompt as a collapsed expandable disclosure', async () => {
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-system-prompt'))
+    const disclosure = page.getByRole('button', { name: 'System prompt', exact: true })
+    const body = page.locator('[data-system-prompt-body]')
+    await expect.poll(() => disclosure.count(), { timeout: 10_000 }).toBe(1)
+    await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('false')
+    expect(await body.count()).toBe(0)
+
+    await disclosure.click()
+    await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('true')
+    const opaque = body.locator('[data-context-text]')
+    await expect.poll(() => opaque.count(), { timeout: 5_000 }).toBe(1)
+    expect(await opaque.textContent()).toContain('You are an AI agent powered by DeepSeek Harness.')
+
+    await disclosure.click()
+    await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('false')
+    await expect.poll(() => body.count()).toBe(0)
+  })
+
   it.skipIf(MODE === 'record')('expands and collapses the reasoning fold from its click target', async () => {
     onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-think'))
     // Interaction over the REAL wire-delivered transcript (the fixture-client
diff --git a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md
index 7207de464b..ebcb6163c7 100644
--- a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md
+++ b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md
@@ -9,6 +9,10 @@
   - tablist:
     - tab "Chat" [selected]
     - tab "Trajectory"
+- button "System prompt":
+  - img
+  - img
+  - text: System prompt
 - text: Stream one TypeScript fence for the highlighting snapshot. {{clock}}
 - button "Copy":
   - img
diff --git a/docs/agent-lifecycle.i18n.yaml b/docs/agent-lifecycle.i18n.yaml
index 0bd71efcb6..7e3e47b3ac 100644
--- a/docs/agent-lifecycle.i18n.yaml
+++ b/docs/agent-lifecycle.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/agent-lifecycle.md
-agent-lifecycle.md: 30509e17ce24ff2d078f86b6cc2a24b77ae3e4fa
-agent-lifecycle.zh.md: 693824913b2b9fcb627591a98804778a09e968a6
+agent-lifecycle.md: 9d1b66888e35d840c95ee9f2bd589dad3aac66f6
+agent-lifecycle.zh.md: f1648792fa15495f878ae2ec362bb760ccf2dc22
diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md
index 30509e17ce..9d1b66888e 100644
--- a/docs/agent-lifecycle.md
+++ b/docs/agent-lifecycle.md
@@ -75,7 +75,7 @@ The `assistant/message` event records every successful provider call, including
 
 `dsh-compaction-basic` uses `agent/pre-step` for pressure before request derivation and `agent/request-error` only for canonical context overflow. Once either trigger qualifies, optional tool-result pruning runs before summary selection. Recovery works between the closed failed step and failed turn close, and opens a fresh retry turn only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative.
 
-The returned `agent/pre-step` decision is authoritative; listeners wrapping `next()` preserve downstream messages unless replacement is intentional. Steering and injected context pass through the same waterfall after a later claim operation takes their next-step batch.
+The returned `agent/pre-step` decision is authoritative; listeners wrapping `next()` preserve downstream messages and `startsRequestSeries` unless replacement is intentional. Steering and injected context pass through the same waterfall after a later claim operation takes their next-step batch.
 
 SDK users that need replayable transcript data should consume `session/event`; `agent/*` is the live coordination API for queue/status, prompt interception, request construction, steering, continuation, and errors.
 
diff --git a/docs/agent-lifecycle.zh.md b/docs/agent-lifecycle.zh.md
index 693824913b..f1648792fa 100644
--- a/docs/agent-lifecycle.zh.md
+++ b/docs/agent-lifecycle.zh.md
@@ -77,7 +77,7 @@ sequenceDiagram
 
 `dsh-compaction-basic` 在派生请求之前通过 `agent/pre-step` 处理压力,而 `agent/request-error` 仅用于规范的上下文溢出。任一触发条件满足后,系统都会先执行可选的工具结果剪枝,再选择摘要。恢复发生在失败步骤结束之后、失败轮次结束之前;只有当剪枝或摘要生成推进了 surface replacement generation 时,系统才会开启一个全新的重试轮次,否则仍以原始请求错误为准。
 
-以返回的 `agent/pre-step` 决策为准;通过包装 `next()` 的监听器会保留下游消息,除非有意替换这些消息。steering(中途引导)和注入的上下文在后续的认领操作取得其下一步骤批次后,会经过同一 waterfall(瀑布式事件)。
+以返回的 `agent/pre-step` 决策为准;通过包装 `next()` 的监听器会保留下游消息与 `startsRequestSeries`,除非有意替换。steering(中途引导)和注入的上下文在后续的认领操作取得其下一步骤批次后,会经过同一 waterfall(瀑布式事件)。
 
 需要可回放 transcript(文本记录)数据的 SDK 用户应当消费 `session/event`;`agent/*` 是用于队列与状态、提示词拦截、请求构造、steering、继续执行和错误处理的实时协调接口。
 
diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml
index 82e57fd2f7..164230cbd6 100644
--- a/docs/architecture.i18n.yaml
+++ b/docs/architecture.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/architecture.md
-architecture.md: add615c252948adab8db7dec7059f94b8f45e52c
-architecture.zh.md: 48baf14d6a29e5ef77e6e47f4d9fa9adc4e9e748
+architecture.md: c6e01b8c30486d292694cbc26836e83522e3e760
+architecture.zh.md: 21d60d0c962097ee6853bf7a3831a2c0b727e9c9
diff --git a/docs/architecture.md b/docs/architecture.md
index add615c252..c6e01b8c30 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -79,7 +79,7 @@ A **step** is one model request plus the tools it calls. A **turn** is zero or m
 turn/start
   claim next-step input plus one queued message
   assemble prompt sections + tool schemas
-  -> agent/pre-step                   reject | enter(messages)
+  -> agent/pre-step                   reject | enter(messages, startsRequestSeries?)
      reject, or a first enter rewritten empty -> close the turn with no step
      step/start
      append entered messages as user/message
@@ -96,7 +96,7 @@ turn/end
 
 Input reaches the driver through one inbox. Some messages wake it immediately; injected context waits in the inbox until another message does.
 
-`agent/pre-step` decides what the model sees. Listeners may rewrite the claimed messages or reject them outright; a rejected or empty first claim still closes a durable turn that spent no step, so the log records the attempt. Each step reads the prompt sections and tool schemas that plugins registered.
+`agent/pre-step` decides what the model sees. Listeners may rewrite the claimed messages or reject them outright; a rejected or empty first claim still closes a durable turn that spent no step, so the log records the attempt. An enter decision may also set `startsRequestSeries` to begin a distinct model-message series: the loop then logs a fresh `request/header` (reason `series`, or `change` carrying `startsSeries: true` when the envelope changed too). A listener that rebuilds a downstream enter decision must spread it (`{ ...decision, messages }`) so the declaration survives. Each step reads the prompt sections and tool schemas that plugins registered.
 
 Details: the [sequence diagram](agent-lifecycle.md), the [tool pipeline](tool-execution-pipeline.md), and [cancellation and error recovery](subsystems/core.md#the-agent-handle).
 
diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md
index 48baf14d6a..21d60d0c96 100644
--- a/docs/architecture.zh.md
+++ b/docs/architecture.zh.md
@@ -83,7 +83,7 @@ Python SDK 遵循相同的应用架构。其运行时 wheel 把普通 `dsh` CLI
 turn/start
   claim next-step input plus one queued message
   assemble prompt sections + tool schemas
-  -> agent/pre-step                   reject | enter(messages)
+  -> agent/pre-step                   reject | enter(messages, startsRequestSeries?)
      reject, or a first enter rewritten empty -> close the turn with no step
      step/start
      append entered messages as user/message
@@ -100,7 +100,7 @@ turn/end
 
 输入通过同一个 inbox 到达驱动器。有些消息会立即唤醒它;注入的上下文会留在 inbox 中,直到另一条消息将其唤醒。
 
-`agent/pre-step` 决定模型看到什么。监听器可以改写已领取的消息,也可以直接拒绝它们;首次领取被拒绝或被改写为空时,仍会关闭一个不含步骤的持久轮次,因此日志会记录这次尝试。每个步骤读取插件注册的提示词片段和工具 schema。
+`agent/pre-step` 决定模型看到什么。监听器可以改写已领取的消息,也可以直接拒绝它们;首次领取被拒绝或被改写为空时,仍会关闭一个不含步骤的持久轮次,因此日志会记录这次尝试。enter 决策还可以设置 `startsRequestSeries` 来开启独立的模型消息序列:loop 会随之记录一个新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。重建下游 enter 决策的监听器必须展开它(`{ ...decision, messages }`),该声明才能存活。每个步骤读取插件注册的提示词片段和工具 schema。
 
 详情见[时序图](agent-lifecycle.zh.md)、[工具流水线](tool-execution-pipeline.zh.md)和[取消与错误恢复](subsystems/core.zh.md#the-agent-handle)。
 
diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml
index c87c5ac974..24a16e691a 100644
--- a/docs/event-producer-consumer.i18n.yaml
+++ b/docs/event-producer-consumer.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/event-producer-consumer.md
-event-producer-consumer.md: 586316e90992447d45ce2b0f0d67c306689f95cb
-event-producer-consumer.zh.md: 4aebaa2f10e4975df238639a1dac40694f50bed2
+event-producer-consumer.md: de2a94abb5e4d16433eae71e34e329fcf0042ede
+event-producer-consumer.zh.md: 7a9e825750213b2d0a67d9c022bffe031194c8ba
diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md
index 586316e909..de2a94abb5 100644
--- a/docs/event-producer-consumer.md
+++ b/docs/event-producer-consumer.md
@@ -9,18 +9,18 @@ This matrix shows which packages dispatch each harness-owned event and which pac
 | --- | --- | --- | --- | --- |
 | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:183`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - |
 | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:23`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `remotes` |
-| `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:161`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
-| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:170`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
-| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:292`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`session-telemetry`](../packages/session/session-telemetry) |
-| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:199`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) |
-| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:207`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) |
-| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:188`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
-| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:233`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-reference`](../packages/context/session-reference), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent) |
-| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:246`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/webhook/webhook) |
-| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:262`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) |
-| `agent/session-start` | `emit` | [`packages/core/agent/src/runtime-types.ts:219`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | `agent-team`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) |
-| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:180`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` |
-| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) |
+| `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:166`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
+| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:175`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
+| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:297`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`session-telemetry`](../packages/session/session-telemetry) |
+| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:204`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) |
+| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:212`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) |
+| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:193`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
+| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:238`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-reference`](../packages/context/session-reference), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent) |
+| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:251`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/webhook/webhook) |
+| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:267`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) |
+| `agent/session-start` | `emit` | [`packages/core/agent/src/runtime-types.ts:224`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | `agent-team`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) |
+| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:185`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` |
+| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:285`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) |
 | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:482`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
 | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:462`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
 | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:489`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md
index 4aebaa2f10..7a9e825750 100644
--- a/docs/event-producer-consumer.zh.md
+++ b/docs/event-producer-consumer.zh.md
@@ -11,18 +11,18 @@
 | --- | --- | --- | --- | --- |
 | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:183`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - |
 | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:23`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `remotes` |
-| `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:161`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
-| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:170`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
-| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`session-telemetry`](../packages/session/session-telemetry) |
-| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:197`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) |
-| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:205`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) |
-| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:186`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
-| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:231`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-reference`](../packages/context/session-reference), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent) |
-| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:244`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/webhook/webhook) |
-| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:260`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) |
-| `agent/session-start` | `emit` | [`packages/core/agent/src/runtime-types.ts:217`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | `agent-team`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) |
-| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:178`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` |
-| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:278`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) |
+| `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:166`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
+| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:175`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) |
+| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:297`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`session-telemetry`](../packages/session/session-telemetry) |
+| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:204`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) |
+| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:212`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) |
+| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:193`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
+| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:238`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-reference`](../packages/context/session-reference), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent) |
+| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:251`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/webhook/webhook) |
+| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:267`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) |
+| `agent/session-start` | `emit` | [`packages/core/agent/src/runtime-types.ts:224`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | `agent-team`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) |
+| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:185`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` |
+| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:285`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) |
 | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:482`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
 | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:462`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
 | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:489`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml
index 30b1894dbe..04ad9a33d7 100644
--- a/docs/persistence-catalog.i18n.yaml
+++ b/docs/persistence-catalog.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/persistence-catalog.md
-persistence-catalog.md: 893ffef71be98afe2356419dcb6ca0d871f26649
-persistence-catalog.zh.md: e34ce2b4b67746f9ce79f3d61add5e7f59e1aa22
+persistence-catalog.md: 12558eeadc009b498c9a178cfcc79116bf1b7c2b
+persistence-catalog.zh.md: f855d6969aa2dcade159ac8d6549e5f0350a7f0f
diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md
index 893ffef71b..12558eeadc 100644
--- a/docs/persistence-catalog.md
+++ b/docs/persistence-catalog.md
@@ -90,7 +90,7 @@ export type SessionEvent = {
 }[T]
 ```
 
-Sources: [`packages/core/session/src/types.ts:321`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:328`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:389`](../packages/core/session/src/types.ts)
+Sources: [`packages/core/session/src/types.ts:328`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:335`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:364`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:396`](../packages/core/session/src/types.ts)
 
 ## Events
 
@@ -215,7 +215,7 @@ Source: [`packages/interaction/user-approval/src/index.ts:32`](../packages/inter
 
 Types: [StreamChunk](subsystems/llm-streaming.md)
 
-Source: [`packages/core/session/src/types.ts:249`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:251`](../packages/core/session/src/types.ts)
 
 
 
@@ -237,7 +237,7 @@ Source: [`packages/core/session/src/types.ts:249`](../packages/core/session/src/
 
 Types: [TokenUsage](subsystems/llm-streaming.md)
 
-Source: [`packages/core/session/src/types.ts:260`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:262`](../packages/core/session/src/types.ts)
 
 ### `command/*`
 
@@ -563,7 +563,7 @@ Source: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/s
 'request/context': RequestContext
 ```
 
-Source: [`packages/core/session/src/types.ts:294`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts)
 
 
 
@@ -574,10 +574,15 @@ Source: [`packages/core/session/src/types.ts:294`](../packages/core/session/src/
  * Full header for the next request, appended inside its step before dispatch.
  * It is log-only; the latest snapshot reconstructs the request header.
  */
-'request/header': { header: EpochHeader; reason: RequestHeaderReason }
+'request/header': {
+  header: EpochHeader
+  reason: RequestHeaderReason
+  /** A changed header also begins a distinct model-message series. */
+  startsSeries?: true
+}
 ```
 
-Source: [`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:291`](../packages/core/session/src/types.ts)
 
 ### `sandbox/*`
 
@@ -652,7 +657,7 @@ Source: [`packages/schedule/schedule/src/types.ts:219`](../packages/schedule/sch
 'session/end-seed': Record
 ```
 
-Source: [`packages/core/session/src/types.ts:317`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:324`](../packages/core/session/src/types.ts)
 
 
 
@@ -712,7 +717,7 @@ Source: [`packages/session/session-log-deepseek/src/types.ts:26`](../packages/se
 'step/end': { turn: number; step: number }
 ```
 
-Source: [`packages/core/session/src/types.ts:239`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:241`](../packages/core/session/src/types.ts)
 
 
 
@@ -723,7 +728,7 @@ Source: [`packages/core/session/src/types.ts:239`](../packages/core/session/src/
 'step/start': { turn: number; step: number }
 ```
 
-Source: [`packages/core/session/src/types.ts:237`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:239`](../packages/core/session/src/types.ts)
 
 ### `subagent/*`
 
@@ -851,7 +856,7 @@ Source: [`packages/todo/tool-todo/src/types.ts:31`](../packages/todo/tool-todo/s
 
 Types: [CallId](subsystems/core.md)
 
-Source: [`packages/core/session/src/types.ts:266`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:268`](../packages/core/session/src/types.ts)
 
 
 
@@ -926,7 +931,7 @@ Source: [`packages/core/tools/src/types.ts:40`](../packages/core/tools/src/types
 }
 ```
 
-Source: [`packages/core/session/src/types.ts:278`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:280`](../packages/core/session/src/types.ts)
 
 ### `tool-workflow/*`
 
@@ -1006,7 +1011,7 @@ Source: [`packages/workflow/tool-workflow/src/types.ts:47`](../packages/workflow
 
 Types: [TurnEndReason](subsystems/session.md)
 
-Source: [`packages/core/session/src/types.ts:235`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:237`](../packages/core/session/src/types.ts)
 
 
 
@@ -1022,7 +1027,7 @@ Source: [`packages/core/session/src/types.ts:235`](../packages/core/session/src/
 'turn/start': { turn: number }
 ```
 
-Source: [`packages/core/session/src/types.ts:226`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:228`](../packages/core/session/src/types.ts)
 
 ### `user/*`
 
@@ -1041,7 +1046,7 @@ Source: [`packages/core/session/src/types.ts:226`](../packages/core/session/src/
 'user/message': UserMessage
 ```
 
-Source: [`packages/core/session/src/types.ts:247`](../packages/core/session/src/types.ts)
+Source: [`packages/core/session/src/types.ts:249`](../packages/core/session/src/types.ts)
 
 ### `web/*`
 
diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md
index e34ce2b4b6..f855d6969a 100644
--- a/docs/persistence-catalog.zh.md
+++ b/docs/persistence-catalog.zh.md
@@ -576,7 +576,12 @@ export type SessionEvent = {
  * Full header for the next request, appended inside its step before dispatch.
  * It is log-only; the latest snapshot reconstructs the request header.
  */
-'request/header': { header: EpochHeader; reason: RequestHeaderReason }
+'request/header': {
+  header: EpochHeader
+  reason: RequestHeaderReason
+  /** A changed header also begins a distinct model-message series. */
+  startsSeries?: true
+}
 ```
 
 来源:[`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts)
diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml
index fb5dd11fbb..6825069021 100644
--- a/docs/subsystems/core.i18n.yaml
+++ b/docs/subsystems/core.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/subsystems/core.md
-core.md: c53bb94fa5918c3a91ee9aedbb2416d0b101b240
-core.zh.md: 93ee45fb88cc100eb77673f2b70e86483c7ed29f
+core.md: d3564b6d50e0087be25f5dd1abc7b19507fd1c21
+core.zh.md: 0f7e49141e27b18ec8b75e944460d3ac04a88c0a
diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md
index c53bb94fa5..d3564b6d50 100644
--- a/docs/subsystems/core.md
+++ b/docs/subsystems/core.md
@@ -224,7 +224,12 @@ It returns a `PreStepDecision`. Reject opens no step. Enter supplies the complet
 /** Whether and with which messages the loop enters a proposed step. */
 type PreStepDecision =
   | { kind: 'reject' }
-  | { kind: 'enter'; messages: UserMessage[] }
+  | {
+    kind: 'enter'
+    messages: UserMessage[]
+    /** Start a distinct model-message series before this step's admitted messages. */
+    startsRequestSeries?: true
+  }
 ```
 
 `agent/request-error` runs after a failed model step closes and before its turn closes. Listeners can repair durable state or await policy work while the failed turn's signal is still live. A handling listener returns `{ kind: 'retry' }` without calling `next()`; the default `undefined` leaves the failure terminal.
diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md
index 93ee45fb88..0f7e49141e 100644
--- a/docs/subsystems/core.zh.md
+++ b/docs/subsystems/core.zh.md
@@ -232,7 +232,12 @@ pre-step 决策使用与持久 user-role 输入相同、带标识的 `UserMessag
 /** Whether and with which messages the loop enters a proposed step. */
 type PreStepDecision =
   | { kind: 'reject' }
-  | { kind: 'enter'; messages: UserMessage[] }
+  | {
+    kind: 'enter'
+    messages: UserMessage[]
+    /** Start a distinct model-message series before this step's admitted messages. */
+    startsRequestSeries?: true
+  }
 ```
 
 `agent/request-error` 在失败的模型步骤关闭之后、其轮次关闭之前运行。listener 可以在失败轮次的 signal 仍然存活时修复持久状态或 await 策略工作。处理该错误的 listener 返回 `{ kind: 'retry' }` 且不调用 `next()`;默认的 `undefined` 会让失败保持终态。
diff --git a/docs/subsystems/session.i18n.yaml b/docs/subsystems/session.i18n.yaml
index e3d112e468..732d6ee6c6 100644
--- a/docs/subsystems/session.i18n.yaml
+++ b/docs/subsystems/session.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/subsystems/session.md
-session.md: 23b3f8535ac432c297595bdf621cad5cecf717d4
-session.zh.md: ad73efb2d1ec8a2a7df3463518f172103f107296
+session.md: dc0f823cbc529b64d1f19abb3a07ffd39f849904
+session.zh.md: 640d3ee279f2fde140a5a89ee614f4db21485171
diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md
index 23b3f8535a..dc0f823cbc 100644
--- a/docs/subsystems/session.md
+++ b/docs/subsystems/session.md
@@ -94,7 +94,12 @@ interface SessionEventMap {
    * Full header for the next request, appended inside its step before dispatch.
    * It is log-only; the latest snapshot reconstructs the request header.
    */
-  'request/header': { header: EpochHeader; reason: RequestHeaderReason }
+  'request/header': {
+    header: EpochHeader
+    reason: RequestHeaderReason
+    /** A changed header also begins a distinct model-message series. */
+    startsSeries?: true
+  }
   /**
    * Route metadata for the next request, logged only when the route or capacity
    * changes. It does not participate in request reconstruction or header equality.
@@ -132,7 +137,7 @@ interface SessionEventMap {
 
 ### The request header event: `request/header`
 
-The request envelope — the `EpochHeader` (call config + markers for adapter-supplied defaults + rendered system prompt + assembled tool schemas) — is logged session state, so every conversation request is a pure function of the log (the reconstructability Agent Note). A full `request/header` snapshot with reason `'initial'` or `'resume'` records each loop-instance boundary; a later changed request records another full snapshot with reason `'change'`. `foldRequestHeader(events)` reconstructs the header by selecting the latest snapshot. The event is not a `SurfaceEventType`: it produces no LLM message.
+The request envelope — the `EpochHeader` (call config + markers for adapter-supplied defaults + rendered system prompt + assembled tool schemas) — is logged session state, so every conversation request is a pure function of the log (the reconstructability Agent Note). A full `request/header` snapshot with reason `'initial'` or `'resume'` records each loop-instance boundary; a changed request appends a snapshot with reason `'change'`; and an unchanged envelope beginning an explicitly declared message series or following a surface replacement appends a snapshot with reason `'series'`. A changed snapshot carries `startsSeries: true` when that request also begins a series. Ordinary append-only later Turns, further Steps, and retries in the same model-message series inherit the latest snapshot. `foldRequestHeader(events)` reconstructs the header by selecting the latest snapshot. The event is not a `SurfaceEventType`: it produces no LLM message.
 
 ```ts type-equiv
 /**
diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md
index ad73efb2d1..640d3ee279 100644
--- a/docs/subsystems/session.zh.md
+++ b/docs/subsystems/session.zh.md
@@ -94,7 +94,12 @@ interface SessionEventMap {
    * Full header for the next request, appended inside its step before dispatch.
    * It is log-only; the latest snapshot reconstructs the request header.
    */
-  'request/header': { header: EpochHeader; reason: RequestHeaderReason }
+  'request/header': {
+    header: EpochHeader
+    reason: RequestHeaderReason
+    /** A changed header also begins a distinct model-message series. */
+    startsSeries?: true
+  }
   /**
    * Route metadata for the next request, logged only when the route or capacity
    * changes. It does not participate in request reconstruction or header equality.
@@ -132,7 +137,7 @@ interface SessionEventMap {
 
 ### 请求头事件:`request/header`
 
-请求信封(即 `EpochHeader`:调用配置 + 适配器所提供默认值的标记 + 渲染后的系统提示词 + 已组装的工具 schema)会作为会话状态写入日志,因此每个对话请求都是日志的纯函数(见可重建性 Agent Note)。带有 reason `'initial'` 或 `'resume'` 的完整 `request/header` 快照记录每个 agent loop 实例的边界;之后请求发生变化时,系统会以 reason `'change'` 记录另一份完整快照。`foldRequestHeader(events)` 通过选择最新快照重建请求头。该事件不是 `SurfaceEventType`,不产生 LLM 消息。
+请求信封(即 `EpochHeader`:调用配置 + 适配器所提供默认值的标记 + 渲染后的系统提示词 + 已组装的工具 schema)会作为会话状态写入日志,因此每个对话请求都是日志的纯函数(见可重建性 Agent Note)。带有 reason `'initial'` 或 `'resume'` 的完整 `request/header` 快照记录每个 agent loop 实例的边界;请求变化时会追加 reason 为 `'change'` 的快照;未变的信封显式开启消息序列或跟随 surface 替换时,会追加 reason 为 `'series'` 的快照。如果发生变化的快照所属请求同时开启序列,它会携带 `startsSeries: true`。普通的仅追加后续 Turn,以及同一模型消息序列内的后续 Step 与重试沿用最新快照。`foldRequestHeader(events)` 通过选择最新快照重建请求头。该事件不是 `SurfaceEventType`,不产生 LLM 消息。
 
 ```ts type-equiv
 /**
diff --git a/packages/api/session-controller/src/agent.ts b/packages/api/session-controller/src/agent.ts
index c2b7b03e61..f96c66b464 100644
--- a/packages/api/session-controller/src/agent.ts
+++ b/packages/api/session-controller/src/agent.ts
@@ -291,12 +291,18 @@ export class ApiSessionAgentController {
     const selection: InstalledSelection = {
       get current(): AgentModelSelection {
         if (picked !== undefined) return picked
-        const logged = agent.session.requestHeader()?.config
-        if (logged === undefined) return defaultModel.currentSelection()
+        const loggedHeader = agent.session.requestHeader()
+        if (loggedHeader === undefined) return defaultModel.currentSelection()
+        const logged = loggedHeader.config
         return {
           provider: logged.provider,
           model: logged.model,
-          ...(logged.reasoningEffort === undefined ? {} : { reasoningEffort: logged.reasoningEffort }),
+          // An effort the adapter defaulted is not a conversation choice: restoring
+          // it as one would make an unchanged default read as a request change.
+          ...(logged.reasoningEffort === undefined
+            || loggedHeader.adapterDefaults?.reasoningEffort === true
+            ? {}
+            : { reasoningEffort: logged.reasoningEffort }),
         }
       },
       set current(next: AgentModelSelection) {
diff --git a/packages/api/session-controller/tests/session-models.host.spec.ts b/packages/api/session-controller/tests/session-models.host.spec.ts
index 65b9f5f7e7..d203585459 100644
--- a/packages/api/session-controller/tests/session-models.host.spec.ts
+++ b/packages/api/session-controller/tests/session-models.host.spec.ts
@@ -12,13 +12,14 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
 import AttachmentStore from '@deepseek-ai/dsh-attachment'
 import LlmRuntime, { LlmAdapter, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
 import type {
-  GenerateOptions, LlmCallConfig, LlmModelInfo, LlmModelReasoningInfo, LlmProviderInfo,
-  LlmResolvedModelInfo, StreamChunk,
+  GenerateOptions, LlmCallConfig, LlmCallConfigAdapterDefaults, LlmModelInfo,
+  LlmModelReasoningInfo, LlmProviderInfo, LlmResolvedModelInfo, StreamChunk,
   UserMessage,
 } from '@deepseek-ai/dsh-llm'
 import SessionStore from '@deepseek-ai/dsh-session'
 import type { SessionId } from '@deepseek-ai/dsh-session'
 import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
+import { ApiSessionAgentController } from '../src/agent.ts'
 import { buildModelCatalog } from '../src/catalog.ts'
 import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
 import { TypertRemoteFailure } from '@deepseek-ai/dsh-typert-protocol'
@@ -86,6 +87,7 @@ async function harness(logged?: {
   provider: string
   model: string
   reasoningEffort?: ReasoningEffortId
+  adapterDefaults?: LlmCallConfigAdapterDefaults
 }): Promise<{
   ctx: Context
   agent: Agent
@@ -121,7 +123,11 @@ async function harness(logged?: {
   ]))
   const session = ctx.sessions.create()
   if (logged !== undefined) {
-    session.append('request/header', { header: { config: logged }, reason: 'initial' })
+    const { adapterDefaults, ...config } = logged
+    session.append('request/header', {
+      header: { config, ...adapterDefaults === undefined ? {} : { adapterDefaults } },
+      reason: 'initial',
+    })
   }
   const agent = {
     id: session.id,
@@ -488,6 +494,23 @@ describe('Web session model selection', () => {
     await ctx.fiber.dispose()
   })
 
+  it('does not reinterpret an adapter-owned reasoning default as an explicit Web selection', async () => {
+    const { ctx, agent } = await harness({
+      provider: 'deepseek-official',
+      model: 'deepseek-chat',
+      reasoningEffort: ReasoningEffortId('high'),
+      adapterDefaults: { reasoningEffort: true },
+    })
+    createSessionTestRemote(ctx, {
+      defaultModelSelection: () => ({ provider: 'duplicate', model: 'same' }),
+      cwd: '/tmp',
+    })
+
+    expect(new ApiSessionAgentController(ctx).selectionFor(agent).current)
+      .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' })
+    await ctx.fiber.dispose()
+  })
+
   it('saves an accepted selection as the default and survives a storage failure', async () => {
     const { ctx, sessionId } = await harness()
     const saved: unknown[] = []
diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml
index 4859153e08..883760c733 100644
--- a/packages/client/ui-chat/README.i18n.yaml
+++ b/packages/client/ui-chat/README.i18n.yaml
@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md
-README.md: 5253cb95b0e5c0b89c32646e2ae2915936d35288
-README.zh.md: 8cd2d0d581a0493892aed23f42ebc0c229a0bc17
+README.md: ef9dc65de0d6b990fd0066c387518dc932bd4d2e
+README.zh.md: c4de06b18077485d7d65734b9bb38ff7745a4d67
diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md
index 5253cb95b0..ef9dc65de0 100644
--- a/packages/client/ui-chat/README.md
+++ b/packages/client/ui-chat/README.md
@@ -4,6 +4,10 @@ English | [中文](README.zh.md)
 
 The browser Chat target for Conversation assembly. It registers Chat event definitions and snapshot construction, supplies `useChat`, renders transcript nodes and details, and owns Chat-specific stores, actions, localization, and scroll restoration; historical image URLs resolve through the Conversation-owned per-session cache (`ctx.uiConversation.imageUrl`).
 
+## System prompt row
+
+Chat contributes a `System prompt` row for a non-empty initial or resumed request, an explicit series start, or an actual system-field change; same-series config-only or tool-only changes, tool steps, and retries do not duplicate it. Chat places the first header in a step at that request's message boundary — turn start for step one, step start thereafter — before the user-role messages sent with the request, matching the provider envelope's system-before-messages order; when the preceding header is outside a partial window, a non-initial header stays at its own Event and renders conservatively until prepend supplies that predecessor. The row stays collapsed by default and mounts the complete prompt in the same 141px code-block body as an opaque context injection — model-facing text with its real line breaks, not Markdown — only while expanded; it has no streaming path. Systemless headers produce no row.
+
 ## Model Experience
 
 None, as this package renders logged conversation state in the browser and registers nothing model-facing.
diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md
index 8cd2d0d581..c4de06b180 100644
--- a/packages/client/ui-chat/README.zh.md
+++ b/packages/client/ui-chat/README.zh.md
@@ -4,6 +4,10 @@
 
 Conversation 组装的浏览器 Chat target。本包注册 Chat event definition 与 snapshot 构造、提供 `useChat`、渲染 transcript node 和详情,并拥有 Chat 专属 store、action、本地化与滚动位置恢复;历史图片 URL 通过 Conversation 持有的按会话缓存(`ctx.uiConversation.imageUrl`)解析。
 
+## 系统提示词行
+
+Chat 会为非空的初始或恢复请求、显式序列起点,或 system 字段真实变化贡献一行 `系统提示词`;同一序列内仅配置变化或仅工具变化、工具 step 和重试不会重复该行。Chat 会把一个 step 中的首条 header 放在该请求的消息边界——step one 使用 turn start,其余 step 使用 step start——位于该请求发送的 user-role 消息之前,与提供方信封「system 在 messages 之前」的顺序一致;部分窗口未包含前序 header 时,非 initial header 会保留在自身 Event 并保守渲染,直到 prepend 补入前序 header。该行默认折叠,仅在展开期间把完整提示词挂到与不透明上下文注入相同的 141px 代码块内容区——保留模型所见真实换行的模型可见文本,而非 Markdown;它没有流式路径。无系统提示词的 header 不生成行。
+
 ## 模型体验
 
 无,因为本包在浏览器中渲染已记录的对话状态,不注册任何面向模型的内容。
diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx
index a647ad5c18..118214fcb6 100644
--- a/packages/client/ui-chat/src/client/chat/ChatView.tsx
+++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx
@@ -13,6 +13,7 @@ import { formatRunDuration } from './message-chrome.ts'
 import css from './ChatView.module.css'
 
 const FOLLOW_THRESHOLD = 24
+const MAX_PAGING_ANCHOR_PROBES = 64
 
 /** Active column host when present; otherwise the view-local scroller. */
 function scrollerOf(from: HTMLElement): HTMLElement {
@@ -26,7 +27,7 @@ interface PagingAnchor {
   top: number
 }
 
-/** Find an already-rendered settled row without interpolating a selector. */
+/** Find an already-rendered row without interpolating a selector. */
 function anchorElement(list: HTMLElement, key: string): HTMLElement | null {
   for (const row of list.querySelectorAll('[data-chat-anchor-key]')) {
     if (row.dataset.chatAnchorKey === key) return row
@@ -45,17 +46,24 @@ function pagingAnchor(list: HTMLElement, scrollport: HTMLElement): HTMLElement |
   const viewport = scrollport.getBoundingClientRect()
   const composer = scrollport.querySelector('[data-composer-seat]')
   const visibleBottom = composer?.getBoundingClientRect().top ?? viewport.bottom
-  // Scroll events are hot: hit-test a few points through the stretched flow
-  // rows before considering the full mounted set. The fallback keeps jsdom
-  // and pre-layout states deterministic; a virtualizer naturally bounds it.
+  // Scroll events are hot: walk down one hit-test line and stop at the first
+  // hit row with layout before considering the full mounted set. Starting at the
+  // viewport edge preserves the reader's leading row when a later row is
+  // inserted between already-visible messages. The fallback keeps jsdom and
+  // pre-layout states deterministic; a virtualizer naturally bounds it.
   if (typeof document.elementsFromPoint === 'function' && visibleBottom > viewport.top) {
     const content = list.getBoundingClientRect()
     const left = Math.max(viewport.left, content.left)
     const right = Math.min(viewport.right, content.right)
     const x = left + Math.max(0, right - left) / 2
     const height = visibleBottom - viewport.top
-    const points = [1, Math.min(32, height / 3), height / 2, Math.max(1, height - 1)]
-    for (const offset of points) {
+    let probes = 0
+    for (
+      let offset = 1;
+      offset < height && probes < MAX_PAGING_ANCHOR_PROBES;
+      offset = offset === 1 ? 16 : offset + 16
+    ) {
+      probes++
       for (const element of document.elementsFromPoint(x, viewport.top + offset)) {
         const row = element instanceof HTMLElement
           ? element.closest('[data-chat-anchor-key]')
diff --git a/packages/client/ui-chat/src/client/chat/ContextInjectionRow.module.css b/packages/client/ui-chat/src/client/chat/ContextInjectionRow.module.css
index e72bd594a2..32f88c135c 100644
--- a/packages/client/ui-chat/src/client/chat/ContextInjectionRow.module.css
+++ b/packages/client/ui-chat/src/client/chat/ContextInjectionRow.module.css
@@ -1,4 +1,5 @@
-/* Figma 10:2482: 24px Tool calls header, 4px gap, 141px code block cap. */
+/* Figma 10:2482: 24px Tool calls header, 4px gap, 141px code block cap.
+   SystemPromptRow reuses this sheet so both disclosures share one body. */
 
 .root {
   min-width: 0;
diff --git a/packages/client/ui-chat/src/client/chat/ContextInjectionRow.tsx b/packages/client/ui-chat/src/client/chat/ContextInjectionRow.tsx
index 8be42c0f42..37f08dc2f5 100644
--- a/packages/client/ui-chat/src/client/chat/ContextInjectionRow.tsx
+++ b/packages/client/ui-chat/src/client/chat/ContextInjectionRow.tsx
@@ -1,6 +1,6 @@
 import { useState } from 'react'
 import type { ChatViewSlotProps } from '../contract/slots.ts'
-import { DisclosureRow, IconBrowseOutline16, ReferenceIcon } from '@deepseek-ai/dsh-client-ui-primitives'
+import { DisclosureRow, IconContextInjectionOutline16, ReferenceIcon } from '@deepseek-ai/dsh-client-ui-primitives'
 import type { ContextMessageNode } from '../contract/snapshot.ts'
 import { contextBody } from './ContextBody.tsx'
 import css from './ContextInjectionRow.module.css'
@@ -39,7 +39,7 @@ export function ContextInjectionRow({ content, source, provenance, form, t }: Co
       className={css.root}
       icon={provenance.role === 'recall'
         ? 
-        : }
+        : }
       chevronClassName={css.chevron}
       title={t(provenance.role === 'recall' ? 'message.contextRecall' : 'message.contextInjection')}
       collapsedContent={provenance.label === null ? undefined : (
diff --git a/packages/client/ui-chat/src/client/chat/SystemPromptRow.tsx b/packages/client/ui-chat/src/client/chat/SystemPromptRow.tsx
new file mode 100644
index 0000000000..26c43b1793
--- /dev/null
+++ b/packages/client/ui-chat/src/client/chat/SystemPromptRow.tsx
@@ -0,0 +1,47 @@
+import { memo, useState } from 'react'
+import type { ChatNodeViewProps, ChatViewSlotProps } from '../contract/slots.ts'
+import { DisclosureRow, IconBrowseOutline16 } from '@deepseek-ai/dsh-client-ui-primitives'
+import { OpaqueBody } from './ContextBody.tsx'
+import css from './ContextInjectionRow.module.css'
+
+/** Props for one complete system prompt disclosure. */
+export interface SystemPromptRowProps {
+  /** Complete model-visible prompt text. */
+  text: string
+  /** The owning view's locale seat. */
+  t: ChatViewSlotProps['t']
+}
+
+/**
+ * Render one complete system prompt as a collapsed disclosure whose expanded
+ * body is the same opaque context chrome: 141px code-block scrollport and
+ * model-facing text with its real line breaks.
+ * @param props - Complete prompt text and the locale seat.
+ * @returns The system-prompt disclosure row.
+ */
+export function SystemPromptRow({ text, t }: SystemPromptRowProps) {
+  const [open, setOpen] = useState(false)
+  return (
+    }
+      chevronClassName={css.chevron}
+      title={t('message.systemPrompt')}
+      open={open}
+      expandable
+      expandOnRowClick
+      onToggle={() => { setOpen(value => !value) }}
+    >
+      
+ +
+
+ ) +} + +/** System-prompt keyed Chat renderer. */ +export const SystemPromptNodeView = memo(function SystemPromptNodeView({ + node, t, +}: Pick, 'node' | 't'>) { + return +}) diff --git a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts index 826e1344f2..748d75a364 100644 --- a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts +++ b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts @@ -7,6 +7,7 @@ import { TurnMaxTokensNodeView, UnknownNodeView, UserMessageNodeView, } from './MessageItem.tsx' import { TurnTailNodeView } from './TurnTailNodeView.tsx' +import { SystemPromptNodeView } from './SystemPromptRow.tsx' /** * Register this package's business renderers behind the keyed Chat Node seat. @@ -19,6 +20,8 @@ export function registerChatNodeRenderers(ctx: Context): void { { name: 'conversation.chat.node', key: 'steering', locale: NS }, UserMessageNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( { name: 'conversation.chat.node', key: 'context', locale: NS }, ContextMessageNodeView)) + ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( + { name: 'conversation.chat.node', key: 'system-prompt', locale: NS }, SystemPromptNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( { name: 'conversation.chat.node', key: 'assistant-step', locale: NS }, AssistantNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({ diff --git a/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts b/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts index f70e657014..21ed2c13f1 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts @@ -305,6 +305,8 @@ function legacyContribution(raw: ChatConversationViewNode): LegacyContribution { running: null, } case 'turn-tail': + case 'system-prompt': + // These known Chat rows intentionally make no legacy timeline contribution. return EMPTY_CONTRIBUTION default: return EMPTY_CONTRIBUTION diff --git a/packages/client/ui-chat/src/client/conversation-nodes/register.ts b/packages/client/ui-chat/src/client/conversation-nodes/register.ts index 5086253e81..d40fb1b00a 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/register.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/register.ts @@ -6,6 +6,7 @@ import { registerCompactionConversationNode } from './compaction.ts' import { registerUnknownConversationFallback } from './fallback.ts' import { registerInboxConversationNodes } from './inbox.ts' import { registerMessageConversationNode } from './message.ts' +import { registerRequestPromptConversationNode } from './request-prompt.ts' import { registerRetryConversationNode } from './retry.ts' import { registerToolConversationNode } from './tool.ts' import { registerTurnErrorConversationNode } from './turn-error.ts' @@ -19,6 +20,7 @@ import { registerTurnTailConversationNode } from './turn-tail.ts' export function registerConversationNodes(ctx: Context): void { registerInboxConversationNodes(ctx) registerMessageConversationNode(ctx) + registerRequestPromptConversationNode(ctx) registerAssistantConversationNode(ctx) registerToolConversationNode(ctx) registerCommandConversationNode(ctx) diff --git a/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts b/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts new file mode 100644 index 0000000000..c7f25cf6db --- /dev/null +++ b/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts @@ -0,0 +1,87 @@ +import type { Context } from '@deepseek-ai/cordis' +import type { + ConversationMatch, ConversationNodeDefinition, RequestPromptInspector, +} from '@deepseek-ai/dsh-client-ui-conversation/client' +import { chatNode } from './common.ts' + +declare module '../contract/chat-nodes.ts' { + interface ChatNodeDataMap { + /** Complete system prompt rendered for one model request. */ + 'system-prompt': { readonly text: string } + } +} + +interface RequestPromptState extends ReturnType { + readonly anchorSeq: number + readonly showsPrompt: boolean + readonly turn?: number + readonly step?: number +} + +/** Place a request's system field at the start of its visible message series. */ +function requestPromptAnchor( + match: ConversationMatch, + previous: Readonly | undefined, + isInitial: boolean, +): number { + if (match.location.kind !== 'step') return match.event.seq + if (previous === undefined && !isInitial) return match.event.seq + if (previous?.turn === match.location.turn.turn + && previous.step === match.location.step.step) return match.event.seq + return match.location.step.step === 1 + ? match.location.turn.start?.seq ?? match.location.step.start?.seq ?? match.event.seq + : match.location.step.start?.seq ?? match.event.seq +} + +/** + * Request-header prompt Definition for the Chat target. + * @param inspect - the shared prompt interpretation, supplied by the + * uiConversation service (a client bundle cannot value-import it). + * @returns the Chat request-prompt Definition. + */ +export function requestPromptDefinition(inspect: RequestPromptInspector): ConversationNodeDefinition { + return { + kind: 'request-prompt', + target: 'chat', + match: event => event.type === 'request/header' + ? { id: String(event.seq), role: 'start' } + : null, + start: (_context, match, reader) => { + if (match.event.type !== 'request/header') { + throw new Error('request-prompt start requires request/header') + } + const previous = reader.previous('request-prompt')?.state + const location = match.location.kind === 'step' + ? { turn: match.location.turn.turn, step: match.location.step.step } + : {} + const inspection = inspect(previous?.prompt, match.event) + const change = inspection.change?.kind + return { + anchorSeq: requestPromptAnchor(match, previous, match.event.data.reason === 'initial'), + showsPrompt: previous === undefined + || match.event.data.reason !== 'change' + || match.event.data.startsSeries === true + || change === 'system' + || change === 'system-and-tools', + ...location, + ...inspection, + } + }, + update: context => context.state, + buildViewNode: (context) => { + const state = context.state + if (state === undefined || !state.showsPrompt || state.prompt.system === '') return null + return chatNode(context, 'system-prompt', state.anchorSeq, { text: state.prompt.system }) + }, + } +} + +/** + * Register model-request system prompts in the Chat flow. + * @param ctx - Owning UI Conversation context. + */ +export function registerRequestPromptConversationNode(ctx: Context): void { + ctx.uiConversation.events.register(requestPromptDefinition( + (previous, event) => ctx.uiConversation.inspectRequestPrompt(previous, event), + )) +} diff --git a/packages/client/ui-chat/src/client/index.ts b/packages/client/ui-chat/src/client/index.ts index c04c2c588e..d9ce71f2d0 100644 --- a/packages/client/ui-chat/src/client/index.ts +++ b/packages/client/ui-chat/src/client/index.ts @@ -5,6 +5,7 @@ export type {} from './conversation-nodes/command.ts' export type {} from './conversation-nodes/compaction.ts' export type {} from './conversation-nodes/fallback.ts' export type {} from './conversation-nodes/message.ts' +export type {} from './conversation-nodes/request-prompt.ts' export type {} from './conversation-nodes/retry.ts' export type {} from './conversation-nodes/tool.ts' export type {} from './conversation-nodes/turn-error.ts' diff --git a/packages/client/ui-chat/src/client/locale.ts b/packages/client/ui-chat/src/client/locale.ts index be8a3521ac..d31f767e66 100644 --- a/packages/client/ui-chat/src/client/locale.ts +++ b/packages/client/ui-chat/src/client/locale.ts @@ -33,6 +33,7 @@ export const zh = { 'fileOpen.folderTitle': '无法打开文件夹', 'fileOpen.folderUnknown': '无法打开此文件夹', 'message.extraBlock': '附加内容块', + 'message.systemPrompt': '系统提示词', 'message.contextInjection': '上下文注入', 'message.contextRecall': '跨会话召回', 'message.referenceSummary': '引用会话 · {labels}', @@ -119,6 +120,7 @@ export const en = { 'fileOpen.folderTitle': 'Couldn’t open folder', 'fileOpen.folderUnknown': 'Couldn’t open this folder', 'message.extraBlock': 'Extra content block', + 'message.systemPrompt': 'System prompt', 'message.contextInjection': 'Context injection', 'message.contextRecall': 'Session recall', 'message.referenceSummary': 'Referenced session · {labels}', diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index d112bd779c..a681f218c4 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -452,6 +452,39 @@ describe('ChatView', () => { expect(scroller.scrollTop).toBe(590) // latest 90 + the anchored row's 500px prepend shift }) + it('bounds no-anchor hit testing before using the mounted-row fallback', () => { + const originalHitTest = Object.getOwnPropertyDescriptor(document, 'elementsFromPoint') + const hitTest = vi.fn((): Element[] => []) + Object.defineProperty(document, 'elementsFromPoint', { + configurable: true, + value: hitTest, + }) + try { + const h = makeHarness({ nodes: [user(1, 'visible row')] }) + const view = render() + const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement + const anchor = view.container.querySelector('[data-chat-anchor-key="fixture:user:1"]') as HTMLElement + installScrollMetrics(scroller, 4_000, 2_000) + vi.spyOn(scroller, 'getBoundingClientRect').mockReturnValue({ + top: 0, bottom: 2_000, left: 0, right: 1_000, + } as DOMRect) + vi.spyOn(anchor, 'getBoundingClientRect').mockReturnValue({ + top: 100, bottom: 140, left: 0, right: 1_000, + } as DOMRect) + + readerScroll(scroller, 100) + + expect(hitTest).toHaveBeenCalledTimes(64) + expect(h.chatScroll.read()?.anchorKey).toBe('fixture:user:1') + } finally { + if (originalHitTest !== undefined) { + Object.defineProperty(document, 'elementsFromPoint', originalHitTest) + } else { + Reflect.deleteProperty(document, 'elementsFromPoint') + } + } + }) + it('renders the fixture main line as independently keyed business nodes', () => { const h = makeHarness({ nodes: [user(1, 'do the thing'), assistant(2, 'running tools'), toolResult(3, 'a'), toolResult(4, 'b')], diff --git a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts index 88b103ae66..04dbbeeb1f 100644 --- a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts +++ b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts @@ -15,6 +15,8 @@ import { compactionDefinition } from '../src/client/conversation-nodes/compactio import { unknownFallbackDefinition } from '../src/client/conversation-nodes/fallback.ts' import { nextStepInboxDefinition, nextTurnInboxDefinition } from '../src/client/conversation-nodes/inbox.ts' import { messageDefinition } from '../src/client/conversation-nodes/message.ts' +import { inspectRequestPrompt } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { requestPromptDefinition } from '../src/client/conversation-nodes/request-prompt.ts' import { retryDefinition } from '../src/client/conversation-nodes/retry.ts' import { toolDefinition } from '../src/client/conversation-nodes/tool.ts' import { turnErrorDefinition } from '../src/client/conversation-nodes/turn-error.ts' @@ -28,6 +30,7 @@ const DEFINITIONS: readonly ConversationNodeDefinition[] = [ nextTurnInboxDefinition, nextStepInboxDefinition, messageDefinition, + requestPromptDefinition(inspectRequestPrompt), assistantDefinition, toolDefinition, commandDefinition, @@ -121,6 +124,18 @@ function toolResult(callId: string, text: string, isError = false) { } describe('built-in conversation node Definitions', () => { + it('rejects an unrelated event passed directly to the request-prompt start', () => { + const input = at(1, 'turn/start', { turn: 1 }) + const invalidStart = { + ...input, + role: 'start' as const, + location: { kind: 'session' as const }, + } + + expect(() => requestPromptDefinition(inspectRequestPrompt).start({} as never, invalidStart, {} as never)) + .toThrow('request-prompt start requires request/header') + }) + it('keeps ordinary command-only history inactive for the Conversation shell', () => { const value = assembler([ at(1, 'command/run', { @@ -560,6 +575,223 @@ describe('built-in conversation node Definitions', () => { }) }) + it('materializes series starts and system changes but not same-series config or tool changes', () => { + const tools = [{ name: 'read', description: 'Read', parameters: { type: 'object' } }] + const expandedTools = [...tools, { name: 'write', description: 'Write', parameters: { type: 'object' } }] + const value = assembler([ + at(1, 'request/header', { + reason: 'initial', + header: { config: { provider: 'fake', model: 'fake' }, system: '# Initial', tools }, + }), + at(2, 'request/header', { + reason: 'change', + header: { + config: { provider: 'fake', model: 'fake' }, + system: '# Initial', + tools: expandedTools, + }, + }), + at(3, 'request/header', { + reason: 'change', + header: { + config: { provider: 'fake', model: 'fake', maxTokens: 1_024 }, + system: '# Initial', + tools: expandedTools, + }, + }), + at(4, 'request/header', { + reason: 'change', + startsSeries: true, + header: { + config: { provider: 'fake', model: 'fake', maxTokens: 2_048 }, + system: '# Initial', + tools: expandedTools, + }, + }), + at(5, 'request/header', { + reason: 'resume', + header: { + config: { provider: 'fake', model: 'fake', maxTokens: 2_048 }, + system: '# Initial', + tools: expandedTools, + }, + }), + at(6, 'request/header', { + reason: 'change', + header: { + config: { provider: 'fake', model: 'fake', maxTokens: 2_048 }, + system: '# Updated', + tools: expandedTools, + }, + }), + ]) + + const prompts = snapshot(value).nodes.values() + .filter(candidate => candidate.kind === 'system-prompt') + expect(prompts.map(prompt => ({ anchorSeq: prompt.anchorSeq, data: prompt.data }))).toEqual([ + { anchorSeq: 1, data: { text: '# Initial' } }, + { anchorSeq: 4, data: { text: '# Initial' } }, + { anchorSeq: 5, data: { text: '# Initial' } }, + { anchorSeq: 6, data: { text: '# Updated' } }, + ]) + + const windowed = assembler([ + at(10, 'request/header', { + reason: 'resume', + header: { config: { provider: 'fake', model: 'fake' }, system: '# Resumed prompt' }, + }), + ], true) + const systemless = assembler([ + at(20, 'request/header', { + reason: 'initial', + header: { config: { provider: 'fake', model: 'fake' } }, + }), + ]) + expect(node(snapshot(windowed), 'system-prompt')?.data).toEqual({ text: '# Resumed prompt' }) + expect(node(snapshot(systemless), 'system-prompt')).toBeUndefined() + + windowed.prepend([ + at(5, 'request/header', { + reason: 'initial', + header: { config: { provider: 'fake', model: 'fake' }, system: '# Original prompt' }, + }), + ], false) + windowed.flush() + const restored = snapshot(windowed) + const restoredPrompts = restored.order.flatMap((key) => { + const candidate = restored.nodes.get(key) + return candidate?.kind === 'system-prompt' ? [candidate] : [] + }) + expect(restoredPrompts.map(prompt => prompt.data)).toEqual([ + { text: '# Original prompt' }, + { text: '# Resumed prompt' }, + ]) + }) + + it('orders the system field before the request messages while preserving message order', () => { + const value = assembler([ + at(1, 'turn/start', { turn: 1 }), + at(2, 'step/start', { turn: 1, step: 1 }), + at(3, 'user/message', textMessage('direct-user', 'prompt'), { surfaceOp: 'append' }), + at(4, 'user/message', { + ...textMessage('runtime-context', 'runtime facts'), + source: { kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt', form: 'snapshot' }, + }, { surfaceOp: 'append' }), + at(5, 'request/header', { + reason: 'initial', + header: { config: { provider: 'fake', model: 'fake' }, system: '# System' }, + }), + ]) + + const current = snapshot(value) + expect(current.order.map(key => current.nodes.get(key)?.kind)).toEqual([ + 'system-prompt', + 'user', + 'context', + ]) + expect(node(current, 'system-prompt')?.anchorSeq).toBe(1) + }) + + it('keeps an append-only later user turn in the existing system-prompt series', () => { + const value = assembler([ + at(1, 'turn/start', { turn: 1 }), + at(2, 'step/start', { turn: 1, step: 1 }), + at(3, 'user/message', textMessage('first-user', 'first'), { surfaceOp: 'append' }), + at(4, 'request/header', { + reason: 'initial', + header: { config: { provider: 'fake', model: 'fake' }, system: '# System' }, + }), + at(5, 'step/end', { turn: 1, step: 1 }), + at(6, 'turn/end', { turn: 1, reason: { kind: 'completed' } }), + at(7, 'turn/start', { turn: 2 }), + at(8, 'step/start', { turn: 2, step: 1 }), + at(9, 'user/message', textMessage('second-user', 'second'), { surfaceOp: 'append' }), + ]) + + const current = snapshot(value) + const ordered = current.order.flatMap((key) => { + const candidate = current.nodes.get(key) + return candidate?.kind === 'system-prompt' || candidate?.kind === 'user' ? [candidate] : [] + }) + expect(ordered.map(candidate => candidate.kind)).toEqual(['system-prompt', 'user', 'user']) + }) + + it('keeps windowed non-initial headers at their event until prepend supplies the preceding header', () => { + const reasons = ['change', 'resume', 'series'] as const + for (const reason of reasons) { + const windowedSystem = reason === 'series' ? '# Original' : '# Windowed' + const windowed = assembler([ + at(5, 'turn/start', { turn: 2 }), + at(6, 'step/start', { turn: 2, step: 1 }), + at(7, 'user/message', textMessage(`second-user-${reason}`, 'second'), { surfaceOp: 'append' }), + at(8, 'request/header', { + reason, + header: { config: { provider: 'fake', model: 'fake' }, system: windowedSystem }, + }), + ], true) + + expect(node(snapshot(windowed), 'system-prompt')?.anchorSeq).toBe(8) + + windowed.prepend([ + at(1, 'turn/start', { turn: 1 }), + at(2, 'step/start', { turn: 1, step: 1 }), + at(3, 'user/message', textMessage(`first-user-${reason}`, 'first'), { surfaceOp: 'append' }), + at(4, 'request/header', { + reason: 'initial', + header: { config: { provider: 'fake', model: 'fake' }, system: '# Original' }, + }), + ], false) + windowed.flush() + + const restored = snapshot(windowed) + const prompts = restored.order.flatMap((key) => { + const candidate = restored.nodes.get(key) + return candidate?.kind === 'system-prompt' ? [candidate] : [] + }) + expect(prompts.map(prompt => prompt.anchorSeq)).toEqual([1, 5]) + } + }) + + it('repeats an unchanged system prompt after a surface rewrite and before an explicit later series', () => { + const value = assembler([ + at(1, 'turn/start', { turn: 1 }), + at(2, 'step/start', { turn: 1, step: 1 }), + at(3, 'user/message', textMessage('first-user', 'first'), { surfaceOp: 'append' }), + at(4, 'request/header', { + reason: 'initial', + header: { config: { provider: 'fake', model: 'fake' }, system: '# Same' }, + }), + at(5, 'user/message', { + ...textMessage('compacted', 'summary'), + source: { kind: 'plugin', plugin: 'compact' }, + }, { surfaceOp: { op: 'replace', start: 3, end: 3 } }), + at(6, 'request/header', { + reason: 'series', + header: { config: { provider: 'fake', model: 'fake' }, system: '# Same' }, + }), + at(7, 'step/end', { turn: 1, step: 1 }), + at(8, 'turn/end', { turn: 1, reason: { kind: 'completed' } }), + at(9, 'turn/start', { turn: 2 }), + at(10, 'step/start', { turn: 2, step: 1 }), + at(11, 'user/message', textMessage('second-user', 'second'), { surfaceOp: 'append' }), + at(12, 'request/header', { + reason: 'series', + header: { config: { provider: 'fake', model: 'fake' }, system: '# Same' }, + }), + ]) + + const current = snapshot(value) + const ordered = current.order.flatMap((key) => { + const candidate = current.nodes.get(key) + return candidate?.kind === 'system-prompt' || candidate?.kind === 'user' ? [candidate] : [] + }) + expect(ordered.map(candidate => candidate?.kind)).toEqual([ + 'system-prompt', 'user', 'system-prompt', 'system-prompt', 'user', + ]) + expect(ordered.filter(candidate => candidate?.kind === 'system-prompt') + .map(candidate => candidate?.anchorSeq)).toEqual([1, 6, 9]) + }) + it('associates each direct message with its immediately following session recall', () => { const value = assembler([ at(1, 'user/message', textMessage('citing-research', '@Research notes what changed?'), { surfaceOp: 'append' }), diff --git a/packages/client/ui-chat/tests/system-prompt-row.client.spec.tsx b/packages/client/ui-chat/tests/system-prompt-row.client.spec.tsx new file mode 100644 index 0000000000..e91524f633 --- /dev/null +++ b/packages/client/ui-chat/tests/system-prompt-row.client.spec.tsx @@ -0,0 +1,44 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { ChatNode } from '../src/client/contract/chat-nodes.ts' +import { SystemPromptNodeView } from '../src/client/chat/SystemPromptRow.tsx' +import { en } from '../src/client/locale.ts' + +afterEach(cleanup) + +describe('SystemPromptNodeView', () => { + it('mounts the opaque context body only while its row is expanded', () => { + const text = '# Agent rules\n\n- Read first\n- **Act carefully**' + const node: ChatNode<'system-prompt'> = { + key: 'request-prompt:1', + kind: 'system-prompt', + id: '1', + target: 'chat', + anchorSeq: 1, + location: { kind: 'unresolved' }, + visibility: 'visible', + data: { text }, + } + const { container } = render() + + const disclosure = screen.getByRole('button', { name: 'System prompt' }) + expect(disclosure.getAttribute('aria-expanded')).toBe('false') + expect(container.querySelector('[data-system-prompt-body]')).toBeNull() + expect(container.querySelector('[data-context-text]')).toBeNull() + + fireEvent.click(disclosure) + expect(disclosure.getAttribute('aria-expanded')).toBe('true') + expect(container.querySelector('[data-system-prompt-body]')).not.toBeNull() + expect(container.querySelector('[data-context-text]')?.textContent).toBe(text) + expect(screen.queryByRole('heading', { name: 'Agent rules' })).toBeNull() + + fireEvent.click(disclosure) + expect(disclosure.getAttribute('aria-expanded')).toBe('false') + expect(container.querySelector('[data-system-prompt-body]')).toBeNull() + }) +}) diff --git a/packages/client/ui-conversation/src/client/contract/request-inspection.ts b/packages/client/ui-conversation/src/client/contract/request-inspection.ts index 773b131ae2..486808745e 100644 --- a/packages/client/ui-conversation/src/client/contract/request-inspection.ts +++ b/packages/client/ui-conversation/src/client/contract/request-inspection.ts @@ -1,4 +1,5 @@ import type { ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm/types' +import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import type { AssistantProvenanceView, AssistantRequestConfig, } from './records.ts' @@ -29,6 +30,61 @@ export interface RequestPromptChange { previous?: ConversationPromptSnapshot } +/** Canonical prompt snapshot and any model-visible change introduced by one request header. */ +export interface RequestPromptInspection { + /** Complete prompt state recorded by the header. */ + prompt: ConversationPromptSnapshot + /** System/tool change relative to the preceding loaded header. */ + change?: RequestPromptChange +} + +/** + * The {@link inspectRequestPrompt} signature as a value seam: Chat and + * Trajectory Definitions receive it from the uiConversation service because a + * client bundle cannot value-import another plugin's module. + */ +export type RequestPromptInspector = ( + previous: ConversationPromptSnapshot | undefined, + event: SessionEvent<'request/header'>, +) => RequestPromptInspection + +/** + * Canonicalize one request header and classify its model-visible prompt change. + * @param previous - Prompt from the preceding loaded request header, when available. + * @param event - Durable full request header to inspect. + * @returns The canonical prompt and an initial/system/tool change when it can be established. + */ +export function inspectRequestPrompt( + previous: ConversationPromptSnapshot | undefined, + event: SessionEvent<'request/header'>, +): RequestPromptInspection { + const header = event.data.header + const rawTools: unknown = header.tools + const prompt: ConversationPromptSnapshot = { + config: header.config, + system: header.system ?? '', + tools: Array.isArray(rawTools) ? rawTools as readonly ToolSchema[] : [], + } + if (previous === undefined && event.data.reason !== 'initial') return { prompt } + const systemChanged = previous !== undefined && previous.system !== prompt.system + const toolsChanged = previous !== undefined + && JSON.stringify(previous.tools) !== JSON.stringify(prompt.tools) + if (previous !== undefined && !systemChanged && !toolsChanged) return { prompt } + return { + prompt, + change: { + seq: event.seq, + time: event.time, + kind: previous === undefined + ? 'initial' + : systemChanged && toolsChanged + ? 'system-and-tools' + : systemChanged ? 'system' : 'tools', + ...(previous === undefined ? {} : { previous }), + }, + } +} + /** Lifecycle fields shared by ordinary generation and compaction requests. */ interface RequestViewBase { /** Sequence that opened the operation represented by this request. */ diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index 26801e161b..9a8a429292 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -14,6 +14,8 @@ import type { ConversationViewSnapshotStore, } from '../contract/conversation.ts' import type { ConversationSnapshot } from '../contract/snapshot.ts' +import type { ConversationPromptSnapshot, RequestPromptInspection } from '../contract/request-inspection.ts' +import { inspectRequestPrompt } from '../contract/request-inspection.ts' import { ConversationNodeAssembler } from './assembler.ts' import { ConversationEventRegistry } from './event-registry.ts' import { HistoricalImageCache } from './historical-images.ts' @@ -217,6 +219,23 @@ export class UiConversation extends Service { return this.images.resolve(sessionId, attachment) } + /** + * Canonicalize one `request/header` event against the previous prompt state. + * + * A pure interpretation shared by the Chat and Trajectory Definitions, exposed + * as a service method because cross-plugin value imports are forbidden in + * client bundles. + * @param previous - prompt recorded by the preceding loaded header, if any. + * @param event - the `request/header` session event to interpret. + * @returns the canonical prompt snapshot and any model-visible change. + */ + inspectRequestPrompt( + previous: ConversationPromptSnapshot | undefined, + event: SessionEvent<'request/header'>, + ): RequestPromptInspection { + return inspectRequestPrompt(previous, event) + } + private drop(record: BindingRecord, releaseScope: boolean): void { if (this.bindings.get(record.source.sessionId) !== record) return this.bindings.delete(record.source.sessionId) diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 966135c043..587772b9d3 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -28,8 +28,9 @@ export type { ContextProvenanceView, ContextRole, KnownContextForm, } from './contract/context-provenance.ts' export type { - ConversationPromptSnapshot, RequestInspectionSnapshot, RequestPromptChange, RequestView, + ConversationPromptSnapshot, RequestInspectionSnapshot, RequestPromptChange, RequestPromptInspection, RequestPromptInspector, RequestView, } from './contract/request-inspection.ts' +export { inspectRequestPrompt } from './contract/request-inspection.ts' export type { ConversationStoreState, ConversationViewRequest, ViewTab } from './contract/views.ts' export { ConversationNodeAssembler } from './conversation/assembler.ts' diff --git a/packages/client/ui-conversation/tests/request-inspection.client.spec.ts b/packages/client/ui-conversation/tests/request-inspection.client.spec.ts new file mode 100644 index 0000000000..1f0471ce8f --- /dev/null +++ b/packages/client/ui-conversation/tests/request-inspection.client.spec.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest' +import type { SessionEvent } from '@deepseek-ai/dsh-session/types' +import { inspectRequestPrompt } from '../src/client/contract/request-inspection.ts' + +const CONFIG = { provider: 'test', model: 'test' } + +function header( + seq: number, + reason: SessionEvent<'request/header'>['data']['reason'], + value: SessionEvent<'request/header'>['data']['header'], +): SessionEvent<'request/header'> { + return { + type: 'request/header', + seq, + time: 1_700_000_000_000 + seq, + data: { reason, header: value }, + } +} + +describe('inspectRequestPrompt', () => { + it('classifies the first complete header as the initial prompt', () => { + expect(inspectRequestPrompt(undefined, header(1, 'initial', { + config: CONFIG, + system: '# System\n\nFollow instructions.', + tools: [{ name: 'read', description: 'Read a file', parameters: { type: 'object' } }], + }))).toMatchObject({ + prompt: { + config: CONFIG, + system: '# System\n\nFollow instructions.', + tools: [{ name: 'read' }], + }, + change: { seq: 1, time: 1_700_000_000_001, kind: 'initial' }, + }) + }) + + it('suppresses a resume header when the earlier prompt is outside the loaded window', () => { + expect(inspectRequestPrompt(undefined, header(2, 'resume', { + config: CONFIG, + system: 'same prompt', + }))).toEqual({ + prompt: { config: CONFIG, system: 'same prompt', tools: [] }, + }) + }) + + it('classifies system, tool, and combined changes against the previous prompt', () => { + const initial = inspectRequestPrompt(undefined, header(1, 'initial', { + config: CONFIG, + system: 'first', + tools: [{ name: 'read', description: 'Read', parameters: { type: 'object' } }], + })).prompt + const system = inspectRequestPrompt(initial, header(2, 'change', { + config: CONFIG, + system: 'second', + tools: [...initial.tools], + })) + const tools = inspectRequestPrompt(system.prompt, header(3, 'change', { + config: CONFIG, + system: 'second', + tools: [{ name: 'write', description: 'Write', parameters: { type: 'object' } }], + })) + const combined = inspectRequestPrompt(tools.prompt, header(4, 'change', { + config: CONFIG, + system: 'third', + tools: [], + })) + + expect(system.change?.kind).toBe('system') + expect(tools.change?.kind).toBe('tools') + expect(combined.change?.kind).toBe('system-and-tools') + expect(combined.change?.previous).toBe(tools.prompt) + }) + + it('omits a change when the prompt and tools are unchanged', () => { + const previous = inspectRequestPrompt(undefined, header(1, 'initial', { + config: CONFIG, + system: 'same', + })).prompt + + expect(inspectRequestPrompt(previous, header(2, 'resume', { + config: { ...CONFIG, maxTokens: 1_024 }, + system: 'same', + }))).toEqual({ + prompt: { config: { ...CONFIG, maxTokens: 1_024 }, system: 'same', tools: [] }, + }) + }) +}) diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 549dc31997..6f0a913f68 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -402,6 +402,22 @@ export const IconBrowseOutline16 = ({ size = 16, className }: IconProps) => ( ) +/** ic_ds_context_injection_outline_16 (figma extract): browse document frame with an open top and an arrow dropping in. */ +export const IconContextInjectionOutline16 = ({ size = 16, className }: IconProps) => ( + + + + + + +) + /** ic_ds_link_outline_14 */ export const IconLinkOutline14 = ({ size = 14, className }: IconProps) => ( diff --git a/packages/client/ui-primitives/tests/icons.client.spec.tsx b/packages/client/ui-primitives/tests/icons.client.spec.tsx index 9d14400e8a..5e4d7dd2a4 100644 --- a/packages/client/ui-primitives/tests/icons.client.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.client.spec.tsx @@ -16,8 +16,8 @@ const icons = Object.fromEntries( const iconNames = Object.keys(icons) describe('ic_ds_ icon set', () => { - it('exports the full icon set (46 deepsuite + 20 figma extracts + four product glyphs outside those sets)', () => { - expect(iconNames.length).toBe(70) + it('exports the full icon set (46 deepsuite + 21 figma extracts + four product glyphs outside those sets)', () => { + expect(iconNames.length).toBe(71) }) it.each(iconNames)('%s renders an svg with currentColor fills and no hardcoded palette', (name) => { diff --git a/packages/client/ui-trajectory/src/client/trajectory-request-header-definition.ts b/packages/client/ui-trajectory/src/client/trajectory-request-header-definition.ts index 0cbb9fee77..53b4176ce0 100644 --- a/packages/client/ui-trajectory/src/client/trajectory-request-header-definition.ts +++ b/packages/client/ui-trajectory/src/client/trajectory-request-header-definition.ts @@ -1,79 +1,55 @@ import type { Context } from '@deepseek-ai/cordis' import type { - ConversationMatch, ConversationNodeDefinition, ConversationPromptSnapshot, RequestPromptChange, + ConversationNodeDefinition, RequestPromptInspector, } from '@deepseek-ai/dsh-client-ui-conversation/client' import { trajectoryNode } from './trajectory-definition-common.ts' import type { TrajectoryRequestHeaderState } from './trajectory-contract.ts' -function requestPrompt(match: ConversationMatch): ConversationPromptSnapshot { - if (match.event.type !== 'request/header') { - throw new Error('trajectory-request-header start requires request/header') - } - const header = match.event.data.header - const tools: unknown = header.tools +/** + * Request-header fact Definition for the Trajectory target. + * @param inspect - the shared prompt interpretation, supplied by the + * uiConversation service (a client bundle cannot value-import it). + * @returns the Trajectory request-header Definition. + */ +function trajectoryRequestHeaderDefinition(inspect: RequestPromptInspector): ConversationNodeDefinition { return { - config: header.config, - system: header.system ?? '', - tools: Array.isArray(tools) ? tools as ConversationPromptSnapshot['tools'] : [], + kind: 'trajectory-request-header', + target: 'trajectory', + match: event => event.type === 'request/header' + ? { id: String(event.seq), role: 'start' } + : null, + start: (_context, match, reader) => { + if (match.event.type !== 'request/header') { + throw new Error('trajectory-request-header start requires request/header') + } + const previous = reader.previous('trajectory-request-header') + ?.state.prompt + const { prompt, change } = inspect(previous, match.event) + return { + seq: match.event.seq, + time: match.event.time, + prompt, + location: match.location, + ...(change === undefined ? {} : { change }), + } + }, + update: context => context.state, + buildViewNode: context => context.state === undefined + ? null + : trajectoryNode(context, context.state.seq, { + kind: 'request-header', + header: context.state, + }), } } -function promptChange( - previous: ConversationPromptSnapshot | undefined, - prompt: ConversationPromptSnapshot, - match: ConversationMatch, -): RequestPromptChange | undefined { - if (match.event.type !== 'request/header') return undefined - if (previous === undefined && match.event.data.reason !== 'initial') return undefined - const systemChanged = previous !== undefined && previous.system !== prompt.system - const toolsChanged = previous !== undefined - && JSON.stringify(previous.tools) !== JSON.stringify(prompt.tools) - if (previous !== undefined && !systemChanged && !toolsChanged) return undefined - return { - seq: match.event.seq, - time: match.event.time, - kind: previous === undefined - ? 'initial' - : systemChanged && toolsChanged - ? 'system-and-tools' - : systemChanged ? 'system' : 'tools', - ...(previous === undefined ? {} : { previous }), - } -} - -const trajectoryRequestHeaderDefinition: ConversationNodeDefinition = { - kind: 'trajectory-request-header', - target: 'trajectory', - match: event => event.type === 'request/header' - ? { id: String(event.seq), role: 'start' } - : null, - start: (_context, match, reader) => { - const prompt = requestPrompt(match) - const previous = reader.previous('trajectory-request-header') - ?.state.prompt - const change = promptChange(previous, prompt, match) - return { - seq: match.event.seq, - time: match.event.time, - prompt, - location: match.location, - ...(change === undefined ? {} : { change }), - } - }, - update: context => context.state, - buildViewNode: context => context.state === undefined - ? null - : trajectoryNode(context, context.state.seq, { - kind: 'request-header', - header: context.state, - }), -} - /** * Register Trajectory request-header facts. * * @param ctx - Plugin context receiving the Definition. */ export function registerTrajectoryRequestHeaderDefinition(ctx: Context): void { - ctx.uiConversation.events.register(trajectoryRequestHeaderDefinition) + ctx.uiConversation.events.register(trajectoryRequestHeaderDefinition( + (previous, event) => ctx.uiConversation.inspectRequestPrompt(previous, event), + )) } diff --git a/packages/client/ui-trajectory/src/client/trajectory-snapshot-builder.ts b/packages/client/ui-trajectory/src/client/trajectory-snapshot-builder.ts index 4c00c47568..60aed23058 100644 --- a/packages/client/ui-trajectory/src/client/trajectory-snapshot-builder.ts +++ b/packages/client/ui-trajectory/src/client/trajectory-snapshot-builder.ts @@ -1,7 +1,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { AssistantMessageNode, ConversationNode, ConversationPromptSnapshot, ConversationViewBuilder, - ConversationViewDefinition, RequestView, ToolCallBlock, + ConversationViewDefinition, RequestPromptChange, RequestView, ToolCallBlock, } from '@deepseek-ai/dsh-client-ui-conversation/client' import { COMPACTION_INTERRUPTED_ERROR } from './copy-codes.ts' import type { @@ -34,26 +34,38 @@ function headerStepKey(header: TrajectoryRequestHeaderState): string | undefined : undefined } +interface StepHeaders { + /** Latest full request snapshot in the step. */ + latest: TrajectoryRequestHeaderState + /** Latest actual prompt change in the step, retained across a later series snapshot. */ + change?: RequestPromptChange +} + function headerFor( request: AssistantRequest, - headersByStep: ReadonlyMap, + headersByStep: ReadonlyMap, previous: TrajectoryRequestHeaderState | undefined, -): TrajectoryRequestHeaderState | undefined { +): StepHeaders | undefined { return headersByStep.get(stepKey(request.turn, request.step)) - ?? (previous !== undefined && previous.seq < request.startSeq ? previous : undefined) + ?? (previous !== undefined && previous.seq < request.startSeq + ? { + latest: previous, + ...(previous.change === undefined ? {} : { change: previous.change }), + } + : undefined) } function applyHeader( request: AssistantRequest, - header: TrajectoryRequestHeaderState | undefined, + header: StepHeaders | undefined, includeChange: boolean, ): AssistantRequest { return header === undefined ? request : { ...request, - prompt: header.prompt, - requestConfig: header.prompt.config, + prompt: header.latest.prompt, + requestConfig: header.latest.prompt.config, ...(includeChange && header.change !== undefined ? { promptChange: header.change } : {}), } } @@ -174,11 +186,18 @@ export class TrajectorySnapshotBuilder implements ConversationViewBuilder< } private snapshot(): TrajectorySnapshot { - const headersByStep = new Map() + const headersByStep = new Map() for (const contribution of this.contributions) { if (contribution.data.kind !== 'request-header') continue const key = headerStepKey(contribution.data.header) - if (key !== undefined) headersByStep.set(key, contribution.data.header) + if (key === undefined) continue + const previous = headersByStep.get(key) + headersByStep.set(key, { + latest: contribution.data.header, + ...(contribution.data.header.change !== undefined + ? { change: contribution.data.header.change } + : previous?.change === undefined ? {} : { change: previous.change }), + }) } const finalized: ConversationNode[] = [] const eventLocations = new Map() @@ -213,13 +232,14 @@ export class TrajectorySnapshotBuilder implements ConversationViewBuilder< const header = data.request === undefined ? undefined : headerFor(data.request, headersByStep, previousHeader) - if (data.node !== undefined) finalized.push(withRequestConfig(data.node, header?.prompt)) + if (data.node !== undefined) finalized.push(withRequestConfig(data.node, header?.latest.prompt)) if (data.partial !== null) partial = data.partial if (data.request !== undefined) { - const includeChange = header?.change !== undefined - && !consumedPromptChanges.has(header.seq) + const change = header?.change + const includeChange = change !== undefined + && !consumedPromptChanges.has(change.seq) requests.push(applyHeader(data.request, header, includeChange)) - if (includeChange) consumedPromptChanges.add(header.seq) + if (includeChange) consumedPromptChanges.add(change.seq) } continue } diff --git a/packages/client/ui-trajectory/tests/conversation-definitions.client.spec.ts b/packages/client/ui-trajectory/tests/conversation-definitions.client.spec.ts index a454431d01..788b42f845 100644 --- a/packages/client/ui-trajectory/tests/conversation-definitions.client.spec.ts +++ b/packages/client/ui-trajectory/tests/conversation-definitions.client.spec.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import type { ConversationEventInput, ConversationNodeDefinition, ConversationViewDefinition, } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { ConversationNodeAssembler } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { ConversationNodeAssembler, inspectRequestPrompt } from '@deepseek-ai/dsh-client-ui-conversation/client' import { registerTrajectoryAssistantDefinition } from '../src/client/trajectory-assistant-definition.ts' import { registerTrajectoryCompactionDefinitions } from '../src/client/trajectory-compaction-definition.ts' import type { TrajectorySnapshot } from '../src/client/trajectory-contract.ts' @@ -21,6 +21,7 @@ const registrationContext = { return () => {} }, }, + inspectRequestPrompt, }, } as unknown as Context diff --git a/packages/client/ui-trajectory/tests/snapshot-builder.client.spec.ts b/packages/client/ui-trajectory/tests/snapshot-builder.client.spec.ts index 59eec5f679..f472455e55 100644 --- a/packages/client/ui-trajectory/tests/snapshot-builder.client.spec.ts +++ b/packages/client/ui-trajectory/tests/snapshot-builder.client.spec.ts @@ -109,6 +109,65 @@ describe('TrajectorySnapshotBuilder', () => { : undefined)).toEqual(['initial', undefined]) }) + it('retains a same-step prompt change when a later series header supplies the latest snapshot', () => { + const initial = { + config: { provider: 'test', model: 'test' }, + system: 'initial prompt', + tools: [], + } + const changed = { ...initial, system: 'changed prompt' } + const nodes: TrajectoryConversationViewNode[] = [ + contribution('header:initial', 2, { + kind: 'request-header', + header: { + seq: 2, + time: 2, + prompt: initial, + change: { seq: 2, time: 2, kind: 'initial' }, + location: { kind: 'session' }, + }, + }), + contribution('assistant:1', 3, { + kind: 'assistant', + partial: null, + request: assistantRequest(3, 1), + }), + contribution('header:change', 5, { + kind: 'request-header', + header: { + seq: 5, + time: 5, + prompt: changed, + change: { seq: 5, time: 5, kind: 'system', previous: initial }, + location: stepLocation(1, 2), + }, + }), + contribution('header:series', 6, { + kind: 'request-header', + header: { + seq: 6, + time: 6, + prompt: changed, + location: stepLocation(1, 2), + }, + }), + contribution('assistant:2', 7, { + kind: 'assistant', + partial: null, + request: assistantRequest(7, 2), + }), + ] + + const snapshot = new TrajectorySnapshotBuilder().replace({ nodes }) + + expect(snapshot.requests.map(request => request.purpose === 'assistant' + ? request.prompt?.system + : undefined)).toEqual(['initial prompt', 'changed prompt']) + expect(snapshot.requests.map(request => request.purpose === 'assistant' + ? request.promptChange?.seq + : undefined)).toEqual([2, 5]) + }) + it('indexes exact step headers and the active tool schema without backward scans', () => { const basePrompt = { config: { provider: 'test', model: 'base' }, diff --git a/packages/context/agent-instructions/src/index.ts b/packages/context/agent-instructions/src/index.ts index 1b00960adb..ab68bce9d0 100644 --- a/packages/context/agent-instructions/src/index.ts +++ b/packages/context/agent-instructions/src/index.ts @@ -344,7 +344,7 @@ export function apply(ctx: Context, config: Config): void { // precedes it and the driver-appended runtime context follows it. const lastClaimedIndex = decision.messages.findLastIndex(message => messages.includes(message)) const entered = decision.messages.toSpliced(lastClaimedIndex + 1, 0, desired) - return { kind: 'enter', messages: entered } + return { ...decision, messages: entered } }) ctx.on('tools/result', (exec: ToolExecution, result: ToolExecutionResult) => { diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index 36d443d67a..c2b1adf3ea 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -107,7 +107,7 @@ export class SessionReferenceResolver extends TypertRemoteService { const decision = await next() if (decision.kind === 'reject') return decision return { - kind: 'enter', + ...decision, messages: await this.prepareDirectMessages(agent, decision.messages, signal), } }, { prepend: true }) diff --git a/packages/context/time-context/src/index.ts b/packages/context/time-context/src/index.ts index a317544a3c..b8320c2d50 100644 --- a/packages/context/time-context/src/index.ts +++ b/packages/context/time-context/src/index.ts @@ -196,7 +196,7 @@ export function apply(ctx: Context, config: Config): void { browser, ) return { - kind: 'enter', + ...decision, messages: [ ...decision.messages, createUserMessage({ diff --git a/packages/context/tmux-context/src/index.ts b/packages/context/tmux-context/src/index.ts index 10ac6a6ab6..0425bc69de 100644 --- a/packages/context/tmux-context/src/index.ts +++ b/packages/context/tmux-context/src/index.ts @@ -234,7 +234,7 @@ export function apply(ctx: Context, config: Config): void { if (previous !== undefined && previous.state === state) return decision const text = renderReading(location, turn) return { - kind: 'enter', + ...decision, messages: [ createUserMessage({ content: [{ type: 'text', text }], diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 88d4e6da7d..9fe9297155 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent-loop/README.md -README.md: 1b233ae1203171930ef5b58de93ec67381ec4918 -README.zh.md: 81af654072f23c5280e2e14bc891972b5e1f37d5 +README.md: 8b35b970aac93ac3c20fe570c79c3524abbe079f +README.zh.md: 4a11d81e6cbdbce1c1e7997785a2cf4456609171 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 1b233ae120..8b35b970aa 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -66,7 +66,7 @@ The driver owns one agent for its lifetime and runs inside `ctx.agents.withIniti Every provider call that reaches a successful finish appends exactly one `assistant/message` completion anchor, including content-less calls and `max-tokens` finishes. The anchor records the assembled content as-is, lists the exact chunk seqs in `sourceEventSeqs` (`[]` for a stream with no chunks), and includes usage when available; empty content stays out of derived message history. A turn cancellation that interrupts streaming also appends an `interrupted: true` anchor when non-empty text or reasoning has reached the user. The anchor cites those chunk seqs and places the rendered prefix in derived message history, so the next request contains what the user saw. Undispatched tool calls are omitted, and an empty or tool-only stream produces no anchor; provider failures still commit no assistant content ([decision](../../../.agents/notes/implemented/architecture/2026-08-10-cancelled-stream-prefix-finalize.md)). -After `agent/request` returns a provider/model call config, the loop asks `ctx.llm.prepareCall()` to validate adapter-owned fields and materialize configured reasoning-effort and output-token defaults under the active turn signal. The prepared call retains the exact adapter registration across this asynchronous resolution, `request/header` logging, and terminal dispatch, so HMR cannot mix one adapter's capability result with another adapter's request. The header records the effective config and which fields came from the adapter. Before the next waterfall, the loop removes those marked fields from the proposal so the current exact route rematerializes its own defaults; unmarked explicit settings persist across steps and route changes. A route with no registered adapter preserves the proposed config so an `llm/stream` listener can own and short-circuit it; unhandled terminal dispatch still fails with `NO_ADAPTER`. A new loop instance follows the same adapter-default marker rule when resuming. +After `agent/request` returns a provider/model call config, the loop asks `ctx.llm.prepareCall()` to validate adapter-owned fields and materialize configured reasoning-effort and output-token defaults under the active turn signal. The prepared call retains the exact adapter registration across this asynchronous resolution, `request/header` logging, and terminal dispatch, so HMR cannot mix one adapter's capability result with another adapter's request. The header records the effective config and which fields came from the adapter. The loop appends a full snapshot for its first request, for a changed header, and when an unchanged header begins an explicitly declared message series or the first request after a surface replacement. A changed header that also begins a series carries `startsSeries: true`; further same-series Steps, ordinary later Turns, and retries with an unchanged header inherit the latest snapshot. Before the next waterfall, the loop removes adapter-marked fields from the proposal so the current exact route rematerializes its own defaults; unmarked explicit settings persist across steps and route changes. A route with no registered adapter preserves the proposed config so an `llm/stream` listener can own and short-circuit it; unhandled terminal dispatch still fails with `NO_ADAPTER`. A new loop instance follows the same adapter-default marker rule and appends a `resume` snapshot. Plugin failure ends the current turn, not the loop. Final adapter selection, dispatch, and iteration failures arrive from `ctx.llm` as terminal error or aborted finishes and enter `agent/request-error`; middleware, result processing, tools, and other extension failures remain thrown and close directly. Recovery receives request coordinates, immutable provider facts, the immutable retry policy captured by the prepared adapter registration, and the turn signal; the policy is absent when middleware owns an unprepared route. A handling listener returns `{ kind: 'retry' }`; an unhandled failure is terminal. AgentLoop owns one cancellation signal for the current admission or turn. An effective `cancel(cause)` clears pending work unless `keepInbox` is set and cooperatively aborts that signal; idle cancellation is a no-op. Waking input that lands after the abort fires but before the activity converges to idle is latched (`wakeRequested`) and replayed at the driver's own convergence boundary, so it runs without a further waking send; a `disposed` cancel never latches, and a wake submitted while already idle always opens its turn boundary (status shows a transient `idle → running → idle` pair even when the message was cleared). Durable `turn/end` records `aborted` for `user` and `parent`, while disposal records `disposed`; undispatched model tool calls receive synthetic `tool/call` and `ABORTED_BEFORE_DISPATCH` result pairs. The cancellation cause changes reporting, not how result context finalized after cancellation is handled. Disposal waits for signal-ignoring work before registry removal. The [explicit-cancellation decision](../../../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md) and the [cancel-convergence wake latch](../../../.agents/notes/implemented/bug-fix/2026-08-07-cancel-convergence-wake-latch.md) own the lifecycle and race contract. diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 81af654072..4a11d81e6c 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -66,7 +66,7 @@ interface Config { 每次提供方调用成功结束时,都会恰好追加一个 `assistant/message` 完成锚点,包括无内容调用和以 `max-tokens` 结束的调用。该锚点原样记录组装后的内容,在 `sourceEventSeqs` 中列出确切的分片 seq(流没有分片时为 `[]`),并在用量可用时包含用量;空内容不会进入派生消息历史。轮次取消打断流式输出时,如果非空文本或推理内容已送达用户,循环也会追加一个带 `interrupted: true` 的锚点。该锚点引用对应的分片 seq,并把已渲染的前缀放入派生消息历史,使下一次请求包含用户看到的内容。未分派的工具调用会被省略,空流或只包含工具调用的流不会生成锚点;提供方故障也不提交 assistant 内容([决策](../../../.agents/notes/implemented/architecture/2026-08-10-cancelled-stream-prefix-finalize.zh.md))。 -在 `agent/request` 返回提供方/模型调用配置后,循环会调用 `ctx.llm.prepareCall()`,在活跃轮次信号的控制下校验由适配器负责的字段,并填入配置的推理(reasoning)强度和输出 token 默认值。准备完成的调用会在这次异步解析、`request/header` 日志记录和最终分派期间保留同一项确切的适配器注册,因此 HMR(热模块替换)不会把某个适配器的能力解析结果与另一适配器的请求混用。请求 header 会记录生效配置以及哪些字段来自适配器。下一次 waterfall(瀑布式事件)前,循环会从提议中移除这些带标记字段,使当前精确路由重新填入自身默认值;未带标记的显式设置会跨步骤和路由变化保留。没有已注册适配器的路由会保留原定配置,使 `llm/stream` 监听器可以接管并短路该请求;最终分派仍会以 `NO_ADAPTER` 拒绝未得到处理的路由。新循环实例在恢复时会遵循同一套适配器默认值标记规则。 +在 `agent/request` 返回提供方/模型调用配置后,循环会调用 `ctx.llm.prepareCall()`,在活跃轮次信号的控制下校验由适配器持有的字段,并填入配置的推理(reasoning)强度和输出 token 默认值。准备完成的调用会在这次异步解析、`request/header` 日志记录和最终分派期间保留同一项确切的适配器注册,因此 HMR(热模块替换)不会把某个适配器的能力解析结果与另一适配器的请求混用。请求 header 会记录生效配置以及哪些字段来自适配器。循环会为实例的首个请求、发生变化的 header,以及显式声明的新消息序列或表层替换后的首个请求中内容未变的 header 追加完整快照。如果变化的 header 同时开启序列,它会携带 `startsSeries: true`;同一序列内 header 未变的后续 Step、普通后续 Turn 与重试继承最新快照。下一次 waterfall(瀑布式事件)前,循环会从提议中移除由适配器标记的字段,使当前精确路由重新填入自身默认值;未带标记的显式设置会跨步骤和路由变化保留。没有已注册适配器的路由会保留原定配置,使 `llm/stream` 监听器可以接管并短路该请求;最终分派仍会以 `NO_ADAPTER` 拒绝未得到处理的路由。新循环实例在恢复时会遵循同一套适配器默认值标记规则,并追加 `resume` 快照。 插件失败会结束当前轮次,而不是结束循环。最终适配器选择、分发与迭代失败会以终止错误或中止结束的形式由 `ctx.llm` 传来,并进入 `agent/request-error`;middleware、结果处理、工具及其他扩展失败仍会抛出并直接关闭轮次。恢复逻辑会接收请求坐标、不可变的提供方事实、准备完成的适配器注册所捕获的不可变重试策略以及轮次信号;middleware 接管未准备路由时,该策略缺失。处理失败的监听器返回 `{ kind: 'retry' }`;未被处理的失败是终态。AgentLoop 为当前准入操作或轮次拥有一个取消信号。有效的 `cancel(cause)` 在未设置 `keepInbox` 时清除待处理工作,并以协作方式中止该信号;空闲取消是空操作。abort 触发后、活动收敛到空闲前到达的唤醒输入会被锁存(`wakeRequested`),并在 driver 自身的收敛边界重放,无需再发一条唤醒 send 即可执行;`disposed` 取消从不锁存,而 agent 已处于空闲时发送的唤醒总是打开自己的 turn 边界(即使消息已被清除,状态也会显示瞬态 `idle → running → idle` 对)。持久 `turn/end` 为 `user` 和 `parent` 记录 `aborted`,dispose 则记录 `disposed`;未分发的模型工具调用会收到合成的 `tool/call` 与 `ABORTED_BEFORE_DISPATCH` 结果对。取消原因只影响报告方式,不影响如何处理在取消后完成终结的结果上下文。dispose 会等待忽略信号的工作完成,然后才从注册表移除。[显式取消决策](../../../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.zh.md)与[取消收敛窗口唤醒锁存](../../../.agents/notes/implemented/bug-fix/2026-08-07-cancel-convergence-wake-latch.zh.md)规定生命周期与竞态约定。 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 6bf7517903..0d3af9663b 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -49,7 +49,12 @@ type StepEndReason = Extract { + private async step(assembly: PromptAssembly, startsRequestSeries: boolean): Promise { /* v8 ignore next -- private callers establish the running phase before executing a step */ if (this.phase.kind !== 'running') throw new Error(`agent "${this.id}": step outside running phase`) const { turn, step, abort: { signal } } = this.phase @@ -337,9 +344,18 @@ export class ReactLoopAgent implements Agent { const system = renderPrompt(assembly) while (true) { + const surfaceGeneration = this.session.surface.replaceGeneration const { request, preparedCall } = await this.buildRequest( - turn, step, assembly.tools, system, this.session.deriveMessages(), signal, + turn, + step, + assembly.tools, + system, + this.session.deriveMessages(), + startsRequestSeries, + surfaceGeneration, + signal, ) + startsRequestSeries = false const assembler = new BlockAssembler() const chunkSeqs: number[] = [] try { @@ -429,6 +445,8 @@ export class ReactLoopAgent implements Agent { tools: GenerateOptions['tools'] & object, system: string, boundaryMessages: Message[], + startsRequestSeries: boolean, + surfaceGeneration: number, signal: AbortSignal, ): Promise<{ request: GenerateOptions; preparedCall?: PreparedLlmCall }> { const { session } = this @@ -482,12 +500,21 @@ export class ReactLoopAgent implements Agent { ...tools.length > 0 ? { tools } : {}, }) const baseline = this.session.requestHeader() + const startsSeries = startsRequestSeries + || this.requestSurfaceGeneration !== surfaceGeneration if (!this.requestHeaderLogged) { this.session.append('request/header', { header, reason: baseline === undefined ? 'initial' : 'resume' }) this.requestHeaderLogged = true } else if (baseline === undefined || !headerEquals(baseline, header)) { - this.session.append('request/header', { header, reason: 'change' }) + this.session.append('request/header', { + header, + reason: 'change', + ...startsSeries ? { startsSeries: true } : {}, + }) + } else if (startsSeries) { + this.session.append('request/header', { header, reason: 'series' }) } + this.requestSurfaceGeneration = surfaceGeneration const contextWindow = preparedCall?.context?.contextWindow const requestContext: RequestContext = { diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index 4082b43452..a8beb82622 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -435,7 +435,8 @@ describe('agent loop', () => { await waitForIdle(ctx, agent) expect(contextEvents()).toHaveLength(3) expect(adapter.requests.map(request => request.system)).toEqual(Array(5).fill(adapter.requests[0]?.system)) - expect(agent.session.events.filter(event => event.type === 'request/header')).toHaveLength(1) + expect(agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial']) }) it('re-emits unchanged runtime context when a surface replacement removed the retained snapshot', async () => { diff --git a/packages/core/agent-loop/tests/request-error.spec.ts b/packages/core/agent-loop/tests/request-error.spec.ts index 9d1c2a42c3..092ede6eb5 100644 --- a/packages/core/agent-loop/tests/request-error.spec.ts +++ b/packages/core/agent-loop/tests/request-error.spec.ts @@ -96,6 +96,8 @@ describe('agent/request-error', () => { expect.objectContaining({ mode: 'normal' }), ]) expect(statuses).toEqual(['running', 'idle']) + expect(agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial']) }) it('lets cancellation win over a retry action', async () => { diff --git a/packages/core/agent-loop/tests/request-reconstruction.spec.ts b/packages/core/agent-loop/tests/request-reconstruction.spec.ts index 287e73303c..a53f0e50a5 100644 --- a/packages/core/agent-loop/tests/request-reconstruction.spec.ts +++ b/packages/core/agent-loop/tests/request-reconstruction.spec.ts @@ -109,6 +109,91 @@ describe('request stability across the loop', () => { expect(adapter.requests).toHaveLength(2) expectPrefixExtension(adapter.requests[0]!, adapter.requests[1]!) + expect(agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial']) + }) + + it('starts a new request series only when the admitted step explicitly asks for one', async () => { + const adapter = new MockAdapter([textResponse('one'), textResponse('two')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) + ctx.on('agent/pre-step', async ({ turn }, next) => { + const decision = await next() + return decision.kind === 'enter' && turn === 2 + ? { ...decision, startsRequestSeries: true } + : decision + }) + + send(agent, 'first') + await waitForIdle(ctx, agent) + send(agent, 'second series') + await waitForIdle(ctx, agent) + + expectPrefixExtension(adapter.requests[0]!, adapter.requests[1]!) + expect(agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial', 'series']) + }) + + it('retains the explicit series boundary when that request also changes its header', async () => { + const adapter = new MockAdapter([textResponse('one'), textResponse('two')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) + ctx.on('agent/pre-step', async ({ turn }, next) => { + const decision = await next() + return decision.kind === 'enter' && turn === 2 + ? { ...decision, startsRequestSeries: true } + : decision + }) + ctx.on('agent/request', async ({ turn }, next) => { + const config = await next() + return turn === 2 ? { ...config, maxTokens: 1_024 } : config + }) + + send(agent, 'first') + await waitForIdle(ctx, agent) + send(agent, 'second series') + await waitForIdle(ctx, agent) + + expectPrefixExtension(adapter.requests[0]!, adapter.requests[1]!) + expect(agent.session.events.flatMap(event => event.type === 'request/header' + ? [{ reason: event.data.reason, startsSeries: event.data.startsSeries }] + : [])).toEqual([ + { reason: 'initial', startsSeries: undefined }, + { reason: 'change', startsSeries: true }, + ]) + }) + + it('keeps the series declaration when an outer listener rebuilds the enter decision', async () => { + const adapter = new MockAdapter([textResponse('one'), textResponse('two')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) + // Context-appending wrapper in the tool-cordis / session-reference shape: + // it rebuilds the downstream decision, so it must spread it to keep fields + // it does not own — a bare `{ kind: 'enter', messages }` drops the series. + ctx.on('agent/pre-step', async (_payload, next) => { + const decision = await next() + if (decision.kind === 'reject') return decision + const appended = createUserMessage({ + content: [{ type: 'text', text: 'appended reference context' }], + source: { kind: 'plugin', plugin: 'outer-wrapper' }, + }) + return { ...decision, messages: [...decision.messages, appended] } + }, { prepend: true }) + ctx.on('agent/pre-step', async ({ turn }, next) => { + const decision = await next() + return decision.kind === 'enter' && turn === 2 + ? { ...decision, startsRequestSeries: true } + : decision + }) + + send(agent, 'first') + await waitForIdle(ctx, agent) + send(agent, 'second series') + await waitForIdle(ctx, agent) + + expectPrefixExtension(adapter.requests[0]!, adapter.requests[1]!) + expect(agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial', 'series']) }) it('logs adapter defaults, supports per-turn effort changes, and restores the effective value', async () => { @@ -407,6 +492,10 @@ describe('request stability across the loop', () => { const adapter = new MockAdapter([textResponse('one'), textResponse('two')]) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) + ctx.on('agent/request', async ({ turn }, next) => { + const config = await next() + return turn === 2 ? { ...config, maxTokens: 1_024 } : config + }) send(agent, 'first') await waitForIdle(ctx, agent) @@ -426,11 +515,49 @@ describe('request stability across the loop', () => { const second = adapter.requests[1]! // The rewritten history: summary replaces turn 1's user+assistant pair. expect(second.messages[0]!.content.some(b => b.type === 'text' && b.text.includes('[summary of turn 1]'))).toBe(true) - // No header event beyond the anchor: the replace is itself in the log. - expect(agent.session.events.filter(e => e.type === 'request/header')).toHaveLength(1) + expect(agent.session.events.flatMap(event => event.type === 'request/header' + ? [{ reason: event.data.reason, startsSeries: event.data.startsSeries }] + : [])).toEqual([ + { reason: 'initial', startsSeries: undefined }, + { reason: 'change', startsSeries: true }, + ]) }) - it('a real system-prompt change is a full changed-header snapshot; a stable prompt logs nothing', async () => { + it('starts a new request series when compaction rewrites a retry in the same step', async () => { + const adapter = new MockAdapter([ + () => { throw new LlmError('request is too large', 'CONTEXT_LENGTH') }, + textResponse('recovered'), + ]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(SessionId('same-step-compaction'), { + provider: 'mock', + model: 'mock', + }) + ctx.on('agent/request-error', async ({ agent: subject }) => { + const first = subject.session.surface.nodes[0] + if (first === undefined) throw new Error('request has no surface message to compact') + subject.session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: '[summary for retry]' }], + source: { kind: 'plugin', plugin: 'test-compact' }, + }), { + surfaceOp: { op: 'replace', start: first, end: first }, + sourceEventSeqs: [first], + }) + return { kind: 'retry' } + }) + + send(agent, 'first series') + await waitForIdle(ctx, agent) + + expect(adapter.requests).toHaveLength(2) + expect(adapter.requests[1]?.messages[0]?.content).toContainEqual({ + type: 'text', text: '[summary for retry]', + }) + expect(agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial', 'series']) + }) + + it('a real system-prompt change is a full changed-header snapshot; a stable new turn reuses it', async () => { const adapter = new MockAdapter([textResponse('one'), textResponse('two'), textResponse('three')]) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) @@ -439,8 +566,8 @@ describe('request stability across the loop', () => { await waitForIdle(ctx, agent) send(agent, 'second') await waitForIdle(ctx, agent) - // Identical assembly re-rendered per step is NOT a change. - expect(agent.session.events.filter(e => e.type === 'request/header')).toHaveLength(1) + expect(agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial']) ctx.systemPrompt.section({ name: 'extra', order: 2, text: 'new guidance' }) send(agent, 'third') @@ -556,9 +683,10 @@ describe('request stability across the loop', () => { send(agent, 'second') await waitForIdle(ctx, agent) - // No changed snapshot was logged (nothing really changed), and the session's own - // fold is immutable state. - expect(agent.session.events.filter(e => e.type === 'request/header')).toHaveLength(1) + // The second turn reuses the same series and header; the session's own + // fold remains immutable state. + expect(agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial']) expect(Object.isFrozen(agent.session.requestHeader())).toBe(true) expect(adapter.requests[1]!.temperature).toBeUndefined() }) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index a9d78f3fad..91cbc2a275 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent/README.md -README.md: 70b396d787de5d95332c379ff20ab92c64065857 -README.zh.md: fee72f3cd1fb456ae639d6444fe3fe914c41220a +README.md: b79a1e7270eaf5b50a05059ecbea760c0888bc1e +README.zh.md: aa4b6a471711a94665b171e06da638fc86c7a39c diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 70b396d787..b79a1e7270 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -52,7 +52,7 @@ The lifecycle edges have two important local caveats. `agent/created` runs after Most interception points are cooperative waterfalls. `agent/pre-step` receives a payload carrying the subject `agent`, the exclusive claimed `UserMessage[]`, and the proposed `turn`, `step`, and cancellation `signal`; its batch may be empty when tools already require another request. Agent-scoped turn extension points carry their explicit `AbortSignal` in the payload; the remaining turn-scoped extension points receive it through their request value. Listeners may cooperate with a signal but must not retain it as authority over another turn. `agent/request-error` is the failed-model-request recovery waterfall: it receives request coordinates, normalized failure facts, the serving registration's retry policy when available, and the signal. A listener returns `{ kind: 'retry' }` without calling `next()` when it owns recovery. `agent/turn-stopping` runs before an otherwise completed turn closes. The [explicit-cancellation decision](../../../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.md) owns signal lifetime; the [agent-scope runtime-design Agent Note](../../../.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.md#three-execution-boundaries-are-deliberately-one-way) owns scoped dispatch and terminal settlement. -`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages }`. The enter branch is the complete identified, frozen batch for the proposed step. A listener that wraps downstream entry preserves that batch unless it intentionally replaces it; additions follow the waterfall's natural return order. Claiming already removed the offered messages from the inbox, so rejection does not retain them. Messages inserted after the claim remain pending for a later boundary. +`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch is the complete identified, frozen batch for the proposed step. `startsRequestSeries: true` declares that this admitted batch begins a distinct model-message series; ordinary follow-ups leave it absent. A listener that wraps downstream entry preserves both that declaration and the batch unless it intentionally replaces either one; additions follow the waterfall's natural return order. Claiming already removed the offered messages from the inbox, so rejection does not retain them. Messages inserted after the claim remain pending for a later boundary. Inbox live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. They complement the durable `agent/inbox/spliced` projection without adding another lifecycle envelope. diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index fee72f3cd1..aa4b6a4717 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -54,7 +54,7 @@ Agent *创建* 由实现 `AgentFactory` 的插件(`dsh-agent-loop`)提供, 大多数拦截点都是协作式 waterfall(瀑布式事件)。`agent/pre-step` 接收一个 payload,携带主体 `agent`、独占的已领取 `UserMessage[]` 以及拟进入的 `turn`、`step` 与取消 `signal`;当工具已经要求继续请求时,该批次可以为空。agent 作用域轮次扩展点在 payload 中携带显式 `AbortSignal`;其余轮次作用域扩展点通过其请求值接收它。监听器可以配合信号,但不得将它保留为控制另一轮次的权限。`agent/request-error` 是失败模型请求的恢复 waterfall:它接收请求坐标、规范化失败事实、可用时提供服务的注册项重试策略以及信号。拥有恢复权的监听器返回 `{ kind: 'retry' }` 且不调用 `next()`。`agent/turn-stopping` 在本可完成的轮次关闭前运行。信号生命周期由[显式取消决策](../../../.agents/notes/implemented/architecture/2026-07-16-explicit-turn-cancellation.zh.md)拥有;作用域分发与终止结算由 [agent 作用域 runtime 设计 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-12-agent-scope-runtime-design.zh.md#three-execution-boundaries-are-deliberately-one-way)拥有。 -`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages }`。enter 分支是拟进入步骤的完整、带标识且冻结的批次。包装下游 enter 的监听器会保留该批次,除非有意替换它;新增消息遵循 waterfall 的自然返回顺序。领取操作已经把候选消息从 inbox 删除,因此 reject 不会保留它们;领取后插入的消息仍等待后续边界。 +`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支是拟进入步骤的完整、带标识且冻结的批次。`startsRequestSeries: true` 声明该接纳批次会开启一个独立的模型消息序列;普通 follow-up 不设置它。包装下游 enter 的监听器会同时保留该声明和消息批次,除非有意替换其中一项;新增消息遵循 waterfall 的自然返回顺序。领取操作已经把候选消息从 inbox 删除,因此 reject 不会保留它们;领取后插入的消息仍等待后续边界。 inbox 的实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。它们补充持久 `agent/inbox/spliced` 投影,但不引入另一层生命周期封套。 diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 3f8f7c512b..c8bc08ecbb 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -55,7 +55,12 @@ export type AgentStatus = 'idle' | 'running' /** Whether and with which messages the loop enters a proposed step. */ export type PreStepDecision = | { kind: 'reject' } - | { kind: 'enter'; messages: UserMessage[] } + | { + kind: 'enter' + messages: UserMessage[] + /** Start a distinct model-message series before this step's admitted messages. */ + startsRequestSeries?: true + } /** Action returned by a listener that owns model-request recovery. */ export type RequestErrorAction = { kind: 'retry' } | undefined diff --git a/packages/core/session/README.i18n.yaml b/packages/core/session/README.i18n.yaml index 15704ada90..482c7c5c89 100644 --- a/packages/core/session/README.i18n.yaml +++ b/packages/core/session/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/session/README.md -README.md: 9f0b4023e897f66ec1bcbc22e908ab2bf1c0d2cc -README.zh.md: dcee2380802c6b7e416366a9388256f9b1d02091 +README.md: 0e3cdcb1e0135cda4d1ac469a0cbc2c2f44c3d94 +README.zh.md: 383777227fa5903c0e7285d31e8d70ee9ebb1eab diff --git a/packages/core/session/README.md b/packages/core/session/README.md index 9f0b4023e8..0e3cdcb1e0 100644 --- a/packages/core/session/README.md +++ b/packages/core/session/README.md @@ -60,7 +60,7 @@ This package owns ordered surface projection, replacement validation, replay, an ### Request-header reconstruction (`request-header.ts`) -`request/header` records a full canonical snapshot of the non-history request envelope with reason `initial`, `resume`, or `change`. Its optional `adapterDefaults` map marks effective `reasoningEffort` or `maxTokens` values materialized by exact-model resolution, allowing the next request proposal to distinguish them from explicit conversation settings. `foldRequestHeader()` selects the latest snapshot; legacy delta events and the removed `fallback` reason are rejected. See the [reconstructable-requests Agent Note](../../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md). +`request/header` records a full canonical snapshot of the non-history request envelope with reason `initial`, `resume`, `change`, or `series`. `series` repeats an unchanged envelope when `agent/pre-step` explicitly starts a distinct model-message series or a surface replacement changes the model's message list; when that boundary coincides with an envelope change, the `change` snapshot carries `startsSeries: true` so both facts survive. Ordinary append-only later turns remain in the current series. Same-series steps and retries with an unchanged envelope keep using the latest snapshot. Repeating the complete system prompt and tool catalog grows the log linearly with message series, but keeps every header self-contained for partial-window rendering and exact request reconstruction; a lightweight reference marker would require predecessor availability and a second replay representation. Its optional `adapterDefaults` map marks effective `reasoningEffort` or `maxTokens` values materialized by exact-model resolution, allowing the next request proposal to distinguish them from explicit conversation settings. `foldRequestHeader()` selects the latest snapshot; legacy delta events and the removed `fallback` reason are rejected. See the [reconstructable-requests Agent Note](../../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md). A `user/message` stores the complete `UserMessage` directly, including the identity created before inbox routing or step entry. It renders its `content` verbatim whether it is a direct human prompt, a synthetic injection, or an entered goal round; its typed `source` is the only channel that tells them apart and carries any domain-specific durable facts. `assistant/message` and `tool/result` likewise store complete message values. Turn execution remains enclosed by `turn/start` and `turn/end`; `agent.inject()` queues input until a later pre-step claims it and returns it in an enter decision. diff --git a/packages/core/session/README.zh.md b/packages/core/session/README.zh.md index dcee238080..383777227f 100644 --- a/packages/core/session/README.zh.md +++ b/packages/core/session/README.zh.md @@ -60,7 +60,7 @@ ### 请求头重建(`request-header.ts`) -`request/header` 记录非历史请求封装的完整规范快照,其原因为 `initial`、`resume` 或 `change`。其可选 `adapterDefaults` 映射会标记由精确模型解析填入的生效 `reasoningEffort` 或 `maxTokens` 值,使下一次请求提议能够将它们与显式对话设置区分开。`foldRequestHeader()` 选择最新快照;旧版增量事件和已移除的 `fallback` 原因会被拒绝。详见[可重建请求 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md)。 +`request/header` 记录非历史请求封装的完整规范快照,其原因为 `initial`、`resume`、`change` 或 `series`。当 `agent/pre-step` 显式开启独立的模型消息序列,或表层替换改变模型消息列表时,`series` 会重复记录内容未变的封装;如果该边界与封装变化同时发生,`change` 快照会携带 `startsSeries: true`,从而同时保留这两个事实。普通的仅追加后续 turn 仍属于当前序列。同一序列内封装未变的 step 和重试继续使用最新快照。重复完整系统提示词和工具目录会使日志随消息序列线性增长,但能让每个 header 自包含,以支持局部窗口渲染和精确请求重建;轻量引用标记则会要求前序始终可用,并引入第二种回放表示。其可选 `adapterDefaults` 映射会标记由精确模型解析填入的生效 `reasoningEffort` 或 `maxTokens` 值,使下一次请求提议能够将它们与显式对话设置区分开。`foldRequestHeader()` 选择最新快照;旧版增量事件和已移除的 `fallback` 原因会被拒绝。详见[可重建请求 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md)。 `user/message` 会直接存储完整的 `UserMessage`,其中包括收件箱路由或进入步骤前创建的标识。无论它是直接人类提示词、合成注入,还是已进入的 Goal Round,都会原样呈现其 `content`;带类型的 `source` 是区分三者的唯一通道,并携带各领域专有的持久事实。`assistant/message` 和 `tool/result` 也会存储完整的消息值。轮次执行仍由 `turn/start` 与 `turn/end` 包围;`agent.inject()` 会把输入排队,直到后续某次 pre-step 领取它,并在 enter 决策中返回它。 diff --git a/packages/core/session/src/types.ts b/packages/core/session/src/types.ts index 85ff73bf04..f331924b2f 100644 --- a/packages/core/session/src/types.ts +++ b/packages/core/session/src/types.ts @@ -206,9 +206,11 @@ export interface RequestContext { * Why a `request/header` snapshot was appended: `'initial'` — the log's first * header (a new conversation); `'resume'` — a loop instance's first request * over a log that already has header events (process restart, fork seed); - * `'change'` — a later request used a different header. + * `'change'` — a later request used a different header, with `startsSeries` + * preserving a coincident series boundary; `'series'` — an unchanged header + * began an explicitly distinct message series or followed a surface replacement. */ -export type RequestHeaderReason = 'initial' | 'resume' | 'change' +export type RequestHeaderReason = 'initial' | 'resume' | 'change' | 'series' /** * The merge-extensible, append-only source of truth for an agent interaction. @@ -286,7 +288,12 @@ export interface SessionEventMap { * Full header for the next request, appended inside its step before dispatch. * It is log-only; the latest snapshot reconstructs the request header. */ - 'request/header': { header: EpochHeader; reason: RequestHeaderReason } + 'request/header': { + header: EpochHeader + reason: RequestHeaderReason + /** A changed header also begins a distinct model-message series. */ + startsSeries?: true + } /** * Route metadata for the next request, logged only when the route or capacity * changes. It does not participate in request reconstruction or header equality. diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index c9f2019f62..189991fd0d 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -287,7 +287,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'useProjection: UseProjection', 'useTrajectory: UseTrajectory', ], - keyDomain: 'fixed by the owner\'s key table { [Kind in ChatNodeKind]: { node: ChatNode } }, already taken: assistant-step, command, command-input, compaction, context, manual-compaction, model-retry, steering, tool-call, turn-error, turn-max-tokens, turn-tail, unknown, user, workflow-run', + keyDomain: 'fixed by the owner\'s key table { [Kind in ChatNodeKind]: { node: ChatNode } }, already taken: assistant-step, command, command-input, compaction, context, manual-compaction, model-retry, steering, system-prompt, tool-call, turn-error, turn-max-tokens, turn-tail, unknown, user, workflow-run', hookContext: 'string', slotInject: 'ChatNodeTurnDataInjected', declaredBy: 'an entry in \'conversation.view\' (client-ui-chat), so it exists while that entry is mounted', @@ -295,6 +295,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ 'client-ui-chat UserMessageNodeView key \'user\'', 'client-ui-chat UserMessageNodeView key \'steering\'', 'client-ui-chat ContextMessageNodeView key \'context\'', + 'client-ui-chat SystemPromptNodeView key \'system-prompt\'', 'client-ui-chat AssistantNodeView key \'assistant-step\'', 'client-ui-chat CommandNodeView key \'command\'', 'client-ui-chat ManualCompactionNodeView key \'manual-compaction\'', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 89b1cb6d77..66f5bd3058 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4171,7 +4171,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'PreStepDecision', - declaration: 'export type PreStepDecision = {\n kind: \'reject\';\n} | {\n kind: \'enter\';\n messages: UserMessage[];\n};', + declaration: 'export type PreStepDecision = {\n kind: \'reject\';\n} | {\n kind: \'enter\';\n messages: UserMessage[];\n startsRequestSeries?: true;\n};', }, { name: 'PreToolDecision', @@ -4259,7 +4259,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'RequestHeaderReason', - declaration: 'export type RequestHeaderReason = \'initial\' | \'resume\' | \'change\';', + declaration: 'export type RequestHeaderReason = \'initial\' | \'resume\' | \'change\' | \'series\';', }, { name: 'RequestImageAttachment', @@ -4463,7 +4463,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionEventMap', - declaration: 'export interface SessionEventMap {\n \'turn/start\': {\n turn: number;\n };\n \'turn/end\': {\n turn: number;\n reason: TurnEndReason;\n };\n \'step/start\': {\n turn: number;\n step: number;\n };\n \'step/end\': {\n turn: number;\n step: number;\n };\n \'user/message\': UserMessage;\n \'assistant/chunk\': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n \'assistant/message\': {\n turn: number;\n step: number;\n message: AssistantMessage;\n usage?: TokenUsage;\n interrupted?: true;\n };\n \'tool/call\': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n \'tool/result\': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n \'request/header\': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n };\n \'request/context\': RequestContext;\n \'session/end-seed\': Record;\n}', + declaration: 'export interface SessionEventMap {\n \'turn/start\': {\n turn: number;\n };\n \'turn/end\': {\n turn: number;\n reason: TurnEndReason;\n };\n \'step/start\': {\n turn: number;\n step: number;\n };\n \'step/end\': {\n turn: number;\n step: number;\n };\n \'user/message\': UserMessage;\n \'assistant/chunk\': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n \'assistant/message\': {\n turn: number;\n step: number;\n message: AssistantMessage;\n usage?: TokenUsage;\n interrupted?: true;\n };\n \'tool/call\': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n \'tool/result\': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n \'request/header\': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n startsSeries?: true;\n };\n \'request/context\': RequestContext;\n \'session/end-seed\': Record;\n}', }, { name: 'SessionEventMetadataFilter', diff --git a/packages/extensions/tool-cordis/src/index.ts b/packages/extensions/tool-cordis/src/index.ts index e090eb993d..4c0915da60 100644 --- a/packages/extensions/tool-cordis/src/index.ts +++ b/packages/extensions/tool-cordis/src/index.ts @@ -398,7 +398,7 @@ export function apply(ctx: Context): void { source: { kind: 'plugin', plugin: name, form: 'instructions' }, }) }) - return { kind: 'enter', messages: [...decision.messages, ...contexts] } + return { ...decision, messages: [...decision.messages, ...contexts] } }) } diff --git a/packages/goal/goal-round-driver/README.i18n.yaml b/packages/goal/goal-round-driver/README.i18n.yaml index a56c3e9738..75e3337263 100644 --- a/packages/goal/goal-round-driver/README.i18n.yaml +++ b/packages/goal/goal-round-driver/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/goal/goal-round-driver/README.md -README.md: 34b11714b8ccf574549567f33b80204f3c0dde6a -README.zh.md: be41c12258214aa8aa5323c73ec144642fb121ff +README.md: b11fba9beaa50edf2627dc62b5910f3802efb10d +README.zh.md: edbf46d344a8b3d6ffdaac36d5e58a64ed305ac0 diff --git a/packages/goal/goal-round-driver/README.md b/packages/goal/goal-round-driver/README.md index 34b11714b8..b11fba9bea 100644 --- a/packages/goal/goal-round-driver/README.md +++ b/packages/goal/goal-round-driver/README.md @@ -21,7 +21,7 @@ The plugin has no tunable configuration. `maxGoalRounds` belongs to the goal def ## Round contract -When an exact live agent is idle with an active, armed goal and remaining capacity, the driver first checkpoints pending goal mutations, then reserves `roundsStarted + 1` for the current `{ goalId, revision }`. It queues one `` prompt with `GoalMessageSource`. The `agent/pre-step` listener verifies the complete claimed record and current goal both before and after downstream listeners; only an entered `user/message` increments `roundsStarted`. A reservation rejected as stale does not consume the round number. +When an exact live agent is idle with an active, armed goal and remaining capacity, the driver first checkpoints pending goal mutations, then reserves `roundsStarted + 1` for the current `{ goalId, revision }`. It queues one `` prompt with `GoalMessageSource`. The `agent/pre-step` listener verifies the complete claimed record and current goal both before and after downstream listeners; an accepted round sets `startsRequestSeries: true`, so that boundary is logged as `series` for an unchanged header or `startsSeries: true` on a coincident `change`. Chat renders the header before the round message to match the provider envelope order. Only an entered `user/message` increments `roundsStarted`. A reservation rejected as stale does not consume the round number. `MessageId` identifies the reserved message through durable inbox insertion and claim; it does not identify a turn result. Human messages do not consume the goal cap. If human work enters the inbox before a reservation or joins its pending batch, automatic work yields until the agent becomes idle; a pending automatic prompt in a mixed batch is rejected and re-reserved only after that checkpoint. diff --git a/packages/goal/goal-round-driver/README.zh.md b/packages/goal/goal-round-driver/README.zh.md index be41c12258..edbf46d344 100644 --- a/packages/goal/goal-round-driver/README.zh.md +++ b/packages/goal/goal-round-driver/README.zh.md @@ -21,7 +21,7 @@ ## Round 约定 -当对应的活跃 agent(智能体)实例处于 idle 状态,且目标 phase 为 active、已启用续行并有剩余容量时,驱动器先为待处理 goal 变更创建检查点,再预留 `roundsStarted + 1`,对应当前 `{ goalId, revision }`。它会排入一条 `` 提示词,并携带 `GoalMessageSource`。`agent/pre-step` 监听器会在下游监听器前后验证完整的已领取记录与当前 goal;只有进入步骤的 `user/message` 才会增加 `roundsStarted`。因陈旧而被拒绝的预留不会消耗 Round 编号。 +当对应的活跃 agent(智能体)实例处于 idle 状态,且目标 phase 为 active、已启用续行并有剩余容量时,驱动器先为待处理 goal 变更创建检查点,再预留 `roundsStarted + 1`,对应当前 `{ goalId, revision }`。它会排入一条 `` 提示词,并携带 `GoalMessageSource`。`agent/pre-step` 监听器会在下游监听器前后验证完整的已领取记录与当前 goal;接纳的 Round 会设置 `startsRequestSeries: true`,因此未变化的 header 以 `series` 记录该边界,而同时发生的 `change` 则携带 `startsSeries: true`。Chat 会把该 header 渲染在 Round 消息之前,以匹配提供方信封顺序。只有进入步骤的 `user/message` 才会增加 `roundsStarted`。因陈旧而被拒绝的预留不会消耗 Round 编号。 `MessageId` 通过持久 inbox 插入和领取来标识预留消息;它不标识轮次结果。人类消息不消耗 goal 上限。如果人类工作在预留前进入 inbox,或加入预留的待处理批次,自动工作会让行,直到 agent 进入 idle;混合批次中的待处理自动提示词会被拒绝,只有在该检查点之后才重新预留。 diff --git a/packages/goal/goal-round-driver/src/index.ts b/packages/goal/goal-round-driver/src/index.ts index b212f920de..4c4a20e7ee 100644 --- a/packages/goal/goal-round-driver/src/index.ts +++ b/packages/goal/goal-round-driver/src/index.ts @@ -410,7 +410,7 @@ export function apply(ctx: Context): void { requestDrive(state) return { kind: 'reject' } } - return decision + return { ...decision, startsRequestSeries: true } }) // Loading a lifecycle driver over existing agents never inherits hidden diff --git a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts index 1bd2032600..2a4059c2ea 100644 --- a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts +++ b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts @@ -207,6 +207,8 @@ describe('same-session goal driving', () => { expect(rounds).toEqual([1, 2]) expect(requestText(test.adapter.requests[0]!)).toContain('Round: 1/2') expect(requestText(test.adapter.requests[1]!)).toContain('Round: 2/2') + expect(test.agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial', 'series']) }) it('never adopts activation from an already-live driver and waits for explicit resume', async () => { @@ -325,6 +327,8 @@ describe('same-session goal driving', () => { expect(requestText(test.adapter.requests[0]!)).toContain('human goes first') expect(requestText(test.adapter.requests[0]!)).not.toContain('') expect(requestText(test.adapter.requests[1]!)).toContain('') + expect(test.agent.session.events.flatMap(event => + event.type === 'request/header' ? [event.data.reason] : [])).toEqual(['initial', 'series']) }) it('makes a reserved round stale when a listener queues human work behind it', async () => { diff --git a/packages/hooks/hooks-claude-code/src/index.ts b/packages/hooks/hooks-claude-code/src/index.ts index 79c2df194c..09594d18b6 100644 --- a/packages/hooks/hooks-claude-code/src/index.ts +++ b/packages/hooks/hooks-claude-code/src/index.ts @@ -229,7 +229,7 @@ export function apply(ctx: Context, config: Config): void { const ours = contextFrom(merged) if (!ours || downstream.kind !== 'enter') return downstream return { - kind: 'enter', + ...downstream, messages: [...downstream.messages, ours], } }) diff --git a/packages/hooks/hooks-codex/src/index.ts b/packages/hooks/hooks-codex/src/index.ts index a76965c970..2189fc9a28 100644 --- a/packages/hooks/hooks-codex/src/index.ts +++ b/packages/hooks/hooks-codex/src/index.ts @@ -216,7 +216,7 @@ export function apply(ctx: Context, config: Config): void { const ours = contextFrom(merged) if (!ours || downstream.kind !== 'enter') return downstream return { - kind: 'enter', + ...downstream, messages: [...downstream.messages, ours], } }) diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index 103060ad44..ac0309f3a4 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md -README.md: 69826d76b437ea482655d91a930310185079414c -README.zh.md: 26d132a9a8e48c0833e6145b139226d765cb9709 +README.md: c96532a673d6b2e53ff1d55cf8a3ae4f7aac756f +README.zh.md: 4f5747a8fdcb96208ca454ddd8df603de094af71 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 69826d76b4..c96532a673 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -8,7 +8,7 @@ The API gateway shared by every client consists of the TypeScript API contract ( `ApiProxyService` consumes `ctx.agentDefaultModel`; it does not own a provider/model config or settings section. The shared service registers `{provider, model, reasoningEffort?}` under `agent-default-model`: the base bundle's composition entry is the lower layer and `settings.yaml` layers the user's choice over it. -A session resolves its model selection from three tiers on every access: a selection made in this process, otherwise the session's latest logged `request/header`, otherwise this default. A session that has run a turn derives its selection from its log, while a blank session observes a default saved after it was created. +A session resolves its model selection from three tiers on every access: a selection made in this process, otherwise the session's latest logged `request/header`, otherwise this default. A session that has run a turn derives its selection from its log, while a blank session observes a default saved after it was created. A logged reasoning effort marked as an adapter default remains absent from the restored selection, so the next model resolution does not promote that default into an explicit choice or record a false header change. `session.selectModel` saves an accepted switch as the deployment default; there is no separate gesture. It stores the resolved `ModelSelection`, including an adapter-materialized default effort. The complete-section write clears a stored effort when the selected model has none. A storage failure is logged without undoing the session selection. A deployment with no settings provider keeps the composition entry and the switch remains session-local. diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 26d132a9a8..4f5747a8fd 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -8,7 +8,7 @@ `ApiProxyService` 消费 `ctx.agentDefaultModel`;它不持有提供方/模型配置或 Settings 分节。共享服务在 `agent-default-model` 下注册 `{provider, model, reasoningEffort?}`:base 组合包的组合条目是底层,`settings.yaml` 把用户选择叠加其上。 -会话每次访问时都按三级解析模型选择:本进程内作出的选择,其次是该会话日志中最新的 `request/header`,最后是这个默认值。已经跑过一轮的会话从自己的日志推导选择,空白会话则能观察到创建之后保存的默认值。 +会话每次访问时都按三级解析模型选择:本进程内作出的选择,其次是该会话日志中最新的 `request/header`,最后是这个默认值。已经跑过一轮的会话从自己的日志推导选择,空白会话则能观察到创建之后保存的默认值。若日志中的推理强度被标记为适配器默认值,恢复的选择仍不包含该强度,因此下一次模型解析不会把这个默认值提升为显式选择,也不会记录虚假的 header 变更。 `session.selectModel` 会把接受的切换保存为部署默认值;没有单独的选择动作。它存储已解析的 `ModelSelection`,包括适配器实体化的默认推理(reasoning)强度。完整分节写入会在所选模型没有推理强度时清除已存值。存储失败只记日志,不会撤销会话选择。没有设置提供方的部署保留组合条目,切换只对当前会话生效。 diff --git a/packages/skill/tool-skill/src/index.ts b/packages/skill/tool-skill/src/index.ts index 596876b5a7..222e8a0ace 100644 --- a/packages/skill/tool-skill/src/index.ts +++ b/packages/skill/tool-skill/src/index.ts @@ -200,7 +200,7 @@ export function apply(ctx: Context, config: Config = {}): void { })) } if (injections.length === 0) return decision - return { kind: 'enter', messages: [...decision.messages, ...injections] } + return { ...decision, messages: [...decision.messages, ...injections] } }) // Register after the tool so reverse teardown removes guidance first. Exact definition @@ -231,19 +231,19 @@ export function apply(ctx: Context, config: Config = {}): void { if (history.visibleDigest === digest) { return existing === undefined ? decision - : { kind: 'enter', messages: decision.messages.filter(message => message.id !== existing.message.id) } + : { ...decision, messages: decision.messages.filter(message => message.id !== existing.message.id) } } if (existing !== undefined && digestCatalogEntries(existing.entries) === digest) return decision if (!history.published && skills.length === 0) { return existing === undefined ? decision - : { kind: 'enter', messages: decision.messages.filter(message => message.id !== existing.message.id) } + : { ...decision, messages: decision.messages.filter(message => message.id !== existing.message.id) } } const catalog = history.published ? renderCatalogUpdate(entries) : renderCatalogMessage(entries) return { - kind: 'enter', + ...decision, messages: existing === undefined ? [...decision.messages, catalog] : decision.messages.map(message => message.id === existing.message.id ? catalog : message), diff --git a/packages/test-support/session-snapshot/src/suite.ts b/packages/test-support/session-snapshot/src/suite.ts index 120359f92a..ad9c6e2ac3 100644 --- a/packages/test-support/session-snapshot/src/suite.ts +++ b/packages/test-support/session-snapshot/src/suite.ts @@ -378,6 +378,54 @@ export function fixtureContext(fixture: string): NormalizeContext { } } +interface NormalizedHeaderEvent { + readonly header: unknown + readonly reason: unknown +} + +/** Normalize request-header payloads while retaining the reason that selects a pin revision. */ +function normalizedHeaderEvents(rawLog: string, ctx: NormalizeContext): NormalizedHeaderEvent[] { + return normalizeSessionLog(rawLog, ctx) + .split('\n') + .filter(line => line.trim().length > 0) + .map(line => JSON.parse(line) as { + type?: unknown + data?: { header?: unknown; reason?: unknown } + }) + .filter(record => record.type === 'request/header') + .map(record => ({ header: record.data?.header, reason: record.data?.reason })) +} + +/** + * Header revisions that own sidecar content. `series` reuses the current revision, while + * `resume` owns sidecars because its full snapshot may drift across the process boundary. + * Pinning fixtures therefore cover one loop instance; a mid-log `resume` fails their + * pin-count invariant. + */ +function pinningHeaderPayloads(rawLog: string, ctx: NormalizeContext): unknown[] { + return normalizedHeaderEvents(rawLog, ctx) + .filter(event => event.reason !== 'series') + .map(event => event.header) +} + +/** Extract every string system prompt from a normalized header sequence. */ +function systemPromptsFrom(headers: readonly unknown[]): string[] { + return headers.flatMap((header) => { + if (header === null || typeof header !== 'object') return [] + const system = (header as { system?: unknown }).system + return typeof system === 'string' ? [system] : [] + }) +} + +/** Extract every array-valued tool catalog from a normalized header sequence. */ +function toolSchemasFrom(headers: readonly unknown[]): unknown[][] { + return headers.flatMap((header) => { + if (header === null || typeof header !== 'object') return [] + const tools = (header as { tools?: unknown }).tools + return Array.isArray(tools) ? [tools] : [] + }) +} + /** * The `data.header` payload of every `request/header` event in a session * JSONL, in log order, with the log's volatile values scrubbed first @@ -390,12 +438,7 @@ export function fixtureContext(fixture: string): NormalizeContext { * @returns The normalized `data.header` payloads, in log order. */ export function normalizedHeaders(rawLog: string, ctx: NormalizeContext): unknown[] { - return normalizeSessionLog(rawLog, ctx) - .split('\n') - .filter(line => line.trim().length > 0) - .map(line => JSON.parse(line) as { type?: unknown; data?: { header?: unknown } }) - .filter(record => record.type === 'request/header') - .map(record => record.data?.header) + return normalizedHeaderEvents(rawLog, ctx).map(event => event.header) } /** @@ -408,11 +451,7 @@ export function normalizedHeaders(rawLog: string, ctx: NormalizeContext): unknow * @returns The normalized system prompts, in header order. */ export function normalizedSystemPrompts(rawLog: string, ctx: NormalizeContext): string[] { - return normalizedHeaders(rawLog, ctx).flatMap((header) => { - if (header === null || typeof header !== 'object') return [] - const system = (header as { system?: unknown }).system - return typeof system === 'string' ? [system] : [] - }) + return systemPromptsFrom(normalizedHeaders(rawLog, ctx)) } /** @@ -425,11 +464,7 @@ export function normalizedSystemPrompts(rawLog: string, ctx: NormalizeContext): * @returns The normalized initial tool-schema arrays, in header order. */ export function normalizedToolSchemas(rawLog: string, ctx: NormalizeContext): unknown[][] { - return normalizedHeaders(rawLog, ctx).flatMap((header) => { - if (header === null || typeof header !== 'object') return [] - const tools = (header as { tools?: unknown }).tools - return Array.isArray(tools) ? [tools] : [] - }) + return toolSchemasFrom(normalizedHeaders(rawLog, ctx)) } /** The structured contents of a tool-schema sidecar. */ @@ -1274,7 +1309,8 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { } if (scenario.pinsHeader === true) { const primary = result.sessionLogs[0] as HarvestedLog - const prompts = normalizedSystemPrompts(primary.content, ctx) + const pinningHeaders = pinningHeaderPayloads(primary.content, ctx) + const prompts = systemPromptsFrom(pinningHeaders) expect(prompts.length, `${mode} produced no system prompt to snapshot`).toBeGreaterThan(0) const promptSnapshot = formatSystemPromptSnapshot(prompts[0] as string, prompts.slice(1)) /* v8 ignore next -- registration guarantees every scenario class has resolved sources. */ @@ -1283,7 +1319,7 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { claimSharedSnapshot(promptClaims, promptPath, scenario.name, promptSnapshot) await writeFile(promptPath, promptSnapshot) - const schemaSets = normalizedToolSchemas(primary.content, ctx) + const schemaSets = toolSchemasFrom(pinningHeaders) expect(schemaSets.length, `${mode} produced no tool schemas to snapshot`).toBeGreaterThan(0) expect(schemaSets.length, `${mode} produced a tool-schema sequence that differs from its prompt sequence`) .toBe(prompts.length) @@ -1301,7 +1337,10 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { const log = result.sessionLogs[index] expect(log, `${mode}: no child session log at index ${index} to snapshot schemas from`) .toBeDefined() - const schemaSets = normalizedToolSchemas((log as HarvestedLog).content, ctx) + const schemaSets = toolSchemasFrom(pinningHeaderPayloads( + (log as HarvestedLog).content, + ctx, + )) expect(schemaSets.length, `${mode}: child ${index} produced no tool schemas to snapshot`) .toBeGreaterThan(0) await writeFile(join(dir, childToolSchemasSnapshot(index)), formatToolSchemasSnapshot( @@ -1313,7 +1352,10 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { const log = result.sessionLogs[index] expect(log, `${mode}: no child session log at index ${index} to snapshot a prompt from`) .toBeDefined() - const prompts = normalizedSystemPrompts((log as HarvestedLog).content, ctx) + const prompts = systemPromptsFrom(pinningHeaderPayloads( + (log as HarvestedLog).content, + ctx, + )) expect(prompts.length, `${mode}: child ${index} produced no system prompt to snapshot`) .toBeGreaterThan(0) await writeFile( @@ -1360,7 +1402,7 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { const schemaSource = schemaSourceByClass.get(classOf(scenario)) ?? pinningScenario const pinningDir = join(snapshotsDir, pinningScenario.name) const pinnedFixture = await readFile(join(pinningDir, 'session.jsonl'), 'utf8') - const pinned = normalizedHeaders(pinnedFixture, fixtureContext(pinnedFixture)) + const pinned = pinningHeaderPayloads(pinnedFixture, fixtureContext(pinnedFixture)) const promptSnapshot = await readFile( join(snapshotsDir, promptSource.name, SYSTEM_PROMPT_SNAPSHOT), 'utf8', @@ -1400,7 +1442,8 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { : 0 expect(headerChangeCount(log.content), `session ${log.id}: changed request/header count`) .toBe(expectedChanges) - const headers = normalizedHeaders(scrubSystemPrompts(log.content), ctx) + const headerEvents = normalizedHeaderEvents(scrubSystemPrompts(log.content), ctx) + const headers = headerEvents.map(event => event.header) const prompts = normalizedSystemPrompts(log.content, ctx) const schemaSets = normalizedToolSchemas(log.content, ctx) expect(prompts.length, `session ${log.id}: every request/header must carry a string system prompt`) @@ -1409,13 +1452,15 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { .toBe(headers.length) if (childSchemas !== undefined) { expect(childSchemas.length, `session ${log.id}: ${childToolSchemasSnapshot(logIndex)} has an unexpected tool-schema count`) - .toBe(schemaSets.length) + .toBe(1 + headerChangeCount(log.content)) } + let revision = 0 for (const [k, header] of headers.entries()) { - const classPin = expectedChanges > 0 ? pinnedHeaders[k] : pinnedHeaders[0] + if (headerEvents[k]?.reason === 'change') revision++ + const classPin = expectedChanges > 0 ? pinnedHeaders[revision] : pinnedHeaders[0] const expected = childSchemas === undefined ? classPin - : { ...classPin as Record, tools: childSchemas[k] } + : { ...classPin as Record, tools: childSchemas[revision] } expect(header, `session ${log.id}: request/header #${k + 1} diverged from the pinned (${pinningScenario.name}) header`) .toEqual(expected) if (expectedChanges === 0) { @@ -1430,14 +1475,17 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { } } if (scenario.pinsHeader === true && logIndex === 0) { + const pinningHeaders = pinningHeaderPayloads(log.content, ctx) + const pinningPrompts = systemPromptsFrom(pinningHeaders) + const pinningSchemas = toolSchemasFrom(pinningHeaders) expect(formatSystemPromptSnapshot( - prompts[0] as string, - prompts.slice(1), + pinningPrompts[0] as string, + pinningPrompts.slice(1), ), `session ${log.id}: changed system prompts diverged from ${promptSource.name}/${SYSTEM_PROMPT_SNAPSHOT}`) .toEqual(promptSnapshot) expect(formatToolSchemasSnapshot( - schemaSets[0] as unknown[], - schemaSets.slice(1), + pinningSchemas[0] as unknown[], + pinningSchemas.slice(1), ), `session ${log.id}: changed tool schemas diverged from ${schemaSource.name}/${TOOL_SCHEMAS_SNAPSHOT}`) .toEqual(toolSchemasSnapshot) } @@ -1526,7 +1574,7 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { /* v8 ignore next -- registration guarantees every pin has resolved sources. */ const schemaSource = schemaSourceByClass.get(classOf(scenario)) ?? scenario const fixture = await readFile(join(snapshotsDir, scenario.name, 'session.jsonl'), 'utf8') - const headers = normalizedHeaders(fixture, fixtureContext(fixture)) + const headers = pinningHeaderPayloads(fixture, fixtureContext(fixture)) const promptSnapshot = await readFile( join(snapshotsDir, promptSource.name, SYSTEM_PROMPT_SNAPSHOT), 'utf8', diff --git a/packages/test-support/session-snapshot/tests/fixtures/suite/pin-turn/behavior.json b/packages/test-support/session-snapshot/tests/fixtures/suite/pin-turn/behavior.json index 4de8f25b7e..bd19a95893 100644 --- a/packages/test-support/session-snapshot/tests/fixtures/suite/pin-turn/behavior.json +++ b/packages/test-support/session-snapshot/tests/fixtures/suite/pin-turn/behavior.json @@ -6,7 +6,8 @@ { "type": "session", "id": "{{SID}}", "createdAt": 100, "cwd": "{{CWD}}", "delegationDepth": 0 }, { "type": "request/header", "seq": 0, "time": 100, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "initial" } }, { "type": "request/header", "seq": 1, "time": 100, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT\n\nNEW PROMPT LINE", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "change" } }, - { "type": "turn/start", "seq": 2, "time": 100, "data": { "turn": 1 } } + { "type": "request/header", "seq": 2, "time": 100, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT\n\nNEW PROMPT LINE", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "series" } }, + { "type": "turn/start", "seq": 3, "time": 100, "data": { "turn": 1 } } ] }] } diff --git a/packages/test-support/session-snapshot/tests/fixtures/suite/pin-turn/session.jsonl b/packages/test-support/session-snapshot/tests/fixtures/suite/pin-turn/session.jsonl index 9cbb321e00..467616c82b 100644 --- a/packages/test-support/session-snapshot/tests/fixtures/suite/pin-turn/session.jsonl +++ b/packages/test-support/session-snapshot/tests/fixtures/suite/pin-turn/session.jsonl @@ -1,4 +1,5 @@ {"type":"session","id":"{{session:1}}","createdAt":7,"cwd":"/rec/pin-cwd","delegationDepth":0} {"type":"request/header","data":{"header":{"config":{"model":"fake"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} {"type":"request/header","data":{"header":{"config":{"model":"fake"},"system":"{{system}}","tools":"{{tools}}"},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"model":"fake"},"system":"{{system}}","tools":"{{tools}}"},"reason":"series"}} {"type":"turn/start","data":{"turn":1}} diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index a564b3d633..150f3cf929 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1332,7 +1332,7 @@ function renderLifecycle(): string { '', '`dsh-compaction-basic` uses `agent/pre-step` for pressure before request derivation and `agent/request-error` only for canonical context overflow. Once either trigger qualifies, optional tool-result pruning runs before summary selection. Recovery works between the closed failed step and failed turn close, and opens a fresh retry turn only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative.', '', - 'The returned `agent/pre-step` decision is authoritative; listeners wrapping `next()` preserve downstream messages unless replacement is intentional. Steering and injected context pass through the same waterfall after a later claim operation takes their next-step batch.', + 'The returned `agent/pre-step` decision is authoritative; listeners wrapping `next()` preserve downstream messages and `startsRequestSeries` unless replacement is intentional. Steering and injected context pass through the same waterfall after a later claim operation takes their next-step batch.', '', 'SDK users that need replayable transcript data should consume `session/event`; `agent/*` is the live coordination API for queue/status, prompt interception, request construction, steering, continuation, and errors.', '', diff --git a/snapshots/session/agent-instructions/session.jsonl b/snapshots/session/agent-instructions/session.jsonl index 553db05424..66216297a5 100644 --- a/snapshots/session/agent-instructions/session.jsonl +++ b/snapshots/session/agent-instructions/session.jsonl @@ -26,14 +26,15 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions.\n\nInstructions from: AGENTS.md\n\nRoot snapshot instruction.\n\n"},{"type":"text","text":"\nAdditional instructions from: nested/AGENTS.md\n\nThese instructions apply to work under `nested`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nNested snapshot instruction.\n\n"}],"source":{"kind":"agent-instructions","form":"instructions","baseline":true,"baselineIdentity":"{\"projectRoot\":\"\",\"projectRootMarkers\":[\".dsh-project\"],\"maxBytes\":65536,\"maxSourceBytes\":1048576,\"instructionFileCandidates\":[\"AGENTS.md\",\"CLAUDE.md\"],\"localInstructionFileCandidates\":[\"AGENTS.local.md\",\"CLAUDE.local.md\"]}","changes":[{"action":"set","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"2e18766c26603608f321508caae00ea8f4434d59"},{"action":"set","scope":"nested\u0000AGENTS.md","path":"nested/AGENTS.md","digest":"c446df9a85c7e73a3055f394a4822a19ac9ead5a"}]},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"series"}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"call_workspace_delimiter_read","name":"read","argumentsDelta":"{\"file_path\":\"scope/task.txt\"}"}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_workspace_delimiter_read","name":"read","arguments":"{\"file_path\":\"scope/task.txt\"}"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_workspace_delimiter_read","name":"read","arguments":"{\"file_path\":\"scope/task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[27,28,29,30,31],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_workspace_delimiter_read","name":"read","arguments":"{\"file_path\":\"scope/task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[28,29,30,31,32],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_workspace_delimiter_read","name":"read","arguments":"{\"file_path\":\"scope/task.txt\"}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_workspace_delimiter_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_delimiter_read","content":[{"type":"text","text":"{{cwd}}/scope/task.txt\nfile\n\n1: delimiter path snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"{{message:9}}"},"meta":{"path":"{{cwd}}/scope/task.txt","offset":1,"lines":[{"number":1,"text":"delimiter path snapshot task"}],"totalLines":1}},"sourceEventSeqs":[33],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_workspace_delimiter_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_delimiter_read","content":[{"type":"text","text":"{{cwd}}/scope/task.txt\nfile\n\n1: delimiter path snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"{{message:9}}"},"meta":{"path":"{{cwd}}/scope/task.txt","offset":1,"lines":[{"number":1,"text":"delimiter path snapshot task"}],"totalLines":1}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nAdditional instructions from: scope<\\/system-reminder>/AGENTS.md\n\nThese instructions apply to work under `scope<\\/system-reminder>`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nDelimiter path snapshot instruction.\n\n"}],"source":{"kind":"agent-instructions","form":"instructions","changes":[{"action":"set","scope":"scope\u0000AGENTS.md","path":"scope/AGENTS.md","digest":"38803cd13e2dff9105ba5fbbc703fe27e989e26e"}]},"role":"user","id":"{{message:10}}"}]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} @@ -44,6 +45,6 @@ {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}}} {"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":10,"outputTokens":2}},"sourceEventSeqs":[40,41,42,43,44],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":10,"outputTokens":2}},"sourceEventSeqs":[41,42,43,44,45],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/agent-instructions/snapshot.yml b/snapshots/session/agent-instructions/snapshot.yml index 0f0bc334dc..5ef4802b50 100644 --- a/snapshots/session/agent-instructions/snapshot.yml +++ b/snapshots/session/agent-instructions/snapshot.yml @@ -6,7 +6,7 @@ recording: authored header: class: agent-instructions pin: true - toolSchemasSource: text-turn + changes: 1 replay: override: true platform: posix diff --git a/snapshots/session/agent-instructions/system-prompt.expected.md b/snapshots/session/agent-instructions/system-prompt.expected.md index 676b6532e3..de3a7c52aa 100644 --- a/snapshots/session/agent-instructions/system-prompt.expected.md +++ b/snapshots/session/agent-instructions/system-prompt.expected.md @@ -5,6 +5,39 @@ You are a coding assistant powered by the deepseek-v4-flash model. Your working Verify your work by running the code or tests. Keep answers brief and factual. +Check the [exit code: N] marker on every bash result; investigate failures before moving on. + +Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. + +Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-observation-policy requires it) and prefer edit for targeted changes. + +Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-observation-policy requires it), unless you just created or edited it in this session. + +Use the glob tool — not shell find — to discover files by path pattern. A pattern with no "/" matches basenames at any depth, so "*" matches every file in the tree rather than its top level. Results are files only, never directories, and include hidden and ignored files: a result that fits comes back in modification-time order, while a larger one keeps the modification-time-ordered head. + +Use the grep tool — not shell grep or rg — to search file contents. Use read on a matched file when you need surrounding context. + +Track every background job id you start. You are notified in-session when a job finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running job's work. Before giving a final answer, collect every still-relevant job with job_output (set wait: true only when you are genuinely blocked on it), and job_kill jobs that stopped mattering. + +Use the web_search tool to discover current information on the web. The required queries array accepts 1–4 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links. + +Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. + +Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. + +Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. + +Use subagent in the background by default. Start independent delegations together in one assistant message and continue useful work while they run. Set `run_in_background: false` only when your next action depends on that subagent's result. When a background run settles, the runtime sends you a notice containing its outcome and any final assistant message. + + + +You are an AI agent powered by DeepSeek Harness. + +You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. + +Verify your work by running the code or tests. Keep answers brief and factual. + + Check the [exit code: N] marker on every bash result; investigate failures before moving on. Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. diff --git a/snapshots/session/agent-instructions/tool-schemas.expected.json b/snapshots/session/agent-instructions/tool-schemas.expected.json new file mode 100644 index 0000000000..75be989751 --- /dev/null +++ b/snapshots/session/agent-instructions/tool-schemas.expected.json @@ -0,0 +1,1392 @@ +{ + "initial": [ + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a job id immediately; read its output with `job_output` and stop it with `job_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." + } + }, + "required": [ + "command", + "description" + ] + } + }, + { + "name": "create_goal", + "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace. Must match exactly." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "exit_plan_mode", + "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", + "parameters": { + "type": "object", + "properties": { + "plan": { + "type": "string", + "description": "The complete plan, as markdown, starting with a # heading that names it." + } + }, + "required": [ + "plan" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files whose paths match a glob pattern. Returns matching file paths — never directories — including hidden and ignored files (VCS metadata directories are excluded). Up to 100 paths come back in modification-time order; a larger result returns the first 100 paths in modification-time order, says so, and reports where the complete sorted list was saved. This tool does not enumerate directory entries.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns the first 250 matches inline; a capped result reports where the complete match list was saved. Use read on a matched file for surrounding context.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "interrupt_agent", + "description": "Request cancellation of a background agent's current turn by its agent id. The target may be your direct child or a deeper agent created under you. Only the current turn stops: messages already queued for the agent stay parked until a later send_message, agents it started keep running, and the agent itself stays available for follow-ups. This call returns as soon as the stop request is accepted, so the target may keep running briefly; interrupting an agent that already finished is an accepted no-op.", + "parameters": { + "type": "object", + "properties": { + "agent_id": { + "type": "string", + "description": "The agent id of the running agent to interrupt." + } + }, + "required": [ + "agent_id" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job by job id. Returns immediately; the job settles as killed once its work actually stops.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job. Stream jobs return only output since the previous read; final-output jobs return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the job alive." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your continuable background subagents by durable id and label. Use it to recall which ones you started, not to poll for completion — you are told when one finishes. Status comes from the live registry: running means the agent is working right now, idle means it is loaded but between turns (it may be waiting on agents it started), and ready means it exists only in storage — resumable, not terminal, and not a result waiting to be collected; a `send_message` starts a new turn on the same conversation, and a direct child remains a `send_message` candidate in every status. The snapshot is not a delivery promise — `send_message` performs the authoritative check and may still fail. Children that could not be read are reported as diagnostics instead of being silently dropped. Scope `descendants` walks the whole tree below you in stable pre-order, annotating each entry with its durable direct-parent session id and depth. You may use `send_message` only for depth-1 entries; deeper entries are candidates for `interrupt_agent` only.", + "parameters": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "description": "children (default) lists direct children only; descendants walks the complete tree below you.", + "enum": [ + "children", + "descendants" + ] + } + } + } + }, + { + "name": "list_subagent_models", + "description": "Discover LLM routes for subagents without changing the current Agent. Call with no arguments to list registered providers, with `provider` to list its advertised models, or with `provider` and `model` to inspect that exact model and its reasoning efforts. Catalog membership is advisory: an adapter may accept an unlisted model id. Use the returned ids with a delegation tool's `provider`, `model`, and `reasoning_effort` fields.", + "parameters": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "description": "Registered LLM provider id. Omit to list providers." + }, + "model": { + "type": "string", + "description": "Exact model id to inspect. Requires provider; omit to list that provider's advertised models." + } + } + } + }, + { + "name": "ralph", + "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The immutable completion objective for every fresh Ralph round." + }, + "maxRounds": { + "type": "number", + "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Harness validates and downscales large supported images before the next model request, so use this tool directly instead of installing image libraries or creating thumbnails merely to inspect an image. Independent files may be read concurrently in small batches. Requires the current model to accept image input.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to a background subagent by its subagent id, continuing the same conversation. It becomes the subagent's next turn: if it is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. This call returns no answer from the subagent — only confirmation that the message was delivered — so use it to give it more work. A failure means the message was NOT delivered.", + "parameters": { + "type": "object", + "properties": { + "subagent_id": { + "type": "string", + "description": "The subagent id returned when the background subagent was started." + }, + "message": { + "type": "string", + "description": "The message to deliver to the subagent." + } + }, + "required": [ + "subagent_id", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "str_replace_editor", + "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with ``\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.", + "enum": [ + "view", + "create", + "str_replace", + "insert" + ] + }, + "path": { + "type": "string", + "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." + }, + "file_text": { + "type": "string", + "description": "Required parameter of `create` command, with the content of the file to be created." + }, + "insert_line": { + "type": "integer", + "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." + }, + "new_str": { + "type": "string", + "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." + }, + "old_str": { + "type": "string", + "description": "Required parameter of `str_replace` command containing the string in `path` to replace." + }, + "view_range": { + "type": "array", + "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.", + "items": { + "type": "integer" + } + } + }, + "required": [ + "command", + "path" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result. Child LLM selection is optional. Omit `provider`, `model`, and `reasoning_effort` to use configured child defaults and inherit compatible missing values from the parent Agent. Supply `provider` and `model` together after using `list_subagent_models` to inspect advertised routes and efforts. Changing the effective route without naming an effort uses the selected model's default effort.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + }, + "provider": { + "type": "string", + "description": "LLM provider route for the child. Supply together with model; omit both to use configured child defaults or inherit the parent route." + }, + "model": { + "type": "string", + "description": "Model id interpreted by provider. Supply together with provider; omit both to use configured child defaults or inherit the parent route." + }, + "reasoning_effort": { + "type": "string", + "description": "Adapter-owned reasoning effort for the effective child route. Omit to inherit a compatible configured/parent effort or use a newly selected model's default." + }, + "run_in_background": { + "type": "boolean", + "description": "Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This call waits for the subagent and returns its result.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Mark every todo being actively worked on `in_progress` — several at once when work genuinely runs in parallel (e.g. concurrent subagents or background commands), one for sequential work; while work remains, at least one task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit | pause | resume | complete | blocked", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Concrete blocking condition; required only with action blocked." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Provide 1–4 queries in the required queries array. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "Required search queries; accepts 1–4 items and merges their results.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return ` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return `)." + }, + "meta": { + "type": "object", + "description": "The workflow identity block (plain JSON — never code).", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [ + [ + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a job id immediately; read its output with `job_output` and stop it with `job_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." + } + }, + "required": [ + "command", + "description" + ] + } + }, + { + "name": "create_goal", + "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace. Must match exactly." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "exit_plan_mode", + "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", + "parameters": { + "type": "object", + "properties": { + "plan": { + "type": "string", + "description": "The complete plan, as markdown, starting with a # heading that names it." + } + }, + "required": [ + "plan" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files whose paths match a glob pattern. Returns matching file paths — never directories — including hidden and ignored files (VCS metadata directories are excluded). Up to 100 paths come back in modification-time order; a larger result returns the first 100 paths in modification-time order, says so, and reports where the complete sorted list was saved. This tool does not enumerate directory entries.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns the first 250 matches inline; a capped result reports where the complete match list was saved. Use read on a matched file for surrounding context.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "interrupt_agent", + "description": "Request cancellation of a background agent's current turn by its agent id. The target may be your direct child or a deeper agent created under you. Only the current turn stops: messages already queued for the agent stay parked until a later send_message, agents it started keep running, and the agent itself stays available for follow-ups. This call returns as soon as the stop request is accepted, so the target may keep running briefly; interrupting an agent that already finished is an accepted no-op.", + "parameters": { + "type": "object", + "properties": { + "agent_id": { + "type": "string", + "description": "The agent id of the running agent to interrupt." + } + }, + "required": [ + "agent_id" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job by job id. Returns immediately; the job settles as killed once its work actually stops.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job. Stream jobs return only output since the previous read; final-output jobs return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the job alive." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your continuable background subagents by durable id and label. Use it to recall which ones you started, not to poll for completion — you are told when one finishes. Status comes from the live registry: running means the agent is working right now, idle means it is loaded but between turns (it may be waiting on agents it started), and ready means it exists only in storage — resumable, not terminal, and not a result waiting to be collected; a `send_message` starts a new turn on the same conversation, and a direct child remains a `send_message` candidate in every status. The snapshot is not a delivery promise — `send_message` performs the authoritative check and may still fail. Children that could not be read are reported as diagnostics instead of being silently dropped. Scope `descendants` walks the whole tree below you in stable pre-order, annotating each entry with its durable direct-parent session id and depth. You may use `send_message` only for depth-1 entries; deeper entries are candidates for `interrupt_agent` only.", + "parameters": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "description": "children (default) lists direct children only; descendants walks the complete tree below you.", + "enum": [ + "children", + "descendants" + ] + } + } + } + }, + { + "name": "list_subagent_models", + "description": "Discover LLM routes for subagents without changing the current Agent. Call with no arguments to list registered providers, with `provider` to list its advertised models, or with `provider` and `model` to inspect that exact model and its reasoning efforts. Catalog membership is advisory: an adapter may accept an unlisted model id. Use the returned ids with a delegation tool's `provider`, `model`, and `reasoning_effort` fields.", + "parameters": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "description": "Registered LLM provider id. Omit to list providers." + }, + "model": { + "type": "string", + "description": "Exact model id to inspect. Requires provider; omit to list that provider's advertised models." + } + } + } + }, + { + "name": "ralph", + "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The immutable completion objective for every fresh Ralph round." + }, + "maxRounds": { + "type": "number", + "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Harness validates and downscales large supported images before the next model request, so use this tool directly instead of installing image libraries or creating thumbnails merely to inspect an image. Independent files may be read concurrently in small batches. Requires the current model to accept image input.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to a background subagent by its subagent id, continuing the same conversation. It becomes the subagent's next turn: if it is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. This call returns no answer from the subagent — only confirmation that the message was delivered — so use it to give it more work. A failure means the message was NOT delivered.", + "parameters": { + "type": "object", + "properties": { + "subagent_id": { + "type": "string", + "description": "The subagent id returned when the background subagent was started." + }, + "message": { + "type": "string", + "description": "The message to deliver to the subagent." + } + }, + "required": [ + "subagent_id", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "str_replace_editor", + "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with ``\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.", + "enum": [ + "view", + "create", + "str_replace", + "insert" + ] + }, + "path": { + "type": "string", + "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." + }, + "file_text": { + "type": "string", + "description": "Required parameter of `create` command, with the content of the file to be created." + }, + "insert_line": { + "type": "integer", + "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." + }, + "new_str": { + "type": "string", + "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." + }, + "old_str": { + "type": "string", + "description": "Required parameter of `str_replace` command containing the string in `path` to replace." + }, + "view_range": { + "type": "array", + "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.", + "items": { + "type": "integer" + } + } + }, + "required": [ + "command", + "path" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result. Child LLM selection is optional. Omit `provider`, `model`, and `reasoning_effort` to use configured child defaults and inherit compatible missing values from the parent Agent. Supply `provider` and `model` together after using `list_subagent_models` to inspect advertised routes and efforts. Changing the effective route without naming an effort uses the selected model's default effort.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + }, + "provider": { + "type": "string", + "description": "LLM provider route for the child. Supply together with model; omit both to use configured child defaults or inherit the parent route." + }, + "model": { + "type": "string", + "description": "Model id interpreted by provider. Supply together with provider; omit both to use configured child defaults or inherit the parent route." + }, + "reasoning_effort": { + "type": "string", + "description": "Adapter-owned reasoning effort for the effective child route. Omit to inherit a compatible configured/parent effort or use a newly selected model's default." + }, + "run_in_background": { + "type": "boolean", + "description": "Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This call waits for the subagent and returns its result.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Mark every todo being actively worked on `in_progress` — several at once when work genuinely runs in parallel (e.g. concurrent subagents or background commands), one for sequential work; while work remains, at least one task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit | pause | resume | complete | blocked", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Concrete blocking condition; required only with action blocked." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Provide 1–4 queries in the required queries array. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "Required search queries; accepts 1–4 items and merges their results.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return ` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return `)." + }, + "meta": { + "type": "object", + "description": "The workflow identity block (plain JSON — never code).", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ] + ] +} diff --git a/snapshots/session/compaction-recovery/session.jsonl b/snapshots/session/compaction-recovery/session.jsonl index 4848baa5fe..990419f159 100644 --- a/snapshots/session/compaction-recovery/session.jsonl +++ b/snapshots/session/compaction-recovery/session.jsonl @@ -26,11 +26,12 @@ {"type":"compaction/summary","data":{"compactionId":"{{id:1}}","summary":[{"type":"text","text":"The request established a durable compaction premise."}],"rawOutput":[{"type":"text","text":"The request established a durable compaction premise."}],"llmStreamCall":true,"shadowedRange":{"start":7,"end":8},"shadowedSeqs":[7,8],"shadowedTokenCount":372,"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":32,"usage":{"inputTokens":20,"outputTokens":4}}} {"type":"user/message","data":{"content":[{"type":"text","text":"This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.\n\n"},{"type":"text","text":"The request established a durable compaction premise."},{"type":"text","text":""}],"source":{"kind":"plugin","plugin":"compact","compactionId":"{{id:1}}"},"role":"user","id":"{{message:5}}"},"sourceEventSeqs":[23,24,7,8],"surfaceOp":{"op":"replace","start":7,"end":8}} {"type":"compaction/end","data":{"compactionId":"{{id:1}}","turn":1}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"series"}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":0,"text":"COMPACTION RECOVERED"}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"COMPACTION RECOVERED"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":20,"outputTokens":4}}}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"COMPACTION RECOVERED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":20,"outputTokens":4}},"sourceEventSeqs":[27,28,29,30,31],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"COMPACTION RECOVERED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":20,"outputTokens":4}},"sourceEventSeqs":[28,29,30,31,32],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/compaction-recovery/snapshot.yml b/snapshots/session/compaction-recovery/snapshot.yml index f25c25166b..606d57ab7d 100644 --- a/snapshots/session/compaction-recovery/snapshot.yml +++ b/snapshots/session/compaction-recovery/snapshot.yml @@ -6,5 +6,4 @@ recording: authored header: class: compaction-recovery pin: true - systemPromptSource: text-turn - toolSchemasSource: text-turn + changes: 1 diff --git a/snapshots/session/compaction-recovery/system-prompt.expected.md b/snapshots/session/compaction-recovery/system-prompt.expected.md new file mode 100644 index 0000000000..dca396e141 --- /dev/null +++ b/snapshots/session/compaction-recovery/system-prompt.expected.md @@ -0,0 +1,63 @@ +You are an AI agent powered by DeepSeek Harness. + +You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + +Verify your work by running the code or tests. Keep answers brief and factual. + + +Check the [exit code: N] marker on every bash result; investigate failures before moving on. + +Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. + +Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-observation-policy requires it) and prefer edit for targeted changes. + +Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-observation-policy requires it), unless you just created or edited it in this session. + +Use the glob tool — not shell find — to discover files by path pattern. A pattern with no "/" matches basenames at any depth, so "*" matches every file in the tree rather than its top level. Results are files only, never directories, and include hidden and ignored files: a result that fits comes back in modification-time order, while a larger one keeps the modification-time-ordered head. + +Use the grep tool — not shell grep or rg — to search file contents. Use read on a matched file when you need surrounding context. + +Track every background job id you start. You are notified in-session when a job finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running job's work. Before giving a final answer, collect every still-relevant job with job_output (set wait: true only when you are genuinely blocked on it), and job_kill jobs that stopped mattering. + +Use the web_search tool to discover current information on the web. The required queries array accepts 1–4 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links. + +Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. + +Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. + +Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. + +Use subagent in the background by default. Start independent delegations together in one assistant message and continue useful work while they run. Set `run_in_background: false` only when your next action depends on that subagent's result. When a background run settles, the runtime sends you a notice containing its outcome and any final assistant message. + + + +You are an AI agent powered by DeepSeek Harness. + +You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + +Verify your work by running the code or tests. Keep answers brief and factual. + + +Check the [exit code: N] marker on every bash result; investigate failures before moving on. + +Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. + +Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-observation-policy requires it) and prefer edit for targeted changes. + +Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-observation-policy requires it), unless you just created or edited it in this session. + +Use the glob tool — not shell find — to discover files by path pattern. A pattern with no "/" matches basenames at any depth, so "*" matches every file in the tree rather than its top level. Results are files only, never directories, and include hidden and ignored files: a result that fits comes back in modification-time order, while a larger one keeps the modification-time-ordered head. + +Use the grep tool — not shell grep or rg — to search file contents. Use read on a matched file when you need surrounding context. + +Track every background job id you start. You are notified in-session when a job finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running job's work. Before giving a final answer, collect every still-relevant job with job_output (set wait: true only when you are genuinely blocked on it), and job_kill jobs that stopped mattering. + +Use the web_search tool to discover current information on the web. The required queries array accepts 1–4 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links. + +Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. + +Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. + +Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. + +Use subagent in the background by default. Start independent delegations together in one assistant message and continue useful work while they run. Set `run_in_background: false` only when your next action depends on that subagent's result. When a background run settles, the runtime sends you a notice containing its outcome and any final assistant message. diff --git a/snapshots/session/compaction-recovery/tool-schemas.expected.json b/snapshots/session/compaction-recovery/tool-schemas.expected.json new file mode 100644 index 0000000000..75be989751 --- /dev/null +++ b/snapshots/session/compaction-recovery/tool-schemas.expected.json @@ -0,0 +1,1392 @@ +{ + "initial": [ + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a job id immediately; read its output with `job_output` and stop it with `job_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." + } + }, + "required": [ + "command", + "description" + ] + } + }, + { + "name": "create_goal", + "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace. Must match exactly." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "exit_plan_mode", + "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", + "parameters": { + "type": "object", + "properties": { + "plan": { + "type": "string", + "description": "The complete plan, as markdown, starting with a # heading that names it." + } + }, + "required": [ + "plan" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files whose paths match a glob pattern. Returns matching file paths — never directories — including hidden and ignored files (VCS metadata directories are excluded). Up to 100 paths come back in modification-time order; a larger result returns the first 100 paths in modification-time order, says so, and reports where the complete sorted list was saved. This tool does not enumerate directory entries.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns the first 250 matches inline; a capped result reports where the complete match list was saved. Use read on a matched file for surrounding context.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "interrupt_agent", + "description": "Request cancellation of a background agent's current turn by its agent id. The target may be your direct child or a deeper agent created under you. Only the current turn stops: messages already queued for the agent stay parked until a later send_message, agents it started keep running, and the agent itself stays available for follow-ups. This call returns as soon as the stop request is accepted, so the target may keep running briefly; interrupting an agent that already finished is an accepted no-op.", + "parameters": { + "type": "object", + "properties": { + "agent_id": { + "type": "string", + "description": "The agent id of the running agent to interrupt." + } + }, + "required": [ + "agent_id" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job by job id. Returns immediately; the job settles as killed once its work actually stops.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job. Stream jobs return only output since the previous read; final-output jobs return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the job alive." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your continuable background subagents by durable id and label. Use it to recall which ones you started, not to poll for completion — you are told when one finishes. Status comes from the live registry: running means the agent is working right now, idle means it is loaded but between turns (it may be waiting on agents it started), and ready means it exists only in storage — resumable, not terminal, and not a result waiting to be collected; a `send_message` starts a new turn on the same conversation, and a direct child remains a `send_message` candidate in every status. The snapshot is not a delivery promise — `send_message` performs the authoritative check and may still fail. Children that could not be read are reported as diagnostics instead of being silently dropped. Scope `descendants` walks the whole tree below you in stable pre-order, annotating each entry with its durable direct-parent session id and depth. You may use `send_message` only for depth-1 entries; deeper entries are candidates for `interrupt_agent` only.", + "parameters": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "description": "children (default) lists direct children only; descendants walks the complete tree below you.", + "enum": [ + "children", + "descendants" + ] + } + } + } + }, + { + "name": "list_subagent_models", + "description": "Discover LLM routes for subagents without changing the current Agent. Call with no arguments to list registered providers, with `provider` to list its advertised models, or with `provider` and `model` to inspect that exact model and its reasoning efforts. Catalog membership is advisory: an adapter may accept an unlisted model id. Use the returned ids with a delegation tool's `provider`, `model`, and `reasoning_effort` fields.", + "parameters": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "description": "Registered LLM provider id. Omit to list providers." + }, + "model": { + "type": "string", + "description": "Exact model id to inspect. Requires provider; omit to list that provider's advertised models." + } + } + } + }, + { + "name": "ralph", + "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The immutable completion objective for every fresh Ralph round." + }, + "maxRounds": { + "type": "number", + "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Harness validates and downscales large supported images before the next model request, so use this tool directly instead of installing image libraries or creating thumbnails merely to inspect an image. Independent files may be read concurrently in small batches. Requires the current model to accept image input.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to a background subagent by its subagent id, continuing the same conversation. It becomes the subagent's next turn: if it is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. This call returns no answer from the subagent — only confirmation that the message was delivered — so use it to give it more work. A failure means the message was NOT delivered.", + "parameters": { + "type": "object", + "properties": { + "subagent_id": { + "type": "string", + "description": "The subagent id returned when the background subagent was started." + }, + "message": { + "type": "string", + "description": "The message to deliver to the subagent." + } + }, + "required": [ + "subagent_id", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "str_replace_editor", + "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with ``\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.", + "enum": [ + "view", + "create", + "str_replace", + "insert" + ] + }, + "path": { + "type": "string", + "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." + }, + "file_text": { + "type": "string", + "description": "Required parameter of `create` command, with the content of the file to be created." + }, + "insert_line": { + "type": "integer", + "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." + }, + "new_str": { + "type": "string", + "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." + }, + "old_str": { + "type": "string", + "description": "Required parameter of `str_replace` command containing the string in `path` to replace." + }, + "view_range": { + "type": "array", + "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.", + "items": { + "type": "integer" + } + } + }, + "required": [ + "command", + "path" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result. Child LLM selection is optional. Omit `provider`, `model`, and `reasoning_effort` to use configured child defaults and inherit compatible missing values from the parent Agent. Supply `provider` and `model` together after using `list_subagent_models` to inspect advertised routes and efforts. Changing the effective route without naming an effort uses the selected model's default effort.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + }, + "provider": { + "type": "string", + "description": "LLM provider route for the child. Supply together with model; omit both to use configured child defaults or inherit the parent route." + }, + "model": { + "type": "string", + "description": "Model id interpreted by provider. Supply together with provider; omit both to use configured child defaults or inherit the parent route." + }, + "reasoning_effort": { + "type": "string", + "description": "Adapter-owned reasoning effort for the effective child route. Omit to inherit a compatible configured/parent effort or use a newly selected model's default." + }, + "run_in_background": { + "type": "boolean", + "description": "Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This call waits for the subagent and returns its result.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Mark every todo being actively worked on `in_progress` — several at once when work genuinely runs in parallel (e.g. concurrent subagents or background commands), one for sequential work; while work remains, at least one task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit | pause | resume | complete | blocked", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Concrete blocking condition; required only with action blocked." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Provide 1–4 queries in the required queries array. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "Required search queries; accepts 1–4 items and merges their results.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return ` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return `)." + }, + "meta": { + "type": "object", + "description": "The workflow identity block (plain JSON — never code).", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [ + [ + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a job id immediately; read its output with `job_output` and stop it with `job_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." + } + }, + "required": [ + "command", + "description" + ] + } + }, + { + "name": "create_goal", + "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace. Must match exactly." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "exit_plan_mode", + "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", + "parameters": { + "type": "object", + "properties": { + "plan": { + "type": "string", + "description": "The complete plan, as markdown, starting with a # heading that names it." + } + }, + "required": [ + "plan" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files whose paths match a glob pattern. Returns matching file paths — never directories — including hidden and ignored files (VCS metadata directories are excluded). Up to 100 paths come back in modification-time order; a larger result returns the first 100 paths in modification-time order, says so, and reports where the complete sorted list was saved. This tool does not enumerate directory entries.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns the first 250 matches inline; a capped result reports where the complete match list was saved. Use read on a matched file for surrounding context.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "interrupt_agent", + "description": "Request cancellation of a background agent's current turn by its agent id. The target may be your direct child or a deeper agent created under you. Only the current turn stops: messages already queued for the agent stay parked until a later send_message, agents it started keep running, and the agent itself stays available for follow-ups. This call returns as soon as the stop request is accepted, so the target may keep running briefly; interrupting an agent that already finished is an accepted no-op.", + "parameters": { + "type": "object", + "properties": { + "agent_id": { + "type": "string", + "description": "The agent id of the running agent to interrupt." + } + }, + "required": [ + "agent_id" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job by job id. Returns immediately; the job settles as killed once its work actually stops.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job. Stream jobs return only output since the previous read; final-output jobs return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the job alive." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your continuable background subagents by durable id and label. Use it to recall which ones you started, not to poll for completion — you are told when one finishes. Status comes from the live registry: running means the agent is working right now, idle means it is loaded but between turns (it may be waiting on agents it started), and ready means it exists only in storage — resumable, not terminal, and not a result waiting to be collected; a `send_message` starts a new turn on the same conversation, and a direct child remains a `send_message` candidate in every status. The snapshot is not a delivery promise — `send_message` performs the authoritative check and may still fail. Children that could not be read are reported as diagnostics instead of being silently dropped. Scope `descendants` walks the whole tree below you in stable pre-order, annotating each entry with its durable direct-parent session id and depth. You may use `send_message` only for depth-1 entries; deeper entries are candidates for `interrupt_agent` only.", + "parameters": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "description": "children (default) lists direct children only; descendants walks the complete tree below you.", + "enum": [ + "children", + "descendants" + ] + } + } + } + }, + { + "name": "list_subagent_models", + "description": "Discover LLM routes for subagents without changing the current Agent. Call with no arguments to list registered providers, with `provider` to list its advertised models, or with `provider` and `model` to inspect that exact model and its reasoning efforts. Catalog membership is advisory: an adapter may accept an unlisted model id. Use the returned ids with a delegation tool's `provider`, `model`, and `reasoning_effort` fields.", + "parameters": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "description": "Registered LLM provider id. Omit to list providers." + }, + "model": { + "type": "string", + "description": "Exact model id to inspect. Requires provider; omit to list that provider's advertised models." + } + } + } + }, + { + "name": "ralph", + "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The immutable completion objective for every fresh Ralph round." + }, + "maxRounds": { + "type": "number", + "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Harness validates and downscales large supported images before the next model request, so use this tool directly instead of installing image libraries or creating thumbnails merely to inspect an image. Independent files may be read concurrently in small batches. Requires the current model to accept image input.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to a background subagent by its subagent id, continuing the same conversation. It becomes the subagent's next turn: if it is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. This call returns no answer from the subagent — only confirmation that the message was delivered — so use it to give it more work. A failure means the message was NOT delivered.", + "parameters": { + "type": "object", + "properties": { + "subagent_id": { + "type": "string", + "description": "The subagent id returned when the background subagent was started." + }, + "message": { + "type": "string", + "description": "The message to deliver to the subagent." + } + }, + "required": [ + "subagent_id", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "str_replace_editor", + "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with ``\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.", + "enum": [ + "view", + "create", + "str_replace", + "insert" + ] + }, + "path": { + "type": "string", + "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`." + }, + "file_text": { + "type": "string", + "description": "Required parameter of `create` command, with the content of the file to be created." + }, + "insert_line": { + "type": "integer", + "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`." + }, + "new_str": { + "type": "string", + "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert." + }, + "old_str": { + "type": "string", + "description": "Required parameter of `str_replace` command containing the string in `path` to replace." + }, + "view_range": { + "type": "array", + "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.", + "items": { + "type": "integer" + } + } + }, + "required": [ + "command", + "path" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result. Child LLM selection is optional. Omit `provider`, `model`, and `reasoning_effort` to use configured child defaults and inherit compatible missing values from the parent Agent. Supply `provider` and `model` together after using `list_subagent_models` to inspect advertised routes and efforts. Changing the effective route without naming an effort uses the selected model's default effort.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + }, + "provider": { + "type": "string", + "description": "LLM provider route for the child. Supply together with model; omit both to use configured child defaults or inherit the parent route." + }, + "model": { + "type": "string", + "description": "Model id interpreted by provider. Supply together with provider; omit both to use configured child defaults or inherit the parent route." + }, + "reasoning_effort": { + "type": "string", + "description": "Adapter-owned reasoning effort for the effective child route. Omit to inherit a compatible configured/parent effort or use a newly selected model's default." + }, + "run_in_background": { + "type": "boolean", + "description": "Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This call waits for the subagent and returns its result.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Mark every todo being actively worked on `in_progress` — several at once when work genuinely runs in parallel (e.g. concurrent subagents or background commands), one for sequential work; while work remains, at least one task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit | pause | resume | complete | blocked", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Concrete blocking condition; required only with action blocked." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Provide 1–4 queries in the required queries array. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "Required search queries; accepts 1–4 items and merges their results.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return ` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return `)." + }, + "meta": { + "type": "object", + "description": "The workflow identity block (plain JSON — never code).", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ] + ] +} diff --git a/snapshots/session/headless.snapshot.ts b/snapshots/session/headless.snapshot.ts index 6e31924b5d..c22ede5c5b 100644 --- a/snapshots/session/headless.snapshot.ts +++ b/snapshots/session/headless.snapshot.ts @@ -426,8 +426,12 @@ async function verifyHeaders(scenario: HeadlessScenario, actualLogs: readonly Se const base = reconstructed[index] ?? reconstructed[0] const expected = selectedSchemas === undefined ? base : { ...base as JsonObject, tools: selectedSchemas } expect(header, `${scenario.name}: request header ${index + 1}`).toEqual(expected) - expect(formatSystemPromptSnapshot(prompts[index] as string), `${scenario.name}: system prompt ${index + 1}`) - .toBe(childPrompts.get(logIndex) ?? prompt) + } + if (prompts.length > 0) { + expect( + formatSystemPromptSnapshot(prompts[0] as string, prompts.slice(1)), + `${scenario.name}: system prompts`, + ).toBe(childPrompts.get(logIndex) ?? prompt) } } } diff --git a/snapshots/session/session-sandbox-root/session.jsonl b/snapshots/session/session-sandbox-root/session.jsonl index 1318431a16..5c8cb8416c 100644 --- a/snapshots/session/session-sandbox-root/session.jsonl +++ b/snapshots/session/session-sandbox-root/session.jsonl @@ -1,4 +1,4 @@ -{"type":"session","version":0,"id":"{{session:1}}","createdAt":0,"cwd":"/Users/cty/acp-snap-cwd-MABAjO","delegationDepth":0} +{"type":"session","version":0,"id":"{{session:1}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0} {"type":"permission/preset","data":{"preset":"workspace-write"}} {"type":"sandbox/mode","data":{"mode":"workspace-write"}} {"type":"approval/policy","data":{"policy":"ask"}} @@ -7,7 +7,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool (NOT bash) to create session-root.txt in the current directory containing exactly: session root. Then reply with exactly the single word DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"/Users/cty/acp-snap-cwd-MABAjO\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"/Users/cty/acp-snap-cwd-MABAjO\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} {"type":"session/title","data":{"title":"Use the write tool (NOT","messageSeqs":[7],"source":{"kind":"fallback"}}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} @@ -18,7 +18,7 @@ {"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_session_root","name":"write","arguments":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:3}}"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[12,13,14,15,16],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_session_root","name":"write","arguments":"{\"file_path\":\"session-root.txt\",\"content\":\"session root\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_session_root"},"content":[{"type":"tool-result","toolCallId":"call_session_root","content":[{"type":"text","text":"/Users/cty/acp-snap-cwd-MABAjO/session-root.txt\nfile\n\nCreated file\n"}],"isError":false}],"role":"user","id":"{{message:4}}"},"meta":{"diffs":[]}},"sourceEventSeqs":[18],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_session_root"},"content":[{"type":"tool-result","toolCallId":"call_session_root","content":[{"type":"text","text":"{{cwd}}/session-root.txt\nfile\n\nCreated file\n"}],"isError":false}],"role":"user","id":"{{message:4}}"},"meta":{"diffs":[]}},"sourceEventSeqs":[18],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} diff --git a/snapshots/web/bash-abort-row/ui.expected.md b/snapshots/web/bash-abort-row/ui.expected.md index b48a5c6bcc..f4b07c037f 100644 --- a/snapshots/web/bash-abort-row/ui.expected.md +++ b/snapshots/web/bash-abort-row/ui.expected.md @@ -7,6 +7,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Run two shell commands: wait for cancellation, then write skipped.txt. {{clock}}" - button "Copy": - img diff --git a/snapshots/web/code-mode-round/ui.expected.md b/snapshots/web/code-mode-round/ui.expected.md index d9809ed53f..bcdd6b6c5d 100644 --- a/snapshots/web/code-mode-round/ui.expected.md +++ b/snapshots/web/code-mode-round/ui.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Using ONE run_code program: run bash `echo CODE_ROUND_OK`, then read the file missing.txt catching its error in the program. Return an object with both outcomes. Then reply DONE and stop. {{clock}}" - button "Copy": - img diff --git a/snapshots/web/cordis-tool-round/ui.expected.md b/snapshots/web/cordis-tool-round/ui.expected.md index cc05c3aed9..2586c609f4 100644 --- a/snapshots/web/cordis-tool-round/ui.expected.md +++ b/snapshots/web/cordis-tool-round/ui.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Use only Cordis tools. First call cordis_inspect_self with no arguments. Then call cordis_define with plugin kind \"new\", idPrefix \"snap\", name \"snapshot noop\", purpose \"does nothing, for the snapshot\", code.host exactly \"return { name: \\\"snapshot-noop\\\", apply(ctx) {} }\" and code.client exactly \"return { inject: [\\\"slots\\\"], apply(ctx) { ctx.slots.register({ name: \\\"shell.overlay\\\", id: \\\"snapshot-probe\\\" }, () => React.createElement(\\\"div\\\", { \\\"data-snapshot-probe\\\": \\\"loaded\\\" })) } }\". Read its returned pluginId and packageId, then call cordis_run with those exact IDs and mode \"run\". After the run request returns, reply exactly CORDIS_UI_READY and stop. {{clock}}" - button "Copy": - img diff --git a/snapshots/web/feedback-command/ack.expected.md b/snapshots/web/feedback-command/ack.expected.md index c12ffc2a97..df302f69ed 100644 --- a/snapshots/web/feedback-command/ack.expected.md +++ b/snapshots/web/feedback-command/ack.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with the single word LIGHTHOUSE and stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/fresh-round-trip/ui.expected.md b/snapshots/web/fresh-round-trip/ui.expected.md index 5a1f64faf8..c7822c503d 100644 --- a/snapshots/web/fresh-round-trip/ui.expected.md +++ b/snapshots/web/fresh-round-trip/ui.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop. {{clock}}" - button "Copy": - img diff --git a/snapshots/web/goal-multi-turn-actions/session.jsonl b/snapshots/web/goal-multi-turn-actions/session.jsonl index 8b2e221682..78d92f9a19 100644 --- a/snapshots/web/goal-multi-turn-actions/session.jsonl +++ b/snapshots/web/goal-multi-turn-actions/session.jsonl @@ -1,9 +1,9 @@ -{"type":"session","version":0,"id":"{{session:1}}","createdAt":1787543212737,"cwd":"{{cwd}}","agentPreset":"standard"} +{"type":"session","version":0,"id":"{{session:1}}","createdAt":1787640083383,"cwd":"{{cwd}}","agentPreset":"standard"} {"type":"permission/preset","data":{"preset":"workspace-write"}} {"type":"sandbox/mode","data":{"mode":"workspace-write"}} {"type":"approval/policy","data":{"policy":"ask"}} {"type":"command/run","data":{"commandId":"{{command:1}}","name":"goal","args":" 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的","source":{"kind":"user"}}} -{"type":"goal/change","data":{"kind":"goal/change","version":1,"operation":"create","goal":{"id":"{{id:1}}","revision":1,"objective":"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的","phase":"active","maxGoalRounds":256},"roundsStarted":0,"createdAt":1787543212949,"updatedAt":1787543212949}} +{"type":"goal/change","data":{"kind":"goal/change","version":1,"operation":"create","goal":{"id":"{{id:1}}","revision":1,"objective":"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的","phase":"active","maxGoalRounds":256},"roundsStarted":0,"createdAt":1787640083556,"updatedAt":1787640083556}} {"type":"command/done","data":{"commandId":"{{command:1}}","kind":"success","text":"Goal created\nStatus: active\nObjective: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\nRounds: 0/256\nActivation: armed\n\nCommands: /goal edit , /goal pause, /goal clear"}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"\nObjective: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\"\nRound: 1/256\n\nContinue working toward the objective in this same session. Treat the current workspace, tool results, and durable session state as authoritative; inspect them instead of assuming earlier narration is still current. Make concrete progress and verify the result. Before claiming completion, gather evidence that the whole objective is achieved, read the current goal, and mark it complete. If work remains, leave the goal active for the next round. Follow the configured goal-tool policy before reporting a blocker.\n"}],"source":{"kind":"goal","goalId":"{{id:1}}","revision":1,"round":1},"role":"user","id":"{{message:1}}"}]}} {"type":"turn/start","data":{"turn":1}} @@ -84,9 +84,9 @@ {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"reasoning-chunks","data":{"turn":1,"step":6,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0],"texts":["Turn"," ","1"," is"," done","."," Per"," the"," objective",":"," \"","你","做完","一个","turn","之后",",","直接","输出","内容",",","停止","\""," —"," after"," finishing"," a"," turn",","," directly"," output"," the"," content"," and"," stop","."," The"," system"," will"," open"," another"," turn",".\n\n","So"," I"," should"," just"," output"," the"," file"," structure"," of"," this"," randomly"," picked"," package"," (","pack","ages","/","context","/s","ession","-reference",")"," and"," stop","."," I"," should"," NOT"," mark"," the"," goal"," complete"," since"," there"," are"," ","2"," turns"," and"," this"," is"," only"," turn"," ","1","."," The"," objective"," says"," the"," system"," will"," open"," another"," turn"," —"," so"," I"," should"," leave"," the"," goal"," active"," for"," the"," next"," round",".\n\n","Let"," me"," output"," the"," file"," structure"," in"," a"," nice"," tree"," format","."]}} +{"type":"reasoning-chunks","data":{"turn":1,"step":6,"index":0,"dt":[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],"texts":["Turn"," ","1"," is"," done","."," Per"," the"," objective",":"," \"","你","做完","一个","turn","之后",",","直接","输出","内容",",","停止","\""," —"," after"," finishing"," a"," turn",","," directly"," output"," the"," content"," and"," stop","."," The"," system"," will"," open"," another"," turn",".\n\n","So"," I"," should"," just"," output"," the"," file"," structure"," of"," this"," randomly"," picked"," package"," (","pack","ages","/","context","/s","ession","-reference",")"," and"," stop","."," I"," should"," NOT"," mark"," the"," goal"," complete"," since"," there"," are"," ","2"," turns"," and"," this"," is"," only"," turn"," ","1","."," The"," objective"," says"," the"," system"," will"," open"," another"," turn"," —"," so"," I"," should"," leave"," the"," goal"," active"," for"," the"," next"," round",".\n\n","Let"," me"," output"," the"," file"," structure"," in"," a"," nice"," tree"," format","."]}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"text-chunks","data":{"turn":1,"step":6,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["**","Turn"," ","1"," /"," ","2","**"," —"," ","随机","选","中的","包",":","`","pack","ages","/","context","/s","ession","-reference","`"," 📦","\n\n","```\n","session","-reference","\n","├","──"," READ","ME",".md","\n","├","──"," package",".json","\n","├","──"," src","\n","│"," "," ├","──"," index",".ts","\n","│"," "," └","──"," uri",".ts","\n","└","──"," tests","\n"," "," └","──"," session","-reference",".s","pec",".ts","\n","```\n\n","```\n","session","-reference","/\n","├","──"," READ","ME",".md"," "," #"," ","包","说明","文档","\n","├","──"," package",".json"," "," #"," ","包","元","数据","与","依赖","声明","\n","├","──"," src","/\n","│"," "," ├","──"," index",".ts"," "," #"," ","入口",",","导出","公共"," API","\n","│"," "," └","──"," uri",".ts"," "," #"," ","会话","引用"," URI"," ","相关","实现","\n","└","──"," tests","/\n"," "," └","──"," session","-reference",".s","pec",".ts"," "," #"," ","单元","测试","\n","```\n\n","这是一个","很","典型的","轻","量"," Type","Script"," ","包","结构",":","入口"," +"," ","实现"," +"," ","测试","。","这一","轮","到此","结束",",","等","系统","开启","下一个"," turn","。"]}} +{"type":"text-chunks","data":{"turn":1,"step":6,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["**","Turn"," ","1"," /"," ","2","**"," —"," ","随机","选","中的","包",":","`","pack","ages","/","context","/s","ession","-reference","`"," 📦","\n\n","```\n","session","-reference","\n","├","──"," READ","ME",".md","\n","├","──"," package",".json","\n","├","──"," src","\n","│"," "," ├","──"," index",".ts","\n","│"," "," └","──"," uri",".ts","\n","└","──"," tests","\n"," "," └","──"," session","-reference",".s","pec",".ts","\n","```\n\n","```\n","session","-reference","/\n","├","──"," READ","ME",".md"," "," #"," ","包","说明","文档","\n","├","──"," package",".json"," "," #"," ","包","元","数据","与","依赖","声明","\n","├","──"," src","/\n","│"," "," ├","──"," index",".ts"," "," #"," ","入口",",","导出","公共"," API","\n","│"," "," └","──"," uri",".ts"," "," #"," ","会话","引用"," URI"," ","相关","实现","\n","└","──"," tests","/\n"," "," └","──"," session","-reference",".s","pec",".ts"," "," #"," ","单元","测试","\n","```\n\n","这是一个","很","典型的","轻","量"," Type","Script"," ","包","结构",":","入口"," +"," ","实现"," +"," ","测试","。","这一","轮","到此","结束",",","等","系统","开启","下一个"," turn","。"]}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Turn 1 is done. Per the objective: \"你做完一个turn之后,直接输出内容,停止\" — after finishing a turn, directly output the content and stop. The system will open another turn.\n\nSo I should just output the file structure of this randomly picked package (packages/context/session-reference) and stop. I should NOT mark the goal complete since there are 2 turns and this is only turn 1. The objective says the system will open another turn — so I should leave the goal active for the next round.\n\nLet me output the file structure in a nice tree format."}}}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"**Turn 1 / 2** — 随机选中的包:`packages/context/session-reference` 📦\n\n```\nsession-reference\n├── README.md\n├── package.json\n├── src\n│ ├── index.ts\n│ └── uri.ts\n└── tests\n └── session-reference.spec.ts\n```\n\n```\nsession-reference/\n├── README.md # 包说明文档\n├── package.json # 包元数据与依赖声明\n├── src/\n│ ├── index.ts # 入口,导出公共 API\n│ └── uri.ts # 会话引用 URI 相关实现\n└── tests/\n └── session-reference.spec.ts # 单元测试\n```\n\n这是一个很典型的轻量 TypeScript 包结构:入口 + 实现 + 测试。这一轮到此结束,等系统开启下一个 turn。"}}}} {"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":166,"outputTokens":318,"cacheReadTokens":9088,"reasoningTokens":123}}}} @@ -99,6 +99,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"user/message","data":{"content":[{"type":"text","text":"\nObjective: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\"\nRound: 2/256\n\nContinue working toward the objective in this same session. Treat the current workspace, tool results, and durable session state as authoritative; inspect them instead of assuming earlier narration is still current. Make concrete progress and verify the result. Before claiming completion, gather evidence that the whole objective is achieved, read the current goal, and mark it complete. If work remains, leave the goal active for the next round. Follow the configured goal-tool policy before reporting a blocker.\n"}],"source":{"kind":"goal","goalId":"{{id:1}}","revision":1,"round":2},"role":"user","id":"{{message:15}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"series"}} {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"This is turn 2 of 2. I need to randomly pick another package and output its file structure. In the first turn I picked `packages/context/session-reference`. Let me pick a different one randomly this time."}}} {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"This is turn 2 of 2. I need to randomly pick another package and output its file structure. In the first turn I picked `packages/context/session-reference`. Let me pick a different one randomly this time."}}}} @@ -107,9 +108,9 @@ {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_wwDXszkz3z9JwKb8jUXj2737","name":"bash","arguments":"{\"command\":\"python3 -c \\\"import random; from pathlib import Path; pkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json')); print(random.Random(1).choice(pkgs))\\\"\",\"description\":\"Randomly select another package with Python\"}"}}}} {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":389,"outputTokens":165,"cacheReadTokens":9216,"reasoningTokens":47}}}} {"type":"assistant/chunk","data":{"turn":2,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"This is turn 2 of 2. I need to randomly pick another package and output its file structure. In the first turn I picked `packages/context/session-reference`. Let me pick a different one randomly this time."},{"type":"tool-call","id":"call_00_wwDXszkz3z9JwKb8jUXj2737","name":"bash","arguments":"{\"command\":\"python3 -c \\\"import random; from pathlib import Path; pkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json')); print(random.Random(1).choice(pkgs))\\\"\",\"description\":\"Randomly select another package with Python\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":389,"outputTokens":165,"cacheReadTokens":9216,"reasoningTokens":47}},"sourceEventSeqs":[408,409,410,411,412,413,414,415],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"This is turn 2 of 2. I need to randomly pick another package and output its file structure. In the first turn I picked `packages/context/session-reference`. Let me pick a different one randomly this time."},{"type":"tool-call","id":"call_00_wwDXszkz3z9JwKb8jUXj2737","name":"bash","arguments":"{\"command\":\"python3 -c \\\"import random; from pathlib import Path; pkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json')); print(random.Random(1).choice(pkgs))\\\"\",\"description\":\"Randomly select another package with Python\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:16}}"},"usage":{"inputTokens":389,"outputTokens":165,"cacheReadTokens":9216,"reasoningTokens":47}},"sourceEventSeqs":[409,410,411,412,413,414,415,416],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"call_00_wwDXszkz3z9JwKb8jUXj2737","name":"bash","arguments":"{\"command\":\"python3 -c \\\"import random; from pathlib import Path; pkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json')); print(random.Random(1).choice(pkgs))\\\"\",\"description\":\"Randomly select another package with Python\"}"}} -{"type":"tool/result","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_wwDXszkz3z9JwKb8jUXj2737"},"content":[{"type":"tool-result","toolCallId":"call_00_wwDXszkz3z9JwKb8jUXj2737","content":[{"type":"text","text":"packages/context/session-reference\n"}],"isError":false}],"role":"user","id":"{{message:17}}"}},"sourceEventSeqs":[417],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_wwDXszkz3z9JwKb8jUXj2737"},"content":[{"type":"tool-result","toolCallId":"call_00_wwDXszkz3z9JwKb8jUXj2737","content":[{"type":"text","text":"packages/context/session-reference\n"}],"isError":false}],"role":"user","id":"{{message:17}}"}},"sourceEventSeqs":[418],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"step/start","data":{"turn":2,"step":2}} {"type":"assistant/chunk","data":{"turn":2,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} @@ -120,9 +121,9 @@ {"type":"assistant/chunk","data":{"turn":2,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_3K2lg9zGfGsTvuh19xv65220","name":"bash","arguments":"{\"command\": \"python3 -c \\\"\\nimport random\\nfrom pathlib import Path\\npkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json'))\\ncandidates = [p for p in pkgs if p != 'packages/context/session-reference']\\nprint(random.Random(0).choice(candidates))\\n\\\"\", \"description\": \"Re-roll excluding the package from turn 1\"}"}}}} {"type":"assistant/chunk","data":{"turn":2,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":62,"outputTokens":164,"cacheReadTokens":9728,"reasoningTokens":46}}}} {"type":"assistant/chunk","data":{"turn":2,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The random pick returned the same package as turn 1. Since turn 1 already covered `session-reference`, it would be better to pick a different one for variety. Let me re-roll, excluding the already-covered package."},{"type":"tool-call","id":"call_00_3K2lg9zGfGsTvuh19xv65220","name":"bash","arguments":"{\"command\": \"python3 -c \\\"\\nimport random\\nfrom pathlib import Path\\npkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json'))\\ncandidates = [p for p in pkgs if p != 'packages/context/session-reference']\\nprint(random.Random(0).choice(candidates))\\n\\\"\", \"description\": \"Re-roll excluding the package from turn 1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":62,"outputTokens":164,"cacheReadTokens":9728,"reasoningTokens":46}},"sourceEventSeqs":[421,422,423,424,425,426,427,428],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The random pick returned the same package as turn 1. Since turn 1 already covered `session-reference`, it would be better to pick a different one for variety. Let me re-roll, excluding the already-covered package."},{"type":"tool-call","id":"call_00_3K2lg9zGfGsTvuh19xv65220","name":"bash","arguments":"{\"command\": \"python3 -c \\\"\\nimport random\\nfrom pathlib import Path\\npkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json'))\\ncandidates = [p for p in pkgs if p != 'packages/context/session-reference']\\nprint(random.Random(0).choice(candidates))\\n\\\"\", \"description\": \"Re-roll excluding the package from turn 1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":62,"outputTokens":164,"cacheReadTokens":9728,"reasoningTokens":46}},"sourceEventSeqs":[422,423,424,425,426,427,428,429],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":2,"callId":"call_00_3K2lg9zGfGsTvuh19xv65220","name":"bash","arguments":"{\"command\": \"python3 -c \\\"\\nimport random\\nfrom pathlib import Path\\npkgs = sorted(str(path.parent) for path in Path('packages').glob('*/*/package.json'))\\ncandidates = [p for p in pkgs if p != 'packages/context/session-reference']\\nprint(random.Random(0).choice(candidates))\\n\\\"\", \"description\": \"Re-roll excluding the package from turn 1\"}"}} -{"type":"tool/result","data":{"turn":2,"step":2,"message":{"source":{"kind":"tool","callId":"call_00_3K2lg9zGfGsTvuh19xv65220"},"content":[{"type":"tool-result","toolCallId":"call_00_3K2lg9zGfGsTvuh19xv65220","content":[{"type":"text","text":"packages/llm/token-meter\n"}],"isError":false}],"role":"user","id":"{{message:19}}"}},"sourceEventSeqs":[430],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":2,"message":{"source":{"kind":"tool","callId":"call_00_3K2lg9zGfGsTvuh19xv65220"},"content":[{"type":"tool-result","toolCallId":"call_00_3K2lg9zGfGsTvuh19xv65220","content":[{"type":"text","text":"packages/llm/token-meter\n"}],"isError":false}],"role":"user","id":"{{message:19}}"}},"sourceEventSeqs":[431],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":2}} {"type":"step/start","data":{"turn":2,"step":3}} {"type":"assistant/chunk","data":{"turn":2,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} @@ -130,15 +131,15 @@ {"type":"assistant/chunk","data":{"turn":2,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_00_ET_mh4Jb1yklK6bS4luMCFO2893","name":"bash","arguments":"{\"command\":\"find packages/llm/token-meter -type f -not -path '*/node_modules/*' -not -path '*/.git/*' | LC_ALL=C sort\",\"description\":\"List all files in token-meter package\"}"}}}} {"type":"assistant/chunk","data":{"turn":2,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":119,"outputTokens":96,"cacheReadTokens":9856,"reasoningTokens":0}}}} {"type":"assistant/chunk","data":{"turn":2,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":2,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_00_ET_mh4Jb1yklK6bS4luMCFO2893","name":"bash","arguments":"{\"command\":\"find packages/llm/token-meter -type f -not -path '*/node_modules/*' -not -path '*/.git/*' | LC_ALL=C sort\",\"description\":\"List all files in token-meter package\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":119,"outputTokens":96,"cacheReadTokens":9856,"reasoningTokens":0}},"sourceEventSeqs":[434,435,436,437,438],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":2,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_00_ET_mh4Jb1yklK6bS4luMCFO2893","name":"bash","arguments":"{\"command\":\"find packages/llm/token-meter -type f -not -path '*/node_modules/*' -not -path '*/.git/*' | LC_ALL=C sort\",\"description\":\"List all files in token-meter package\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":119,"outputTokens":96,"cacheReadTokens":9856,"reasoningTokens":0}},"sourceEventSeqs":[435,436,437,438,439],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":3,"callId":"call_00_ET_mh4Jb1yklK6bS4luMCFO2893","name":"bash","arguments":"{\"command\":\"find packages/llm/token-meter -type f -not -path '*/node_modules/*' -not -path '*/.git/*' | LC_ALL=C sort\",\"description\":\"List all files in token-meter package\"}"}} -{"type":"tool/result","data":{"turn":2,"step":3,"message":{"source":{"kind":"tool","callId":"call_00_ET_mh4Jb1yklK6bS4luMCFO2893"},"content":[{"type":"tool-result","toolCallId":"call_00_ET_mh4Jb1yklK6bS4luMCFO2893","content":[{"type":"text","text":"packages/llm/token-meter/README.md\npackages/llm/token-meter/package.json\npackages/llm/token-meter/src/index.ts\npackages/llm/token-meter/tests/token-meter.spec.ts\n"}],"isError":false}],"role":"user","id":"{{message:21}}"}},"sourceEventSeqs":[440],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":3,"message":{"source":{"kind":"tool","callId":"call_00_ET_mh4Jb1yklK6bS4luMCFO2893"},"content":[{"type":"tool-result","toolCallId":"call_00_ET_mh4Jb1yklK6bS4luMCFO2893","content":[{"type":"text","text":"packages/llm/token-meter/README.md\npackages/llm/token-meter/package.json\npackages/llm/token-meter/src/index.ts\npackages/llm/token-meter/tests/token-meter.spec.ts\n"}],"isError":false}],"role":"user","id":"{{message:21}}"}},"sourceEventSeqs":[441],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":3}} {"type":"step/start","data":{"turn":2,"step":4}} {"type":"assistant/chunk","data":{"turn":2,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} -{"type":"reasoning-chunks","data":{"turn":2,"step":4,"index":0,"dt":[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],"texts":["This"," is"," turn"," ","2"," of"," ","2","."," I","'ve"," output"," the"," file"," structure"," for"," `","pack","ages","/","ll","m","/t","oken","-meter","`."," Both"," turns"," are"," done","."," I"," should"," output"," the"," content",","," stop",","," and"," then"," mark"," the"," goal"," as"," complete"," since"," both"," turns"," are"," finished","."]}} +{"type":"reasoning-chunks","data":{"turn":2,"step":4,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["This"," is"," turn"," ","2"," of"," ","2","."," I","'ve"," output"," the"," file"," structure"," for"," `","pack","ages","/","ll","m","/t","oken","-meter","`."," Both"," turns"," are"," done","."," I"," should"," output"," the"," content",","," stop",","," and"," then"," mark"," the"," goal"," as"," complete"," since"," both"," turns"," are"," finished","."]}} {"type":"assistant/chunk","data":{"turn":2,"step":4,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} -{"type":"text-chunks","data":{"turn":2,"step":4,"index":1,"dt":[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],"texts":["**","Turn"," ","2"," /"," ","2","**"," —"," ","随机","选","中的","包",":","`","pack","ages","/","ll","m","/t","oken","-meter","`"," 📦","\n\n","```\n","token","-meter","\n","├","──"," READ","ME",".md","\n","├","──"," package",".json","\n","├","──"," src","\n","│"," "," └","──"," index",".ts","\n","└","──"," tests","\n"," "," └","──"," token","-meter",".s","pec",".ts","\n","```\n\n","```\n","token","-meter","/\n","├","──"," READ","ME",".md"," "," #"," ","包","说明","文档","\n","├","──"," package",".json"," "," #"," ","包","元","数据","与","依赖","声明","\n","├","──"," src","/\n","│"," "," └","──"," index",".ts"," "," #"," ","入口",",","导出","公共"," API","(","token"," ","计量","逻辑",")\n","└","──"," tests","/\n"," "," └","──"," token","-meter",".s","pec",".ts"," "," #"," ","单元","测试","\n","```\n\n","两个"," turn"," ","都","完成了","(","turn"," ","1",":","`","session","-reference","`",",","turn"," ","2",":","`","token","-meter","`",")。","这一","轮","到此","结束","。"]}} +{"type":"text-chunks","data":{"turn":2,"step":4,"index":1,"dt":[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["**","Turn"," ","2"," /"," ","2","**"," —"," ","随机","选","中的","包",":","`","pack","ages","/","ll","m","/t","oken","-meter","`"," 📦","\n\n","```\n","token","-meter","\n","├","──"," READ","ME",".md","\n","├","──"," package",".json","\n","├","──"," src","\n","│"," "," └","──"," index",".ts","\n","└","──"," tests","\n"," "," └","──"," token","-meter",".s","pec",".ts","\n","```\n\n","```\n","token","-meter","/\n","├","──"," READ","ME",".md"," "," #"," ","包","说明","文档","\n","├","──"," package",".json"," "," #"," ","包","元","数据","与","依赖","声明","\n","├","──"," src","/\n","│"," "," └","──"," index",".ts"," "," #"," ","入口",",","导出","公共"," API","(","token"," ","计量","逻辑",")\n","└","──"," tests","/\n"," "," └","──"," token","-meter",".s","pec",".ts"," "," #"," ","单元","测试","\n","```\n\n","两个"," turn"," ","都","完成了","(","turn"," ","1",":","`","session","-reference","`",",","turn"," ","2",":","`","token","-meter","`",")。","这一","轮","到此","结束","。"]}} {"type":"assistant/chunk","data":{"turn":2,"step":4,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}}} {"type":"assistant/chunk","data":{"turn":2,"step":4,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_AKGba6PMDSJdtJI2ZhAz7514","name":"get_goal","argumentsDelta":""}}} {"type":"assistant/chunk","data":{"turn":2,"step":4,"chunk":{"type":"tool-call-delta","index":2,"id":"call_00_AKGba6PMDSJdtJI2ZhAz7514","name":"get_goal","argumentsDelta":"{}"}}} @@ -147,9 +148,9 @@ {"type":"assistant/chunk","data":{"turn":2,"step":4,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_AKGba6PMDSJdtJI2ZhAz7514","name":"get_goal","arguments":"{}"}}}} {"type":"assistant/chunk","data":{"turn":2,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":152,"outputTokens":256,"cacheReadTokens":9984,"reasoningTokens":52}}}} {"type":"assistant/chunk","data":{"turn":2,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":2,"step":4,"message":{"role":"assistant","content":[{"type":"reasoning","text":"This is turn 2 of 2. I've output the file structure for `packages/llm/token-meter`. Both turns are done. I should output the content, stop, and then mark the goal as complete since both turns are finished."},{"type":"text","text":"**Turn 2 / 2** — 随机选中的包:`packages/llm/token-meter` 📦\n\n```\ntoken-meter\n├── README.md\n├── package.json\n├── src\n│ └── index.ts\n└── tests\n └── token-meter.spec.ts\n```\n\n```\ntoken-meter/\n├── README.md # 包说明文档\n├── package.json # 包元数据与依赖声明\n├── src/\n│ └── index.ts # 入口,导出公共 API(token 计量逻辑)\n└── tests/\n └── token-meter.spec.ts # 单元测试\n```\n\n两个 turn 都完成了(turn 1:`session-reference`,turn 2:`token-meter`)。这一轮到此结束。"},{"type":"tool-call","id":"call_00_AKGba6PMDSJdtJI2ZhAz7514","name":"get_goal","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:22}}"},"usage":{"inputTokens":152,"outputTokens":256,"cacheReadTokens":9984,"reasoningTokens":52}},"sourceEventSeqs":[444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":2,"step":4,"message":{"role":"assistant","content":[{"type":"reasoning","text":"This is turn 2 of 2. I've output the file structure for `packages/llm/token-meter`. Both turns are done. I should output the content, stop, and then mark the goal as complete since both turns are finished."},{"type":"text","text":"**Turn 2 / 2** — 随机选中的包:`packages/llm/token-meter` 📦\n\n```\ntoken-meter\n├── README.md\n├── package.json\n├── src\n│ └── index.ts\n└── tests\n └── token-meter.spec.ts\n```\n\n```\ntoken-meter/\n├── README.md # 包说明文档\n├── package.json # 包元数据与依赖声明\n├── src/\n│ └── index.ts # 入口,导出公共 API(token 计量逻辑)\n└── tests/\n └── token-meter.spec.ts # 单元测试\n```\n\n两个 turn 都完成了(turn 1:`session-reference`,turn 2:`token-meter`)。这一轮到此结束。"},{"type":"tool-call","id":"call_00_AKGba6PMDSJdtJI2ZhAz7514","name":"get_goal","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:22}}"},"usage":{"inputTokens":152,"outputTokens":256,"cacheReadTokens":9984,"reasoningTokens":52}},"sourceEventSeqs":[445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":4,"callId":"call_00_AKGba6PMDSJdtJI2ZhAz7514","name":"get_goal","arguments":"{}"}} -{"type":"tool/result","data":{"turn":2,"step":4,"message":{"source":{"kind":"tool","callId":"call_00_AKGba6PMDSJdtJI2ZhAz7514"},"content":[{"type":"tool-result","toolCallId":"call_00_AKGba6PMDSJdtJI2ZhAz7514","content":[{"type":"text","text":"{\"goal\":{\"id\":\"{{id:1}}\",\"revision\":1,\"objective\":\"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\",\"phase\":\"active\",\"roundsStarted\":2,\"maxGoalRounds\":256},\"activation\":\"armed\"}"}],"isError":false}],"role":"user","id":"{{message:23}}"}},"sourceEventSeqs":[676],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":4,"message":{"source":{"kind":"tool","callId":"call_00_AKGba6PMDSJdtJI2ZhAz7514"},"content":[{"type":"tool-result","toolCallId":"call_00_AKGba6PMDSJdtJI2ZhAz7514","content":[{"type":"text","text":"{\"goal\":{\"id\":\"{{id:1}}\",\"revision\":1,\"objective\":\"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\",\"phase\":\"active\",\"roundsStarted\":2,\"maxGoalRounds\":256},\"activation\":\"armed\"}"}],"isError":false}],"role":"user","id":"{{message:23}}"}},"sourceEventSeqs":[677],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":4}} {"type":"step/start","data":{"turn":2,"step":5}} {"type":"assistant/chunk","data":{"turn":2,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} @@ -160,20 +161,20 @@ {"type":"assistant/chunk","data":{"turn":2,"step":5,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_goal_complete","name":"update_goal","arguments":"{\"goal_id\":\"{{id:1}}\",\"revision\":1,\"action\":\"complete\"}"}}}} {"type":"assistant/chunk","data":{"turn":2,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":132,"outputTokens":157,"cacheReadTokens":10368,"reasoningTokens":44}}}} {"type":"assistant/chunk","data":{"turn":2,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","data":{"turn":2,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"两个 turn 均已完成,目标达成,标记 goal 为完成。"},{"type":"tool-call","id":"call_goal_complete","name":"update_goal","arguments":"{\"goal_id\":\"{{id:1}}\",\"revision\":1,\"action\":\"complete\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:24}}"},"usage":{"inputTokens":132,"outputTokens":157,"cacheReadTokens":10368,"reasoningTokens":44}},"sourceEventSeqs":[680,681,682,683,684,685,686,687],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":2,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"两个 turn 均已完成,目标达成,标记 goal 为完成。"},{"type":"tool-call","id":"call_goal_complete","name":"update_goal","arguments":"{\"goal_id\":\"{{id:1}}\",\"revision\":1,\"action\":\"complete\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:24}}"},"usage":{"inputTokens":132,"outputTokens":157,"cacheReadTokens":10368,"reasoningTokens":44}},"sourceEventSeqs":[681,682,683,684,685,686,687,688],"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":5,"callId":"call_goal_complete","name":"update_goal","arguments":"{\"goal_id\":\"{{id:1}}\",\"revision\":1,\"action\":\"complete\"}"}} -{"type":"goal/change","data":{"kind":"goal/change","version":1,"operation":"complete","goal":{"id":"{{id:1}}","revision":2,"objective":"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的","phase":"complete","maxGoalRounds":256},"roundsStarted":2,"createdAt":1787543212949,"updatedAt":1787543213546}} -{"type":"tool/result","data":{"turn":2,"step":5,"message":{"source":{"kind":"tool","callId":"call_goal_complete"},"content":[{"type":"tool-result","toolCallId":"call_goal_complete","content":[{"type":"text","text":"{\"goal\":{\"id\":\"{{id:1}}\",\"revision\":2,\"objective\":\"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\",\"phase\":\"complete\",\"roundsStarted\":2,\"maxGoalRounds\":256},\"activation\":\"disarmed\"}"}],"isError":false}],"role":"user","id":"{{message:25}}"}},"sourceEventSeqs":[689],"surfaceOp":"append"} +{"type":"goal/change","data":{"kind":"goal/change","version":1,"operation":"complete","goal":{"id":"{{id:1}}","revision":2,"objective":"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的","phase":"complete","maxGoalRounds":256},"roundsStarted":2,"createdAt":1787640083556,"updatedAt":1787640084238}} +{"type":"tool/result","data":{"turn":2,"step":5,"message":{"source":{"kind":"tool","callId":"call_goal_complete"},"content":[{"type":"tool-result","toolCallId":"call_goal_complete","content":[{"type":"text","text":"{\"goal\":{\"id\":\"{{id:1}}\",\"revision\":2,\"objective\":\"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\",\"phase\":\"complete\",\"roundsStarted\":2,\"maxGoalRounds\":256},\"activation\":\"disarmed\"}"}],"isError":false}],"role":"user","id":"{{message:25}}"}},"sourceEventSeqs":[690],"surfaceOp":"append"} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nObjective: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\"\nThe goal is marked complete and this autonomous run is ending. Write the closing message to the user now: state the outcome, summarize what was done and how it was verified, and point to the concrete results (files, commits, or other artifacts). Report only what earlier rounds and tool results in this session actually establish; when a detail is not in the session, say so instead of inventing it. Note anything the user should review or do next. Address the user directly. Do not call any more tools in this run; further work waits for the user's next instruction.\n"}],"source":{"kind":"plugin","plugin":"tool-goal","form":"notice","summary":"complete: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的"},"role":"user","id":"{{message:26}}"}]}} {"type":"step/end","data":{"turn":2,"step":5}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":6}} {"type":"user/message","data":{"content":[{"type":"text","text":"\nObjective: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\"\nThe goal is marked complete and this autonomous run is ending. Write the closing message to the user now: state the outcome, summarize what was done and how it was verified, and point to the concrete results (files, commits, or other artifacts). Report only what earlier rounds and tool results in this session actually establish; when a detail is not in the session, say so instead of inventing it. Note anything the user should review or do next. Address the user directly. Do not call any more tools in this run; further work waits for the user's next instruction.\n"}],"source":{"kind":"plugin","plugin":"tool-goal","form":"notice","summary":"complete: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的"},"role":"user","id":"{{message:26}}"},"surfaceOp":"append"} {"type":"assistant/chunk","data":{"turn":2,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} -{"type":"text-chunks","data":{"turn":2,"step":6,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["两个"," turn"," ","都","完成了"," ✅","\n\n","**","总结",":","**\n\n","-"," **","Turn"," ","1","**"," —"," ","随机","选中"," `","pack","ages","/","context","/s","ession","-reference","`",",","输","出了","文件","结构",":\n"," "," ```\n"," "," session","-reference","/\n"," "," ├","──"," READ","ME",".md","\n"," "," ├","──"," package",".json","\n"," "," ├","──"," src","/\n"," "," │"," "," ├","──"," index",".ts","\n"," "," │"," "," └","──"," uri",".ts","\n"," "," └","──"," tests","/\n"," "," └","──"," session","-reference",".s","pec",".ts","\n"," "," ```\n","-"," **","Turn"," ","2","**"," —"," ","随机","选中"," `","pack","ages","/","ll","m","/t","oken","-meter","`",",","输","出了","文件","结构",":\n"," "," ```\n"," "," token","-meter","/\n"," "," ├","──"," READ","ME",".md","\n"," "," ├","──"," package",".json","\n"," "," ├","──"," src","/\n"," "," │"," "," └","──"," index",".ts","\n"," "," └","──"," tests","/\n"," "," └","──"," token","-meter",".s","pec",".ts","\n"," "," ```\n\n","**","验证","方式",":","**"," ","两个","包的","随机","选择","都","通过"," `","python","3"," random",".choice","`"," ","从","工作","区的"," `","pack","ages","/","`"," ","目录","下","实际","枚举","的"," ","4"," ","个","候选","包","中","抽取","(","`","ui","-con","vers","ation","`","、","`","session","-reference","`","、","`","token","-meter","`","、","`","skill","-local","`","),","文件","结构","则","用"," `","find","`"," ","实际","列出","文件","后","整理","输出",",","均已","排除"," `","node","_modules","`"," ","和"," `.","git","`","。","第二次","随机","抽","到了","与"," turn"," ","1"," ","相同的","包",",","为避免","重复","换","抽","了","另一个","。\n\n","**","说明",":","**"," ","本轮","没有","产生","任何","文件","修改","或","提交","——","任务","本身就是","\"","输出","文件","结构","\",","所有","产物","都在","上面的","消息","文本","里","。\n\n","如果你","还想","看","剩下","两个","包","(","`","ui","-con","vers","ation","`","、","`","skill","-local","`",")","的结构",",","或者其他","格式","的输出","(","比如","带","文件","大小的","树","形","图","),","随时","告诉我","。"]}} +{"type":"text-chunks","data":{"turn":2,"step":6,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["两个"," turn"," ","都","完成了"," ✅","\n\n","**","总结",":","**\n\n","-"," **","Turn"," ","1","**"," —"," ","随机","选中"," `","pack","ages","/","context","/s","ession","-reference","`",",","输","出了","文件","结构",":\n"," "," ```\n"," "," session","-reference","/\n"," "," ├","──"," READ","ME",".md","\n"," "," ├","──"," package",".json","\n"," "," ├","──"," src","/\n"," "," │"," "," ├","──"," index",".ts","\n"," "," │"," "," └","──"," uri",".ts","\n"," "," └","──"," tests","/\n"," "," └","──"," session","-reference",".s","pec",".ts","\n"," "," ```\n","-"," **","Turn"," ","2","**"," —"," ","随机","选中"," `","pack","ages","/","ll","m","/t","oken","-meter","`",",","输","出了","文件","结构",":\n"," "," ```\n"," "," token","-meter","/\n"," "," ├","──"," READ","ME",".md","\n"," "," ├","──"," package",".json","\n"," "," ├","──"," src","/\n"," "," │"," "," └","──"," index",".ts","\n"," "," └","──"," tests","/\n"," "," └","──"," token","-meter",".s","pec",".ts","\n"," "," ```\n\n","**","验证","方式",":","**"," ","两个","包的","随机","选择","都","通过"," `","python","3"," random",".choice","`"," ","从","工作","区的"," `","pack","ages","/","`"," ","目录","下","实际","枚举","的"," ","4"," ","个","候选","包","中","抽取","(","`","ui","-con","vers","ation","`","、","`","session","-reference","`","、","`","token","-meter","`","、","`","skill","-local","`","),","文件","结构","则","用"," `","find","`"," ","实际","列出","文件","后","整理","输出",",","均已","排除"," `","node","_modules","`"," ","和"," `.","git","`","。","第二次","随机","抽","到了","与"," turn"," ","1"," ","相同的","包",",","为避免","重复","换","抽","了","另一个","。\n\n","**","说明",":","**"," ","本轮","没有","产生","任何","文件","修改","或","提交","——","任务","本身就是","\"","输出","文件","结构","\",","所有","产物","都在","上面的","消息","文本","里","。\n\n","如果你","还想","看","剩下","两个","包","(","`","ui","-con","vers","ation","`","、","`","skill","-local","`",")","的结构",",","或者其他","格式","的输出","(","比如","带","文件","大小的","树","形","图","),","随时","告诉我","。"]}} {"type":"assistant/chunk","data":{"turn":2,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"两个 turn 都完成了 ✅\n\n**总结:**\n\n- **Turn 1** — 随机选中 `packages/context/session-reference`,输出了文件结构:\n ```\n session-reference/\n ├── README.md\n ├── package.json\n ├── src/\n │ ├── index.ts\n │ └── uri.ts\n └── tests/\n └── session-reference.spec.ts\n ```\n- **Turn 2** — 随机选中 `packages/llm/token-meter`,输出了文件结构:\n ```\n token-meter/\n ├── README.md\n ├── package.json\n ├── src/\n │ └── index.ts\n └── tests/\n └── token-meter.spec.ts\n ```\n\n**验证方式:** 两个包的随机选择都通过 `python3 random.choice` 从工作区的 `packages/` 目录下实际枚举的 4 个候选包中抽取(`ui-conversation`、`session-reference`、`token-meter`、`skill-filesystem`),文件结构则用 `find` 实际列出文件后整理输出,均已排除 `node_modules` 和 `.git`。第二次随机抽到了与 turn 1 相同的包,为避免重复换抽了另一个。\n\n**说明:** 本轮没有产生任何文件修改或提交——任务本身就是\"输出文件结构\",所有产物都在上面的消息文本里。\n\n如果你还想看剩下两个包(`ui-conversation`、`skill-filesystem`)的结构,或者其他格式的输出(比如带文件大小的树形图),随时告诉我。"}}}} {"type":"assistant/chunk","data":{"turn":2,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":311,"outputTokens":348,"cacheReadTokens":10624,"reasoningTokens":0}}}} {"type":"assistant/chunk","data":{"turn":2,"step":6,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","data":{"turn":2,"step":6,"message":{"role":"assistant","content":[{"type":"text","text":"两个 turn 都完成了 ✅\n\n**总结:**\n\n- **Turn 1** — 随机选中 `packages/context/session-reference`,输出了文件结构:\n ```\n session-reference/\n ├── README.md\n ├── package.json\n ├── src/\n │ ├── index.ts\n │ └── uri.ts\n └── tests/\n └── session-reference.spec.ts\n ```\n- **Turn 2** — 随机选中 `packages/llm/token-meter`,输出了文件结构:\n ```\n token-meter/\n ├── README.md\n ├── package.json\n ├── src/\n │ └── index.ts\n └── tests/\n └── token-meter.spec.ts\n ```\n\n**验证方式:** 两个包的随机选择都通过 `python3 random.choice` 从工作区的 `packages/` 目录下实际枚举的 4 个候选包中抽取(`ui-conversation`、`session-reference`、`token-meter`、`skill-filesystem`),文件结构则用 `find` 实际列出文件后整理输出,均已排除 `node_modules` 和 `.git`。第二次随机抽到了与 turn 1 相同的包,为避免重复换抽了另一个。\n\n**说明:** 本轮没有产生任何文件修改或提交——任务本身就是\"输出文件结构\",所有产物都在上面的消息文本里。\n\n如果你还想看剩下两个包(`ui-conversation`、`skill-filesystem`)的结构,或者其他格式的输出(比如带文件大小的树形图),随时告诉我。"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:27}}"},"usage":{"inputTokens":311,"outputTokens":348,"cacheReadTokens":10624,"reasoningTokens":0}},"sourceEventSeqs":[697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":2,"step":6,"message":{"role":"assistant","content":[{"type":"text","text":"两个 turn 都完成了 ✅\n\n**总结:**\n\n- **Turn 1** — 随机选中 `packages/context/session-reference`,输出了文件结构:\n ```\n session-reference/\n ├── README.md\n ├── package.json\n ├── src/\n │ ├── index.ts\n │ └── uri.ts\n └── tests/\n └── session-reference.spec.ts\n ```\n- **Turn 2** — 随机选中 `packages/llm/token-meter`,输出了文件结构:\n ```\n token-meter/\n ├── README.md\n ├── package.json\n ├── src/\n │ └── index.ts\n └── tests/\n └── token-meter.spec.ts\n ```\n\n**验证方式:** 两个包的随机选择都通过 `python3 random.choice` 从工作区的 `packages/` 目录下实际枚举的 4 个候选包中抽取(`ui-conversation`、`session-reference`、`token-meter`、`skill-filesystem`),文件结构则用 `find` 实际列出文件后整理输出,均已排除 `node_modules` 和 `.git`。第二次随机抽到了与 turn 1 相同的包,为避免重复换抽了另一个。\n\n**说明:** 本轮没有产生任何文件修改或提交——任务本身就是\"输出文件结构\",所有产物都在上面的消息文本里。\n\n如果你还想看剩下两个包(`ui-conversation`、`skill-filesystem`)的结构,或者其他格式的输出(比如带文件大小的树形图),随时告诉我。"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:27}}"},"usage":{"inputTokens":311,"outputTokens":348,"cacheReadTokens":10624,"reasoningTokens":0}},"sourceEventSeqs":[698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":6}} {"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/snapshots/web/goal-multi-turn-actions/ui.expected.md b/snapshots/web/goal-multi-turn-actions/ui.expected.md index 80733e2719..90d92f9de2 100644 --- a/snapshots/web/goal-multi-turn-actions/ui.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui.expected.md @@ -14,6 +14,10 @@ - img - img - text: "goal Goal created Status: active Objective: 做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的 Rounds: 0/256 Activation: armed Commands: /goal edit , /goal pause, /goal clear" +- button "System prompt": + - img + - img + - text: System prompt - button "Context injection goal": - img - img @@ -88,6 +92,10 @@ - button "Branch into a new conversation": - img - text: {{clock}} Ran for {{duration}} TTFT {{duration}} {{throughput}} tok/s +- button "System prompt": + - img + - img + - text: System prompt - button "Context injection goal": - img - img diff --git a/snapshots/web/lifecycle-chrome/reloaded.expected.md b/snapshots/web/lifecycle-chrome/reloaded.expected.md index 4d3fe1aa9f..39060d7135 100644 --- a/snapshots/web/lifecycle-chrome/reloaded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with the single word LIGHTHOUSE and stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/live-interactions/cancel.expected.md b/snapshots/web/live-interactions/cancel.expected.md index 85a3661eb8..407235a379 100644 --- a/snapshots/web/live-interactions/cancel.expected.md +++ b/snapshots/web/live-interactions/cancel.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/live-interactions/error-auth.expected.md b/snapshots/web/live-interactions/error-auth.expected.md index 341ddf22db..870fc89ffe 100644 --- a/snapshots/web/live-interactions/error-auth.expected.md +++ b/snapshots/web/live-interactions/error-auth.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/live-interactions/loading.expected.md b/snapshots/web/live-interactions/loading.expected.md index 7e6a7af832..34a5ce76cd 100644 --- a/snapshots/web/live-interactions/loading.expected.md +++ b/snapshots/web/live-interactions/loading.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/live-interactions/retry-exhausted.expected.md b/snapshots/web/live-interactions/retry-exhausted.expected.md index 827faf4486..a923ae8387 100644 --- a/snapshots/web/live-interactions/retry-exhausted.expected.md +++ b/snapshots/web/live-interactions/retry-exhausted.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/live-interactions/retry.expected.md b/snapshots/web/live-interactions/retry.expected.md index 7f4275344b..754c1af0ae 100644 --- a/snapshots/web/live-interactions/retry.expected.md +++ b/snapshots/web/live-interactions/retry.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/live-interactions/running-draft.expected.md b/snapshots/web/live-interactions/running-draft.expected.md index d4e15c0498..4c4403f11e 100644 --- a/snapshots/web/live-interactions/running-draft.expected.md +++ b/snapshots/web/live-interactions/running-draft.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/message-actions/ui.expected.md b/snapshots/web/message-actions/ui.expected.md index 0419f0f1b1..5c82749291 100644 --- a/snapshots/web/message-actions/ui.expected.md +++ b/snapshots/web/message-actions/ui.expected.md @@ -7,6 +7,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. 7/25 {{clock}}" - button "Copy": - img diff --git a/snapshots/web/plan-review/approved.expected.md b/snapshots/web/plan-review/approved.expected.md index e2e41dd34c..2d694d6162 100644 --- a/snapshots/web/plan-review/approved.expected.md +++ b/snapshots/web/plan-review/approved.expected.md @@ -10,7 +10,12 @@ - tab "Chat" [selected] - tab "Trajectory" - img -- text: "plan Plan mode on. Use /plan off to leave. Plan a small change: add a --greeting flag to a CLI. Do not read or write any files. Call exit_plan_mode with a short plan of at most five bullet points. Once the plan is approved, reply with the single word DONE and stop. {{clock}}" +- text: plan Plan mode on. Use /plan off to leave. +- button "System prompt": + - img + - img + - text: System prompt +- text: "Plan a small change: add a --greeting flag to a CLI. Do not read or write any files. Call exit_plan_mode with a short plan of at most five bullet points. Once the plan is approved, reply with the single word DONE and stop. {{clock}}" - button "Copy": - img - button "Context injection @deepseek-ai/dsh-system-prompt": @@ -29,6 +34,10 @@ - img - img - text: "Tool call exit_plan_mode · # Add `--greeting` flag to CLI" +- button "System prompt": + - img + - img + - text: System prompt - 'button "Think The plan was approved. The user''s last instruction says: \"Once the plan is approved, reply with the single word DONE and stop.\" So I should just reply with DONE and stop."': - img - img diff --git a/snapshots/web/question-composer/answered.expected.md b/snapshots/web/question-composer/answered.expected.md index 7815286fe9..c516407e3d 100644 --- a/snapshots/web/question-composer/answered.expected.md +++ b/snapshots/web/question-composer/answered.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Use the ask_user_question tool to ask me exactly one multi-select question with id \"color\", question \"Which color do you prefer?\", header \"Pick one\", and two options: label \"Blue\" with description \"A cool recessive hue that reads as calm and trustworthy in long reading sessions and dense dashboards.\", and label \"Green\" with description \"A restful mid-spectrum hue with the highest perceived brightness, easiest on the eye over long sessions.\" Set multi_select to true. After I answer, reply with the single word DONE and stop. {{clock}}" - button "Copy": - img diff --git a/snapshots/web/queue-actions/collapsed.expected.md b/snapshots/web/queue-actions/collapsed.expected.md index 150c6060fb..9ce8b0be96 100644 --- a/snapshots/web/queue-actions/collapsed.expected.md +++ b/snapshots/web/queue-actions/collapsed.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/queue-actions/editing.expected.md b/snapshots/web/queue-actions/editing.expected.md index 74dcf76b8b..4c64c771f0 100644 --- a/snapshots/web/queue-actions/editing.expected.md +++ b/snapshots/web/queue-actions/editing.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/queue-actions/layout.expected.md b/snapshots/web/queue-actions/layout.expected.md index e7d6577325..666cb935b7 100644 --- a/snapshots/web/queue-actions/layout.expected.md +++ b/snapshots/web/queue-actions/layout.expected.md @@ -14,6 +14,10 @@ - img - img - text: "goal Goal created Status: active Objective: Keep the composer context panels aligned Rounds: 0/256 Activation: armed Commands: /goal edit , /goal pause, /goal clear" +- button "System prompt": + - img + - img + - text: System prompt - button "Context injection goal": - img - img diff --git a/snapshots/web/queue-actions/preserved.expected.md b/snapshots/web/queue-actions/preserved.expected.md index 09f677bcc8..0e13eb6e8d 100644 --- a/snapshots/web/queue-actions/preserved.expected.md +++ b/snapshots/web/queue-actions/preserved.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/queue-actions/ui.expected.md b/snapshots/web/queue-actions/ui.expected.md index 2ae4f81331..48c85e44f4 100644 --- a/snapshots/web/queue-actions/ui.expected.md +++ b/snapshots/web/queue-actions/ui.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/seeded-history/command-row.expected.md b/snapshots/web/seeded-history/command-row.expected.md index 4402a0c69b..e3c1eff67a 100644 --- a/snapshots/web/seeded-history/command-row.expected.md +++ b/snapshots/web/seeded-history/command-row.expected.md @@ -7,6 +7,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. 7/25 {{clock}}" - button "Copy": - img diff --git a/snapshots/web/seeded-history/feedback-row.expected.md b/snapshots/web/seeded-history/feedback-row.expected.md index 3f7148828e..d5907165b2 100644 --- a/snapshots/web/seeded-history/feedback-row.expected.md +++ b/snapshots/web/seeded-history/feedback-row.expected.md @@ -7,6 +7,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. 7/25 {{clock}}" - button "Copy": - img diff --git a/snapshots/web/seeded-history/ui.expected.md b/snapshots/web/seeded-history/ui.expected.md index 3ca7fba7ca..b1dbc8ffa7 100644 --- a/snapshots/web/seeded-history/ui.expected.md +++ b/snapshots/web/seeded-history/ui.expected.md @@ -7,6 +7,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop. 7/25 {{clock}}" - button "Copy": - img diff --git a/snapshots/web/skill-tool-row/ui.expected.md b/snapshots/web/skill-tool-row/ui.expected.md index 6c54404742..ca0e12d5cd 100644 --- a/snapshots/web/skill-tool-row/ui.expected.md +++ b/snapshots/web/skill-tool-row/ui.expected.md @@ -7,6 +7,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Load the editing-cordis-compositions skill with the skill tool, then reply DONE. {{date}} {{clock}} - button "Copy": - img diff --git a/snapshots/web/steering/mid-steer.expected.md b/snapshots/web/steering/mid-steer.expected.md index 9de5436d86..557e5bc0ff 100644 --- a/snapshots/web/steering/mid-steer.expected.md +++ b/snapshots/web/steering/mid-steer.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/steering/settled.expected.md b/snapshots/web/steering/settled.expected.md index 528d53ced1..561e1a5342 100644 --- a/snapshots/web/steering/settled.expected.md +++ b/snapshots/web/steering/settled.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Use the ask_user_question tool to ask me exactly one question with id "checkpoint", question "Ready to continue?", header "Checkpoint", and options labeled "Yes" and "No". After I answer, reply with one short sentence acknowledging my answer and stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/subagent-conversation/ui.expected.md b/snapshots/web/subagent-conversation/ui.expected.md index dc26ca3e97..0b3d521d6d 100644 --- a/snapshots/web/subagent-conversation/ui.expected.md +++ b/snapshots/web/subagent-conversation/ui.expected.md @@ -14,6 +14,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Explain event sourcing in one sentence. {{clock}} - button "Copy": - img @@ -34,7 +38,12 @@ - img - button "Branch into a new conversation": - img -- text: {{clock}} Ran for {{duration}} TTFT {{duration}} {{throughput}} tok/s Now give the same explanation to a human reader. {{clock}} +- text: {{clock}} Ran for {{duration}} TTFT {{duration}} {{throughput}} tok/s +- button "System prompt": + - img + - img + - text: System prompt +- text: Now give the same explanation to a human reader. {{clock}} - button "Copy": - img - button "Think The user is asking for a one-sentence description of event sourcing. This is a straightforward knowledge question that doesn't require any skill loading or tool calls.": diff --git a/snapshots/web/subagent-interrupt/offline-composer.expected.md b/snapshots/web/subagent-interrupt/offline-composer.expected.md index 378ebea7d0..24365b84e1 100644 --- a/snapshots/web/subagent-interrupt/offline-composer.expected.md +++ b/snapshots/web/subagent-interrupt/offline-composer.expected.md @@ -11,6 +11,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Explain event sourcing in one sentence. {{clock}} - button "Copy": - img diff --git a/snapshots/web/turn-tail-actions/running.expected.md b/snapshots/web/turn-tail-actions/running.expected.md index 8af07a3543..dc3cd57ff6 100644 --- a/snapshots/web/turn-tail-actions/running.expected.md +++ b/snapshots/web/turn-tail-actions/running.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/turn-tail-actions/settled.expected.md b/snapshots/web/turn-tail-actions/settled.expected.md index cbac0d4880..0a031aec85 100644 --- a/snapshots/web/turn-tail-actions/settled.expected.md +++ b/snapshots/web/turn-tail-actions/settled.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Begin your reply with the plain sentence "Reading the workspace now." as text, and in that same message call the bash tool with the command "echo alpha". After the tool result, reply with the single word DONE and stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/web-search-round/ui.expected.md b/snapshots/web/web-search-round/ui.expected.md index c92014e916..746c5cff00 100644 --- a/snapshots/web/web-search-round/ui.expected.md +++ b/snapshots/web/web-search-round/ui.expected.md @@ -9,6 +9,10 @@ - tablist: - tab "Chat" [selected] - tab "Trajectory" +- button "System prompt": + - img + - img + - text: System prompt - text: Use web_search once with queries ["DeepSeek Harness snapshot search","DeepSeek Harness multi-query search"]. Then reply exactly SEARCH_DONE and stop. {{clock}} - button "Copy": - img diff --git a/snapshots/web/workflow-run/ui.expected.md b/snapshots/web/workflow-run/ui.expected.md index 5ad87e217b..617a06bbf5 100644 --- a/snapshots/web/workflow-run/ui.expected.md +++ b/snapshots/web/workflow-run/ui.expected.md @@ -1,3 +1,7 @@ +- button "System prompt": + - img + - img + - text: System prompt - text: "Use the workflow tool exactly once, with args omitted, meta set to { \"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\" }, and this EXACT script body (copy it verbatim): phase('Run') const reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.') return { reply } After the workflow returns, reply with the single word WORKFLOW_DONE and stop. Do not use any other tool. {{clock}}" - button "Copy": - img From 211e6939e39212267cd73f89c65637be676743df Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 25 Aug 2026 15:30:10 +0800 Subject: [PATCH 31/31] Revert "Merge pull request #2698 from deepseek-harness/xtr/session-format-migration" This reverts commit 4b592eb90df20dc53dd12215921d5a9137214777, reversing changes made to d15d3275d905e4d21229cd70a074388a428189d1. --- .../2026-06-14-session-persistence.i18n.yaml | 4 +- .../2026-06-14-session-persistence.md | 2 +- .../2026-06-14-session-persistence.zh.md | 2 +- ...10-session-log-version-mechanism.i18n.yaml | 4 +- ...026-08-10-session-log-version-mechanism.md | 15 +- ...-08-10-session-log-version-mechanism.zh.md | 15 +- docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/subsystems/persistence.i18n.yaml | 4 +- docs/subsystems/persistence.md | 26 +- docs/subsystems/persistence.zh.md | 26 +- .../tests/session-cold.host.spec.ts | 22 +- packages/core/session/src/types.ts | 6 +- .../webworker-runtime/package.json | 1 - .../tests/vfs-example-fixture.spec.ts | 30 +- .../README.i18n.yaml | 4 +- .../session-persistence-jsonl/README.md | 4 +- .../session-persistence-jsonl/README.zh.md | 4 +- .../session-persistence-jsonl/src/format.ts | 71 +- .../session-persistence-jsonl/src/index.ts | 266 +--- .../session-persistence-jsonl/src/win32.ts | 14 - .../tests/jsonl.spec.ts | 343 +---- .../tests/win32.spec.ts | 36 - .../tests/zstd.spec.ts | 52 +- .../session-persistence-sqlite/src/store.ts | 142 +-- .../resources/sql/count-session-events.sql | 3 - .../sql/create-temp-replace-trigger.sql | 5 - .../resources/sql/delete-session-by-id.sql | 2 - .../sql/drop-temp-replace-trigger.sql | 1 - .../resources/sql/update-session-cwd.sql | 3 - .../resources/sql/update-session-revision.sql | 3 - .../tests/sqlite.spec.ts | 161 --- .../tests/test-sql.ts | 6 - .../session-persistence/README.i18n.yaml | 4 +- .../session/session-persistence/README.md | 20 +- .../session/session-persistence/README.zh.md | 20 +- .../session-persistence/src/coordinator.ts | 696 ++++++++--- .../session-persistence/src/format-decoder.ts | 500 -------- .../session-persistence/src/format-json.ts | 56 - .../src/format-migrations/index.ts | 6 - .../src/format-v0-compat.ts | 297 ----- .../session/session-persistence/src/index.ts | 37 +- .../session-persistence/src/revision.ts | 9 - .../tests/format-decoder.spec.ts | 1101 ----------------- .../tests/persistence.spec.ts | 367 +----- pnpm-lock.yaml | 3 - scripts/type-equiv.manifest.json | 5 - 48 files changed, 737 insertions(+), 3669 deletions(-) delete mode 100644 packages/session/session-persistence-sqlite/tests/resources/sql/count-session-events.sql delete mode 100644 packages/session/session-persistence-sqlite/tests/resources/sql/create-temp-replace-trigger.sql delete mode 100644 packages/session/session-persistence-sqlite/tests/resources/sql/delete-session-by-id.sql delete mode 100644 packages/session/session-persistence-sqlite/tests/resources/sql/drop-temp-replace-trigger.sql delete mode 100644 packages/session/session-persistence-sqlite/tests/resources/sql/update-session-cwd.sql delete mode 100644 packages/session/session-persistence-sqlite/tests/resources/sql/update-session-revision.sql delete mode 100644 packages/session/session-persistence/src/format-decoder.ts delete mode 100644 packages/session/session-persistence/src/format-json.ts delete mode 100644 packages/session/session-persistence/src/format-migrations/index.ts delete mode 100644 packages/session/session-persistence/src/format-v0-compat.ts delete mode 100644 packages/session/session-persistence/tests/format-decoder.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.i18n.yaml index 9232de3c69..8f9aa62e49 100644 --- a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-06-14-session-persistence.md -2026-06-14-session-persistence.md: cef11271f26c304ad484d7851801bc69d0c1dfda -2026-06-14-session-persistence.zh.md: b6c2467888d0d348aa492c265542565563b75fab +2026-06-14-session-persistence.md: 62228bd2f5b25b13880a563818d08f3a2d52d956 +2026-06-14-session-persistence.zh.md: ebf004333c383336cd025aa8a4aabc9d1e07f0e5 diff --git a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.md b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.md index cef11271f2..62228bd2f5 100644 --- a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.md +++ b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.md @@ -29,7 +29,7 @@ Key durable, contested choices: Each key choice above records its rejected alternative where the choice is stated: a **chunk-filtered canonical log** (Codex's `policy.rs` shape) — breaks the contiguous-seq contract; **truncating a crashed turn** — silently destroys a long autonomous run's real work; an **in-log `session/meta` event as line 0** — metadata is not replayable state; **finite fractional `createdAt` values** — have no producer and diverge from integer Unix-millisecond storage and query columns; **adopting a non-pristine unversioned SQLite file** — can overwrite unrelated objects or identity; **hard-injecting `sessionPersistence` into the loop** — would pend non-persistent demos forever. -Format versioning: the header carries a `version`; cold reads accept the current version or a complete static adjacent-version decoder path and reject future versions or missing steps. The format decoder owns historical header and event conversion, while the Coordinator owns operation-specific recovery after decoding ([Session log versioning](2026-08-10-session-log-version-mechanism.md)). The pre-release session format stays pinned at `SESSION_FORMAT_VERSION = 0` and carries no broad compatibility promise. Append-only + flush is robust to partial trailing writes (tolerated during cold preparation) but not to fsync-less power loss mid-line; a DB/WAL backend is the stronger option there. +Format versioning: the header carries a `version`; cold reads reject any non-current version. The pre-release session format stays pinned at `SESSION_FORMAT_VERSION = 0` and carries no broad compatibility promise, while the coordinator may own an explicit narrow import upgrade when persisted user data requires it ([pre-identity message recovery](../bug-fix/2026-07-28-load-pre-identity-session-messages.md)). Append-only + flush is robust to partial trailing writes (tolerated during cold preparation) but not to fsync-less power loss mid-line; a DB/WAL backend is the stronger option there. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.zh.md b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.zh.md index b6c2467888..ebf004333c 100644 --- a/.agents/notes/implemented/architecture/2026-06-14-session-persistence.zh.md +++ b/.agents/notes/implemented/architecture/2026-06-14-session-persistence.zh.md @@ -29,7 +29,7 @@ Status: implemented 上述每个关键选择都在陈述处记录了被否决的替代方案:**过滤分片的规范日志**(Codex 的 `policy.rs` 形式)破坏连续 seq 约定;**截断崩溃的轮次**会静默销毁长时间自主运行中的真实工作;**日志内 `session/meta` 事件作为第 0 行**——元数据不是可回放状态;**有限的非整数 `createdAt` 值**没有生产方,且与整数 Unix 毫秒存储及查询列不一致;**接受非全新的未版本化 SQLite 文件**可能覆盖无关对象或应用标识;**将 `sessionPersistence` 硬注入循环**会让非持久化的演示永远挂起。 -格式版本控制:header 携带一个 `version`;冷读取接受当前版本或完整的静态相邻版本 decoder 路径,并拒绝未来版本或缺失步骤。Format decoder 负责历史 header 和 event 转换,Coordinator 只在解码后负责各操作自己的 recovery([Session log 版本机制](2026-08-10-session-log-version-mechanism.zh.md))。预发布阶段的会话格式仍固定为 `SESSION_FORMAT_VERSION = 0`,不承诺广泛兼容。仅追加 + 刷写对尾部的不完整写入具有健壮性(冷准备时可容忍),但无法抵御未使用 fsync 时在行写入中途断电;数据库/WAL 后端是该场景下更强的选项。 +格式版本控制:header 携带一个 `version`;冷读取拒绝任何非当前版本。预发布阶段的会话格式仍固定为 `SESSION_FORMAT_VERSION = 0`,不承诺广泛兼容;当持久化用户数据确有需要时,协调器可以负责显式且范围受限的导入升级([消息标识机制引入前的消息恢复](../bug-fix/2026-07-28-load-pre-identity-session-messages.zh.md))。仅追加 + 刷写对尾部的不完整写入具有健壮性(冷准备时可容忍),但无法抵御未使用 fsync 时在行写入中途断电;数据库/WAL 后端是该场景下更强的选项。 ## 后果 diff --git a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.i18n.yaml index ee8c71110e..85793a0b5c 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md -2026-08-10-session-log-version-mechanism.md: dfbe5c1926cf683a34ec6694f188f57c44b9ca10 -2026-08-10-session-log-version-mechanism.zh.md: 00d58757d3ea4bf1689a0847613557613d40ebf6 +2026-08-10-session-log-version-mechanism.md: 81108ceaf23405c8f2def9aaef88505d635808a3 +2026-08-10-session-log-version-mechanism.zh.md: cbb127420e2695853fdc2ad0bb98a7a0bf230b5b diff --git a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md index dfbe5c1926..81108ceaf2 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md +++ b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md @@ -14,21 +14,13 @@ Session logs must be upgradable after release, and the runtime that ships first **The writer decides bumps, not the reader.** A bump is required exactly when an old runtime could no longer handle a new log with full semantic correctness. "Parses without error" is not the bar: silently skipping content that shapes reconstruction is a wrong read. Only structural changes qualify — header shape, event envelope, core event semantics, the surface mechanism (`SurfaceEventType` set, `SurfaceOp` variants). When unsure, bump: a near-identity upgrader is almost free, a missed bump silently corrupts old readers. -**Read rules by direction.** Equal version: decode normally. Newer than the reader: refuse, name the direction ("written by a newer harness — upgrade"), and point at the raw log artifact so the user can still see the text (`SessionFormatUnsupportedError`, distinct from `SessionPersistenceCorruptionError` because nothing is damaged). Older than the reader: require a complete chain of static n→n+1 `SessionFormatMigration` classes; a missing migration refuses the read and names the gap. The registry is part of the build rather than Cordis composition, so one build has the same durable read capability under every plugin set. - -**Format migration is the decoder, not a Coordinator repair branch.** Backends expose parsed durable data as `unknown` through a repeatable `StoredSessionSource`: one raw header, one exact revision, and `readEvents()` factories that create independently consumable `AsyncIterable` streams bound to that revision. Each migration class carries static adjacent `from`/`to` versions. One fresh instance handles one decode attempt: `header()` runs once, `event()` maps each input record to exactly one lossless-JSON output with the same seq, and optional `finish()` validates accumulated state after EOF. Instance fields may retain header and earlier-event facts without sharing state across sessions, concurrent reads, or revision retries. Header-only reads stop after `header()` and never call `finish()`, so that method validates EOF state rather than releasing resources. Any version conversion reads the complete event stream and applies the requested suffix only after all migrations; an equal-version read retains backend suffix seek. The decoder validates each output header version and each migration's seq preservation, then applies current `SessionHeader` and `SessionEvent` validation only after the complete chain. - -**A future format bump adds one format-owned migration.** The change adds `format-migrations/vN-to-vN+1.ts`, exports its class from the static `SESSION_FORMAT_MIGRATIONS` array, and increments `SESSION_FORMAT_VERSION`. The migration owns every old header and event variant it accepts, its instance state, and explicit failure for malformed input. It cannot add, remove, reorder, or renumber events: durable references use seq as event identity. A format change that alters facts consumed by a projection increments that projection's `stateVersion`; unchanged projections retain their cache rows. Backends and the Coordinator do not gain version-specific branches. Historical variants that never changed the version remain isolated in the format-v0 compatibility decoder and are not a template for later version migrations. This decoder maps the historical `compact/start`, `compact/summary`, `compact/end`, and `compact/prune` names to canonical `compaction/*` events while preserving the rest of each record. - -**Recovery and writeback consume current-format data.** `inspect()` and `readFrom()` decode only in memory. Cold `prepare()`/`load()` first decode the whole source, add the current recovery closers, and replace the exact old revision with that complete balanced current-format stream. Live HMR adoption uses the same replacement primitive after seed verification but does not synthesize closers for a turn still owned by the live Session. A successful replacement or revision conflict discards the prepared object and reopens the stored source before continuing. - -**Replacement is an internal backend compare-and-swap.** `replaceStored(expectedRevision, meta, events)` accepts a streaming current-format log and checks storage identity plus the source revision at the commit boundary. JSONL writes and fsyncs a sibling temporary artifact, rechecks the source revision immediately before the atomic replace, atomically replaces the path (using the Windows write-through replacement primitive there), and syncs the parent directory on POSIX; like every other coordinator freshness check, the recheck adds no cross-process writer exclusion — JSONL assumes one live writer per session. SQLite stages the event iterator, then rechecks and replaces the header and event rows in one transaction. A failed commit leaves one complete old or new log; retaining a permanent pre-upgrade copy is a separate recovery policy, not part of the format migration API. +**Read rules by direction.** Equal version: read normally. Newer than the reader: refuse, name the direction ("written by a newer harness — upgrade"), and point at the raw log artifact so the user can still see the text (`SessionFormatUnsupportedError`, distinct from `SessionPersistenceCorruptionError` because nothing is damaged). Older than the reader: convert in memory through the chain of n→n+1 upgraders for viewing; persist the converted log only when the session is actually continued (atomic temp-file replace, original kept as backup). A step whose upgrader cannot be written is left empty, which cuts off every version at or below it — those degrade to raw-text viewing. **A per-event `ignorable` marker covers vocabulary growth, so ordinary event additions never bump the version.** The event vocabulary is decided by which plugins are mounted, which a single version integer cannot describe. A reader meeting an unrecognized event type refuses to interpret the log unless the event carries `ignorable: true` in its envelope. The default is *required*: forgetting the marker over-refuses a resumable session (an inconvenience), while a default of ignorable would make the same mistake silently resume a gutted one (a safety failure). The architecture makes this sound: model-visible content flows only through the three `surfaceOp`-marked surface event types plus the `request/header`/`request/context` folds, so the dangerous unknowns are exactly the non-surface events that change how the rest of the log is read (`session/end-seed` is the existing example). ## Consequences -Format v0 carries direction-aware refusal with the raw-log path; the unknown-event guard against a generated known-vocabulary list (`KNOWN_SESSION_EVENT_TYPES`, emitted by `gen-persistence-catalog` from every `SessionEventMap` merge and kept fresh by `verify-persistence-catalog`); the `ignorable` envelope field accepted by seed validation, both backends (a dedicated SQLite column, `SCHEMA_VERSION` 15), and the BFF wire schema; and the static streaming migration decoder with an empty adjacent-version registry. `SESSION_FORMAT_VERSION` remains 0 until a real v0→v1 step lands. The decoder and backend replacement APIs therefore have direct tests without manufacturing a format bump. Writers do not yet set `ignorable` because no producer needs it. Until a registration surface exists, an out-of-repo plugin's events refuse resume under first-party readers; the refusal is loud rather than silent. The unknown-type guard is read-side only: `appendCore` keeps rejecting retired legacy shapes but does not vocabulary-check new types, because an append-time refusal would stall a live session's durability mid-flight, which costs more than a loud refusal at the log's next load. The JSONL backend additionally refuses a foreign version from the raw header line before validating today's header fields or decoding any event record, so a structurally different future format still reports the upgrade direction instead of "corrupt"; SQLite gates whole-file structure through its own `SCHEMA_VERSION` pragma first. +What shipped in v0 (release 0812): direction-aware refusal with the raw-log path; the unknown-event guard against a generated known-vocabulary list (`KNOWN_SESSION_EVENT_TYPES`, emitted by `gen-persistence-catalog` from every `SessionEventMap` merge and kept fresh by `verify-persistence-catalog`); the `ignorable` envelope field accepted by seed validation, both backends (a dedicated SQLite column, `SCHEMA_VERSION` 15), and the BFF wire schema. The upgrader chain itself is deferred until the first real v0→v1 step exists to test it against; writers do not yet set `ignorable` (no producer needs it), so `Session.append` gains that surface with its first user. Until a registration surface exists, an out-of-repo plugin's events refuse resume under first-party readers — the pre-release stance accepts that, and the refusal is loud rather than silent. The unknown-type guard is read-side only: `appendCore` keeps rejecting retired legacy shapes but does not vocabulary-check new types, because an append-time refusal would stall a live session's durability mid-flight, which costs more than a loud refusal at the log's next load. The JSONL backend additionally refuses a foreign version from the raw header line before validating this format version's header shape or decoding any event row, so a structurally different future format still reports the upgrade direction instead of "corrupt"; SQLite gates whole-file structure through its own `SCHEMA_VERSION` pragma first. ## Alternatives considered @@ -36,6 +28,3 @@ Format v0 carries direction-aware refusal with the raw-log path; the unknown-eve - **Default-ignorable unknown events** — inverts the failure mode of a forgotten marker from visible over-refusal into silent corruption. - **Auto-migrating on view** — rewriting the artifact on open turns a read into a destructive write: a converter bug corrupts logs at browse time, and a same-directory older runtime loses access because a newer one merely looked. - **Per-plugin runtime registration of known event types** — would make the known set composition-dependent, so a leaner same-version composition would refuse logs a fuller one wrote. The generated repo-wide list keeps same-version reads uniform; out-of-repo plugin events are outside it by construction, and a registration surface for them is deferred until such a consumer exists. -- **Materializing migrations as header and event arrays** — makes the framework proportional to complete log size in memory even when each transformation is record-local. Repeatable revision-bound readers plus one-at-a-time event transforms preserve retry semantics without imposing that allocation. -- **Version-specific conversion in `PersistenceCoordinator`** — mixes format decoding with operation-specific crash recovery and duplicates behavior across inspect, suffix read, cold continuation, and live adoption. The shared decoder produces only current-format data; each consumer retains its own recovery intent. -- **A mandatory permanent backup for every upgrade** — is not needed for atomicity and cannot promise the same physical representation across JSONL and SQLite. Backends may add recovery copies as a separate product policy without changing migrations. diff --git a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md index 00d58757d3..cbb127420e 100644 --- a/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md @@ -14,21 +14,13 @@ Session log 在发布后必须能升级格式,而最先发布的运行时决 **升不升版本由写入方决定,与读取方能力无关。**当且仅当老运行时无法在语义上完全正确地处理新日志时才必须升版本。"解析不报错"不是标准:静默跳过影响重建的内容就是读错。只有结构性变更够得上这条线:header 形状、事件信封、核心事件语义、surface 机制(`SurfaceEventType` 集合、`SurfaceOp` 变体)。拿不准就升:近似恒等的升级器几乎没有成本,漏升一次会让老读取器静默读坏。 -**读取规则按方向区分。**版本相等:正常解码。比读取器新:拒绝,说明方向("由更新的 harness 写入,请升级"),并给出原始日志文件的路径,用户仍能看到文本(`SessionFormatUnsupportedError`,与 `SessionPersistenceCorruptionError` 区分,因为数据没有损坏)。比读取器旧:要求静态 n→n+1 `SessionFormatMigration` 类组成完整链路,缺失任何 migration 都会拒绝并指出断点。注册表属于 build 而不是 Cordis composition,因此同一个 build 在任何插件组合下都具有相同的持久化读取能力。 - -**格式迁移就是 decoder,不是 Coordinator 的修复分支。**后端通过可重复读取的 `StoredSessionSource` 把解析后的持久化数据作为 `unknown` 暴露:一个原始 header、一个精确 revision,以及每次产生独立 `AsyncIterable` 且绑定该 revision 的 `readEvents()` factory。每个 migration class 用静态且相邻的 `from`/`to` 标识版本。每次 decode 都创建一个新实例:`header()` 调用一次;`event()` 把每条输入记录映射为一条 seq 相同、可无损表示为 JSON 的输出;可选的 `finish()` 在 EOF 后验证累计状态。实例字段可以保留 header 与之前事件的事实,而不会在 Session、并发读取或 revision retry 之间共享状态。只读 header 时在 `header()` 后结束,绝不调用 `finish()`,因此该方法用于验证 EOF 状态而不是释放资源。只要发生版本转换,就读取完整事件流,并在所有 migration 完成后才应用请求的 suffix;版本相等时仍保留 backend suffix seek。Decoder 验证每一步输出的 header version 和每个 migration 是否保持 seq,完整链路结束后才执行当前 `SessionHeader` 和 `SessionEvent` 校验。 - -**以后每次 format bump 只增加一个格式 migration。**改动新增 `format-migrations/vN-to-vN+1.ts`,把它的 class 导出到静态 `SESSION_FORMAT_MIGRATIONS` 数组,并递增 `SESSION_FORMAT_VERSION`。Migration 自己负责它接受的所有旧 header 和 event 变体、实例状态,以及对畸形输入的明确失败。它不能增加、删除、重排事件或重编号:持久引用以 seq 作为事件身份。如果格式变化影响了某个 projection 消费的事实,就递增该 projection 的 `stateVersion`;未受影响的 projection 保留 cache 记录。Backend 和 Coordinator 不增加版本特判。没有改变版本号的历史变体继续隔离在 format-v0 compatibility decoder 中,不作为后续版本 migration 的模板。该 decoder 将历史 `compact/start`、`compact/summary`、`compact/end`、`compact/prune` 名称映射为规范的 `compaction/*` 事件,并保留每条记录的其余内容。 - -**Recovery 和写回只消费当前格式数据。**`inspect()` 和 `readFrom()` 只在内存中解码。Cold `prepare()`/`load()` 先解码完整 source,补充当前 recovery closers,再用完整、平衡的当前格式 stream 替换精确的旧 revision。Live HMR adoption 在 seed 校验后使用同一个 replacement primitive,但不会为仍由 live Session 掌握的 turn 合成 closer。替换成功或 revision 冲突后都会丢弃 prepared object,重新打开持久化 source 后再继续。 - -**Replacement 是 backend 内部的 compare-and-swap。**`replaceStored(expectedRevision, meta, events)` 接受流式当前格式日志,并在提交边界检查存储身份和 source revision。JSONL 写入并 fsync 同目录临时 artifact,在原子替换路径前立即复核 source revision,然后原子替换(Windows 使用 write-through replacement primitive),并在 POSIX 上同步父目录;与协调器的其他新鲜性检查一样,复核不提供跨进程写者排他——JSONL 假定每个 session 同时只有一个 live writer。SQLite 先暂存 event iterator,再在一个事务中复核并替换 header 与 event rows。提交失败后只会留下完整旧日志或完整新日志;永久保留升级前副本是独立的恢复策略,不属于 format migration API。 +**读取规则按方向区分。**版本相等:正常读。比读取器新:拒绝,说明方向("由更新的 harness 写入,请升级"),并给出原始日志文件的路径,用户仍能看到文本(`SessionFormatUnsupportedError`,与 `SessionPersistenceCorruptionError` 区分,因为数据没有损坏)。比读取器旧:查看时经 n→n+1 升级器链在内存中逐级转换;只有会话真正被继续时才把转换落盘(临时文件原子替换,原文件留备份)。写不出升级器的那一步留空,这会切断该步及更早所有版本的升级路径,它们降级为只能看原文。 **逐事件的 `ignorable` 标记吸收词汇表增长,普通的新增事件永远不用升版本。**事件词汇表由挂载了哪些插件决定,单个版本整数描述不了它。读取器遇到不认识的事件类型时拒绝解读日志,除非该事件的信封带 `ignorable: true`。默认为必需:忘写标记的后果是把一个本可恢复的会话拒绝过头(体验问题),而默认可忽略会让同样的疏忽静默恢复出残缺会话(安全事故)。架构保证了这条规则成立:模型可见内容只经三种带 `surfaceOp` 标记的 surface 事件加 `request/header`、`request/context` 折叠进入重建,危险的未知事件恰好是那些不进 surface 但改变日志其余部分解读方式的事件(`session/end-seed` 是现存例子)。 ## 影响 -Format v0 包含:分方向的拒绝并带原始日志路径;基于生成的已知词汇清单(`KNOWN_SESSION_EVENT_TYPES`,由 `gen-persistence-catalog` 从所有 `SessionEventMap` 声明合并生成,`verify-persistence-catalog` 保证新鲜)的未知事件守卫;`ignorable` 信封字段被种子校验、两个后端(SQLite 专用列,`SCHEMA_VERSION` 15)和 BFF 线上 schema 接受;以及使用空相邻版本注册表的静态流式 migration decoder。`SESSION_FORMAT_VERSION` 保持 0,直到真实 v0→v1 步骤合入。Decoder 和 backend replacement API 因此可以直接测试,不需要制造一次 format bump。写入侧目前不写 `ignorable`,因为还没有生产者需要它。在注册表面出现之前,仓库外插件的事件在第一方读取器下无法恢复会话;拒绝是显式的而非静默的。未知类型守卫只在读取侧生效:`appendCore` 继续拒绝已淘汰的 legacy 形状,但不对新类型做词汇检查,因为写入时拒绝会让活跃会话的持久化中途停摆,代价大于下次加载时的显式拒绝。JSONL 后端还会在校验当前 header 字段、解码任何 event record 之前,直接从原始 header 行拒绝外来版本,因此结构完全不同的未来格式仍会报告升级方向而不是"损坏";SQLite 则先由自己的 `SCHEMA_VERSION` pragma 把关整个文件的结构。 +v0(0812 发布)交付的内容:分方向的拒绝并带原始日志路径;基于生成的已知词汇清单(`KNOWN_SESSION_EVENT_TYPES`,由 `gen-persistence-catalog` 从所有 `SessionEventMap` 声明合并生成,`verify-persistence-catalog` 保证新鲜)的未知事件守卫;`ignorable` 信封字段被种子校验、两个后端(SQLite 专用列,`SCHEMA_VERSION` 升到 15)和 BFF 线上 schema 接受。升级器链本身推迟到第一个真实的 v0→v1 变更出现、有真实对象可测时再建;写入侧目前不写 `ignorable`(还没有生产者需要它),`Session.append` 的这一表面随第一个使用者一起落地。在注册表面出现之前,仓库外插件的事件在第一方读取器下无法恢复会话,预发布立场接受这一点,而且拒绝是显式的而非静默的。未知类型守卫只在读取侧生效:`appendCore` 继续拒绝已淘汰的 legacy 形状,但不对新类型做词汇检查,因为写入时拒绝会让活跃会话的持久化中途停摆,代价大于下次加载时的显式拒绝。JSONL 后端还会在校验本格式版本的 header 形状、解码任何事件行之前,直接从原始 header 行拒绝外来版本,因此结构完全不同的未来格式仍会报告升级方向而不是"损坏";SQLite 则先由自己的 `SCHEMA_VERSION` pragma 把关整个文件的结构。 ## 曾考虑的替代方案 @@ -36,6 +28,3 @@ Format v0 包含:分方向的拒绝并带原始日志路径;基于生成的 - **未知事件默认可忽略**:把忘写标记的后果从可见的过度拒绝反转成静默损坏。 - **查看时自动迁移落盘**:打开即改写把读操作变成破坏性写操作,转换器的 bug 会在浏览时损坏日志,同目录的旧版本运行时也会因为新版本只是看了一眼就失去访问能力。 - **插件运行时注册已知事件类型**:会让已知集依赖插件组合,同版本的精简组合会拒绝完整组合写出的日志。生成的全仓库清单保证同版本读取行为一致;仓库外插件的事件按构造就在清单之外,为它们提供注册表面推迟到真有这样的消费者时再做。 -- **把 migration 物化为 header 和 event 数组**:即使每步转换只依赖单条 record,也会让框架内存占用与完整日志大小成正比。可重复、绑定 revision 的 reader 加逐事件转换保留重试语义,又不强制这笔分配。 -- **在 `PersistenceCoordinator` 内写版本转换**:会把格式解码和各操作不同的 crash recovery 混在一起,并在 inspect、suffix read、cold continuation 和 live adoption 间复制行为。共享 decoder 只产出当前格式数据,各 consumer 保留自己的 recovery intent。 -- **每次升级都强制永久备份**:原子性不依赖永久副本,而且 JSONL 与 SQLite 无法承诺相同的物理表示。Backend 可以把恢复副本作为独立产品策略加入,不需要修改 migration。 diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 09b331539a..29cbb04c3d 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: f1e930c4ae7a5c9f0c045b17e61e224f75ce0116 -config-catalog.zh.md: e9afb428ccd196ce945d5fed74f771fcec3f46f9 +config-catalog.md: 20dbf55aff834a77e2049bcbb6485d84cd38589c +config-catalog.zh.md: 6cccf68e0c191a0de43bf190380cd0d2329d4391 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index f1e930c4ae..20dbf55aff 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1780,7 +1780,7 @@ export interface Config { export type JsonlCompression = 'zstd' | 'none' ``` -Source: [`packages/session/session-persistence-jsonl/src/index.ts:64`](../packages/session/session-persistence-jsonl/src/index.ts) +Source: [`packages/session/session-persistence-jsonl/src/index.ts:62`](../packages/session/session-persistence-jsonl/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index e9afb428cc..6cccf68e0c 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1782,7 +1782,7 @@ export interface Config { export type JsonlCompression = 'zstd' | 'none' ``` -来源:[`packages/session/session-persistence-jsonl/src/index.ts:64`](../packages/session/session-persistence-jsonl/src/index.ts) +来源:[`packages/session/session-persistence-jsonl/src/index.ts:62`](../packages/session/session-persistence-jsonl/src/index.ts) diff --git a/docs/subsystems/persistence.i18n.yaml b/docs/subsystems/persistence.i18n.yaml index 0bc2413aa3..f85e085da9 100644 --- a/docs/subsystems/persistence.i18n.yaml +++ b/docs/subsystems/persistence.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/persistence.md -persistence.md: 5046be0f2ff65faa7fa71f41d8141399d55bfa96 -persistence.zh.md: 71bbca1121e5b8d1e9441d857a0d0989c9946d51 +persistence.md: 098f5798e5313ca97e90e67dce1d67177f003ca7 +persistence.zh.md: d6b3baf7cdb7f1735008e0c1da9740e0b756baff diff --git a/docs/subsystems/persistence.md b/docs/subsystems/persistence.md index 5046be0f2f..098f5798e5 100644 --- a/docs/subsystems/persistence.md +++ b/docs/subsystems/persistence.md @@ -51,8 +51,8 @@ Source: [`packages/core/session/src/types.ts`](../../packages/core/session/src/t interface SessionHeader { /** * On-disk format version, stamped from {@link SESSION_FORMAT_VERSION} when the - * session is created. Persistence refuses newer versions and older versions - * without a complete registered migration path. + * session is created. A persistence backend rejects any other version on load + * (no migration — see the constant). */ readonly version: number /** The session's id (mirrors the {@link Session}'s id). */ @@ -91,27 +91,7 @@ interface SessionHeader { ## Format refusal — logs a build cannot faithfully read -A backend refuses a log it cannot faithfully interpret with `SessionFormatUnsupportedError`, distinct from `SessionPersistenceCorruptionError` because nothing is damaged. A header `version` ahead of `SESSION_FORMAT_VERSION` names the direction ("written by a newer harness — upgrade the harness to open it"); one behind it requires a complete registered adjacent-version migration path or names the missing step. After legacy-shape normalization, an event type outside this build's generated vocabulary (`KNOWN_SESSION_EVENT_TYPES`, emitted by `gen-persistence-catalog`) refuses the same way unless the event's envelope carries `ignorable: true` — silently skipping an unrecognized required event could change how the rest of the log must be read. The message appends the raw log path when the backend keeps one artifact per session, so the refused text stays reachable. The JSONL backend refuses a foreign version straight from the raw header line, before validating today's header shape or decoding any event row — a structurally different future format still reports the upgrade direction, never "corrupt"; SQLite gates whole-file structure through its own `SCHEMA_VERSION` pragma first. Design rationale lives in the [session-log-version-mechanism note](../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md). - -## `SessionFormatMigration` — adjacent static format upgrades - -Each migration class declares one adjacent `from`/`to` pair and creates fresh state for one decode attempt. The decoder snapshots every header and event output as detached lossless JSON before the next migration receives it, preserves event sequence numbers, and calls optional EOF validation only after the complete event stream is consumed. The [package README](../../packages/session/session-persistence/README.md) owns the registration and version-bump procedure. - -```ts type-equiv -/** Static identity and constructor for one adjacent-version migration. */ -interface SessionFormatMigration { - /** Input Session format version. */ - readonly from: number - /** Output Session format version; must equal `from + 1`. */ - readonly to: number - /** - * Create fresh state for one header decode and its optional complete event - * stream. Instances are never shared across sessions or decode attempts. - * @returns a single-use migration instance. - */ - new(): SessionFormatMigrationInstance -} -``` +A backend refuses a log it cannot faithfully interpret with `SessionFormatUnsupportedError`, distinct from `SessionPersistenceCorruptionError` because nothing is damaged. A header `version` ahead of `SESSION_FORMAT_VERSION` names the direction ("written by a newer harness — upgrade the harness to open it"); one behind it states that this build ships no upgrade path. After legacy-shape normalization, an event type outside this build's generated vocabulary (`KNOWN_SESSION_EVENT_TYPES`, emitted by `gen-persistence-catalog`) refuses the same way unless the event's envelope carries `ignorable: true` — silently skipping an unrecognized required event could change how the rest of the log must be read. The message appends the raw log path when the backend keeps one artifact per session, so the refused text stays reachable. The JSONL backend refuses a foreign version straight from the raw header line, before validating this format version's header shape or decoding any event row — a structurally different future format still reports the upgrade direction, never "corrupt"; SQLite gates whole-file structure through its own `SCHEMA_VERSION` pragma first. Design rationale and the deferred upgrader chain live in the [session-log-version-mechanism note](../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md). ## `CreateSessionOptions` — seeding and metadata diff --git a/docs/subsystems/persistence.zh.md b/docs/subsystems/persistence.zh.md index 71bbca1121..d6b3baf7cd 100644 --- a/docs/subsystems/persistence.zh.md +++ b/docs/subsystems/persistence.zh.md @@ -51,8 +51,8 @@ interface SessionLocation { interface SessionHeader { /** * On-disk format version, stamped from {@link SESSION_FORMAT_VERSION} when the - * session is created. Persistence refuses newer versions and older versions - * without a complete registered migration path. + * session is created. A persistence backend rejects any other version on load + * (no migration — see the constant). */ readonly version: number /** The session's id (mirrors the {@link Session}'s id). */ @@ -91,27 +91,7 @@ interface SessionHeader { ## 格式拒绝:本构建无法可靠读取的日志 -后端用 `SessionFormatUnsupportedError` 拒绝无法可靠解读的日志,它与 `SessionPersistenceCorruptionError` 区分,因为数据没有损坏。header 的 `version` 比 `SESSION_FORMAT_VERSION` 新时,消息说明方向("由更新的 harness 写入,请升级 harness 后打开");比它旧时则要求一条完整注册的相邻版本迁移路径,否则会指出缺失步骤。经过 legacy 形状归一化后,本构建生成词汇表(`KNOWN_SESSION_EVENT_TYPES`,由 `gen-persistence-catalog` 生成)之外的事件类型同样被拒绝,除非该事件的信封带 `ignorable: true`:静默跳过一个不认识的必需事件可能改变日志其余部分的解读方式。后端为每个会话保留独立文件时,消息附上原始日志路径,被拒绝的文本仍然可读。JSONL 后端直接从原始 header 行拒绝外来版本,先于当前 header 形状校验和任何事件行解码,因此结构完全不同的未来格式仍会报告升级方向,绝不会报"损坏";SQLite 则先由自己的 `SCHEMA_VERSION` pragma 把关整个文件的结构。设计理由见 [session-log 版本机制 Agent Note](../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md)。 - -## `SessionFormatMigration`:相邻静态格式升级 - -每个迁移 class 声明一组相邻的 `from`/`to`,并为一次解码创建全新状态。decoder 会将每次 header 和事件输出快照为分离的无损 JSON,再交给下一项迁移,同时保留事件 seq;只有完整消费事件流后,才会调用可选的 EOF 验证。[包 README](../../packages/session/session-persistence/README.zh.md)负责说明注册与版本递增步骤。 - -```ts type-equiv -/** Static identity and constructor for one adjacent-version migration. */ -interface SessionFormatMigration { - /** Input Session format version. */ - readonly from: number - /** Output Session format version; must equal `from + 1`. */ - readonly to: number - /** - * Create fresh state for one header decode and its optional complete event - * stream. Instances are never shared across sessions or decode attempts. - * @returns a single-use migration instance. - */ - new(): SessionFormatMigrationInstance -} -``` +后端用 `SessionFormatUnsupportedError` 拒绝无法可靠解读的日志,它与 `SessionPersistenceCorruptionError` 区分,因为数据没有损坏。header 的 `version` 比 `SESSION_FORMAT_VERSION` 新时,消息说明方向("由更新的 harness 写入,请升级 harness 后打开");比它旧时说明本构建没有升级路径。经过 legacy 形状归一化后,本构建生成词汇表(`KNOWN_SESSION_EVENT_TYPES`,由 `gen-persistence-catalog` 生成)之外的事件类型同样被拒绝,除非该事件的信封带 `ignorable: true`:静默跳过一个不认识的必需事件可能改变日志其余部分的解读方式。后端为每个会话保留独立文件时,消息附上原始日志路径,被拒绝的文本仍然可读。JSONL 后端直接从原始 header 行拒绝外来版本,先于本格式版本的 header 形状校验和任何事件行解码,因此结构完全不同的未来格式仍会报告升级方向,绝不会报"损坏";SQLite 则先由自己的 `SCHEMA_VERSION` pragma 把关整个文件的结构。设计理由与推迟建设的升级器链见 [session-log 版本机制 Agent Note](../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md)。 ## `CreateSessionOptions`:seed 与元数据 diff --git a/packages/api/session-controller/tests/session-cold.host.spec.ts b/packages/api/session-controller/tests/session-cold.host.spec.ts index b53bfdd9c7..7771bc112d 100644 --- a/packages/api/session-controller/tests/session-cold.host.spec.ts +++ b/packages/api/session-controller/tests/session-cold.host.spec.ts @@ -24,7 +24,7 @@ import { PersistenceCoordinator, SessionPersistenceRevision, type PersistenceBackend, - type StoredSessionSource, + type StoredPrefix, } from '@deepseek-ai/dsh-session-persistence' import { ApiSessionList } from '../src/list.ts' import { @@ -359,29 +359,19 @@ describe('cold history recovery view', () => { await ctx.plugin(SessionStore) const sessionId = sid('session-interrupted') const meta = header(sessionId, 1000) - const revision = SessionPersistenceRevision('history-recovery-test:1') - const stored: StoredSessionSource = { + const stored: StoredPrefix = { meta, - revision, - readEvents: ({ fromSeq = 0 } = {}) => ({ - events: (async function* () { - const events: SessionEvent[] = [ - { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, - ] - for (const event of events.slice(fromSeq)) yield structuredClone(event) - })(), - completed: Promise.resolve({}), - }), + events: [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }], + revision: SessionPersistenceRevision('history-recovery-test:1'), } const backend: PersistenceBackend = { name: 'history-recovery-test', - openStored: id => Promise.resolve(id === sessionId ? stored : undefined), + loadStored: id => Promise.resolve(id === sessionId ? structuredClone(stored) : undefined), readStoredRevision: id => Promise.resolve( - id === sessionId ? revision : undefined, + id === sessionId ? SessionPersistenceRevision('history-recovery-test:1') : undefined, ), appendBatch: () => Promise.resolve(), commitRepair: () => Promise.resolve(), - replaceStored: () => Promise.resolve(), list: () => Promise.resolve([structuredClone(meta)]), } const coordinator = new PersistenceCoordinator(ctx, backend) diff --git a/packages/core/session/src/types.ts b/packages/core/session/src/types.ts index 85ff73bf04..b5aa518590 100644 --- a/packages/core/session/src/types.ts +++ b/packages/core/session/src/types.ts @@ -35,7 +35,7 @@ export function SessionId(id: string): SessionId { * and enforced by every persistence backend on load. The single source of truth for the * version — write sites and the load-time check all read it. * While the harness is unreleased it is pinned at `0`: no compatibility is - * implied; older logs load only through a complete adjacent migration path. + * implied, incompatible logs are rejected, and no migration is provided. * * The version is a single monotonic integer with no major/minor split. Whether * a bump is needed is decided by what the WRITER emits, never by what a newer @@ -61,8 +61,8 @@ export const SESSION_FORMAT_VERSION = 0 export interface SessionHeader { /** * On-disk format version, stamped from {@link SESSION_FORMAT_VERSION} when the - * session is created. Persistence refuses newer versions and older versions - * without a complete registered migration path. + * session is created. A persistence backend rejects any other version on load + * (no migration — see the constant). */ readonly version: number /** The session's id (mirrors the {@link Session}'s id). */ diff --git a/packages/experimental/webworker-runtime/package.json b/packages/experimental/webworker-runtime/package.json index 624c28a7d9..68643425f8 100644 --- a/packages/experimental/webworker-runtime/package.json +++ b/packages/experimental/webworker-runtime/package.json @@ -58,7 +58,6 @@ "@deepseek-ai/dsh-sandbox-local": "workspace:^", "@deepseek-ai/dsh-sandbox-policy": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", - "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-subagent": "workspace:^", "@deepseek-ai/dsh-subprocess-local": "workspace:^", diff --git a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts index 631c000bad..561cf04699 100644 --- a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts +++ b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts @@ -1,9 +1,7 @@ import { readFileSync, readdirSync } from 'node:fs' import { join, relative } from 'node:path' import { describe, expect, it } from 'vitest' -import { Session, SessionId, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session' -import { SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence' -import { decodeStoredSession } from '@deepseek-ai/dsh-session-persistence/src/format-decoder.ts' +import { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import { scanLog } from '@deepseek-ai/dsh-session-persistence-jsonl/src/format.ts' import { foldSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import { @@ -28,24 +26,10 @@ function filesUnder(root: string): string[] { return files.sort() } -async function readSession(id: string): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { - const stored = scanLog(readFileSync( +function readSession(id: string): ReturnType { + return scanLog(readFileSync( join(VFS_EXAMPLE_ROOT, 'home/sessions/--dsh-workspace--', id, 'session.jsonl'), )) - const decoded = decodeStoredSession({ - meta: stored.meta, - revision: SessionPersistenceRevision(`vfs-example:${id}`), - readEvents: () => ({ - events: (async function* (): AsyncIterable { - yield* stored.events - })(), - completed: Promise.resolve({}), - }), - }, SessionId(id)) - const events: SessionEvent[] = [] - for await (const event of decoded.events) events.push(event) - await decoded.completed - return { meta: decoded.meta, events } } function textOf(event: SessionEvent): string { @@ -82,8 +66,8 @@ describe('WebWorker preview VFS example', () => { }) }) - it('restores the main production log with paging and tool coverage', async () => { - const { meta, events } = await readSession(VFS_EXAMPLE_SESSION_IDS.main) + it('restores the main production log with paging and tool coverage', () => { + const { meta, events } = readSession(VFS_EXAMPLE_SESSION_IDS.main) expect(meta).toMatchObject({ id: VFS_EXAMPLE_SESSION_IDS.main, cwd: '/dsh/workspace', @@ -110,13 +94,13 @@ describe('WebWorker preview VFS example', () => { expect(events.some(event => event.type === 'tool/result' && event.data.message.content[0].isError === true)).toBe(true) }) - it('restores one-shot and continuable child Sessions with durable descriptors', async () => { + it('restores one-shot and continuable child Sessions with durable descriptors', () => { const expected = [ [VFS_EXAMPLE_SESSION_IDS.oneShot, 'one-shot'], [VFS_EXAMPLE_SESSION_IDS.continuable, 'continuable'], ] as const for (const [id, mode] of expected) { - const { meta, events } = await readSession(id) + const { meta, events } = readSession(id) expect(meta).toMatchObject({ id, cwd: '/dsh/workspace', diff --git a/packages/session/session-persistence-jsonl/README.i18n.yaml b/packages/session/session-persistence-jsonl/README.i18n.yaml index 04e7a4ce0a..099e407149 100644 --- a/packages/session/session-persistence-jsonl/README.i18n.yaml +++ b/packages/session/session-persistence-jsonl/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/session/session-persistence-jsonl/README.md -README.md: b7ee18add7716054b24e71d0273a4e04bd544973 -README.zh.md: e4249ec130c0cf981004de442f38e2e0a7cca471 +README.md: 0301691acbe42c7973274e717ee9ae6f405ebea1 +README.zh.md: c05c380166b65a9826b6cb7f31729a51628ab49b diff --git a/packages/session/session-persistence-jsonl/README.md b/packages/session/session-persistence-jsonl/README.md index b7ee18add7..0301691acb 100644 --- a/packages/session/session-persistence-jsonl/README.md +++ b/packages/session/session-persistence-jsonl/README.md @@ -35,7 +35,7 @@ The JSONL durable session-persistence backend — a concrete `SessionPersistence The default artifact is a standard concatenation of independent [Zstandard frames](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.md): one checksummed frame containing only the header line, followed by one checksummed frame per durable append batch. The backend uses Node's built-in Zstandard API with its default compression level and exposes no level knob. Listing reads and validates only the header frame. `compression: 'none'` keeps the same logical lines in the original raw representation. -A root belongs to one encoding. Startup discovery and targeted lookup reject the opposite suffix with an error naming the incompatible artifact and instructing the caller to select the matching mode or a separate root. Flat `/.jsonl*` artifacts are also rejected instead of ignored. Session format migrations can replace a logical log within its configured encoding; there is no compression migration, mixed-root fallback, or dual write. +A root belongs to one encoding. Startup discovery and targeted lookup reject the opposite suffix with an error naming the incompatible artifact and instructing the caller to select the matching mode or a separate root. Flat `/.jsonl*` artifacts are also rejected instead of ignored. There is no migration, mixed-root fallback, or dual write. ## Durability and crash semantics @@ -69,7 +69,7 @@ JSONL storage does not mutate live request prefixes. A resumed loop can reuse pr ## Known Limitations and Deferred Work -- **Only format versions with a complete registered upgrade path load** — the registry is empty while `SESSION_FORMAT_VERSION` remains v0. Changing compression still requires a separate/fresh root or selecting the legacy raw mode. +- **Only the configured encoding and current `SESSION_FORMAT_VERSION` (v0) load** — changing compression requires a separate/fresh root or selecting the legacy raw mode; the pre-release format has no migration. - **The flat-file storage layout does not load** — use a separate root or move pre-release artifacts into the project/session directory layout before loading. - **Compressed files are not directly line-readable** — use the backend to load them, or select `compression: 'none'` before writing a fresh root when external line readers are required. - **Nothing deletes session files** — logs accumulate under `root` until removed externally (the seam has no deletion API). diff --git a/packages/session/session-persistence-jsonl/README.zh.md b/packages/session/session-persistence-jsonl/README.zh.md index e4249ec130..c05c380166 100644 --- a/packages/session/session-persistence-jsonl/README.zh.md +++ b/packages/session/session-persistence-jsonl/README.zh.md @@ -35,7 +35,7 @@ JSONL 持久会话存储后端:`SessionPersistence` 的一个具体实现(`d 默认产物是独立 [Zstandard frame](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.zh.md) 的标准拼接:一个仅包含 header 行的带 checksum frame,后跟每个持久 append 批次一个带 checksum frame。后端使用 Node 内置 Zstandard API 和默认压缩级别,不提供级别开关。列表只读取并验证 header frame。`compression: 'none'` 在原始表示中保留相同逻辑行。 -一个根只属于一种编码。启动发现和定向查找会拒绝相反 suffix,错误会命名不兼容产物,并指示调用方选择匹配 mode 或独立根。平铺 `/.jsonl*` 产物也会被拒绝,而不是忽略。Session 格式迁移可以在已配置编码内替换逻辑日志;不提供压缩迁移、混合根回退或双写。 +一个根只属于一种编码。启动发现和定向查找会拒绝相反 suffix,错误会命名不兼容产物,并指示调用方选择匹配 mode 或独立根。平铺 `/.jsonl*` 产物也会被拒绝,而不是忽略。不提供迁移、混合根回退或双写。 ## 持久性与崩溃语义 @@ -69,7 +69,7 @@ JSONL 存储不修改实时请求前缀。只有重建历史、当前 envelope ## 已知限制与暂缓事项 -- **只加载存在完整注册升级路径的格式版本**:`SESSION_FORMAT_VERSION` 保持 v0 时 registry 为空。更改压缩仍需要独立/全新根,或选择遗留原始 mode。 +- **只加载已配置编码和当前 `SESSION_FORMAT_VERSION`(v0)**:更改压缩需要独立/全新根,或选择遗留原始 mode;预发布格式没有迁移。 - **平铺文件存储布局不加载**:加载前使用独立根,或将预发布产物移入项目/会话目录布局。 - **压缩文件不能直接按行读取**:使用后端加载;或在写入新根前选择 `compression: 'none'`,以便外部行 reader 使用。 - **不删除会话文件**:日志在 `root` 下累积,直到外部移除(seam 无删除接口)。 diff --git a/packages/session/session-persistence-jsonl/src/format.ts b/packages/session/session-persistence-jsonl/src/format.ts index 321278088a..8092991eef 100644 --- a/packages/session/session-persistence-jsonl/src/format.ts +++ b/packages/session/session-persistence-jsonl/src/format.ts @@ -11,6 +11,7 @@ import { join } from 'node:path' import { decodeStorageRecord, packChunkRuns, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionHeader, SessionId, StorageRecord } from '@deepseek-ai/dsh-session' +import { SessionFormatUnsupportedError, sessionFormatVersionRefusal } from '@deepseek-ai/dsh-session-persistence' /** Physical encoding selected for JSONL session artifacts. */ export type JsonlCompression = 'zstd' | 'none' @@ -223,26 +224,29 @@ export function eventLines(events: readonly SessionEvent[], packChunks: boolean) } interface SessionLogScan { - meta: unknown - events: unknown[] + meta: SessionHeader + events: SessionEvent[] committedBytes: number } -/** Parse the version-independent identity fields from one physical header row. */ -function parseStoredHeader(value: unknown): Record | undefined { - if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined - const record = value as Record - if (record['type'] !== 'session' - || !Number.isSafeInteger(record['version'])) return undefined - if (record['version'] === SESSION_FORMAT_VERSION) { - return isHeaderLine(record) ? fromHeaderLine(record) as unknown as Record : undefined - } - const { type: _type, ...meta } = record - return meta +/** Parse one complete header record supplied independently from event rows. */ +/** + * Refuse a header carrying a format version this build does not read BEFORE + * validating the current header shape or decoding any event row: a future + * format need not satisfy this build's structural checks at all, and its user + * must see "upgrade the harness", never "corrupt session log". + * @param parsed - the JSON-parsed first line of a session artifact. + */ +function refuseForeignFormatVersion(parsed: unknown): void { + if (typeof parsed !== 'object' || parsed === null) return + const { version, id } = parsed as { version?: unknown; id?: unknown } + if (typeof version !== 'number' || version === SESSION_FORMAT_VERSION) return + throw new SessionFormatUnsupportedError( + sessionFormatVersionRefusal(typeof id === 'string' ? id : String(id), version), + ) } -/** Parse one complete header record supplied independently from event rows. */ -function parseHeaderRecord(record: Buffer): unknown { +function parseHeaderRecord(record: Buffer): SessionHeader { if (record.length === 0 || record.at(-1) !== 0x0A || record.indexOf(0x0A) !== record.length - 1) { throw new Error('empty or header-less session log') } @@ -252,11 +256,11 @@ function parseHeaderRecord(record: Buffer): unknown { } catch { throw new Error('corrupt session log: header line is not valid JSON') } - const meta = parseStoredHeader(parsed) - if (meta === undefined) { + refuseForeignFormatVersion(parsed) + if (!isHeaderLine(parsed)) { throw new Error('corrupt session log: first line is not a session header') } - return meta + return fromHeaderLine(parsed) } /** @@ -266,8 +270,8 @@ function parseHeaderRecord(record: Buffer): unknown { * copied because a decoder may reuse its output buffer after `write()` returns. */ export class SessionLogScanner { - private readonly meta: unknown - private readonly events: unknown[] = [] + private readonly meta: SessionHeader + private readonly events: SessionEvent[] = [] private fragments: Buffer[] = [] private fragmentBytes = 0 private inputBytes: number @@ -342,7 +346,7 @@ export class SessionLogScanner { /** Decode one complete event row and update the contiguous prefix. */ private consumeEventLine(line: Buffer, endByte: number): void { this.eventLine += 1 - let decoded: unknown[] + let decoded: SessionEvent[] try { decoded = decodeStorageRecord(JSON.parse(line.toString('utf8'))) } catch { @@ -351,21 +355,20 @@ export class SessionLogScanner { } if (this.issue !== undefined) { - if (decoded.some(event => (event as { type?: unknown }).type === 'turn/end')) throw this.issue + if (decoded.some(event => event.type === 'turn/end')) throw this.issue return } const rowStart = this.events.length for (const event of decoded) { - const seq = (event as { seq?: unknown }).seq - if (seq !== this.events.length) { + if (event.seq !== this.events.length) { const expected = this.events.length this.events.length = rowStart this.issue = new Error( `corrupt session log: seq gap in committed region at line ${this.eventLine} ` - + `(expected ${expected}, got ${String(seq)})`, + + `(expected ${expected}, got ${event.seq})`, ) - if (decoded.some(candidate => (candidate as { type?: unknown }).type === 'turn/end')) throw this.issue + if (decoded.some(candidate => candidate.type === 'turn/end')) throw this.issue return } this.events.push(event) @@ -391,18 +394,20 @@ export function scanLog(buffer: Buffer): SessionLogScan { } /** - * Parse only the version-independent identity envelope from one physical - * header line. Format migration and current validation run in the persistence - * decoder. - * @param firstLine - first JSONL record without its newline. - * @returns normalized logical header JSON, or `undefined` for invalid framing. + * Parse just the header line of a log into a {@link SessionHeader}, or + * `undefined` if it is missing/not a header. Used by `list()` to read session + * metadata WITHOUT parsing the whole log: a session picker scales with the + * number of sessions, not the total size of every conversation. + * @param firstLine - the first line of a log file (without its trailing newline). + * @returns the parsed header, or `undefined` when the line is not a well-formed session header. */ -export function parseStoredHeaderMeta(firstLine: string): Record | undefined { +export function parseHeaderMeta(firstLine: string): SessionHeader | undefined { let parsed: unknown try { parsed = JSON.parse(firstLine) } catch { return undefined } - return parseStoredHeader(parsed) + if (!isHeaderLine(parsed)) return undefined + return fromHeaderLine(parsed) } diff --git a/packages/session/session-persistence-jsonl/src/index.ts b/packages/session/session-persistence-jsonl/src/index.ts index f4a6c5c1b8..4bed7aefb9 100644 --- a/packages/session/session-persistence-jsonl/src/index.ts +++ b/packages/session/session-persistence-jsonl/src/index.ts @@ -9,43 +9,41 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { readdirSync } from 'node:fs' -import { open, mkdir, readFile, readdir, realpath, link, rename, rm, stat, truncate } from 'node:fs/promises' +import { open, mkdir, readFile, readdir, realpath, link, rm, stat, truncate } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { performance } from 'node:perf_hooks' import { scheduler } from 'node:timers/promises' import { randomBytes } from 'node:crypto' import { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, - decodeStoredSessionHeader, SessionPersistence, SessionPersistenceRevision, - SessionPersistenceRevisionConflictError, PersistenceCoordinator, + SessionPersistence, SessionPersistenceRevision, PersistenceCoordinator, SessionFormatUnsupportedError, type BorrowedSessionSource, type PersistenceBackend, type SessionLocation, type SessionPersistenceSnapshot, - type SessionInspection, type SessionPersistenceRevision as PersistenceRevision, type SessionRawArtifact, - type StoredEventRead, type StoredSessionSource, + type SessionInspection, + type SessionPersistenceRevision as PersistenceRevision, type SessionRawArtifact, + type StoredPrefix, } from '@deepseek-ai/dsh-session-persistence' -import { SessionId } from '@deepseek-ai/dsh-session' -import type { Session, SessionEvent, SessionHeader, SessionPreparation } from '@deepseek-ai/dsh-session' +import type { Session, SessionEvent, SessionId, SessionHeader, SessionPreparation } from '@deepseek-ai/dsh-session' import { - encodeSegment, eventLines, logPath, logSuffix, parseStoredHeaderMeta, projectDir, scanLog, sessionDir, + encodeSegment, eventLines, logPath, logSuffix, parseHeaderMeta, projectDir, scanLog, sessionDir, SessionLogScanner, toHeaderLine, type JsonlCompression, } from './format.ts' import { compressZstdFrame, createZstdFrameDecoder, decompressZstdFrame, decompressZstdPrefix, scanZstdFrames, } from './zstd.ts' -import { ensureDurableDirectoryWin32, publishNewFileWin32, replaceFileWin32 } from './win32.ts' +import { ensureDurableDirectoryWin32, publishNewFileWin32 } from './win32.ts' export type { JsonlCompression } from './format.ts' const DEFAULT_PACK_CHUNKS = true const DEFAULT_COMPRESSION: JsonlCompression = 'zstd' /** - * Internal scheduling constants, not deployment configuration: decode yields - * balance frame latency against `setImmediate` overhead; replacement batches - * bound memory and frame granularity without changing durable behavior. + * Internal scheduling constant, not deployment configuration: balance + * frame-boundary event-loop yields against `setImmediate` overhead. One frame + * remains an indivisible synchronous decode. */ const ZSTD_DECODE_YIELD_INTERVAL_MS = 500 -const REPLACEMENT_BATCH_SIZE = 128 /** Assert that the independently decodable first frame contains only the header record. */ function assertZstdHeaderFrame(plaintext: Buffer): void { @@ -92,18 +90,6 @@ interface JsonlTornMarker { recoveredEvents: SessionEvent[] } -interface JsonlStoredPrefix { - readonly meta: unknown - readonly events: unknown[] - readonly revision: PersistenceRevision - readonly tornMarker?: JsonlTornMarker -} - -interface JsonlStoredHeader { - readonly meta: unknown - readonly revision: PersistenceRevision -} - interface FileRevisionIdentity { readonly dev: bigint readonly ino: bigint @@ -217,8 +203,8 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi return this.coordinator.borrowSession(id, signal) } - // JSONL is sequential media: its source reader parses the stored prefix and - // filters only after physical framing and sequence checks. + // JSONL is sequential media: no loadStoredFrom hook, so the coordinator + // parses the stored prefix (both encodings) and skips forward to fromSeq. readFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { return this.coordinator.readFrom(id, fromSeq, signal) } @@ -229,38 +215,14 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi /* jscpd:ignore-end */ // --- PersistenceBackend hooks (the file-bytes storage primitives) --- - /** Open repeatable reads over one revision resolved across project directories. */ - async openStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { + /** Read a stored prefix by id across all project directories when cwd is unknown. */ + async loadStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { signal?.throwIfAborted() await this.ensureRootEncoding() signal?.throwIfAborted() const path = await this.findLog(id, signal) if (path === undefined) return undefined - const { meta, revision } = await this.readStoredHeader(path, id, signal) - return { - meta, - revision, - location: { kind: 'jsonl', path }, - readEvents: (options = {}): StoredEventRead => { - const fromSeq = options.fromSeq ?? 0 - return this.createStoredEventRead( - async () => { - const prefix = await this.readPrefix(path, id, signal) - if (prefix.revision !== revision) { - throw new SessionPersistenceRevisionConflictError( - `session "${id}" changed while reading revision ${revision}`, - ) - } - return prefix - }, - (event) => { - const seq = (event as { seq?: unknown }).seq - return typeof seq !== 'number' || seq >= fromSeq - }, - signal, - ) - }, - } + return this.readPrefix(path, id, signal) } /** @@ -320,11 +282,10 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi } else { content = buffer.toString('utf8') } - const rawMeta = parseStoredHeaderMeta(content.split('\n', 1)[0] as string) - if (rawMeta === undefined) { + const meta = parseHeaderMeta(content.split('\n', 1)[0] as string) + if (meta === undefined || meta.id !== id) { throw new Error(`corrupt session log: invalid header line in "${path}"`) } - const meta = decodeStoredSessionHeader(rawMeta, id, { kind: 'jsonl', path }) // The logical artifact name is `session.jsonl` regardless of the physical // encoding suffix (`.jsonl.zstd` marks compression only). return { meta, filename: 'session.jsonl', content } @@ -352,31 +313,6 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi } } - /** Read one version-independent header at a stable file revision. */ - private async readStoredHeader( - path: string, - _expectedId?: SessionId, - signal?: AbortSignal, - ): Promise { - for (;;) { - signal?.throwIfAborted() - const before = fileRevision(await stat(path, { bigint: true })) - const firstLine = this.compression === 'zstd' - ? await this.readFirstZstdLine(path, signal) - : await this.readFirstLine(path, signal) - const after = fileRevision(await stat(path, { bigint: true })) - if (before !== after) continue - if (firstLine === undefined) { - throw new Error(this.compression === 'zstd' - ? `empty or header-less Zstandard session log at "${path}"` - : `empty or header-less session log at "${path}"`) - } - const meta = parseStoredHeaderMeta(firstLine) - if (meta === undefined) throw new Error(`corrupt session log: first line is not a session header in "${path}"`) - return { meta, revision: after } - } - } - /** * Read a stored prefix and convert torn-tail state to the opaque marker the * coordinator can round-trip without knowing the physical encoding. @@ -385,22 +321,32 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi path: string, expectedId?: SessionId, signal?: AbortSignal, - ): Promise { + ): Promise> { const { buffer, revision } = await this.readStableFile(path, signal) - let prefix: Omit - if (this.compression === 'zstd') { - prefix = await this.readZstdPrefix(buffer, signal) - } else { - signal?.throwIfAborted() - const { meta, events, committedBytes } = scanLog(buffer) - signal?.throwIfAborted() - prefix = { - meta, - events, - ...committedBytes < buffer.byteLength - ? { tornMarker: { truncateTo: committedBytes, recoveredEvents: [] } } - : {}, + let prefix: Omit, 'revision'> + try { + if (this.compression === 'zstd') { + prefix = await this.readZstdPrefix(buffer, signal) + } else { + signal?.throwIfAborted() + const { meta, events, committedBytes } = scanLog(buffer) + signal?.throwIfAborted() + prefix = { + meta, + events, + ...committedBytes < buffer.byteLength + ? { tornMarker: { truncateTo: committedBytes, recoveredEvents: [] } } + : {}, + } } + } catch (error: unknown) { + // A parse-time format refusal predates any SessionHeader, so the + // coordinator's locate-based enrichment cannot run; attach the artifact + // this read actually refused. + if (error instanceof SessionFormatUnsupportedError && error.location === undefined) { + throw new SessionFormatUnsupportedError(`${error.message} (raw log: ${path})`, { kind: 'jsonl', path }) + } + throw error } signal?.throwIfAborted() await this.assertStoredIdentity(path, prefix.meta, expectedId, signal) @@ -412,7 +358,7 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi private async readZstdPrefix( buffer: Buffer, signal?: AbortSignal, - ): Promise> { + ): Promise, 'revision'>> { signal?.throwIfAborted() const { frames, tornStart } = scanZstdFrames(buffer) signal?.throwIfAborted() @@ -470,7 +416,7 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi events: recoveredPrefix.events, tornMarker: { truncateTo: tornStart, - recoveredEvents: recoveredPrefix.events.slice(complete.eventCount) as SessionEvent[], + recoveredEvents: recoveredPrefix.events.slice(complete.eventCount), }, } } catch (error) { @@ -513,61 +459,6 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi if (tornMarker !== undefined) this.ctx.logger.warn(`${this.name}: session "${meta.id}" recovered from a torn tail; incomplete tail bytes were discarded`) } - /** Replace one exact source revision through a synced sibling and atomic namespace update. */ - async replaceStored( - expectedRevision: PersistenceRevision, - meta: SessionHeader, - events: AsyncIterable, - ): Promise { - await this.ensureRootEncoding() - const path = await this.findLog(meta.id) - if (path === undefined) { - throw new SessionPersistenceRevisionConflictError( - `session "${meta.id}" no longer has revision ${expectedRevision}`, - ) - } - let current: JsonlStoredHeader - try { - current = await this.readStoredHeader(path, meta.id) - } catch (error: unknown) { - if (isENOENT(error)) { - throw new SessionPersistenceRevisionConflictError( - `session "${meta.id}" no longer has revision ${expectedRevision}`, - ) - } - throw error - } - if (current.revision !== expectedRevision) { - throw new SessionPersistenceRevisionConflictError( - `session "${meta.id}" changed before replacement of revision ${expectedRevision}`, - ) - } - const currentIdentity = this.storedIdentity(current.meta, path) - if (meta.cwd !== currentIdentity.cwd) { - throw new Error(`replacement for session "${meta.id}" changes its stored identity`) - } - - const tmp = `${path}.${randomBytes(6).toString('hex')}.upgrade.tmp` - try { - await this.writeReplacement(tmp, meta, events) - const beforeCommit = fileRevision(await stat(path, { bigint: true })) - if (beforeCommit !== expectedRevision) { - throw new SessionPersistenceRevisionConflictError( - `session "${meta.id}" changed before replacement of revision ${expectedRevision}`, - ) - } - /* v8 ignore next -- Windows uses its write-through replacement primitive. */ - if (process.platform === 'win32') { - await replaceFileWin32(tmp, path) - } else { - await rename(tmp, path) - await this.syncDirPosix(dirname(path)) - } - } finally { - await rm(tmp, { force: true }) - } - } - /** List valid unique stored sessions' metadata (header line only — no full-log parse). */ async list(signal?: AbortSignal): Promise { return (await this.listArtifacts(signal)).map(artifact => artifact.header) @@ -618,15 +509,9 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi : await this.readFirstLine(path, signal) signal?.throwIfAborted() if (first === undefined) continue // empty/half-written file - const rawMeta = parseStoredHeaderMeta(first) - if (rawMeta === undefined) continue // not a session header - const rawId = rawMeta['id'] - const expectedId = typeof rawId === 'string' - ? SessionId(rawId) - : SessionId('') - const meta = decodeStoredSessionHeader(rawMeta, expectedId, { kind: 'jsonl', path }) - this.storedIdentity(rawMeta, path) - await this.assertStoredIdentity(path, rawMeta, undefined, signal) + const meta = parseHeaderMeta(first) + if (meta === undefined) continue // not a session header + await this.assertStoredIdentity(path, meta, undefined, signal) signal?.throwIfAborted() if (ids.has(meta.id)) { throw new Error(`duplicate JSONL session id "${meta.id}" appears in multiple project directories`) @@ -746,34 +631,6 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi return tmp } - /** Stream one complete current-format replacement into a synced temp file. */ - private async writeReplacement( - path: string, - meta: SessionHeader, - events: AsyncIterable, - ): Promise { - const handle = await open(path, 'wx', 0o600) - try { - const header = JSON.stringify(toHeaderLine(meta)) + '\n' - await handle.writeFile(this.compression === 'zstd' ? await compressZstdFrame(header) : header) - let batch: SessionEvent[] = [] - const writeBatch = async (): Promise => { - if (batch.length === 0) return - const body = eventLines(batch, this.packChunks) + '\n' - await handle.writeFile(this.compression === 'zstd' ? await compressZstdFrame(body) : body) - batch = [] - } - for await (const event of events) { - batch.push(event) - if (batch.length === REPLACEMENT_BATCH_SIZE) await writeBatch() - } - await writeBatch() - await handle.sync() - } finally { - await handle.close() - } - } - /** Encode the header and first batch without combining their frame boundaries. */ private async encodeMaterialization(meta: SessionHeader, events: readonly SessionEvent[]): Promise { const header = JSON.stringify(toHeaderLine(meta)) + '\n' @@ -969,45 +826,26 @@ export class JsonlSessionPersistence extends SessionPersistence implements Persi /** Reject metadata that does not identify the selected physical log. */ private async assertStoredIdentity( path: string, - meta: unknown, + meta: SessionHeader, expectedId?: SessionId, signal?: AbortSignal, ): Promise { signal?.throwIfAborted() - const identity = this.storedIdentity(meta, path) - if (expectedId !== undefined && identity.id !== expectedId) { - throw new Error(`corrupt session log "${path}": requested id "${expectedId}" does not match header id "${identity.id}"`) + if (expectedId !== undefined && meta.id !== expectedId) { + throw new Error(`corrupt session log "${path}": requested id "${expectedId}" does not match header id "${meta.id}"`) } let expectedPath: string try { - expectedPath = logPath(this.root, identity.cwd, identity.id, this.compression) + expectedPath = logPath(this.root, meta.cwd, meta.id, this.compression) } catch (error) { throw new Error(`corrupt session log "${path}": header id cannot name a storage path`, { cause: error }) } if (path !== expectedPath && !await this.sameFile(path, expectedPath, signal)) { - throw new Error(`corrupt session log "${path}": header id "${identity.id}" and cwd identify "${expectedPath}"`) + throw new Error(`corrupt session log "${path}": header id "${meta.id}" and cwd identify "${expectedPath}"`) } signal?.throwIfAborted() } - /** Read storage identity fields shared by every Session format version. */ - private storedIdentity(meta: unknown, path: string): { id: SessionId; cwd?: string } { - if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) { - throw new Error(`corrupt session log "${path}": header is not a record`) - } - const record = meta as Record - if (typeof record['id'] !== 'string') { - throw new Error(`corrupt session log "${path}": header id is not a string`) - } - if (record['cwd'] !== undefined && typeof record['cwd'] !== 'string') { - throw new Error(`corrupt session log "${path}": header cwd is not a string`) - } - return { - id: SessionId(record['id']), - ...typeof record['cwd'] === 'string' ? { cwd: record['cwd'] } : {}, - } - } - /** * Whether two path spellings resolve to the same physical file. This admits * case aliases on case-insensitive filesystems without weakening identity diff --git a/packages/session/session-persistence-jsonl/src/win32.ts b/packages/session/session-persistence-jsonl/src/win32.ts index 51456bd740..c3fa852b08 100644 --- a/packages/session/session-persistence-jsonl/src/win32.ts +++ b/packages/session/session-persistence-jsonl/src/win32.ts @@ -28,7 +28,6 @@ interface Win32ErrnoException extends NodeJS.ErrnoException { } const MOVEFILE_WRITE_THROUGH = 0x00000008 -const MOVEFILE_REPLACE_EXISTING = 0x00000001 const ERROR_FILE_NOT_FOUND = 2 const ERROR_PATH_NOT_FOUND = 3 const ERROR_ACCESS_DENIED = 5 @@ -120,19 +119,6 @@ export async function publishNewFileWin32(existing: string, replacement: string) if (ok === 0) throw win32Error('MoveFileExW', api.getLastError(), existing, replacement) } -/** - * Atomically replace an existing file with a synced staging file and request - * write-through namespace durability. The move stays within one volume. - * @param existing - synced staging path to move. - * @param replacement - existing final path to replace. - */ -export async function replaceFileWin32(existing: string, replacement: string): Promise { - const api = await win32() - const flags = MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH - const ok = api.moveFileExW(toNamespacedPath(existing), toNamespacedPath(replacement), flags) - if (ok === 0) throw win32Error('MoveFileExW', api.getLastError(), existing, replacement) -} - /** * Create `target` and its missing ancestors with durable Windows namespace * publication. Each missing directory is first created as a random staging diff --git a/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts b/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts index 69227bbd4e..eea36d5089 100644 --- a/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts +++ b/packages/session/session-persistence-jsonl/tests/jsonl.spec.ts @@ -8,12 +8,7 @@ import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import { - SessionPersistenceRevisionConflictError, - type StoredEventRead, -} from '@deepseek-ai/dsh-session-persistence' -import { - encodeSegment, eventLines, fromHeaderLine, logPath, parseStoredHeaderMeta, projectDir, projectKey, scanLog, sessionDir, - SessionLogScanner, toHeaderLine, + encodeSegment, eventLines, logPath, projectDir, projectKey, scanLog, sessionDir, SessionLogScanner, toHeaderLine, } from '../src/format.ts' import { runPersistenceContract, meta, oneTurnLog, appendLog } from '../../session-persistence/tests/contract.ts' import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts' @@ -21,8 +16,6 @@ import { runCoordinatorContract, type CoordinatorFixture } from '../../session-p const statRace = vi.hoisted(() => ({ path: undefined as string | undefined, reads: 0, - renamePath: undefined as string | undefined, - renameError: undefined as Error | undefined, })) vi.mock('node:fs/promises', async (importOriginal) => { @@ -36,25 +29,6 @@ vi.mock('node:fs/promises', async (importOriginal) => { if (statRace.reads !== 2) return identity return { ...identity, mtimeNs: identity.mtimeNs + 1n } }) as typeof actual.stat, - rename: async (...args: Parameters) => { - if (String(args[1]) === statRace.renamePath && statRace.renameError !== undefined) { - throw statRace.renameError - } - return actual.rename(...args) - }, - } -}) - -vi.mock('../src/win32.ts', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - replaceFileWin32: async (existing: string, replacement: string) => { - if (replacement === statRace.renamePath && statRace.renameError !== undefined) { - throw statRace.renameError - } - return actual.replaceFileWin32(existing, replacement) - }, } }) @@ -68,17 +42,6 @@ function mutableHeader(header: SessionHeader): MutableSessionHeader { return header } -async function collectStoredRead(read: StoredEventRead): Promise { - const events: unknown[] = [] - for await (const event of read.events) events.push(event) - await read.completed - return events -} - -async function* replacementEvents(events: readonly SessionEvent[]): AsyncIterable { - for (const event of events) yield structuredClone(event) -} - /** Rewrite only a stored header while preserving every event byte below it. */ async function rewriteHeader(path: string, update: (header: Record) => void): Promise { const lines = (await readFile(path, 'utf8')).split('\n') @@ -123,8 +86,6 @@ function rawLogPath(root: string, cwd: string | undefined, id: SessionId): strin afterEach(async () => { statRace.path = undefined statRace.reads = 0 - statRace.renamePath = undefined - statRace.renameError = undefined vi.restoreAllMocks() for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) }) @@ -172,18 +133,6 @@ runCoordinatorContract('jsonl-none', async (): Promise => { }) describe('JsonlSessionPersistence: format helpers', () => { - it('parses only the version-independent stored header envelope', () => { - expect(parseStoredHeaderMeta('{')).toBeUndefined() - expect(parseStoredHeaderMeta('42')).toBeUndefined() - expect(parseStoredHeaderMeta(JSON.stringify({ type: 'event', version: 9, id: 'wrong-type' }))) - .toBeUndefined() - expect(parseStoredHeaderMeta(JSON.stringify({ type: 'session', version: 9, id: 'future', futureOnly: true }))) - .toEqual({ version: 9, id: 'future', futureOnly: true }) - expect(parseStoredHeaderMeta(JSON.stringify({ - type: 'session', version: 0, id: 'current', createdAt: 1, delegationDepth: 0, - }))).toEqual({ version: 0, id: 'current', createdAt: 1, delegationDepth: 0 }) - }) - it('encodeSegment neutralizes traversal, separators, and absolute paths', () => { expect(encodeSegment('..')).toBe('~002E~002E') expect(encodeSegment('.')).toBe('~002E') @@ -370,8 +319,7 @@ describe('JsonlSessionPersistence: durability and crash semantics', () => { expect(raw!.content).toBe(await readFile(rawLogPath(root, '/work', m.id), 'utf8')) expect(raw!.content.split('\n')[0]).toBe(JSON.stringify(toHeaderLine(m))) const scanned = scanLog(Buffer.from(raw!.content)) - expect(scanned.events.map(event => (event as SessionEvent).type)) - .toEqual(oneTurnLog().map(event => event.type)) + expect(scanned.events.map(event => event.type)).toEqual(oneTurnLog().map(event => event.type)) }) it('readRaw is undefined for an absent session', async () => { @@ -469,261 +417,28 @@ describe('JsonlSessionPersistence: durability and crash semantics', () => { await otherCtx.fiber.dispose() }) - it('binds a stored source to the same revision as a lightweight read', async () => { + it('binds a full stored prefix to the same revision as a lightweight read', async () => { const m = meta('stored-prefix-revision') await ctx.sessionPersistence.create(m) await ctx.sessionPersistence.append(m.id, oneTurnLog()) const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const stored = await persistence.openStored(m.id) + const stored = await persistence.loadStored(m.id) expect(stored?.revision).toBe(await persistence.readStoredRevision(m.id)) expect(await persistence.readStoredRevision(SessionId('missing-revision'))).toBeUndefined() }) - it('retries a revision-bound source read when the file changes during the read', async () => { + it('retries a full-prefix read when the file revision changes during the read', async () => { const m = meta('stored-prefix-revision-race') await ctx.sessionPersistence.create(m) await ctx.sessionPersistence.append(m.id, oneTurnLog()) const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const stored = await persistence.openStored(m.id) - if (stored === undefined) throw new Error('test session must be materialized') statRace.path = rawLogPath(root, m.cwd, m.id) - await expect(collectStoredRead(stored.readEvents())).resolves.toEqual(oneTurnLog()) + await expect(persistence.loadStored(m.id)).resolves.toMatchObject({ events: oneTurnLog() }) expect(statRace.reads).toBe(4) }) - it('rejects a revision-bound source after a complete append changes its revision', async () => { - const m = meta('stored-source-stale') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const stored = await persistence.openStored(m.id) - if (stored === undefined) throw new Error('test session must be materialized') - - await ctx.sessionPersistence.append(m.id, [ - { type: 'turn/start', seq: oneTurnLog().length, time: 7, data: { turn: 2 } }, - ]) - - const read = stored.readEvents() - const completion = read.completed.catch((error: unknown) => error) - await expect(collectStoredRead(read)).rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - await expect(completion).resolves.toBeInstanceOf(SessionPersistenceRevisionConflictError) - }) - - it('retries a header read whose revision changes around the first-line read', async () => { - const m = meta('stored-header-revision-race') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const path = rawLogPath(root, m.cwd, m.id) - const internals = persistence as unknown as { - findLog(id: SessionId): Promise - } - vi.spyOn(internals, 'findLog').mockResolvedValue(path) - statRace.path = path - - await expect(persistence.openStored(m.id)).resolves.toMatchObject({ meta: { id: m.id } }) - expect(statRace.reads).toBe(4) - }) - - it('reports a present empty plaintext artifact as header-less', async () => { - const m = meta('empty-plaintext-log') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - await writeFile(rawLogPath(root, m.cwd, m.id), '') - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - - await expect(persistence.openStored(m.id)) - .rejects.toThrow('empty or header-less session log') - }) - - it('forwards prepare through the concrete backend API', async () => { - const m = meta('jsonl-prepare-forward') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - - const preparation = await persistence.prepare(m.id) - expect(preparation.session.id).toBe(m.id) - preparation[Symbol.dispose]() - }) - - it('atomically replaces one exact revision and rejects a stale replacement', async () => { - const m = meta('format-replace', '/work') - const original = [ - ...oneTurnLog(), - { type: 'turn/start', seq: 6, time: 7, data: { turn: 2 } }, - { type: 'turn/end', seq: 7, time: 8, data: { turn: 2, reason: { kind: 'completed' } } }, - ] as SessionEvent[] - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, original) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - - await persistence.replaceStored(source.revision, m, replacementEvents(oneTurnLog())) - const replaced = await persistence.openStored(m.id) - if (replaced === undefined) throw new Error('replacement must preserve the session') - expect(replaced.revision).not.toBe(source.revision) - expect(await collectStoredRead(replaced.readEvents())).toEqual(oneTurnLog()) - - await expect( - persistence.replaceStored(source.revision, m, replacementEvents(original)), - ).rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - const afterConflict = await persistence.openStored(m.id) - if (afterConflict === undefined) throw new Error('conflict must preserve the session') - expect(await collectStoredRead(afterConflict.readEvents())).toEqual(oneTurnLog()) - }) - - it('preserves the old complete log when atomic replacement rename fails', async () => { - const m = meta('format-replace-rename-failure', '/work') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - const path = rawLogPath(root, m.cwd, m.id) - const failure = new Error('simulated format replacement rename failure') - statRace.renamePath = path - statRace.renameError = failure - - await expect( - persistence.replaceStored(source.revision, m, replacementEvents([])), - ).rejects.toBe(failure) - - statRace.renameError = undefined - const preserved = await persistence.openStored(m.id) - if (preserved === undefined) throw new Error('failed replacement must preserve the session') - expect(await collectStoredRead(preserved.readEvents())).toEqual(oneTurnLog()) - expect((await readdir(dirname(path))).some(name => name.endsWith('.upgrade.tmp'))).toBe(false) - }) - - it('rejects replacement when the artifact disappears before or after discovery', async () => { - const m = meta('format-replace-disappeared', '/work') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - const path = rawLogPath(root, m.cwd, m.id) - - await rm(path) - await expect(persistence.replaceStored(source.revision, m, replacementEvents([]))) - .rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - - const internals = persistence as unknown as { - findLog(id: SessionId): Promise - } - vi.spyOn(internals, 'findLog').mockResolvedValue(path) - await expect(persistence.replaceStored(source.revision, m, replacementEvents([]))) - .rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - }) - - it('propagates a non-absence error while rechecking a replacement source', async () => { - const m = meta('format-replace-header-error', '/work') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - const failure = new Error('simulated header read failure') - const internals = persistence as unknown as { - readStoredHeader(path: string, id: SessionId): Promise - } - vi.spyOn(internals, 'readStoredHeader').mockRejectedValue(failure) - - await expect(persistence.replaceStored(source.revision, m, replacementEvents([]))) - .rejects.toBe(failure) - }) - - it('rejects a replacement that changes cwd storage identity', async () => { - const m = meta('format-replace-identity', '/work') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - - await expect(persistence.replaceStored( - source.revision, - { ...m, cwd: '/other' }, - replacementEvents(oneTurnLog()), - )).rejects.toThrow(/changes its stored identity/) - }) - - it('rejects a replacement when the source changes after the temp file is synced', async () => { - const m = meta('format-replace-final-cas', '/work') - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - const path = rawLogPath(root, m.cwd, m.id) - const internals = persistence as unknown as { - writeReplacement(path: string, meta: SessionHeader, events: AsyncIterable): Promise - } - const writeReplacement = internals.writeReplacement.bind(internals) - vi.spyOn(internals, 'writeReplacement').mockImplementation(async (...args) => { - await writeReplacement(...args) - await appendFile(path, '\n') - }) - - await expect(persistence.replaceStored(source.revision, m, replacementEvents(oneTurnLog()))) - .rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - expect((await readdir(dirname(path))).some(name => name.endsWith('.upgrade.tmp'))).toBe(false) - }) - - it('streams replacement events in bounded batches', async () => { - const m = meta('format-replace-batches', '/work') - const events = Array.from({ length: 128 }, (_, seq): SessionEvent => ({ - type: 'turn/start', seq, time: seq + 1, data: { turn: seq + 1 }, - })) - await ctx.sessionPersistence.create(m) - await ctx.sessionPersistence.append(m.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - - await persistence.replaceStored(source.revision, m, replacementEvents(events)) - - const replaced = await persistence.openStored(m.id) - if (replaced === undefined) throw new Error('replacement must preserve the session') - expect(await collectStoredRead(replaced.readEvents())).toHaveLength(128) - }) - - it('rejects malformed version-independent storage identity fields', async () => { - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const path = rawLogPath(root, '/work', SessionId('identity-fields')) - const internals = persistence as unknown as { - storedIdentity(meta: unknown, path: string): { id: SessionId; cwd?: string } - } - - expect(() => internals.storedIdentity(null, path)).toThrow(/header is not a record/) - expect(() => internals.storedIdentity({ id: 1 }, path)).toThrow(/header id is not a string/) - expect(() => internals.storedIdentity({ id: 'identity-fields', cwd: 1 }, path)) - .toThrow(/header cwd is not a string/) - }) - - it('rejects a physical log whose requested id differs from its header id', async () => { - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const requested = SessionId('requested-identity') - const path = rawLogPath(root, '/work', requested) - const internals = persistence as unknown as { - assertStoredIdentity( - path: string, - meta: unknown, - expectedId?: SessionId, - ): Promise - } - - await expect(internals.assertStoredIdentity( - path, - { id: 'different-identity', cwd: '/work' }, - requested, - )).rejects.toThrow(/requested id .* does not match header id/) - }) - it('handles revision-stat races and errors after log discovery', async () => { const m = meta('stored-revision-race') await ctx.sessionPersistence.create(m) @@ -1053,7 +768,7 @@ describe('JsonlSessionPersistence: durability and crash semantics', () => { const beforeB = await readFile(bPath) await expect(ctx.sessionPersistence.load(a.id)) - .rejects.toThrow(/identity mismatch: requested "identity-a", header contains "identity-b"/) + .rejects.toThrow(/requested id "identity-a" does not match header id "identity-b"/) expect(await readFile(aPath)).toEqual(beforeA) expect(await readFile(bPath)).toEqual(beforeB) }) @@ -1244,20 +959,7 @@ describe('JsonlSessionPersistence: scanLog unit', () => { // The preset decides the resumed session's tools and prompt; dropping it // on disk would restore a composition the logged history contradicts. - expect((scanLog(Buffer.from(log)).meta as SessionHeader).agentPreset).toBe('minimal') - }) - - it('round-trips and validates a subagent origin', () => { - const header: SessionHeader = { - ...meta('subagent-origin'), - delegationDepth: 1, - origin: 'subagent', - } - const line = toHeaderLine(header) - - expect(fromHeaderLine(line)).toEqual(header) - expect(() => scanLog(Buffer.from(`${JSON.stringify({ ...line, origin: 'parent' })}\n`))) - .toThrow(/session header/) + expect(scanLog(Buffer.from(log)).meta.agentPreset).toBe('minimal') }) it('rejects a session header whose agentPreset is not a string', () => { @@ -1275,7 +977,7 @@ describe('JsonlSessionPersistence: scanLog unit', () => { // No committed turn/end, so the gap is a tolerated crash boundary: scanLog PRESERVES the // contiguous prefix (turn/start seq 0) — real interrupted-turn work, not discarded — and // stops at the gap. `loadCore`, not this scanner, later closes the orphaned turn. - expect(scanLog(Buffer.from(log)).events.map(e => (e as SessionEvent).seq)).toEqual([0]) + expect(scanLog(Buffer.from(log)).events.map(e => e.seq)).toEqual([0]) }) it('rejects a seq gap BEFORE a later committed turn/end (committed data damaged)', () => { @@ -1315,7 +1017,7 @@ describe('JsonlSessionPersistence: scanLog unit', () => { ].join('\n') + '\n' // The contiguous prefix (turn/start seq 0) is preserved; the corrupt // fragment after it is the tolerated crash boundary. - expect(scanLog(Buffer.from(log)).events.map(e => (e as SessionEvent).seq)).toEqual([0]) + expect(scanLog(Buffer.from(log)).events.map(e => e.seq)).toEqual([0]) }) it('tolerates a seq gap AFTER a turn/end (uncommitted tail)', () => { @@ -1326,7 +1028,7 @@ describe('JsonlSessionPersistence: scanLog unit', () => { JSON.stringify({ type: 'step/start', seq: 9, time: 3, data: { turn: 2, step: 1 } }), // gap in uncommitted tail ].join('\n') + '\n' const { events } = scanLog(Buffer.from(log)) - expect(events.map(e => (e as SessionEvent).seq)).toEqual([0, 1]) // tail dropped + expect(events.map(e => e.seq)).toEqual([0, 1]) // tail dropped }) }) @@ -1447,7 +1149,7 @@ describe('JsonlSessionPersistence: default packed chunk rows', () => { JSON.stringify({ type: 'turn/end', seq: 4, time: 5, data: { turn: 1, reason: { kind: 'completed' } } }), ].join('\n') + '\n' const { events } = scanLog(Buffer.from(logText)) - expect(events.map(e => (e as SessionEvent).seq)).toEqual([0, 1, 2, 3, 4]) + expect(events.map(e => e.seq)).toEqual([0, 1, 2, 3, 4]) expect(events[2]).toEqual({ type: 'assistant/chunk', seq: 2, time: 3, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'b' } } }) }) @@ -1469,7 +1171,7 @@ describe('JsonlSessionPersistence: default packed chunk rows', () => { JSON.stringify({ type: 'text-chunks', seq0: 2, time0: 2, data: { turn: 1, step: 1, index: 0, dt: [1, 1], texts: ['a', 'b', 'c'] } }), ].join('\n') + '\n' const scanned = scanLog(Buffer.from(logText)) - expect(scanned.events.map(e => (e as SessionEvent).seq)).toEqual([0]) + expect(scanned.events.map(e => e.seq)).toEqual([0]) // committedBytes stays on the line boundary BEFORE the dropped row. const headerAndTurn = logText.split('\n').slice(0, 2).join('\n') + '\n' expect(scanned.committedBytes).toBe(Buffer.byteLength(headerAndTurn, 'utf8')) @@ -1544,23 +1246,6 @@ describe('JsonlSessionPersistence: edge cases', () => { expect(await ctx.sessionPersistence.list()).toEqual([]) }) - it('listing refuses a future format before validating current identity fields', async () => { - const id = SessionId('future-list') - const path = rawLogPath(root, '/work', id) - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, `${JSON.stringify({ type: 'session', version: 42, id: 123 })}\n`) - - for (const list of [ - () => ctx.sessionPersistence.list(), - () => ctx.sessionPersistence.listSnapshots(), - ]) { - const failure = await list().then(() => undefined, (error: unknown) => error as Error) - expect(failure?.name).toBe('SessionFormatUnsupportedError') - expect(failure?.message).toContain('session "123" uses log format v42') - expect(failure?.message).toMatch(/written by a newer harness.*upgrade the harness/) - } - }) - it('keeps the transcript in an extensible session-owned directory', async () => { const m = meta('owned-directory', '/project') await ctx.sessionPersistence.create(m) @@ -1728,7 +1413,7 @@ describe('JsonlSessionPersistence: edge cases', () => { // The "/w" log is untouched — no no-cwd events were grafted onto it, and no // `_no-cwd` log for "x" was created. const inW = scanLog(await readFile(rawLogPath(root, '/w', SessionId('x')))) - expect((inW.meta as SessionHeader).cwd).toBe('/w') + expect(inW.meta.cwd).toBe('/w') expect(inW.events).toHaveLength(6) await expect(stat(rawLogPath(root, undefined, SessionId('x')))).rejects.toThrow() await ctx2.fiber.dispose() diff --git a/packages/session/session-persistence-jsonl/tests/win32.spec.ts b/packages/session/session-persistence-jsonl/tests/win32.spec.ts index 33b8d2328f..3b6cfc4f78 100644 --- a/packages/session/session-persistence-jsonl/tests/win32.spec.ts +++ b/packages/session/session-persistence-jsonl/tests/win32.spec.ts @@ -11,7 +11,6 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' const MOVEFILE_WRITE_THROUGH = 0x00000008 -const MOVEFILE_REPLACE_EXISTING = 0x00000001 const ERROR_FILE_NOT_FOUND = 2 const ERROR_PATH_NOT_FOUND = 3 const ERROR_ACCESS_DENIED = 5 @@ -91,17 +90,6 @@ async function importWithFilesystemMove(): Promise { - return importWithMove((existing, replacement, flags, setLastError) => { - expect(flags).toBe(MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) - const from = stripNamespace(existing) - const to = stripNamespace(replacement) - if (!existsSync(from)) { setLastError(ERROR_FILE_NOT_FOUND); return 0 } - renameSync(from, to) - return 1 - }) -} - afterEach(async () => { vi.doUnmock('koffi') vi.doUnmock('node:fs/promises') @@ -153,30 +141,6 @@ describe('Windows durable namespace helpers', () => { expect(readFileSync(final, 'utf8')).toBe('content') }) - it('replaces an existing file with write-through MoveFileExW semantics', async () => { - const { replaceFileWin32 } = await importWithFilesystemReplace() - const root = await tempRoot() - const tmp = join(root, 'log.tmp') - const final = join(root, 'log.jsonl') - await writeFile(tmp, 'replacement') - await writeFile(final, 'original') - - await replaceFileWin32(tmp, final) - expect(existsSync(tmp)).toBe(false) - expect(readFileSync(final, 'utf8')).toBe('replacement') - }) - - it('maps a Win32 replacement failure to a Node-style error', async () => { - const { replaceFileWin32 } = await importWithError(ERROR_ACCESS_DENIED) - - await expect(replaceFileWin32('from', 'to')).rejects.toMatchObject({ - code: 'EACCES', - win32Code: ERROR_ACCESS_DENIED, - path: 'from', - dest: 'to', - }) - }) - it('maps Win32 publish failures to Node-style errno codes', async () => { const cases = [ [ERROR_FILE_NOT_FOUND, 'ENOENT'], diff --git a/packages/session/session-persistence-jsonl/tests/zstd.spec.ts b/packages/session/session-persistence-jsonl/tests/zstd.spec.ts index b01ed44a3f..27ab56540a 100644 --- a/packages/session/session-persistence-jsonl/tests/zstd.spec.ts +++ b/packages/session/session-persistence-jsonl/tests/zstd.spec.ts @@ -332,27 +332,6 @@ describe('Zstandard frame structure', () => { }) describe('JsonlSessionPersistence: default Zstandard encoding', () => { - it('atomically replaces a stored revision with compressed header and event frames', async () => { - const root = await freshRoot() - const ctx = await mount(root) - const header = meta('replace-zstd', '/work') - await ctx.sessionPersistence.create(header) - await ctx.sessionPersistence.append(header.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(header.id) - if (source === undefined) throw new Error('test session must be materialized') - const replacement = oneTurnLog().slice(0, 2) - - await persistence.replaceStored(source.revision, header, (async function* () { - yield* replacement - })()) - - const buffer = await readFile(logPath(root, header.cwd, header.id, 'zstd')) - expect(scanZstdFrames(buffer).frames).toHaveLength(2) - const plaintext = (await decodeCompleteFrames(buffer)).toString() - expect(scanLog(Buffer.from(plaintext)).events).toEqual(replacement) - }) - it('materializes an explicitly durable empty session as one header frame', async () => { const root = await freshRoot() const ctx = await mount(root) @@ -408,8 +387,7 @@ describe('JsonlSessionPersistence: default Zstandard encoding', () => { '', ].join('\n')) const scanned = scanLog(Buffer.from(raw!.content)) - expect(scanned.events.map(event => (event as SessionEvent).type)) - .toEqual(oneTurnLog().map(event => event.type)) + expect(scanned.events.map(event => event.type)).toEqual(oneTurnLog().map(event => event.type)) }) it('readRaw rejects a present zstd artifact that carries no frame', async () => { @@ -422,32 +400,6 @@ describe('JsonlSessionPersistence: default Zstandard encoding', () => { await writeFile(logPath(root, '/work', header.id, 'zstd'), Buffer.alloc(0)) await expect(ctx.sessionPersistence.readRaw(header.id)) .rejects.toThrow('empty or header-less Zstandard session log') - await expect(ctx.sessionPersistence.load(header.id)) - .rejects.toThrow('empty or header-less Zstandard session log') - }) - - it('rejects a zero-frame artifact through an already-open stored reader', async () => { - const root = await freshRoot() - const ctx = await mount(root) - const header = meta('stored-zero-frame', '/work') - await ctx.sessionPersistence.create(header) - await ctx.sessionPersistence.append(header.id, oneTurnLog()) - const persistence = ctx.sessionPersistence as JsonlSessionPersistence - const source = await persistence.openStored(header.id) - if (source === undefined) throw new Error('test session must be materialized') - await writeFile(logPath(root, '/work', header.id, 'zstd'), Buffer.alloc(0)) - - const read = source.readEvents() - const completion = read.completed.catch((error: unknown) => error) - const consumption = (async (): Promise => { - for await (const _event of read.events) { - // A zero-frame artifact cannot yield a logical event. - } - })().catch((error: unknown) => error) - const [streamFailure, completionFailure] = await Promise.all([consumption, completion]) - - expect(streamFailure).toBe(completionFailure) - expect(streamFailure).toMatchObject({ message: 'empty or header-less Zstandard session log' }) }) it('resolves the default when a programmatic wrapper bypasses Loader schema normalization', async () => { @@ -790,7 +742,7 @@ describe('JsonlSessionPersistence: encoding selection', () => { '', ].join('\n')) await expect(ctx.sessionPersistence.load(loadHeader.id)).rejects.toThrow(/uses \.jsonl/) - await expect((ctx.sessionPersistence as JsonlSessionPersistence).openStored(loadHeader.id)) + await expect((ctx.sessionPersistence as JsonlSessionPersistence).loadStored(loadHeader.id)) .rejects.toThrow(/uses \.jsonl/) await expect(ctx.sessionPersistence.list()).rejects.toThrow(/uses \.jsonl/) }) diff --git a/packages/session/session-persistence-sqlite/src/store.ts b/packages/session/session-persistence-sqlite/src/store.ts index 4cbd788adc..c28a9e2fa7 100644 --- a/packages/session/session-persistence-sqlite/src/store.ts +++ b/packages/session/session-persistence-sqlite/src/store.ts @@ -10,21 +10,17 @@ import { lstat, mkdir, open } from 'node:fs/promises' import { dirname, resolve } from 'node:path' import type { DatabaseSync, StatementSync } from 'node:sqlite' import { - SessionId, type SessionEvent, type SessionHeader, + type SessionId, } from '@deepseek-ai/dsh-session' import { - createStoredEventRead, - decodeStoredSessionHeader, SessionPersistenceRevision, - SessionPersistenceRevisionConflictError, type PersistenceBackend, type SessionPersistenceRevision as PersistenceRevision, type SessionPersistenceSnapshot, - type StoredEventRead, - type StoredEventReadOptions, - type StoredSessionSource, + type StoredPrefix, + type StoredSuffix, } from '@deepseek-ai/dsh-session-persistence' import { MAX_PACKED_ROW_MEMBERS, @@ -56,21 +52,6 @@ export interface SqliteStoreOptions { readonly busyTimeoutMs: number } -/** A stored session's header, valid event prefix, and revision at one snapshot. */ -interface SqliteStoredPrefix { - readonly meta: SessionHeader - readonly events: SessionEvent[] - readonly revision: PersistenceRevision - readonly tornMarker?: number -} - -/** A stored session's suffix (events at or past a seq) and its snapshot revision. */ -interface SqliteStoredSuffix { - readonly meta: SessionHeader - readonly events: SessionEvent[] - readonly revision: PersistenceRevision -} - /** SQLite implementation of the coordinator's physical backend hooks. */ export class SqliteStore implements PersistenceBackend { readonly name = 'session-persistence-sqlite' @@ -150,13 +131,7 @@ export class SqliteStore implements PersistenceBackend { } } - /** - * Load one row's complete validated prefix at a single snapshot. - * @param id - persisted session id to resolve. - * @param signal - optional cancellation for backend read work. - * @returns the stored prefix, or `undefined` when the session has no stored row. - */ - async loadStored(id: SessionId, signal?: AbortSignal): Promise { + async loadStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { await this.observe(signal) const snapshot = this.readTransaction(() => { const row = this.rowFor(id) @@ -182,14 +157,7 @@ export class SqliteStore implements PersistenceBackend { return row === undefined ? undefined : sqliteRevision(this.storeIdentity, row) } - /** - * Load one row's physical suffix at or past a sequence at a single snapshot. - * @param id - persisted session id to resolve. - * @param fromSeq - first physical event sequence to include. - * @param signal - optional cancellation for backend read work. - * @returns the stored suffix, or `undefined` when the session has no stored row. - */ - async loadStoredFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise { + async loadStoredFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise { await this.observe(signal) const snapshot = this.readTransaction(() => { const row = this.rowFor(id) @@ -199,48 +167,7 @@ export class SqliteStore implements PersistenceBackend { signal?.throwIfAborted() if (snapshot === undefined) return undefined const { preserved } = scanRows(snapshot.eventRows, snapshot.base) - return { - meta: rowToMeta(snapshot.row), - events: preserved.filter(event => event.seq >= fromSeq), - revision: sqliteRevision(this.storeIdentity, snapshot.row), - } - } - - /** - * Open repeatable reads over one row revision. Each event reader reproduces - * this revision or rejects when a concurrent writer changed the row. - * @param id - persisted session id to resolve. - * @param signal - optional cancellation for backend read work. - * @returns the source, or `undefined` when the session has no stored row. - */ - async openStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { - await this.observe(signal) - const row = this.rowFor(id) - signal?.throwIfAborted() - if (row === undefined) return undefined - const revision = sqliteRevision(this.storeIdentity, row) - return { - meta: rowToMeta(row), - revision, - readEvents: (options: StoredEventReadOptions = {}): StoredEventRead => { - const fromSeq = options.fromSeq ?? 0 - return createStoredEventRead( - async () => { - const stored = fromSeq === 0 - ? await this.loadStored(id, signal) - : await this.loadStoredFrom(id, fromSeq, signal) - if (stored === undefined || stored.revision !== revision) { - throw new SessionPersistenceRevisionConflictError( - `session "${id}" changed while reading revision ${revision}`, - ) - } - return stored - }, - () => true, - signal, - ) - }, - } + return { meta: rowToMeta(snapshot.row), events: preserved.filter(event => event.seq >= fromSeq) } } async appendBatch( @@ -324,64 +251,11 @@ export class SqliteStore implements PersistenceBackend { } } - /** - * Atomically replace one exact stored revision with a complete current log. - * The streamed events are staged in memory, then the swap commits in one - * transaction that rechecks the revision and storage identity. - * @param expectedRevision - exact source revision decoded by the caller. - * @param meta - complete current-format header. - * @param events - complete current-format event stream. - */ - async replaceStored( - expectedRevision: PersistenceRevision, - meta: SessionHeader, - events: AsyncIterable, - ): Promise { - await this.open() - const observed = this.rowFor(meta.id) - if (observed === undefined - || sqliteRevision(this.storeIdentity, observed) !== expectedRevision) { - throw new SessionPersistenceRevisionConflictError( - `session "${meta.id}" changed before replacement of revision ${expectedRevision}`, - ) - } - if (meta.cwd !== (observed.cwd ?? undefined)) { - throw new Error(`replacement for session "${meta.id}" changes its stored identity`) - } - // Stage the complete replacement before the swap transaction so a failed - // or cancelled stream leaves the stored log untouched. - const staged: SessionEvent[] = [] - for await (const event of events) staged.push(event) - const records = packChunkRuns(staged) - this.db.exec(sql('begin-immediate')) - try { - validateSchemaForMutation(this.databaseConstructor, this.db, this.databasePath) - const row = this.rowFor(meta.id) - if (row === undefined - || sqliteRevision(this.storeIdentity, row) !== expectedRevision) { - throw new SessionPersistenceRevisionConflictError( - `session "${meta.id}" changed before replacement of revision ${expectedRevision}`, - ) - } - if (meta.cwd !== (row.cwd ?? undefined)) { - throw new Error(`replacement for session "${meta.id}" changes its stored identity`) - } - this.db.prepare(sql('delete-events-from')).run(meta.id, 0) - const insert = this.insertStatement() - for (const record of records) this.insertRecord(insert, meta.id, bindRecord(record)) - this.writeRow(meta) - this.incrementRevision(meta.id) - this.db.exec(sql('commit')) - } catch (error: unknown) { - this.rollback(error, 'replacement') - } - } - async list(signal?: AbortSignal): Promise { await this.observe(signal) const rows = this.sessionRows() signal?.throwIfAborted() - return rows.map(row => decodeStoredSessionHeader(rowToMeta(row), SessionId(row.id))) + return rows.map(rowToMeta) } /** @@ -394,7 +268,7 @@ export class SqliteStore implements PersistenceBackend { const rows = this.sessionRows() signal?.throwIfAborted() return rows.map(row => ({ - header: decodeStoredSessionHeader(rowToMeta(row), SessionId(row.id)), + header: rowToMeta(row), revision: sqliteRevision(this.storeIdentity, row), })) } diff --git a/packages/session/session-persistence-sqlite/tests/resources/sql/count-session-events.sql b/packages/session/session-persistence-sqlite/tests/resources/sql/count-session-events.sql deleted file mode 100644 index da02575e16..0000000000 --- a/packages/session/session-persistence-sqlite/tests/resources/sql/count-session-events.sql +++ /dev/null @@ -1,3 +0,0 @@ -SELECT COUNT(*) AS n -FROM events -WHERE session_id = ?; diff --git a/packages/session/session-persistence-sqlite/tests/resources/sql/create-temp-replace-trigger.sql b/packages/session/session-persistence-sqlite/tests/resources/sql/create-temp-replace-trigger.sql deleted file mode 100644 index 1fbf6ae0c7..0000000000 --- a/packages/session/session-persistence-sqlite/tests/resources/sql/create-temp-replace-trigger.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TEMP TRIGGER fail_format_replace -BEFORE UPDATE ON sessions -BEGIN - SELECT RAISE(ABORT, 'simulated format replacement failure'); -END diff --git a/packages/session/session-persistence-sqlite/tests/resources/sql/delete-session-by-id.sql b/packages/session/session-persistence-sqlite/tests/resources/sql/delete-session-by-id.sql deleted file mode 100644 index afe9d6c0ec..0000000000 --- a/packages/session/session-persistence-sqlite/tests/resources/sql/delete-session-by-id.sql +++ /dev/null @@ -1,2 +0,0 @@ -DELETE FROM sessions -WHERE id = ?; diff --git a/packages/session/session-persistence-sqlite/tests/resources/sql/drop-temp-replace-trigger.sql b/packages/session/session-persistence-sqlite/tests/resources/sql/drop-temp-replace-trigger.sql deleted file mode 100644 index b41f647451..0000000000 --- a/packages/session/session-persistence-sqlite/tests/resources/sql/drop-temp-replace-trigger.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TRIGGER fail_format_replace; diff --git a/packages/session/session-persistence-sqlite/tests/resources/sql/update-session-cwd.sql b/packages/session/session-persistence-sqlite/tests/resources/sql/update-session-cwd.sql deleted file mode 100644 index 7586325b16..0000000000 --- a/packages/session/session-persistence-sqlite/tests/resources/sql/update-session-cwd.sql +++ /dev/null @@ -1,3 +0,0 @@ -UPDATE sessions -SET cwd = ? -WHERE id = ?; diff --git a/packages/session/session-persistence-sqlite/tests/resources/sql/update-session-revision.sql b/packages/session/session-persistence-sqlite/tests/resources/sql/update-session-revision.sql deleted file mode 100644 index 2cfbcb2b82..0000000000 --- a/packages/session/session-persistence-sqlite/tests/resources/sql/update-session-revision.sql +++ /dev/null @@ -1,3 +0,0 @@ -UPDATE sessions -SET revision = revision + 1 -WHERE id = ?; diff --git a/packages/session/session-persistence-sqlite/tests/sqlite.spec.ts b/packages/session/session-persistence-sqlite/tests/sqlite.spec.ts index 93e07ff6e5..01dace269c 100644 --- a/packages/session/session-persistence-sqlite/tests/sqlite.spec.ts +++ b/packages/session/session-persistence-sqlite/tests/sqlite.spec.ts @@ -15,14 +15,12 @@ import SessionPersistenceSqlite, { DEFAULT_BUSY_TIMEOUT_MS, SCHEMA_VERSION, } from '@deepseek-ai/dsh-session-persistence-sqlite' -import { SessionPersistenceRevisionConflictError } from '@deepseek-ai/dsh-session-persistence' import { runCoordinatorContract, type CoordinatorFixture, } from '../../session-persistence/tests/coordinator-contract.ts' import { meta, - oneTurnLog, runPersistenceContract, } from '../../session-persistence/tests/contract.ts' import { MAX_PACKED_DATA_BYTES } from '../src/codec.ts' @@ -201,11 +199,6 @@ async function measureWriteTraffic( } } -/** Yield immutable event copies as one replacement stream. */ -async function* replacementEvents(events: readonly SessionEvent[]): AsyncIterable { - for (const event of events) yield structuredClone(event) -} - runPersistenceContract('sqlite', async () => { const ctx = new Context() await ctx.plugin(SessionStore) @@ -861,157 +854,3 @@ describe('SessionPersistenceSqlite edge behavior', () => { await store.close() }) }) - -describe('SessionPersistenceSqlite stored-source and replacement primitives', () => { - it('binds a stored source to the same revision as a lightweight read', async () => { - const path = await freshDbPath() - const store = new SqliteStore({ path, journalMode: 'wal', busyTimeoutMs: DEFAULT_BUSY_TIMEOUT_MS }) - const m = meta('stored-prefix-revision') - await store.appendBatch(m, oneTurnLog(), false) - - const stored = await store.openStored(m.id) - expect(stored?.revision).toBe(await store.readStoredRevision(m.id)) - expect(await store.readStoredRevision(SessionId('missing-revision'))).toBeUndefined() - await store.close() - }) - - it('rejects revision-bound full and suffix readers after the row changes or disappears', async () => { - const path = await freshDbPath() - const store = new SqliteStore({ path, journalMode: 'wal', busyTimeoutMs: DEFAULT_BUSY_TIMEOUT_MS }) - const m = meta('stored-reader-conflict') - await store.appendBatch(m, oneTurnLog(), false) - const changed = await store.openStored(m.id) - if (changed === undefined) throw new Error('test session must be materialized') - await store.appendBatch(m, [ - { type: 'turn/start', seq: oneTurnLog().length, time: 7, data: { turn: 2 } }, - ], true) - const changedRead = changed.readEvents() - const changedCompletion = changedRead.completed.catch((error: unknown) => error) - await expect((async () => { for await (const _event of changedRead.events) { /* consume */ } })()) - .rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - await expect(changedCompletion).resolves.toBeInstanceOf(SessionPersistenceRevisionConflictError) - - const removed = await store.openStored(m.id) - if (removed === undefined) throw new Error('test session must remain materialized') - const db = (store as unknown as { db: DatabaseSync }).db - db.prepare(testSql('delete-session-by-id')).run(m.id) - const removedRead = removed.readEvents({ fromSeq: 1 }) - const removedCompletion = removedRead.completed.catch((error: unknown) => error) - await expect((async () => { for await (const _event of removedRead.events) { /* consume */ } })()) - .rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - await expect(removedCompletion).resolves.toBeInstanceOf(SessionPersistenceRevisionConflictError) - await store.close() - }) - - it('rolls back a suffix snapshot when its SQL read fails and reports absent direct snapshots', async () => { - const path = await freshDbPath() - const store = new SqliteStore({ path, journalMode: 'wal', busyTimeoutMs: DEFAULT_BUSY_TIMEOUT_MS }) - expect(await store.loadStored(SessionId('missing-prefix'))).toBeUndefined() - expect(await store.loadStoredFrom(SessionId('missing-suffix'), 1)).toBeUndefined() - - const m = meta('suffix-rollback') - await store.appendBatch(m, oneTurnLog(), false) - const db = (store as unknown as { db: DatabaseSync }).db - const prepare = db.prepare.bind(db) - const spy = vi.spyOn(db, 'prepare').mockImplementation((source) => { - if (source.includes('seq >= ?')) throw new Error('simulated suffix SELECT failure') - return prepare(source) - }) - await expect(store.loadStoredFrom(m.id, 1)).rejects.toThrow('simulated suffix SELECT failure') - spy.mockRestore() - expect((db.prepare(testSql('count-session-events')).get(m.id) as { n: number }).n) - .toBe(oneTurnLog().length) - await store.close() - }) - - it('atomically replaces one exact revision and rejects a stale replacement', async () => { - const path = await freshDbPath() - const store = new SqliteStore({ path, journalMode: 'wal', busyTimeoutMs: DEFAULT_BUSY_TIMEOUT_MS }) - const m = meta('format-replace') - const original = [ - ...oneTurnLog(), - { type: 'turn/start', seq: oneTurnLog().length, time: 7, data: { turn: 2 } }, - { type: 'turn/end', seq: oneTurnLog().length + 1, time: 8, data: { turn: 2, reason: { kind: 'completed' } } }, - ] as SessionEvent[] - await store.appendBatch(m, original, false) - const source = await store.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - - await store.replaceStored(source.revision, m, replacementEvents(oneTurnLog())) - const replaced = await store.openStored(m.id) - if (replaced === undefined) throw new Error('replacement must preserve the session') - expect(replaced.revision).not.toBe(source.revision) - expect((await store.loadStored(m.id))?.events).toEqual(oneTurnLog()) - - await expect( - store.replaceStored(source.revision, m, replacementEvents(original)), - ).rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - expect((await store.loadStored(m.id))?.events).toEqual(oneTurnLog()) - await store.close() - }) - - it('rejects replacement identity changes before and during the transaction', async () => { - const path = await freshDbPath() - const store = new SqliteStore({ path, journalMode: 'wal', busyTimeoutMs: DEFAULT_BUSY_TIMEOUT_MS }) - const m = meta('format-replace-identity', '/work') - await store.appendBatch(m, oneTurnLog(), false) - const source = await store.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - - await expect(store.replaceStored( - source.revision, - { ...m, cwd: '/other' }, - replacementEvents(oneTurnLog()), - )).rejects.toThrow(/changes its stored identity/) - - const db = (store as unknown as { db: DatabaseSync }).db - const changesDuringStaging = (async function* (): AsyncIterable { - yield* oneTurnLog() - db.prepare(testSql('update-session-cwd')).run('/raced', m.id) - })() - await expect(store.replaceStored(source.revision, m, changesDuringStaging)) - .rejects.toThrow(/changes its stored identity/) - expect((db.prepare(testSql('count-session-events')).get(m.id) as { n: number }).n) - .toBe(oneTurnLog().length) - await store.close() - }) - - it('rejects a revision change that occurs while replacement events are staged', async () => { - const path = await freshDbPath() - const store = new SqliteStore({ path, journalMode: 'wal', busyTimeoutMs: DEFAULT_BUSY_TIMEOUT_MS }) - const m = meta('format-replace-staging-race', '/work') - await store.appendBatch(m, oneTurnLog(), false) - const source = await store.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - const db = (store as unknown as { db: DatabaseSync }).db - const changesDuringStaging = (async function* (): AsyncIterable { - yield* oneTurnLog() - db.prepare(testSql('update-session-revision')).run(m.id) - })() - - await expect(store.replaceStored(source.revision, m, changesDuringStaging)) - .rejects.toBeInstanceOf(SessionPersistenceRevisionConflictError) - expect((db.prepare(testSql('count-session-events')).get(m.id) as { n: number }).n) - .toBe(oneTurnLog().length) - await store.close() - }) - - it('rolls back the complete replacement when the transaction fails after it begins', async () => { - const path = await freshDbPath() - const store = new SqliteStore({ path, journalMode: 'wal', busyTimeoutMs: DEFAULT_BUSY_TIMEOUT_MS }) - const m = meta('format-replace-rollback') - await store.appendBatch(m, oneTurnLog(), false) - const source = await store.openStored(m.id) - if (source === undefined) throw new Error('test session must be materialized') - const db = (store as unknown as { db: DatabaseSync }).db - db.exec(testSql('create-temp-replace-trigger')) - - await expect( - store.replaceStored(source.revision, m, replacementEvents([])), - ).rejects.toThrow(/simulated format replacement failure/) - db.exec(testSql('drop-temp-replace-trigger')) - - expect((await store.loadStored(m.id))?.events).toEqual(oneTurnLog()) - await store.close() - }) -}) diff --git a/packages/session/session-persistence-sqlite/tests/test-sql.ts b/packages/session/session-persistence-sqlite/tests/test-sql.ts index beb11d6f65..77b53a404e 100644 --- a/packages/session/session-persistence-sqlite/tests/test-sql.ts +++ b/packages/session/session-persistence-sqlite/tests/test-sql.ts @@ -8,14 +8,10 @@ export type TestSqlName = | 'count-ignorable-events' | 'count-packed-events' | 'count-physical-types' - | 'count-session-events' | 'create-loose-schema' - | 'create-temp-replace-trigger' | 'create-unrelated-table' | 'delete-persistence-state' - | 'delete-session-by-id' | 'delete-session-events' - | 'drop-temp-replace-trigger' | 'empty-store-id' | 'insert-corrupt-event' | 'measure-write-traffic' @@ -29,8 +25,6 @@ export type TestSqlName = | 'set-user-version-16' | 'set-user-version-17' | 'update-invalid-session-metadata' - | 'update-session-cwd' - | 'update-session-revision' /** Load one fixed test SQL resource. */ export function testSql(name: TestSqlName): string { diff --git a/packages/session/session-persistence/README.i18n.yaml b/packages/session/session-persistence/README.i18n.yaml index 1605bdbee5..9a9b20071e 100644 --- a/packages/session/session-persistence/README.i18n.yaml +++ b/packages/session/session-persistence/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/session/session-persistence/README.md -README.md: 323d7b23cff6438264ae4aa4a3fecbd06a832037 -README.zh.md: bb667f6989f1a0df9d258d223f0f6721a233433a +README.md: 76df109936070e0dd7afb18e98c6c94855be4f21 +README.zh.md: 6c366bf8287e4c96052935e46410fd27d28714f5 diff --git a/packages/session/session-persistence/README.md b/packages/session/session-persistence/README.md index 323d7b23cf..76df109936 100644 --- a/packages/session/session-persistence/README.md +++ b/packages/session/session-persistence/README.md @@ -17,9 +17,9 @@ The persisted unit IS the existing `SessionEvent` (event-sourced model — the l | `ensureMaterialized(session): Promise` | Explicitly make an exact live session durable even with zero events, without inventing an event. Lifecycle frontends use this only when the empty session itself is a resumable resource; ordinary creation remains lazy. | | `append(id, events): Promise` | Durably persist a batch. Append-only; first event `seq` == stored next-seq after any repair; rejects non-JSON-serializable data naming the offending type. | | `prepare(id, signal?): Promise` | Reserve the exact unpublished Session used by resume. A coordinator reuses an earlier inspection when available, commits pending recovery, and releases an unpublished reservation back to its bounded cache on disposal. | -| `load(id): Promise<{ meta; events }>` | Return an immutable balanced logical log after decoding a supported format path and committing any format replacement plus cold recovery. A live load first flushes its snapshot and rejects while its turn is open; a cold load preserves an interrupted final turn and durably closes it with synthetic `tool/result`/`step/end?`/`turn/end {interrupted}` events. Only a torn tail fragment is dropped; committed corruption and malformed records reject as `SessionPersistenceCorruptionError`, while an unsupported format `version` or an event type unknown to this build (without the envelope's `ignorable` marker) refuses as `SessionFormatUnsupportedError`, naming the refusal direction and the raw log path when the backend keeps one artifact per session. | +| `load(id): Promise<{ meta; events }>` | Return an immutable balanced logical log after converting supported older records from the same format version and committing cold recovery. A live load first flushes its snapshot and rejects while its turn is open; a cold load preserves an interrupted final turn and durably closes it with synthetic `tool/result`/`step/end?`/`turn/end {interrupted}` events. Only a torn tail fragment is dropped; committed corruption and malformed records reject as `SessionPersistenceCorruptionError`, while an unsupported format `version` or an event type unknown to this build (without the envelope's `ignorable` marker) refuses as `SessionFormatUnsupportedError`, naming the refusal direction and the raw log path when the backend keeps one artifact per session. | | `inspect(id, signal?): Promise<{ meta; events }>` | Return an upgraded, validated, deeply frozen logical view without committing recovery or publishing a Session. A cold view receives in-memory synthetic recovery closers while its physical torn tail remains untouched; an already-live view is its current immutable snapshot and may contain an open turn. Coordinator-backed implementations retain the exact cold unpublished Session in a bounded LRU for later `prepare`, but discard and reload it when the stored revision changes. Same-id inspections share an in-flight read. | -| `readFrom(id, fromSeq, signal?): Promise<{ meta; events }>` | Return valid stored events with `seq >= fromSeq` without preparation caching, truncation, closers, or coordinator state. A `fromSeq` at or past the stored end returns an empty event list; a negative or non-safe-integer `fromSeq` rejects. Current-format reads request a suffix from the backend; a format migration requires the complete source and applies `fromSeq` only after migration. Sequential media may still scan framing before filtering, while seek-capable media can avoid reading earlier rows. Intended for checkpoint consumers that apply only events after a stored sequence number. | +| `readFrom(id, fromSeq, signal?): Promise<{ meta; events }>` | Return valid stored events with `seq >= fromSeq` without preparation caching, truncation, closers, or coordinator state. A `fromSeq` at or past the stored end returns an empty event list; a negative or non-safe-integer `fromSeq` rejects. Seek-capable backends (SQLite) read only the suffix unless converting a supported older record requires earlier records; sequential backends (JSONL) parse the whole artifact and skip forward. Unknown-type refusal follows that access pattern: a seek read checks only the returned suffix, while the sequential fallback also refuses on an unknown required event below the window. Intended for checkpoint consumers that apply only events after a stored sequence number. | | `list(signal?): Promise` | Lightweight listing from metadata, no full-log parse. The optional signal cancels backend listing work. A zero-event session is absent until a consumer explicitly materializes it. | | `listSnapshots(signal?): Promise` | Lightweight metadata plus an opaque branded per-log revision, without loading event logs. A revision stays equal while that log and its backing store are unchanged, changes after append or mutating load repair, and cannot collide solely because two stores use the same local counter. The optional signal requests cancellation of backend discovery work; first-party backends settle any started listing work before rejecting so an awaited call is quiescent. | @@ -36,15 +36,9 @@ The persisted unit IS the existing `SessionEvent` (event-sourced model — the l Each `session/event` copies its event into the session controller. The first pending event starts a fixed batching window; later events join without resetting its deadline. The configured `writeBatchMaxDelayMs` bounds this intentional wait, not event-loop, initialization, serialized-operation, or backend latency. Events admitted during a write form a new bounded batch. `session/flush` cancels the wait and is a shared quiescence barrier that drains events admitted while it runs. A background failure is logged once, retains the ordered batch, and pauses automatic retry; a new event starts a fresh window, while explicit flush or backend teardown retries immediately and surfaces a repeated failure. -Crash repair is cold-only. For a live id, `load(id)` snapshots the authoritative in-memory log, waits for that snapshot to become durable, and returns it only when balanced; an open live turn rejects instead of receiving synthetic interruption closers. For a cold id, inspection reads, validates, freezes, and constructs one unpublished Session; repeated inspection reuses that object graph only while its source revision remains current. `prepare(id)` performs the same check before repair, reserves the exact Session, commits any pending torn-tail/interrupted-turn repair, and returns it for publication. HMR adoption opens the same revision-bound source, applies the coordinator's cwd check, and never closes the active turn. +Crash repair is cold-only. For a live id, `load(id)` snapshots the authoritative in-memory log, waits for that snapshot to become durable, and returns it only when balanced; an open live turn rejects instead of receiving synthetic interruption closers. For a cold id, inspection reads, validates, freezes, and constructs one unpublished Session; repeated inspection reuses that object graph only while its source revision remains current. `prepare(id)` performs the same check before repair, reserves the exact Session, commits any pending torn-tail/interrupted-turn repair, and returns it for publication. HMR adoption reads through `loadStored`, applies the coordinator's cwd check, and never closes the active turn. -## Format decoding and upgrades - -Every logical read opens a repeatable `StoredSessionSource` containing an untrusted header, an exact revision, and a `readEvents()` factory. The static decoder chooses a complete adjacent-version path, creates one migration instance per version, calls `header()` once, calls `event()` once per input record, and calls optional `finish()` after EOF. It then validates the final header and events as the current format. `inspect()` and `readFrom()` do not write. Cold continuation and live adoption replace a converted source through the backend's revision compare-and-swap, then reopen it; a concurrent change discards the decoded result and restarts from the new source. The [session-log versioning Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.md) owns the rationale and refusal rules. - -A future vN→vN+1 change adds `src/format-migrations/vN-to-vN+1.ts`, exports its class from the static `SESSION_FORMAT_MIGRATIONS` array, and increments `SESSION_FORMAT_VERSION`. Static `from`/`to` identify adjacent versions; instance fields retain header and cross-event state. `header()` validates and converts the old header, `event()` returns exactly one lossless-JSON event with the input event's seq, and optional `finish()` validates state that can be settled only at EOF. Header-only reads do not call `finish()`. A migration that changes facts consumed by a projection also increments that projection's `stateVersion`; persistence does not invalidate every projection cache entry. Backends and the coordinator remain version-independent. - -The v0 decoder also recognizes the bounded pre-versioning variants recorded by the [pre-identity message](../../../.agents/notes/implemented/bug-fix/2026-07-28-load-pre-identity-session-messages.md) and [pre-react-loop session](../../../.agents/notes/implemented/bug-fix/2026-08-04-load-pre-react-loop-sessions.md) decisions, and normalizes the historical `compact/start`, `compact/summary`, `compact/end`, and `compact/prune` names to their canonical `compaction/*` names. These compatibility transforms are not format migrations. +Backend reads convert the exact supported older records from the same format version before validating current records. Pre-identity messages receive the deterministic id `legacy-message::`; a tool-result content replacement inherits its target's imported id. A pre-react-loop `turn/start` loses its obsolete trigger, a removed `steering/message` becomes the same identified `user/message`, and an older `turn/end` maps its terminal reason without inventing a caller that the old record did not name. The coordinator uses the same converted view for `load`, `inspect`, `readFrom`, ownerless-state claims, and HMR prefix adoption. Storage remains append-only: reads do not rewrite old records, and later appends use the current format. These are narrow import exceptions from the [pre-identity message](../../../.agents/notes/implemented/bug-fix/2026-07-28-load-pre-identity-session-messages.md) and [pre-react-loop session](../../../.agents/notes/implemented/bug-fix/2026-08-04-load-pre-react-loop-sessions.md) decisions, not a general v0 migration promise. When a live session emits `session/disposed`, the coordinator waits for its controller, serializes a final drain, then releases state owned by that exact `Session` object. Failed retirement leaves the controller in the live-session map, so backend teardown can retry it. Backend teardown stops event admission first, flushes every remaining controller, awaits per-id operations, and only then closes the storage handle. @@ -55,12 +49,12 @@ The `PersistenceBackend` hooks (the only contract between the coordi | Hook | Role | |---|---| | `name` | Backend label for the dispose-failure `AggregateError`. | -| `openStored(id, signal?)` | Open an untrusted header plus repeatable event readers bound to one exact source revision. Each `readEvents({ fromSeq? })` reproduces that revision and exposes backend-owned torn-tail metadata only after EOF, or rejects with `SessionPersistenceRevisionConflictError` when the source changed. | -| `readStoredRevision(id, signal?)` | Read the current source-qualified revision for one id without loading its event log. It uses the same revision representation as `openStored` and returns `undefined` when the id is absent. | +| `loadStored(id, signal?)` | Read a stored prefix by id across every storage scope. Used by resume/load, non-mutating inspect, live adoption, and the create-collision probe. The optional signal belongs to observation-only reads. Returned metadata identifies `id`; `revision` identifies exactly the returned header and events; an opaque `tornMarker` is present iff a torn tail must be truncated. | +| `readStoredRevision(id, signal?)` | Read the current source-qualified revision for one id without loading its event log. It uses the same revision representation as `loadStored` and returns `undefined` when the id is absent. | +| `loadStoredFrom?(id, fromSeq, signal?)` | Optional seek-capable suffix read behind the service's `readFrom`: the header plus stored events with `seq >= fromSeq`, non-mutating, no torn marker. SQLite implements it (`WHERE seq >= ?`); a backend that omits it gets the coordinator's fallback — `loadStored` plus a forward skip. | | `appendBatch(meta, events, isMaterialized)` | Durably append a contiguous batch, lazily materializing ATOMICALLY when not yet materialized. | | `materializeHeader?(meta)` | Durably create a header-only artifact for `ensureMaterialized`; required by providers that support durable empty sessions. | | `commitRepair(meta, tornMarker, closers)` | Make a crash repair durable: truncate the torn tail (iff `tornMarker !== undefined` — a marker may be falsy, e.g. seq/offset `0`) and append `closers`. NOT required to be atomic. Used by load (truncate + closers) and live-adoption (truncate only). | -| `replaceStored(expectedRevision, meta, events)` | Atomically replace one exact revision with a complete current-format header and event stream. Revision and stored identity checks occur at the commit boundary — immediately before the atomic rename on JSONL, inside the replacing transaction on SQLite; the checks add no cross-process writer exclusion. A mismatch rejects with `SessionPersistenceRevisionConflictError`. | | `list(signal?)` | List all stored metadata, observing optional cancellation. | | `close?()` | Optional lifecycle teardown (e.g. close a db handle), awaited after the dispose drain. | diff --git a/packages/session/session-persistence/README.zh.md b/packages/session/session-persistence/README.zh.md index bb667f6989..6c366bf828 100644 --- a/packages/session/session-persistence/README.zh.md +++ b/packages/session/session-persistence/README.zh.md @@ -17,9 +17,9 @@ | `ensureMaterialized(session): Promise` | 在不虚构事件的情况下,显式使一个确切 live session 即使零事件也保持持久。只有当空会话本身是可恢复资源时,生命周期前端才使用它;普通创建仍保持延迟实体化。 | | `append(id, events): Promise` | 持久保存一个批次。仅追加;任何修复后,第一个事件 `seq` == 已存储 next-seq;非 JSON 可序列化数据会被拒绝,并命名违规类型。 | | `prepare(id, signal?): Promise` | 预留恢复所使用的那个未发布 Session。协调器会尽可能复用之前的检查结果、提交待处理恢复,并在 dispose(资源释放)时将未发布 reservation 释放回有界缓存。 | -| `load(id): Promise<{ meta; events }>` | 沿受支持的格式路径解码,并提交格式替换与冷恢复后,返回不可变、平衡的逻辑日志。实时 load 先 flush 其快照,并在轮次开放时拒绝;冷 load 保留中断的最终轮次,并用合成 `tool/result`/`step/end?`/`turn/end {interrupted}` 事件持久关闭它。只丢弃撕裂尾部碎片;已提交损坏和格式错误的记录以 `SessionPersistenceCorruptionError` 拒绝,不支持的格式 `version` 或本构建不认识且信封未带 `ignorable` 标记的事件类型以 `SessionFormatUnsupportedError` 拒绝,消息说明拒绝方向,并在后端为每个会话保留独立文件时给出原始日志路径。 | +| `load(id): Promise<{ meta; events }>` | 转换同一格式版本中受支持的旧记录后,返回不可变、平衡的逻辑日志,并提交冷恢复。实时 load 先 flush 其快照,并在轮次开放时拒绝;冷 load 保留中断的最终轮次,并用合成 `tool/result`/`step/end?`/`turn/end {interrupted}` 事件持久关闭它。只丢弃撕裂尾部碎片;已提交损坏和格式错误的记录以 `SessionPersistenceCorruptionError` 拒绝,不支持的格式 `version` 或本构建不认识且信封未带 `ignorable` 标记的事件类型以 `SessionFormatUnsupportedError` 拒绝,消息说明拒绝方向,并在后端为每个会话保留独立文件时给出原始日志路径。 | | `inspect(id, signal?): Promise<{ meta; events }>` | 返回已经升级、验证和深度冻结的逻辑视图,但不提交恢复或发布 Session。冷视图会获得仅存在于内存的合成恢复 closer,物理撕裂尾部保持不变;实时状态下的视图则是当前不可变快照,可能包含开放的轮次。基于协调器的实现会在有界 LRU 中保留该冷状态下未发布的 Session 本身,供后续 `prepare` 使用,但已存储修订值变化后会丢弃并重新读取。同 id 检查共享进行中的读取。 | -| `readFrom(id, fromSeq, signal?): Promise<{ meta; events }>` | 返回 `seq >= fromSeq` 的有效已存储事件,不进入 preparation 缓存、不截断、不合成 closer,也不发布协调器状态。`fromSeq` 达到或超过已存储末尾时返回空事件列表;负数或非安全整数 `fromSeq` 会被拒绝。当前格式读取向后端请求 suffix;存在格式迁移时则读取完整 source,迁移后才应用 `fromSeq`。顺序介质可能仍需扫描物理 framing 后再过滤,可寻址介质则可不读取更早的记录。供 checkpoint 消费方只应用已存序号之后的事件。 | +| `readFrom(id, fromSeq, signal?): Promise<{ meta; events }>` | 返回 `seq >= fromSeq` 的有效已存储事件,不进入 preparation 缓存、不截断、不合成 closer,也不发布协调器状态。`fromSeq` 达到或超过已存储末尾时返回空事件列表;负数或非安全整数 `fromSeq` 会被拒绝。可寻址后端(SQLite)只读后缀,除非转换受支持的旧记录需要读取更早的记录;顺序后端(JSONL)解析整个产物并向前跳过。未知类型拒绝遵循同一读取方式:寻址读取只检查返回的后缀,顺序回退路径还会拒绝窗口以下的未知必需事件。供 checkpoint 消费方只应用已存序号之后的事件。 | | `list(signal?): Promise` | 从元数据轻量列出,不解析完整日志。可选信号取消后端列表工作。零事件会话在 consumer 显式实体化前不在 `list` 中。 | | `listSnapshots(signal?): Promise` | 返回轻量元数据和每份日志一个不透明、带品牌类型的修订值,不加载事件日志。日志及其后端存储不变时,修订保持相等;append 或变更性 load 修复后会改变;不会仅因两个存储使用相同本地计数器而冲突。可选信号请求取消后端发现工作;第一方后端会先等待所有已启动的列出工作结束,再予以拒绝,因此调用返回拒绝时,相关工作已完全停稳。 | @@ -36,15 +36,9 @@ 每个 `session/event` 将事件复制到会话 controller。第一个待处理事件会开启固定批处理窗口;后续事件会加入该批次,但不会重置截止时间。配置的 `writeBatchMaxDelayMs` 只限制这段有意等待,而不限制事件循环、初始化、串行化操作或后端延迟。写入期间接纳的事件会形成一个新的有界批次。`session/flush` 会取消等待,并作为共享的完全停稳屏障,排空屏障运行期间接纳的事件。后台写入失败只记录一次日志,保留顺序不变的批次,并暂停自动重试;新事件会开启新的固定窗口,而显式 flush 或后端拆卸会立即重试,并在失败再次发生时向调用方暴露失败。 -崩溃修复只适用于冷状态。对于已有活动会话的 id,`load(id)` 为权威内存日志制作快照,等待该快照持久,并只在平衡时返回;活动会话中开放的轮次会被拒绝,而不会收到合成中断 closer。对于冷 id,检查只读取、验证、冻结并构造一次未发布 Session;只有来源修订值仍然是当前值时,重复检查才会复用该对象图。`prepare(id)` 在修复前执行相同校验,预留该 Session 本身,提交任何待处理的撕裂尾部或中断轮次修复,并将其返回用于发布。HMR(热模块替换)接管打开同一份绑定 revision 的 source,应用协调器 cwd 检查,并绝不关闭活动轮次。 +崩溃修复只适用于冷状态。对于已有活动会话的 id,`load(id)` 为权威内存日志制作快照,等待该快照持久,并只在平衡时返回;活动会话中开放的轮次会被拒绝,而不会收到合成中断 closer。对于冷 id,检查只读取、验证、冻结并构造一次未发布 Session;只有来源修订值仍然是当前值时,重复检查才会复用该对象图。`prepare(id)` 在修复前执行相同校验,预留该 Session 本身,提交任何待处理的撕裂尾部或中断轮次修复,并将其返回用于发布。HMR(热模块替换)接管通过 `loadStored` 读取,应用协调器 cwd 检查,并绝不关闭活动轮次。 -## 格式解码与升级 - -每次逻辑读取都会打开可重复使用的 `StoredSessionSource`,其中包含不可信 header、精确 revision 和 `readEvents()` factory。静态 decoder 选择完整的相邻版本路径,为每个版本创建一个 migration 实例,调用一次 `header()`,为每条输入记录调用一次 `event()`,并在 EOF 后调用可选的 `finish()`,最后按当前格式验证 header 与事件。`inspect()` 和 `readFrom()` 不写存储;冷 continuation 与实时接管通过后端的 revision compare-and-swap 替换已转换 source,然后重新打开。并发变更会丢弃解码结果,并从新 source 重新开始。[Session log 版本机制 Agent Note](../../../.agents/notes/implemented/architecture/2026-08-10-session-log-version-mechanism.zh.md)规定其原因和拒绝规则。 - -以后新增 vN→vN+1 时,在 `src/format-migrations/vN-to-vN+1.ts` 添加 class,从静态 `SESSION_FORMAT_MIGRATIONS` 数组导出,并递增 `SESSION_FORMAT_VERSION`。静态 `from`/`to` 标识相邻版本,实例字段保留 header 和跨事件状态。`header()` 验证并转换旧 header;`event()` 只返回一条可无损表示为 JSON 且 seq 与输入相同的事件;可选的 `finish()` 验证只能在 EOF 时结算的状态。只读 header 时不调用 `finish()`。如果 migration 改变了某个 projection 消费的事实,还要递增该 projection 的 `stateVersion`;persistence 不统一作废所有 projection cache 记录。后端和协调器不增加版本特判。 - -v0 decoder 还识别[消息标识机制引入前的消息](../../../.agents/notes/implemented/bug-fix/2026-07-28-load-pre-identity-session-messages.zh.md)与 [react-loop 引入前会话](../../../.agents/notes/implemented/bug-fix/2026-08-04-load-pre-react-loop-sessions.zh.md)决策所限定的版本机制建立前变体,并将历史 `compact/start`、`compact/summary`、`compact/end`、`compact/prune` 名称归一化为规范的 `compaction/*` 名称。这些兼容转换不是格式迁移。 +后端读取会在验证当前记录前,转换同一格式版本中明确受支持的旧记录。消息标识机制引入前的消息会获得确定性的 id `legacy-message::`;工具结果的内容替换会继承其目标导入后的 id。react-loop 引入前的 `turn/start` 会移除过时的 trigger,已移除的 steering(中途引导)事件 `steering/message` 会转换为同一条带标识的 `user/message`;旧版 `turn/end` 会映射终止原因,但不会虚构旧记录中没有记载的调用方。协调器对 `load`、`inspect`、`readFrom`、无所有者状态的认领和 HMR 前缀接管使用同一份转换后视图。存储仍然仅追加:读取不会重写旧记录,此后追加的事件使用当前格式。这些是[消息标识机制引入前的消息](../../../.agents/notes/implemented/bug-fix/2026-07-28-load-pre-identity-session-messages.zh.md)与 [react-loop 引入前会话](../../../.agents/notes/implemented/bug-fix/2026-08-04-load-pre-react-loop-sessions.zh.md)决策所规定的范围受限的导入例外,并不构成通用的 v0 迁移承诺。 活动会话发出 `session/disposed` 时,协调器等待其 controller,以串行方式执行最终 drain,然后释放该精确 `Session` 对象拥有的状态。失败退役会将 controller 保留在活动会话 map 中,使后端拆卸可重试。后端拆卸先停止事件接纳,flush 每个剩余 controller,等待每 id 操作,最后才关闭存储句柄。 @@ -55,12 +49,12 @@ v0 decoder 还识别[消息标识机制引入前的消息](../../../.agents/note | 钩子 | 职责 | |---|---| | `name` | dispose 失败 `AggregateError` 的后端标签。 | -| `openStored(id, signal?)` | 打开不可信 header 和绑定同一精确 source revision 的可重复事件 reader。每次 `readEvents({ fromSeq? })` 都重现该 revision,并只在 EOF 后暴露 backend 自有 torn-tail metadata;source 已变化时以 `SessionPersistenceRevisionConflictError` 拒绝。 | -| `readStoredRevision(id, signal?)` | 在不加载事件日志的情况下读取一个 id 当前的来源限定修订值。它使用与 `openStored` 相同的修订值表示;id 不存在时返回 `undefined`。 | +| `loadStored(id, signal?)` | 在全部存储范围中按 id 读取已存储前缀。用于恢复/加载、非修改式 inspect、活动会话接管和 create 冲突探测。可选信号属于仅观察读取。返回元数据标识 `id`;`revision` 精确标识返回的 header 和事件;当且仅当必须截断撕裂尾部时才存在不透明 `tornMarker`。 | +| `readStoredRevision(id, signal?)` | 在不加载事件日志的情况下读取一个 id 当前的来源限定修订值。它使用与 `loadStored` 相同的修订值表示;id 不存在时返回 `undefined`。 | +| `loadStoredFrom?(id, fromSeq, signal?)` | 服务 `readFrom` 背后的可选可寻址后缀读取:返回 header 和 `seq >= fromSeq` 的已存储事件,非修改式、无撕裂标记。SQLite 实现它(`WHERE seq >= ?`);不实现的后端使用协调器回退——`loadStored` 加向前跳过。 | | `appendBatch(meta, events, isMaterialized)` | 持久追加连续批次;尚未实体化时以原子方式延迟实体化。 | | `materializeHeader?(meta)` | 为 `ensureMaterialized` 持久创建仅含 header 的 artifact;支持持久空会话的 provider 必须实现。 | | `commitRepair(meta, tornMarker, closers)` | 使崩溃修复持久:截断撕裂尾部(当且仅当 `tornMarker !== undefined`;标记可为 falsy,例如 seq/offset `0`),并追加 `closers`。不要求原子性。由 load(截断 + closer)和活动会话接管(仅截断)使用。 | -| `replaceStored(expectedRevision, meta, events)` | 用完整的当前格式 header 与事件流原子替换一个精确 revision。Revision 与存储身份检查发生在提交边界——JSONL 在原子替换前立即检查,SQLite 在替换事务内检查;该检查不提供跨进程写者排他。不匹配时以 `SessionPersistenceRevisionConflictError` 拒绝。 | | `list(signal?)` | 列出全部已存储元数据,并遵循可选的取消信号。 | | `close?()` | 可选生命周期拆卸(例如关闭 db 句柄),在 dispose drain 后等待其完成。 | diff --git a/packages/session/session-persistence/src/coordinator.ts b/packages/session/session-persistence/src/coordinator.ts index 9f20d00214..37c9558137 100644 --- a/packages/session/session-persistence/src/coordinator.ts +++ b/packages/session/session-persistence/src/coordinator.ts @@ -9,24 +9,16 @@ import { Context } from '@deepseek-ai/cordis' import { adoptSessionEvent, interruptedTurnClosers, + KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION, SessionPreparation, snapshotJsonValue, + snapshotSessionEvent, } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' -import type { BorrowedSessionSource, SessionInspection } from './index.ts' -import { - decodeStoredSession, - SessionFormatUnsupportedError, -} from './format-decoder.ts' -import { assertNoRetiredSessionEvent } from './format-json.ts' -import type { - DecodedSession, - StoredSessionSource, -} from './format-decoder.ts' +import type { BorrowedSessionSource, SessionInspection, SessionLocation } from './index.ts' import { SessionPersistenceNotFoundError } from './errors.ts' -import { SessionPersistenceRevisionConflictError } from './revision.ts' import type { SessionPersistenceRevision } from './revision.ts' import { observeQueuedAbort, SessionPreparations } from './preparations.ts' import type { SessionPreparationReservation } from './preparations.ts' @@ -53,6 +45,42 @@ export class SessionPersistenceCorruptionError extends Error { } } +/** + * The stored log is intact but this runtime cannot faithfully interpret it: + * the header carries an unsupported format version, or an event's type is + * unknown to this build and the event is not marked ignorable. Distinct from + * {@link SessionPersistenceCorruptionError} — nothing is damaged; the raw log + * remains readable at {@link location} when the backend keeps one artifact + * per session. + */ +export class SessionFormatUnsupportedError extends Error { + /** + * @param message - stable reason the log cannot be interpreted, already + * including the raw-log path when one exists. + * @param location - the backend's artifact location, when one exists. + */ + constructor(message: string, readonly location?: SessionLocation) { + super(message) + this.name = 'SessionFormatUnsupportedError' + } +} + +/** + * Direction-aware refusal text for a stored session whose format version this + * build does not read. Shared by the coordinator's load-time check and by + * backends that must refuse BEFORE decoding version-dependent structure (a + * future format may not satisfy this build's structural checks at all, and the + * user must see "upgrade the harness", never "corrupt"). + * @param id - the stored session id, for message context. + * @param version - the stored format version. + * @returns the stable refusal text, without a raw-log path suffix. + */ +export function sessionFormatVersionRefusal(id: string, version: number): string { + return version > SESSION_FORMAT_VERSION + ? `session "${id}" uses log format v${version}, but this harness reads only v${SESSION_FORMAT_VERSION}: the log was written by a newer harness — upgrade the harness to open it` + : `session "${id}" uses log format v${version}, older than the supported v${SESSION_FORMAT_VERSION}, and this build ships no upgrade path for it` +} + /** Coordinator policy supplied by a concrete persistence backend. */ export interface PersistenceCoordinatorOptions { /** Maximum completed unpublished preparations retained for reuse. */ @@ -61,6 +89,32 @@ export interface PersistenceCoordinatorOptions { readonly writeBatchMaxDelayMs: number } +/** + * A stored session's header, valid contiguous event prefix, source-qualified + * revision, and optional opaque torn-tail marker. The revision identifies the + * exact detached prefix. The coordinator only checks marker presence and + * returns its value to {@link PersistenceBackend.commitRepair}; each backend + * owns the marker type. + */ +export interface StoredPrefix { + meta: SessionHeader + events: SessionEvent[] + /** Revision observed for exactly this detached prefix. */ + revision: SessionPersistenceRevision + tornMarker?: TornMarker +} + +/** + * A stored session's header plus the events at or past a requested seq — the + * return shape of the optional seek-capable + * {@link PersistenceBackend.loadStoredFrom} hook. Non-mutating reads carry no + * torn marker: there is nothing to repair. + */ +export interface StoredSuffix { + meta: SessionHeader + events: SessionEvent[] +} + /** * The storage contract between {@link PersistenceCoordinator} and a concrete * backend: the minimal set of durable primitives the orchestration calls. A @@ -68,21 +122,27 @@ export interface PersistenceCoordinatorOptions { * coordinator supplies everything else (buffering, serialization, cursors, * adoption, crash repair sequencing, dispose quiescence). * - * @typeParam TornMarker - the backend's opaque torn-tail repair token returned - * after a complete event read. The coordinator treats it as fully opaque. + * @typeParam TornMarker - the backend's opaque torn-tail repair token (see + * {@link StoredPrefix}). The coordinator treats it as fully opaque. */ export interface PersistenceBackend { /** Human-readable backend name, used in the dispose-failure AggregateError. */ readonly name: string /** - * Open repeatable access to one stored revision by id, scanning every backend - * storage scope. Returns `undefined` if no artifact exists. Each event reader - * reproduces this revision or rejects when a concurrent writer changed it. + * Read a stored prefix by id, scanning every backend storage scope. Returns + * `undefined` if no stored artifact exists. Returned metadata must identify + * `id` before repair or state publication. Used by resume/load, live adoption, + * and — via `!== undefined` — the create-collision probe. The returned + * `tornMarker` is present iff there is a torn tail to truncate. Every header + * and event graph must be fresh, mutually unaliased, and unretained by the + * backend because preparation freezes and publishes them in place. The + * returned revision must identify exactly those values and use the same + * representation as {@link readStoredRevision}. * @param id - persisted session id to resolve. * @param signal - optional cancellation for backend read work. */ - openStored(id: SessionId, signal?: AbortSignal): Promise | undefined> + loadStored(id: SessionId, signal?: AbortSignal): Promise | undefined> /** * Read the current source-qualified revision for one stored session without @@ -92,6 +152,30 @@ export interface PersistenceBackend { */ readStoredRevision(id: SessionId, signal?: AbortSignal): Promise + /** + * Optional seek-capable suffix read behind the service's `readFrom`: return + * the header plus the stored events with `seq >= fromSeq` without reading + * the whole log. A backend whose medium can address events by seq (SQLite) + * implements this so `readFrom` scales with the suffix; sequential backends + * omit it and the coordinator falls back to {@link loadStored} plus a + * forward skip. Non-mutating (no truncation, no closers). Validation of the + * region strictly below `fromSeq` is limited to seq contiguity — the + * service contract scopes this read to the suffix — unless that suffix + * contains a supported legacy shape whose normalization needs earlier + * message-identity facts, in which case the coordinator falls back + * to the complete stored prefix. + * Unknown-type refusal follows the same suffix scope: a seek-capable + * backend's `readFrom` checks only the returned suffix, while the + * sequential fallback parses the whole artifact and refuses on an unknown + * required event anywhere in it — over-refusal on the sequential side is + * accepted rather than widening the seek read. + * @param id - persisted session id to resolve. + * @param fromSeq - first event seq to include (non-negative safe integer, + * validated by the coordinator before this hook runs). + * @param signal - optional cancellation for backend read work. + */ + loadStoredFrom?(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise + /** Durably create an empty header-only session artifact. */ materializeHeader?(meta: SessionHeader): Promise @@ -112,27 +196,20 @@ export interface PersistenceBackend { */ commitRepair(meta: SessionHeader, tornMarker: TornMarker | undefined, closers: readonly SessionEvent[]): Promise - /** - * Atomically replace one exact stored revision with a complete current log. - * The backend checks revision and storage identity at the commit boundary: - * immediately before the atomic rename on JSONL, inside the replacing - * transaction on SQLite. The check adds no cross-process writer exclusion. - * @param expectedRevision - exact source revision decoded by the caller. - * @param meta - complete current-format header. - * @param events - complete current-format event stream. - */ - replaceStored( - expectedRevision: SessionPersistenceRevision, - meta: SessionHeader, - events: AsyncIterable, - ): Promise - /** * List all stored (materialized) sessions' metadata. * @param signal - optional cancellation for backend listing work. */ list(signal?: AbortSignal): Promise + /** + * Optional side-effect-free artifact locator, used to point refusal + * diagnostics ({@link SessionFormatUnsupportedError}) at the raw log. + * Backends without one artifact per session omit it or return `undefined`. + * @param meta - the header whose artifact is requested. + */ + locate?(meta: SessionHeader): SessionLocation | undefined + /** * Optional lifecycle teardown (e.g. close a database handle). Awaited by the * coordinator's dispose effect AFTER the quiescence drain. A stateless file @@ -172,7 +249,6 @@ interface PreparedSessionSource { readonly inspection: SessionInspection readonly session: Session readonly revision: SessionPersistenceRevision - readonly sourceVersion: number /** Session length after constructor-owned seed markers were appended. */ readonly sessionLength: number readonly tornMarker: TornMarker | undefined @@ -198,34 +274,306 @@ function seedCoversPrefix(seed: readonly SessionEvent[], prefix: readonly Sessio }) } -/** Reject obsolete v0 event records before a live writer persists them. */ +/** Reject events from an obsolete v0 vocabulary that this build cannot replay. */ function assertSupportedEvents(events: readonly SessionEvent[], id: SessionId): void { - for (const event of events) assertNoRetiredSessionEvent(event, id) -} - -/** Materialize one decoded event read and observe its physical EOF metadata. */ -async function collectDecodedEvents( - read: DecodedSession, -): Promise<{ events: SessionEvent[]; tornMarker: TornMarker | undefined }> { - const events: SessionEvent[] = [] - try { - for await (const event of read.events) events.push(event) - } catch (error: unknown) { - await read.completed.catch(() => undefined) - throw error + const legacyType: string = 'request/header-delta' + const legacy = events.find(event => event.type === legacyType) + if (legacy !== undefined) { + throw new Error(`session "${id}" contains unsupported legacy request/header-delta event at seq ${legacy.seq}`) + } + const legacyModeType: string = 'mode/set' + const legacyMode = events.find(event => event.type === legacyModeType) + if (legacyMode !== undefined) { + throw new Error(`session "${id}" contains unsupported legacy mode/set event at seq ${legacyMode.seq}`) + } + const fallback = events.find(event => event.type === 'request/header' + && (event.data as { reason?: string }).reason === 'fallback') + if (fallback !== undefined) { + throw new Error(`session "${id}" contains unsupported legacy request/header reason "fallback" at seq ${fallback.seq}`) } - const { tornMarker } = await read.completed - return { events, tornMarker } } -/** Yield an immutable event array as one replacement stream. */ -function eventStream(events: readonly SessionEvent[]): AsyncIterable { +/** Return an object record without widening arrays into message payloads. */ +function asRecord(value: unknown): Record | undefined { + return typeof value === 'object' && value !== null && !Array.isArray(value) + ? value as Record + : undefined +} + +/** Whether a record contains every required key and no key outside the optional extension set. */ +function hasOnlyKeys( + record: Record, + required: readonly string[], + optional: readonly string[] = [], +): boolean { + const allowed = [...required, ...optional] + return Object.keys(record).every(key => allowed.includes(key)) + && required.every(key => Object.hasOwn(record, key)) +} + +type PersistedMessageId = SessionEvent<'user/message'>['data']['id'] + +/** Mint the stable import identity for a message persisted before identities existed. */ +function legacyMessageId(id: SessionId, seq: number): PersistedMessageId { + return `legacy-message:${id}:${seq}` as PersistedMessageId +} + +/** Read a replacement target while leaving malformed surface metadata to the session validator. */ +function replacementStart(event: SessionEvent): number | undefined { + const op = asRecord((event as SessionEvent & { surfaceOp?: unknown }).surfaceOp) + return op?.['op'] === 'replace' && typeof op['start'] === 'number' + ? op['start'] + : undefined +} + +/** Whether one suffix event needs facts available only from the preceding stored prefix. */ +function needsLegacyPrefix(event: SessionEvent): boolean { + const data = asRecord(event.data) + const legacySteeringType: string = 'steering/message' + if (event.type === legacySteeringType) return true + if (data === undefined) return false + switch (event.type) { + case 'user/message': + return !Object.hasOwn(data, 'id') && Object.hasOwn(data, 'content') + case 'assistant/message': + return !Object.hasOwn(data, 'message') && Object.hasOwn(data, 'content') + case 'tool/result': + return !Object.hasOwn(data, 'message') && Object.hasOwn(data, 'callId') + default: + return false + } +} + +/** Upgrade the removed steering surface event into its current user-message equivalent. */ +function migrateLegacySteeringEvent(event: SessionEvent, id: SessionId): SessionEvent { + const legacyType: string = 'steering/message' + if (event.type !== legacyType) return event + const data = asRecord(event.data) + if (data === undefined) { + throw new Error(`session "${id}" contains malformed pre-react-loop steering/message at seq ${event.seq}`) + } + const wrapped = asRecord(data['message']) + if (wrapped !== undefined && Number.isSafeInteger(data['turn']) + && hasOnlyKeys(data, ['turn', 'message'])) { + return { ...event, type: 'user/message', data: wrapped } as SessionEvent + } + if (!Number.isSafeInteger(data['turn']) || !hasOnlyKeys(data, ['turn', 'content', 'source'])) { + throw new Error(`session "${id}" contains malformed pre-react-loop steering/message at seq ${event.seq}`) + } + const { turn: _turn, ...message } = data return { - [Symbol.asyncIterator]() { - const iterator = events[Symbol.iterator]() - return { next: () => Promise.resolve(iterator.next()) } + ...event, + type: 'user/message', + data: { + ...message, + id: legacyMessageId(id, event.seq), + role: 'user', }, + } as SessionEvent +} + +/** Remove the obsolete trigger after verifying the complete old turn-start envelope. */ +function migrateLegacyTurnStartEvent(event: SessionEvent, id: SessionId): SessionEvent { + if (event.type !== 'turn/start') return event + const data = asRecord(event.data) + if (data === undefined || !Object.hasOwn(data, 'trigger')) return event + const trigger = asRecord(data['trigger']) + if (!Number.isSafeInteger(data['turn']) || (data['turn'] as number) < 1 + || !hasOnlyKeys(data, ['turn', 'trigger']) + || trigger === undefined || typeof trigger['kind'] !== 'string' || trigger['kind'].length === 0) { + throw new Error(`session "${id}" contains malformed pre-react-loop turn/start at seq ${event.seq}`) } + return { ...event, data: { turn: data['turn'] } } as SessionEvent +} + +/** Upgrade an obsolete turn ending while preserving the latest-master envelope. */ +function migrateLegacyTurnEndEvent(event: SessionEvent, id: SessionId): SessionEvent { + if (event.type !== 'turn/end') return event + const data = asRecord(event.data) + /* v8 ignore next -- a non-record current envelope cannot match a legacy shape. */ + if (data === undefined) return event + const malformed = (): never => { + throw new Error(`session "${id}" contains malformed pre-react-loop turn/end at seq ${event.seq}`) + } + const reason = asRecord(data['reason']) + if (!Number.isSafeInteger(data['turn']) || (data['turn'] as number) < 1 + || !hasOnlyKeys(data, ['turn', 'reason']) + || reason === undefined || typeof reason['kind'] !== 'string') return malformed() + + let currentReason: Record | undefined + switch (reason['kind']) { + case 'completed': + case 'blocked': + case 'max-tokens': + case 'interrupted': + if (!hasOnlyKeys(reason, ['kind'])) return malformed() + return event + case 'aborted': + if (Object.hasOwn(reason, 'reason')) return event + if (!hasOnlyKeys(reason, ['kind'])) return malformed() + currentReason = { kind: 'aborted', reason: { kind: 'legacy' } } + break + case 'disposed': + if (!hasOnlyKeys(reason, ['kind'])) return malformed() + currentReason = { kind: 'aborted', reason: { kind: 'disposed' } } + break + case 'error': { + if (Object.hasOwn(reason, 'error')) return event + if (!Number.isSafeInteger(reason['step']) || (reason['step'] as number) < 0) return malformed() + const failure = asRecord(reason['failure']) + if (failure !== undefined && hasOnlyKeys(reason, ['kind', 'step', 'failure']) + && hasOnlyKeys(failure, ['message', 'code'], ['status', 'providerRetryAfterMs', 'requestId']) + && typeof failure['message'] === 'string' && typeof failure['code'] === 'string' + && (failure['status'] === undefined || typeof failure['status'] === 'number') + && (failure['providerRetryAfterMs'] === undefined || typeof failure['providerRetryAfterMs'] === 'number') + && (failure['requestId'] === undefined || typeof failure['requestId'] === 'string')) { + currentReason = { kind: 'error', error: failure } + break + } + const messageKeys = reason['code'] === undefined + ? ['kind', 'step', 'message'] + : ['kind', 'step', 'message', 'code'] + if (!hasOnlyKeys(reason, messageKeys) + || typeof reason['message'] !== 'string' + || (reason['code'] !== undefined && typeof reason['code'] !== 'string')) return malformed() + currentReason = { + kind: 'error', + error: { + message: reason['message'], + code: typeof reason['code'] === 'string' ? reason['code'] : 'UNKNOWN', + }, + } + break + } + default: + return event + } + + return { + ...event, + data: { + ...data, + reason: currentReason, + }, + } as SessionEvent +} + +/** + * Upgrade one pre-identity message event into the current wrapper shape. + * Current-looking malformed events remain untouched so validation rejects them + * instead of disguising corruption as legacy data. + */ +function migrateLegacyMessageEvent( + event: SessionEvent, + id: SessionId, + messageIds: ReadonlyMap, +): SessionEvent { + const data = asRecord(event.data) + if (data === undefined) return event + switch (event.type) { + case 'user/message': { + if (Object.hasOwn(data, 'id') || Object.hasOwn(data, 'role') + || Object.hasOwn(data, 'message') + || !Object.hasOwn(data, 'content') || !Object.hasOwn(data, 'source')) return event + return { + ...event, + data: { + ...data, + id: legacyMessageId(id, event.seq), + role: 'user', + }, + } as SessionEvent + } + case 'assistant/message': { + if (Object.hasOwn(data, 'message') + || !Object.hasOwn(data, 'content') || !Object.hasOwn(data, 'provenance')) return event + const { content, provenance, ...eventData } = data + return { + ...event, + data: { + ...eventData, + message: { + id: legacyMessageId(id, event.seq), + role: 'assistant', + content, + source: { + ...asRecord(provenance), + kind: 'model', + }, + }, + }, + } as SessionEvent + } + case 'tool/result': { + if (Object.hasOwn(data, 'message') + || !Object.hasOwn(data, 'callId') || !Object.hasOwn(data, 'content') + || !Object.hasOwn(data, 'isError')) return event + const { callId, content, isError, ...eventData } = data + const inheritedId = replacementStart(event) + return { + ...event, + data: { + ...eventData, + message: { + id: inheritedId === undefined + ? legacyMessageId(id, event.seq) + : messageIds.get(inheritedId), + role: 'user', + content: [{ + type: 'tool-result', + toolCallId: callId, + content, + isError, + }], + source: { + kind: 'tool', + callId, + }, + }, + }, + } as SessionEvent + } + default: + return event + } +} + +/** Read the identified message carried by one validated current event. */ +function eventMessageId(event: SessionEvent): PersistedMessageId | undefined { + const data = asRecord(event.data) + const message = event.type === 'user/message' ? data : asRecord(data?.['message']) + return typeof message?.['id'] === 'string' ? message['id'] as PersistedMessageId : undefined +} + +/** Materialize stored events as upgraded, validated snapshots with immutable messages. */ +function snapshotStoredEvents(events: readonly SessionEvent[], id: SessionId): SessionEvent[] { + assertSupportedEvents(events, id) + const messageIds = new Map() + return events.map((event) => { + const migratedStart = migrateLegacyTurnStartEvent(event, id) + const migratedTurn = migrateLegacyTurnEndEvent(migratedStart, id) + const migratedSteering = migrateLegacySteeringEvent(migratedTurn, id) + const snapshot = snapshotSessionEvent(migrateLegacyMessageEvent(migratedSteering, id, messageIds)) + const messageId = eventMessageId(snapshot) + if (messageId !== undefined) messageIds.set(snapshot.seq, messageId) + return snapshot + }) +} + +/** Upgrade and validate an exclusively owned backend result without copying it. */ +function adoptStoredEvents(events: SessionEvent[], id: SessionId): SessionEvent[] { + assertSupportedEvents(events, id) + const messageIds = new Map() + for (const [index, event] of events.entries()) { + const migratedStart = migrateLegacyTurnStartEvent(event, id) + const migratedTurn = migrateLegacyTurnEndEvent(migratedStart, id) + const migratedSteering = migrateLegacySteeringEvent(migratedTurn, id) + const adopted = adoptSessionEvent(migrateLegacyMessageEvent(migratedSteering, id, messageIds)) + events[index] = adopted + const messageId = eventMessageId(adopted) + if (messageId !== undefined) messageIds.set(adopted.seq, messageId) + } + return events } /** @@ -326,7 +674,7 @@ export class PersistenceCoordinator { // A persisted artifact under this id (in ANY scope) blocks creation: load/ // resume identify a session by id alone, so a second artifact would make // resume nondeterministic. - if (await this.backend.openStored(meta.id) !== undefined) { + if (await this.backend.loadStored(meta.id) !== undefined) { throw new Error(`session "${meta.id}" already has a persisted log on disk; load/resume it instead of creating`) } // Pure lazy: record intent only. No artifact until the first append. @@ -555,8 +903,9 @@ export class PersistenceCoordinator { /** * Read the stored events from `fromSeq` onward, detached and non-mutating * (the read-from-seq primitive behind the service's `readFrom`). Runs on - * the same per-id chain as writes. The format decoder requests a backend - * suffix only when every selected transform can start at `fromSeq`. + * the same per-id chain as writes; a backend with the seek-capable + * {@link PersistenceBackend.loadStoredFrom} hook reads only the suffix, + * every other backend reads its stored prefix and skips forward here. * @param id - persisted session to read. * @param fromSeq - first event seq to include; a non-negative safe integer. * @param signal - optional cancellation for queued and backend read work. @@ -576,64 +925,90 @@ export class PersistenceCoordinator { fromSeq: number, signal?: AbortSignal, ): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { - for (;;) { - signal?.throwIfAborted() - const stored = await this.backend.openStored(id, signal) - signal?.throwIfAborted() - if (stored === undefined) throw new SessionPersistenceNotFoundError(id) + signal?.throwIfAborted() + if (this.backend.loadStoredFrom !== undefined) { + let suffix: StoredSuffix | undefined try { - const current = decodeStoredSession(stored, id, fromSeq) - const { events } = await collectDecodedEvents(current) - signal?.throwIfAborted() - return { meta: structuredClone(current.meta), events } + suffix = await this.backend.loadStoredFrom(id, fromSeq, signal) } catch (error: unknown) { - signal?.throwIfAborted() - if (error instanceof SessionPersistenceRevisionConflictError) continue + if (signal?.aborted) signal.throwIfAborted() throw error } + signal?.throwIfAborted() + if (suffix === undefined) throw new SessionPersistenceNotFoundError(id) + this.assertStoredId(id, suffix.meta) + this.assertVersion(suffix.meta) + if (suffix.events.some(needsLegacyPrefix)) { + const whole = await this.readStoredPrefix(id, signal) + return { meta: whole.meta, events: whole.events.filter(event => event.seq >= fromSeq) } + } + const events = snapshotStoredEvents(suffix.events, id) + this.assertEventsSupported(suffix.meta, events) + return { meta: structuredClone(suffix.meta), events } + } + const whole = await this.readStoredPrefix(id, signal) + // Sequential fallback: contiguous seqs from 0 make the suffix an index slice. + return { meta: whole.meta, events: whole.events.slice(fromSeq) } + } + + /** Read one detached physical prefix without logical recovery or caching. */ + private async readStoredPrefix( + id: SessionId, + signal?: AbortSignal, + ): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + signal?.throwIfAborted() + const stored = await this.backend.loadStored(id, signal) + signal?.throwIfAborted() + if (stored === undefined) throw new SessionPersistenceNotFoundError(id) + this.assertStoredId(id, stored.meta) + this.assertVersion(stored.meta) + const events = snapshotStoredEvents(stored.events, id) + this.assertEventsSupported(stored.meta, events) + return { + meta: structuredClone(stored.meta), + events, } } /** Read, repair in memory, validate, and freeze one cold source once. */ private async prepareCore(id: SessionId): Promise> { - for (;;) { - const stored = await this.backend.openStored(id) - if (stored === undefined) throw new SessionPersistenceNotFoundError(id) - try { - const current = decodeStoredSession(stored, id) - const { events: storedEvents, tornMarker } = await collectDecodedEvents(current) + const stored = await this.backend.loadStored(id) + if (stored === undefined) throw new SessionPersistenceNotFoundError(id) + try { + const { meta, events, revision, tornMarker } = stored + this.assertStoredId(id, meta) + this.assertVersion(meta) + const storedEvents = adoptStoredEvents(events, id) + this.assertEventsSupported(meta, storedEvents) - // Preserve complete interrupted events and synthesize only missing closers. - const closers = interruptedTurnClosers(storedEvents).map(adoptSessionEvent) - const balanced = [...storedEvents, ...closers] - const session = this.ctx.sessions.prepare(id, { - seed: balanced, - meta: current.meta, - seedSource: 'persistence', - }) - const inspection: SessionInspection = Object.freeze({ - meta: session.header, - events: Object.freeze(balanced), - }) - return { - inspection, - session, - revision: current.revision, - sourceVersion: current.sourceVersion, - sessionLength: session.events.length, - tornMarker, - closers, - } - } catch (error: unknown) { - if (error instanceof SessionPersistenceRevisionConflictError) continue - // An unsupported format is a refusal over an intact log, not damage — - // surface it unwrapped so callers can point at the raw artifact. - if (error instanceof SessionFormatUnsupportedError) throw error - throw new SessionPersistenceCorruptionError( - `stored session "${id}" failed validation: ${String(error)}`, - { cause: error }, - ) + // Preserve complete interrupted events and synthesize only missing closers. + const closers = interruptedTurnClosers(storedEvents).map(adoptSessionEvent) + const balanced = [...storedEvents, ...closers] + const session = this.ctx.sessions.prepare(id, { + seed: balanced, + meta, + seedSource: 'persistence', + }) + const inspection: SessionInspection = Object.freeze({ + meta: session.header, + events: Object.freeze(balanced), + }) + return { + inspection, + session, + revision, + sessionLength: session.events.length, + tornMarker, + closers, } + } catch (error: unknown) { + // An unsupported format is a refusal over an intact log, not damage — + // surface it unwrapped so callers can point at the raw artifact. + if (error instanceof SessionFormatUnsupportedError) throw error + throw new SessionPersistenceCorruptionError( + `stored session "${id}" failed validation: ${String(error)}`, + { cause: error }, + ) } } @@ -648,19 +1023,6 @@ export class PersistenceCoordinator { throw new Error(`session "${id}" already has a live persistence owner`) } if (!await this.isPreparedSourceCurrent(source)) return undefined - if (source.sourceVersion !== SESSION_FORMAT_VERSION) { - try { - await this.backend.replaceStored( - source.revision, - source.inspection.meta, - eventStream(source.inspection.events), - ) - } catch (error: unknown) { - if (!(error instanceof SessionPersistenceRevisionConflictError)) throw error - } - // A commit has a new revision; a conflict names a different source. - return undefined - } if (source.tornMarker !== undefined || source.closers.length > 0) { await this.backend.commitRepair(source.inspection.meta, source.tornMarker, source.closers) // The repair changed the durable revision. Reload the exact committed @@ -763,6 +1125,44 @@ export class PersistenceCoordinator { } } + private assertVersion(meta: SessionHeader): void { + if (meta.version === SESSION_FORMAT_VERSION) return + throw this.unsupported(meta, sessionFormatVersionRefusal(meta.id, meta.version)) + } + + /** + * Refuse a log containing an event type this build does not know, unless the + * writer marked the event ignorable: an unrecognized required event may + * change how the rest of the log must be interpreted, so silently skipping + * it would reconstruct a wrong session (the envelope contract on + * `SessionEvent.ignorable`). Runs on NORMALIZED events — after + * `snapshotStoredEvents`/`adoptStoredEvents` has upgraded the legacy shapes + * this build still reads and rejected the ones it does not, so those keep + * their specific diagnostics. + */ + private assertEventsSupported(meta: SessionHeader, events: readonly SessionEvent[]): void { + for (const event of events) { + if (KNOWN_SESSION_EVENT_TYPES.has(event.type) || event.ignorable === true) continue + throw this.unsupported(meta, `session "${meta.id}" contains event type "${event.type}" (seq ${event.seq}) unknown to this harness and not marked ignorable; refusing to interpret the log — it was likely written by a newer harness`) + } + } + + /** Build a format refusal that points at the raw artifact when the backend has one. */ + private unsupported(meta: SessionHeader, reason: string): SessionFormatUnsupportedError { + const location = this.backend.locate?.(meta) + return new SessionFormatUnsupportedError( + location === undefined ? reason : `${reason} (raw log: ${location.path})`, + location, + ) + } + + /** Reject backend metadata that is not bound to the requested session id. */ + private assertStoredId(id: SessionId, meta: SessionHeader): void { + if (meta.id !== id) { + throw new Error(`stored session identity mismatch: requested "${id}", header contains "${meta.id}"`) + } + } + // --- write path (session/event → flush drain) --- private installWritePath(): void { @@ -895,19 +1295,11 @@ export class PersistenceCoordinator { */ private async seedMatchesPersisted(id: SessionId, seed: readonly SessionEvent[], cursor: number): Promise { if (cursor === 0) return true - for (;;) { - const stored = await this.backend.openStored(id) - /* v8 ignore next -- a cursor > 0 means the session was materialized, so it exists */ - if (stored === undefined) return false - try { - const current = decodeStoredSession(stored, id) - const { events } = await collectDecodedEvents(current) - return seedCoversPrefix(seed, events.slice(0, cursor)) - } catch (error: unknown) { - if (error instanceof SessionPersistenceRevisionConflictError) continue - throw error - } - } + const stored = await this.backend.loadStored(id) + /* v8 ignore next -- a cursor > 0 means the session was materialized, so it exists */ + if (stored === undefined) return false + this.assertStoredId(id, stored.meta) + return seedCoversPrefix(seed, snapshotStoredEvents(stored.events, id).slice(0, cursor)) } /** @@ -961,18 +1353,13 @@ export class PersistenceCoordinator { // case 2/3: resolve the id once across storage, then let adoption reject a // cwd mismatch before repair or state publication. - for (;;) { - const live = await this.backend.openStored(id) - if (live === undefined) break + const live = await this.backend.loadStored(id) + if (live !== undefined) { // Do NOT route through cold preparation: that crash-repairs open turns as // interrupted, which is wrong for HMR while the live Session is still the // authority and may append the real step/turn end later. - try { - if (await this.adoptLivePrefix(session, seed, live)) return - } catch (error: unknown) { - if (error instanceof SessionPersistenceRevisionConflictError) continue - throw error - } + await this.adoptLivePrefix(session, seed, live) + return } // case 4: a genuinely new session. Register its meta (lazy), then persist its @@ -993,39 +1380,28 @@ export class PersistenceCoordinator { * the live Session is still the authority), bind ownership, and persist the * live suffix that was ahead of the stored prefix. */ - private async adoptLivePrefix( - session: Session, - seed: readonly SessionEvent[], - stored: StoredSessionSource, - ): Promise { - const current = decodeStoredSession(stored, session.header.id) - if (current.meta.cwd !== session.header.cwd) { - throw new Error(`session "${session.header.id}" is already persisted at a different cwd (persisted: ${String(current.meta.cwd)}, live: ${String(session.header.cwd)}) (id collision)`) + private async adoptLivePrefix(session: Session, seed: readonly SessionEvent[], stored: StoredPrefix): Promise { + const { meta, events, tornMarker } = stored + this.assertStoredId(session.header.id, meta) + if (meta.cwd !== session.header.cwd) { + throw new Error(`session "${session.header.id}" is already persisted at a different cwd (persisted: ${String(meta.cwd)}, live: ${String(session.header.cwd)}) (id collision)`) } - const { events: storedEvents, tornMarker } = await collectDecodedEvents(current) + this.assertVersion(meta) + const storedEvents = snapshotStoredEvents(events, session.header.id) + this.assertEventsSupported(meta, storedEvents) if (!seedCoversPrefix(seed, storedEvents)) { throw new Error(`session "${session.header.id}" already has a persisted log on disk that does not match this live session (id collision)`) } - if (current.sourceVersion !== SESSION_FORMAT_VERSION) { - await this.backend.replaceStored( - current.revision, - current.meta, - eventStream(storedEvents), - ) - // Reopen after the commit because it produced a new source revision. - return false - } // Truncate-only repair (no closers): the open turn is NOT closed here. - if (tornMarker !== undefined) await this.backend.commitRepair(current.meta, tornMarker, []) + if (tornMarker !== undefined) await this.backend.commitRepair(meta, tornMarker, []) this.states.set(session.header.id, { - meta: { ...current.meta }, + meta: { ...meta }, cursor: storedEvents.length, materialized: true, owner: session, }) const suffix = seed.slice(storedEvents.length) if (suffix.length > 0) await this.appendCore(session.header.id, suffix) - return true } private async flush(session: Session): Promise { diff --git a/packages/session/session-persistence/src/format-decoder.ts b/packages/session/session-persistence/src/format-decoder.ts deleted file mode 100644 index 398b487860..0000000000 --- a/packages/session/session-persistence/src/format-decoder.ts +++ /dev/null @@ -1,500 +0,0 @@ -/** - * Static Session format decoding from backend-owned JSON records to the - * current durable header and event types. - * @module @deepseek-ai/dsh-session-persistence/format-decoder - */ - -import { - adoptSessionEvent, - KNOWN_SESSION_EVENT_TYPES, - SESSION_FORMAT_VERSION, - Session, - SessionId, - snapshotJsonValue, -} from '@deepseek-ai/dsh-session' -import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' -import { - unversionedFormatCompatibility, -} from './format-v0-compat.ts' -import type { UnversionedFormatCompatibility } from './format-v0-compat.ts' -import { asStoredRecord, assertNoRetiredSessionEvent, readStoredEventEnvelope } from './format-json.ts' -import type { SessionLocation } from './index.ts' -import { SESSION_FORMAT_MIGRATIONS } from './format-migrations/index.ts' -import type { SessionPersistenceRevision } from './revision.ts' - -/** One single-use adjacent-version migration instance. */ -interface SessionFormatMigrationInstance { - /** - * Transform and validate the header fields understood by this migration. - * The detached result must carry the constructor's `to` version and preserve - * the source id and cwd. - * @param meta - detached input header for the constructor's `from` version. - * @returns detached header JSON carrying the constructor's `to` version. - */ - header(meta: unknown): unknown - /** - * Transform exactly one event into detached lossless JSON while retaining - * its sequence number. Instance fields may accumulate facts from the header - * and earlier events. - * @param event - detached input event in durable sequence order. - * @returns exactly one detached event for the same sequence number. - */ - event(event: unknown): unknown - /** - * Validate accumulated state after the complete input stream reaches EOF. - * Header-only reads do not call this method; it cannot emit another event. - */ - finish?(): void -} - -/** Static identity and constructor for one adjacent-version migration. */ -export interface SessionFormatMigration { - /** Input Session format version. */ - readonly from: number - /** Output Session format version; must equal `from + 1`. */ - readonly to: number - /** - * Create fresh state for one header decode and its optional complete event - * stream. Instances are never shared across sessions or decode attempts. - * @returns a single-use migration instance. - */ - new(): SessionFormatMigrationInstance -} - -/** Options for one physical event read. */ -export interface StoredEventReadOptions { - /** First physical event sequence to request. */ - readonly fromSeq?: number -} - -/** Completion metadata produced after a physical event stream reaches EOF. */ -export interface StoredEventReadCompletion { - /** Backend-owned token for a recoverable physical tail. */ - readonly tornMarker?: TornMarker -} - -/** One revision-bound physical event stream. */ -export interface StoredEventRead { - /** Parsed JSON records from the exact source revision. */ - readonly events: AsyncIterable - /** Resolves only after the stream reaches EOF at the same revision. */ - readonly completed: Promise> -} - -/** Repeatable access to one stored header and exact durable revision. */ -export interface StoredSessionSource { - /** Parsed header JSON; format validation belongs to the decoder. */ - readonly meta: unknown - /** Exact backend revision every event read must reproduce or reject. */ - readonly revision: SessionPersistenceRevision - /** Raw artifact location used to enrich unsupported-format diagnostics. */ - readonly location?: SessionLocation - /** - * Open a new event read bound to {@link revision}. A concurrent replacement - * rejects the read instead of returning events from another revision. - * @param options - optional suffix request. - * @returns one independently consumable physical event read. - */ - readEvents(options?: StoredEventReadOptions): StoredEventRead -} - -/** - * Build the standard lazy event stream and EOF metadata around one backend - * read, shared by every first-party backend. - * @param load - revision-checked batch loader owned by the backend. - * @param include - whether one loaded event belongs in this physical read. - * @param signal - optional cancellation checked between yielded events. - * @returns an independently consumable event read. - */ -export function createStoredEventRead( - load: () => Promise<{ readonly events: readonly unknown[]; readonly tornMarker?: TornMarker }>, - include: (event: unknown) => boolean, - signal?: AbortSignal, -): StoredEventRead { - const completed = Promise.withResolvers>() - const events = (async function* (): AsyncIterable { - try { - const batch = await load() - for (const event of batch.events) { - signal?.throwIfAborted() - if (include(event)) yield event - } - completed.resolve(batch.tornMarker === undefined ? {} : { tornMarker: batch.tornMarker }) - } catch (error: unknown) { - completed.reject(error) - throw error - } - })() - return { events, completed: completed.promise } -} - -/** One decoded current-format read bound to an exact stored revision. */ -export interface DecodedSession { - /** Validated current-format header. */ - readonly meta: SessionHeader - /** Version observed before any format migration ran. */ - readonly sourceVersion: number - /** Exact backend revision represented by this source. */ - readonly revision: SessionPersistenceRevision - /** Validated current-format events at or past the requested sequence. */ - readonly events: AsyncIterable - /** - * Completion metadata from the physical read supplying the events. Settles - * only after the events iterable is fully consumed or fails. - */ - readonly completed: Promise> -} - -/** - * The stored log is intact but this runtime cannot faithfully interpret its - * format version or required event vocabulary. - */ -export class SessionFormatUnsupportedError extends Error { - /** - * @param message - stable refusal reason, including the raw location when available. - * @param location - backend artifact location when one exists. - */ - constructor(message: string, readonly location?: SessionLocation) { - super(message) - this.name = 'SessionFormatUnsupportedError' - } -} - -/** - * Direction-aware refusal text for a stored format version this build cannot - * decode. - * @param id - stored session identity. - * @param version - stored format version. - * @returns stable refusal text without a raw-location suffix. - */ -export function sessionFormatVersionRefusal(id: string, version: number): string { - return version > SESSION_FORMAT_VERSION - ? `session "${id}" uses log format v${version}, but this harness reads only v${SESSION_FORMAT_VERSION}: the log was written by a newer harness — upgrade the harness to open it` - : `session "${id}" uses log format v${version}, older than the supported v${SESSION_FORMAT_VERSION}, and this build ships no upgrade path for it` -} - -function buildMigrationIndex( - migrations: readonly SessionFormatMigration[], -): ReadonlyMap { - const byFrom = new Map() - for (const Migration of migrations) { - if (!Number.isSafeInteger(Migration.from) || Migration.from < 0 || Migration.to !== Migration.from + 1) { - throw new TypeError(`Session format migration must be an adjacent non-negative version, got v${Migration.from} -> v${Migration.to}`) - } - if (byFrom.has(Migration.from)) { - throw new TypeError(`duplicate Session format migration from v${Migration.from}`) - } - if (Migration.to > SESSION_FORMAT_VERSION) { - throw new TypeError(`Session format migration v${Migration.from} -> v${Migration.to} targets a version newer than this build's v${SESSION_FORMAT_VERSION}`) - } - byFrom.set(Migration.from, Migration) - } - // A missing migration is a per-session concern, decided by planMigrations() at decode - // time: it refuses sessions at or below the gap, while later versions whose - // path to the current version is complete still upgrade. Initialization - // therefore checks only migration legality and duplicates here. - return byFrom -} - -const MIGRATION_BY_FROM = buildMigrationIndex(SESSION_FORMAT_MIGRATIONS) - -type PlannedMigration = readonly [SessionFormatMigration, SessionFormatMigrationInstance] - -interface DecodedHeader { - readonly meta: SessionHeader - readonly sourceVersion: number - readonly migrations: readonly PlannedMigration[] - readonly unversionedCompatibility?: UnversionedFormatCompatibility -} - -interface StoredHeaderSource { - readonly meta: unknown - readonly location?: SessionLocation -} - -function unsupported( - source: StoredHeaderSource, - reason: string, -): SessionFormatUnsupportedError { - const location = source.location - return new SessionFormatUnsupportedError( - location === undefined ? reason : `${reason} (raw log: ${location.path})`, - location, - ) -} - -function readSourceHeader( - source: StoredHeaderSource, - expectedId: SessionId, -): { meta: Record; version: number; id: SessionId } { - const snapshot = snapshotJsonValue(source.meta) - const meta = asStoredRecord(snapshot) - if (meta === undefined) throw new Error('stored session header is not a lossless JSON record') - if (!Number.isSafeInteger(meta['version'])) { - throw new Error(`stored session header has invalid format version ${String(meta['version'])}`) - } - const version = meta['version'] as number - if (version > SESSION_FORMAT_VERSION) { - throw unsupported(source, sessionFormatVersionRefusal(String(meta['id']), version)) - } - if (typeof meta['id'] !== 'string') throw new Error('stored session header has no string id') - const id = SessionId(meta['id']) - if (id !== expectedId) { - throw new Error(`stored session identity mismatch: requested "${expectedId}", header contains "${id}"`) - } - return { meta, version, id } -} - -function planMigrations( - source: StoredHeaderSource, - id: SessionId, - fromVersion: number, -): readonly SessionFormatMigration[] { - const migrations: SessionFormatMigration[] = [] - for (let version = fromVersion; version < SESSION_FORMAT_VERSION; version++) { - const Migration = MIGRATION_BY_FROM.get(version) - if (Migration === undefined) { - throw unsupported( - source, - `session "${id}" uses log format v${fromVersion}, older than the supported v${SESSION_FORMAT_VERSION}, and this build has no upgrade path to it: missing v${version} -> v${version + 1}`, - ) - } - migrations.push(Migration) - } - return migrations -} - -function decodeHeader( - source: StoredHeaderSource, - expectedId: SessionId, -): DecodedHeader { - const stored = readSourceHeader(source, expectedId) - const migrations: PlannedMigration[] = [] - let meta: unknown = stored.meta - for (const Migration of planMigrations(source, stored.id, stored.version)) { - let instance: SessionFormatMigrationInstance - try { - instance = new Migration() - meta = snapshotJsonValue(instance.header(meta)) - } catch (error: unknown) { - throw new Error( - `session "${stored.id}" header migration v${Migration.from} -> v${Migration.to} failed`, - { cause: error }, - ) - } - const record = asStoredRecord(meta) - const actual = record?.['version'] - if (actual !== Migration.to) { - throw new Error(`Session format migration v${Migration.from} -> v${Migration.to} returned header version ${String(actual)}`) - } - if (record === undefined - || record['id'] !== stored.id - || record['cwd'] !== stored.meta['cwd']) { - throw new Error(`Session format migration v${Migration.from} -> v${Migration.to} changed session storage identity`) - } - migrations.push([Migration, instance]) - } - const current = Session.create(stored.id, undefined, meta as SessionHeader).header - const compatibility = unversionedFormatCompatibility(stored.version) - return { - meta: current, - sourceVersion: stored.version, - migrations, - ...(compatibility === undefined ? {} : { unversionedCompatibility: compatibility }), - } -} - -/** - * Decode one stored header without opening its event log. Listing uses the - * same static format path as full Session reads. - * @param meta - parsed backend header JSON. - * @param expectedId - identity selected by the backend or caller. - * @param location - optional raw artifact location for refusal diagnostics. - * @returns the validated current-format header. - */ -export function decodeStoredSessionHeader( - meta: unknown, - expectedId: SessionId, - location?: SessionLocation, -): SessionHeader { - return decodeHeader({ meta, ...location === undefined ? {} : { location } }, expectedId).meta -} - -function assertCurrentEnvelope(value: unknown, id: SessionId): SessionEvent { - const snapshot = snapshotJsonValue(value) - return readStoredEventEnvelope(snapshot, id) -} - -function assertCurrentEventSupported( - source: StoredSessionSource, - meta: SessionHeader, - event: SessionEvent, -): void { - assertNoRetiredSessionEvent(event, meta.id) - if (KNOWN_SESSION_EVENT_TYPES.has(event.type) || event.ignorable === true) return - throw unsupported( - source, - `session "${meta.id}" contains event type "${event.type}" (seq ${event.seq}) unknown to this harness and not marked ignorable; refusing to interpret the log — it was likely written by a newer harness`, - ) -} - -async function* decodeCurrentEvents( - source: StoredSessionSource, - meta: SessionHeader, - events: AsyncIterable, - expectedSeq: number, -): AsyncIterable { - let nextSeq = expectedSeq - for await (const raw of events) { - const event = assertCurrentEnvelope(raw, meta.id) - if (event.seq !== nextSeq) { - throw new Error(`session "${meta.id}" event seq mismatch: expected ${nextSeq}, got ${event.seq}`) - } - const current = adoptSessionEvent(event) - assertCurrentEventSupported(source, meta, current) - nextSeq += 1 - yield current - } -} - -async function* transformEvents( - events: AsyncIterable, - migrations: readonly PlannedMigration[], - id: SessionId, -): AsyncIterable { - for await (let value of events) { - for (const [Migration, instance] of migrations) { - const sourceSeq = asStoredRecord(value)?.['seq'] - let output: unknown - try { - output = snapshotJsonValue(instance.event(value)) - if (output === undefined) { - throw new Error('migration returned an event that is not losslessly JSON-serializable') - } - } catch (error: unknown) { - throw new Error( - `session "${id}" event migration v${Migration.from} -> v${Migration.to} failed at seq ${String(sourceSeq)}`, - { cause: error }, - ) - } - const targetSeq = asStoredRecord(output)?.['seq'] - if (targetSeq !== sourceSeq) { - throw new Error(`session "${id}" event migration v${Migration.from} -> v${Migration.to} changed event seq ${String(sourceSeq)} to ${String(targetSeq)}`) - } - value = output - } - yield value - } - for (const [Migration, instance] of migrations) { - try { - instance.finish?.() - } catch (error: unknown) { - throw new Error( - `session "${id}" event migration v${Migration.from} -> v${Migration.to} failed at EOF`, - { cause: error }, - ) - } - } -} - -async function* snapshotStoredEvents( - events: AsyncIterable, - id: SessionId, -): AsyncIterable { - for await (const event of events) { - const snapshot = snapshotJsonValue(event) - if (snapshot === undefined) { - throw new Error(`session "${id}" contains an event that is not losslessly JSON-serializable`) - } - yield snapshot - } -} - -function decodedRead( - source: StoredSessionSource, - header: DecodedHeader, - requestedFromSeq: number, -): { - readonly events: AsyncIterable - readonly completed: Promise> -} { - const completion = Promise.withResolvers>() - const migrating = header.migrations.length > 0 - const compatibility = header.unversionedCompatibility - let physical: StoredEventRead | undefined - - const events = (async function* (): AsyncIterable { - try { - let physicalFromSeq = migrating ? 0 : requestedFromSeq - physical = source.readEvents({ fromSeq: physicalFromSeq }) - void physical.completed.catch(() => undefined) - let raw: AsyncIterable = physical.events - let physicalCompletion: StoredEventReadCompletion | undefined - - if (!migrating && requestedFromSeq > 0 && compatibility !== undefined) { - const suffix: unknown[] = [] - for await (const value of raw) suffix.push(value) - physicalCompletion = await physical.completed - if (suffix.some(value => compatibility.requiresPrefix(value))) { - physicalFromSeq = 0 - physical = source.readEvents({ fromSeq: 0 }) - void physical.completed.catch(() => undefined) - raw = physical.events - physicalCompletion = undefined - } else { - raw = (async function* () { - for (const value of suffix) yield await Promise.resolve(value) - })() - } - } - - const storedEvents = snapshotStoredEvents(raw, header.meta.id) - const canonicalEvents = compatibility === undefined - ? storedEvents - : compatibility.canonicalizeEvents(storedEvents, header.meta.id) - const transformed = transformEvents( - canonicalEvents, - header.migrations, - header.meta.id, - ) - const current = decodeCurrentEvents(source, header.meta, transformed, physicalFromSeq) - for await (const event of current) { - if (event.seq >= requestedFromSeq) yield event - } - completion.resolve(physicalCompletion ?? await physical.completed) - } catch (error: unknown) { - completion.reject(error) - throw error - } - })() - - return { events, completed: completion.promise } -} - -/** - * Decode one backend source through the static adjacent-version migrations and - * the current header/event validators. Format selection is complete before any - * consumer-specific recovery runs. - * @param source - backend-owned header, revision, and event reader factory. - * @param expectedId - session identity selected by the caller. - * @param fromSeq - first current-format event sequence to return. - * @returns one decoded current-format stream bound to the stored revision. - */ -export function decodeStoredSession( - source: StoredSessionSource, - expectedId: SessionId, - fromSeq = 0, -): DecodedSession { - if (!Number.isSafeInteger(fromSeq) || fromSeq < 0) { - throw new TypeError(`stored event fromSeq must be a non-negative safe integer, got ${String(fromSeq)}`) - } - const header = decodeHeader(source, expectedId) - const read = decodedRead(source, header, fromSeq) - return { - meta: header.meta, - sourceVersion: header.sourceVersion, - revision: source.revision, - events: read.events, - completed: read.completed, - } -} diff --git a/packages/session/session-persistence/src/format-json.ts b/packages/session/session-persistence/src/format-json.ts deleted file mode 100644 index f4e911a220..0000000000 --- a/packages/session/session-persistence/src/format-json.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** Shared JSON validation for stored Session format records. */ - -import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' - -/** - * Narrow an unknown JSON value to a non-array object. - * @param value - parsed JSON value. - * @returns the object, or `undefined` for every other JSON value. - */ -export function asStoredRecord(value: unknown): Record | undefined { - return typeof value === 'object' && value !== null && !Array.isArray(value) - ? value as Record - : undefined -} - -/** - * Validate fields common to every stored Session event envelope. - * @param value - detached parsed event JSON. - * @param id - Session identity used in diagnostics. - * @returns the structurally valid event envelope. - */ -export function readStoredEventEnvelope(value: unknown, id: SessionId): SessionEvent { - const event = asStoredRecord(value) - if (event === undefined) throw new Error(`session "${id}" contains a non-record event`) - if (typeof event['type'] !== 'string') throw new Error(`session "${id}" contains an event without a string type`) - if (!Number.isSafeInteger(event['seq']) || (event['seq'] as number) < 0) { - throw new Error(`session "${id}" contains event type "${event['type']}" with invalid seq ${String(event['seq'])}`) - } - if (typeof event['time'] !== 'number' || !Number.isFinite(event['time'])) { - throw new Error(`session "${id}" contains event type "${event['type']}" at seq ${String(event['seq'])} with invalid time`) - } - if (!Object.hasOwn(event, 'data')) { - throw new Error(`session "${id}" contains event type "${event['type']}" at seq ${String(event['seq'])} without data`) - } - return event as unknown as SessionEvent -} - -/** - * Reject event records retired before the current durable event vocabulary. - * @param event - current-envelope event presented for reading or writing. - * @param id - Session identity used in diagnostics. - */ -export function assertNoRetiredSessionEvent(event: SessionEvent, id: SessionId): void { - const retiredType: string = 'request/header-delta' - if (event.type === retiredType) { - throw new Error(`session "${id}" contains unsupported legacy request/header-delta event at seq ${event.seq}`) - } - const retiredModeType: string = 'mode/set' - if (event.type === retiredModeType) { - throw new Error(`session "${id}" contains unsupported legacy mode/set event at seq ${event.seq}`) - } - if (event.type === 'request/header' - && (event.data as { reason?: string }).reason === 'fallback') { - throw new Error(`session "${id}" contains unsupported legacy request/header reason "fallback" at seq ${event.seq}`) - } -} diff --git a/packages/session/session-persistence/src/format-migrations/index.ts b/packages/session/session-persistence/src/format-migrations/index.ts deleted file mode 100644 index ecdce5e841..0000000000 --- a/packages/session/session-persistence/src/format-migrations/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** Static adjacent-version Session format migrations shipped by this build. */ - -import type { SessionFormatMigration } from '../format-decoder.ts' - -/** Ordered durable format migrations; format v0 is current, so the chain is empty. */ -export const SESSION_FORMAT_MIGRATIONS: readonly SessionFormatMigration[] = Object.freeze([]) diff --git a/packages/session/session-persistence/src/format-v0-compat.ts b/packages/session/session-persistence/src/format-v0-compat.ts deleted file mode 100644 index 9ad747818e..0000000000 --- a/packages/session/session-persistence/src/format-v0-compat.ts +++ /dev/null @@ -1,297 +0,0 @@ -/** - * Same-version normalization for durable format-v0 Session records. - * @module @deepseek-ai/dsh-session-persistence/format-v0-compat - */ - -import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' -import { asStoredRecord, readStoredEventEnvelope } from './format-json.ts' - -/** One format-specific normalizer selected before adjacent-version migrations. */ -export interface UnversionedFormatCompatibility { - /** Header version whose historical records require this normalizer. */ - readonly version: number - /** - * Whether converting one suffix record requires facts from earlier events. - * @param value - parsed event JSON from a suffix read. - * @returns whether the decoder must reopen the complete event stream. - */ - requiresPrefix(value: unknown): boolean - /** - * Convert recognized historical records into the canonical representation - * carrying the same version number. - * @param events - parsed event JSON in durable sequence order. - * @param sessionId - identity read from the stored header. - * @returns a lazy stream in the canonical representation for {@link version}. - */ - canonicalizeEvents(events: AsyncIterable, sessionId: SessionId): AsyncIterable -} - -function hasOnlyKeys( - record: Record, - required: readonly string[], - optional: readonly string[] = [], -): boolean { - const allowed = [...required, ...optional] - return Object.keys(record).every(key => allowed.includes(key)) - && required.every(key => Object.hasOwn(record, key)) -} - -type PersistedMessageId = SessionEvent<'user/message'>['data']['id'] - -function legacyMessageId(id: SessionId, seq: number): PersistedMessageId { - return `legacy-message:${id}:${seq}` as PersistedMessageId -} - -function replacementStart(event: SessionEvent): number | undefined { - const op = asStoredRecord((event as SessionEvent & { surfaceOp?: unknown }).surfaceOp) - return op?.['op'] === 'replace' && typeof op['start'] === 'number' - ? op['start'] - : undefined -} - -function requiresV0Prefix(value: unknown): boolean { - const event = asStoredRecord(value) - if (event === undefined) return false - const data = asStoredRecord(event['data']) - if (event['type'] === 'steering/message') return true - if (data === undefined) return false - switch (event['type']) { - case 'user/message': - return !Object.hasOwn(data, 'id') && Object.hasOwn(data, 'content') - case 'assistant/message': - return !Object.hasOwn(data, 'message') && Object.hasOwn(data, 'content') - case 'tool/result': - return !Object.hasOwn(data, 'message') && Object.hasOwn(data, 'callId') - default: - return false - } -} - -function readV0Event(value: unknown, id: SessionId): SessionEvent { - return readStoredEventEnvelope(value, id) -} - -/** - * PR #2302 changed these durable v0 discriminants without a format-version bump. - * @see https://github.com/deepseek-harness/deepseek-harness/pull/2302 - */ -function canonicalizeLegacyCompactionEvent(event: SessionEvent): SessionEvent { - const type: string = event.type - switch (type) { - case 'compact/start': - return { ...event, type: 'compaction/start' } as SessionEvent - case 'compact/summary': - return { ...event, type: 'compaction/summary' } as SessionEvent - case 'compact/end': - return { ...event, type: 'compaction/end' } as SessionEvent - case 'compact/prune': - return { ...event, type: 'compaction/prune' } as SessionEvent - default: - return event - } -} - -function canonicalizeLegacySteeringEvent(event: SessionEvent, id: SessionId): SessionEvent { - const legacyType: string = 'steering/message' - if (event.type !== legacyType) return event - const data = asStoredRecord(event.data) - if (data === undefined) { - throw new Error(`session "${id}" contains malformed pre-react-loop steering/message at seq ${event.seq}`) - } - const wrapped = asStoredRecord(data['message']) - if (wrapped !== undefined && Number.isSafeInteger(data['turn']) - && hasOnlyKeys(data, ['turn', 'message'])) { - return { ...event, type: 'user/message', data: wrapped } as SessionEvent - } - if (!Number.isSafeInteger(data['turn']) || !hasOnlyKeys(data, ['turn', 'content', 'source'])) { - throw new Error(`session "${id}" contains malformed pre-react-loop steering/message at seq ${event.seq}`) - } - const { turn: _turn, ...message } = data - return { - ...event, - type: 'user/message', - data: { ...message, id: legacyMessageId(id, event.seq), role: 'user' }, - } as SessionEvent -} - -function canonicalizeLegacyTurnStartEvent(event: SessionEvent, id: SessionId): SessionEvent { - if (event.type !== 'turn/start') return event - const data = asStoredRecord(event.data) - if (data === undefined || !Object.hasOwn(data, 'trigger')) return event - const trigger = asStoredRecord(data['trigger']) - if (!Number.isSafeInteger(data['turn']) || (data['turn'] as number) < 1 - || !hasOnlyKeys(data, ['turn', 'trigger']) - || trigger === undefined || typeof trigger['kind'] !== 'string' || trigger['kind'].length === 0) { - throw new Error(`session "${id}" contains malformed pre-react-loop turn/start at seq ${event.seq}`) - } - return { ...event, data: { turn: data['turn'] } } as SessionEvent -} - -function canonicalizeLegacyTurnEndEvent(event: SessionEvent, id: SessionId): SessionEvent { - if (event.type !== 'turn/end') return event - const data = asStoredRecord(event.data) - if (data === undefined) return event - const malformed = (): never => { - throw new Error(`session "${id}" contains malformed pre-react-loop turn/end at seq ${event.seq}`) - } - const reason = asStoredRecord(data['reason']) - if (!Number.isSafeInteger(data['turn']) || (data['turn'] as number) < 1 - || !hasOnlyKeys(data, ['turn', 'reason']) - || reason === undefined || typeof reason['kind'] !== 'string') return malformed() - - let currentReason: Record | undefined - switch (reason['kind']) { - case 'completed': - case 'blocked': - case 'max-tokens': - case 'interrupted': - if (!hasOnlyKeys(reason, ['kind'])) return malformed() - return event - case 'aborted': - if (Object.hasOwn(reason, 'reason')) return event - if (!hasOnlyKeys(reason, ['kind'])) return malformed() - currentReason = { kind: 'aborted', reason: { kind: 'legacy' } } - break - case 'disposed': - if (!hasOnlyKeys(reason, ['kind'])) return malformed() - currentReason = { kind: 'aborted', reason: { kind: 'disposed' } } - break - case 'error': { - if (Object.hasOwn(reason, 'error')) return event - if (!Number.isSafeInteger(reason['step']) || (reason['step'] as number) < 0) return malformed() - const failure = asStoredRecord(reason['failure']) - if (failure !== undefined && hasOnlyKeys(reason, ['kind', 'step', 'failure']) - && hasOnlyKeys(failure, ['message', 'code'], ['status', 'providerRetryAfterMs', 'requestId']) - && typeof failure['message'] === 'string' && typeof failure['code'] === 'string' - && (failure['status'] === undefined || typeof failure['status'] === 'number') - && (failure['providerRetryAfterMs'] === undefined || typeof failure['providerRetryAfterMs'] === 'number') - && (failure['requestId'] === undefined || typeof failure['requestId'] === 'string')) { - currentReason = { kind: 'error', error: failure } - break - } - const messageKeys = reason['code'] === undefined - ? ['kind', 'step', 'message'] - : ['kind', 'step', 'message', 'code'] - if (!hasOnlyKeys(reason, messageKeys) - || typeof reason['message'] !== 'string' - || (reason['code'] !== undefined && typeof reason['code'] !== 'string')) return malformed() - currentReason = { - kind: 'error', - error: { - message: reason['message'], - code: typeof reason['code'] === 'string' ? reason['code'] : 'UNKNOWN', - }, - } - break - } - default: - return event - } - return { ...event, data: { ...data, reason: currentReason } } as SessionEvent -} - -function canonicalizeLegacyMessageEvent( - event: SessionEvent, - id: SessionId, - messageIds: ReadonlyMap, -): SessionEvent { - const data = asStoredRecord(event.data) - if (data === undefined) return event - switch (event.type) { - case 'user/message': - if (Object.hasOwn(data, 'id') || Object.hasOwn(data, 'role') - || Object.hasOwn(data, 'message') - || !Object.hasOwn(data, 'content') || !Object.hasOwn(data, 'source')) return event - return { ...event, data: { ...data, id: legacyMessageId(id, event.seq), role: 'user' } } as SessionEvent - case 'assistant/message': { - if (Object.hasOwn(data, 'message') - || !Object.hasOwn(data, 'content') || !Object.hasOwn(data, 'provenance')) return event - const { content, provenance, ...eventData } = data - return { - ...event, - data: { - ...eventData, - message: { - id: legacyMessageId(id, event.seq), - role: 'assistant', - content, - source: { ...asStoredRecord(provenance), kind: 'model' }, - }, - }, - } as SessionEvent - } - case 'tool/result': { - if (Object.hasOwn(data, 'message') - || !Object.hasOwn(data, 'callId') || !Object.hasOwn(data, 'content') - || !Object.hasOwn(data, 'isError')) return event - const { callId, content, isError, ...eventData } = data - const inheritedId = replacementStart(event) - return { - ...event, - data: { - ...eventData, - message: { - id: inheritedId === undefined ? legacyMessageId(id, event.seq) : messageIds.get(inheritedId), - role: 'user', - content: [{ type: 'tool-result', toolCallId: callId, content, isError }], - source: { kind: 'tool', callId }, - }, - }, - } as SessionEvent - } - default: - return event - } -} - -function eventMessageId(event: SessionEvent): PersistedMessageId | undefined { - const data = asStoredRecord(event.data) - const message = event.type === 'user/message' ? data : asStoredRecord(data?.['message']) - return typeof message?.['id'] === 'string' ? message['id'] as PersistedMessageId : undefined -} - -async function* canonicalizeV0Events( - events: AsyncIterable, - id: SessionId, -): AsyncIterable { - const messageIds = new Map() - for await (const value of events) { - const event = readV0Event(value, id) - const compaction = canonicalizeLegacyCompactionEvent(event) - const turnStart = canonicalizeLegacyTurnStartEvent(compaction, id) - const turnEnd = canonicalizeLegacyTurnEndEvent(turnStart, id) - const steering = canonicalizeLegacySteeringEvent(turnEnd, id) - const canonical = canonicalizeLegacyMessageEvent(steering, id, messageIds) - const messageId = eventMessageId(canonical) - if (messageId !== undefined) messageIds.set(canonical.seq, messageId) - yield canonical - } -} - -/** - * Durable v0 includes first-party records whose structural changes were not - * accompanied by a format-version change. Their headers cannot select an - * adjacent-version migration, so this exact legacy recognition runs before - * any v0-to-v1 step and produces canonical v0 without changing the version. - * It remains necessary while v0 is current and whenever v0 is an upgrade - * source. Normalization alone is read-only; a selected versioned migration - * causes the canonicalized events to participate in atomic replacement. - */ -const V0_UNVERSIONED_FORMAT_COMPATIBILITY: UnversionedFormatCompatibility = Object.freeze({ - version: 0, - requiresPrefix: requiresV0Prefix, - canonicalizeEvents: canonicalizeV0Events, -}) - -/** - * Select same-version compatibility for one stored header version. - * @param version - format version read from the stored header. - * @returns the static normalizer for that version, if one is required. - */ -export function unversionedFormatCompatibility( - version: number, -): UnversionedFormatCompatibility | undefined { - return version === V0_UNVERSIONED_FORMAT_COMPATIBILITY.version - ? V0_UNVERSIONED_FORMAT_COMPATIBILITY - : undefined -} diff --git a/packages/session/session-persistence/src/index.ts b/packages/session/session-persistence/src/index.ts index 0a97fc7214..627098c648 100644 --- a/packages/session/session-persistence/src/index.ts +++ b/packages/session/session-persistence/src/index.ts @@ -9,11 +9,10 @@ import { Context, Service } from '@deepseek-ai/cordis' import { SessionPreparation } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session' import type { SessionPersistenceRevision } from './revision.ts' -import { createStoredEventRead, type StoredEventRead } from './format-decoder.ts' // Re-export the metadata vocabulary so Consumers import it from the Service Definition. export type { SessionHeader } from '@deepseek-ai/dsh-session' -export { SessionPersistenceRevision, SessionPersistenceRevisionConflictError } from './revision.ts' +export { SessionPersistenceRevision } from './revision.ts' export { SessionPersistenceNotFoundError } from './errors.ts' /** Lightweight immutable source identity returned without loading a full log. */ @@ -68,18 +67,17 @@ export { DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, PersistenceCoordinator, + SessionFormatUnsupportedError, SessionPersistenceCorruptionError, + sessionFormatVersionRefusal, } from './coordinator.ts' export type { PersistenceBackend, PersistenceCoordinatorOptions, + StoredPrefix, + StoredSuffix, } from './coordinator.ts' -export { - createStoredEventRead, - decodeStoredSessionHeader, - SessionFormatUnsupportedError, - sessionFormatVersionRefusal, -} from './format-decoder.ts' + declare module '@deepseek-ai/cordis' { interface Context { sessionPersistence: SessionPersistence @@ -109,21 +107,6 @@ export abstract class SessionPersistence extends Service { super(ctx, 'sessionPersistence') } - /** - * Build the standard lazy event stream and EOF metadata around one backend read. - * @param load - revision-checked batch loader owned by the backend. - * @param include - whether one loaded event belongs in this physical read. - * @param signal - optional cancellation checked between yielded events. - * @returns an independently consumable event read. - */ - protected createStoredEventRead( - load: () => Promise<{ readonly events: readonly unknown[]; readonly tornMarker?: TornMarker }>, - include: (event: unknown) => boolean, - signal?: AbortSignal, - ): StoredEventRead { - return createStoredEventRead(load, include, signal) - } - /** * Resolve this backend's independent local artifact for a session without * reading, creating, flushing, or otherwise materializing it. Backends such @@ -300,11 +283,3 @@ export abstract class SessionPersistence extends Service { } export default SessionPersistence - -export type { - SessionFormatMigration, - StoredEventRead, - StoredEventReadCompletion, - StoredEventReadOptions, - StoredSessionSource, -} from './format-decoder.ts' diff --git a/packages/session/session-persistence/src/revision.ts b/packages/session/session-persistence/src/revision.ts index 36a79291b3..cb037ffafc 100644 --- a/packages/session/session-persistence/src/revision.ts +++ b/packages/session/session-persistence/src/revision.ts @@ -16,12 +16,3 @@ export type SessionPersistenceRevision = Branded<'SessionPersistenceRevision'> export function SessionPersistenceRevision(value: string): SessionPersistenceRevision { return value as SessionPersistenceRevision } - -/** A repeatable source can no longer reproduce the revision it represents. */ -export class SessionPersistenceRevisionConflictError extends Error { - /** @param message - source identity and expected revision context. */ - constructor(message: string) { - super(message) - this.name = 'SessionPersistenceRevisionConflictError' - } -} diff --git a/packages/session/session-persistence/tests/format-decoder.spec.ts b/packages/session/session-persistence/tests/format-decoder.spec.ts deleted file mode 100644 index 5b80ac15c6..0000000000 --- a/packages/session/session-persistence/tests/format-decoder.spec.ts +++ /dev/null @@ -1,1101 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { SessionId } from '@deepseek-ai/dsh-session' -import type { SessionEvent } from '@deepseek-ai/dsh-session' -import { - SessionPersistenceRevision, - SessionPersistenceRevisionConflictError, -} from '../src/revision.ts' -import type { - SessionFormatMigration, - StoredEventReadCompletion, - StoredSessionSource, -} from '../src/format-decoder.ts' -import { sessionFormatVersionRefusal } from '../src/format-decoder.ts' -import { unversionedFormatCompatibility } from '../src/format-v0-compat.ts' - -const id = SessionId('format-migration') -type SessionFormatMigrationInstance = InstanceType - -function eventLog(): SessionEvent[] { - return [ - { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, - { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } }, - ] -} - -async function collectEvents(events: AsyncIterable): Promise { - const collected: SessionEvent[] = [] - for await (const event of events) collected.push(event) - return collected -} - -async function decodedFailure( - decoded: ReturnType, -): Promise { - const completion = decoded.completed.catch((error: unknown) => error) - const consumption = collectEvents(decoded.events).catch((error: unknown) => error) - const [streamFailure, completionFailure] = await Promise.all([consumption, completion]) - expect(streamFailure).toBe(completionFailure) - expect(streamFailure).toBeInstanceOf(Error) - return streamFailure as Error -} - -function storedSource( - version: number, - events: readonly unknown[], -): { source: StoredSessionSource; reads: number[]; meta: Record } { - const reads: number[] = [] - const meta: Record = { version, id, createdAt: 1 } - return { - meta, - reads, - source: { - meta, - revision: SessionPersistenceRevision(`format-v${version}`), - readEvents({ fromSeq = 0 } = {}) { - reads.push(fromSeq) - return { - events: (async function* (): AsyncIterable { - for (const event of events) { - const seq = typeof event === 'object' && event !== null - ? (event as { seq?: unknown }).seq - : undefined - if (!Number.isSafeInteger(seq) || (seq as number) < 0 || (seq as number) >= fromSeq) { - yield structuredClone(event) - } - } - })(), - completed: Promise.resolve({}), - } - }, - }, - } -} - -function defineMigration( - from: number, - create: () => SessionFormatMigrationInstance, - to = from + 1, -): SessionFormatMigration { - return class implements SessionFormatMigrationInstance { - static readonly from = from - static readonly to = to - - private readonly delegate = create() - - header(meta: unknown): unknown { - return this.delegate.header(meta) - } - - event(value: unknown): unknown { - return this.delegate.event(value) - } - - finish(): void { - this.delegate.finish?.() - } - } -} - -function migration( - from: number, - calls: string[], - to = from + 1, -): SessionFormatMigration { - return defineMigration(from, () => { - let observedInput = false - return { - header(meta) { - calls.push(`header:${from}`) - return { ...(meta as Record), version: to } - }, - event(value) { - if (!observedInput) { - calls.push(`events:${from}`) - observedInput = true - } - const event = value as SessionEvent - const data = event.data as Record - const migrationPath = Array.isArray(data['migrationPath']) - ? data['migrationPath'] as unknown[] - : [] - return { - ...event, - data: { - ...data, - [`migratedFrom${from}`]: true, - migrationPath: [...migrationPath, from], - }, - } - }, - } - }, to) -} - -async function configuredDecoder( - currentVersion: number, - migrations: readonly SessionFormatMigration[], - calls: string[] = [], -): Promise<{ - decodeStoredSession: typeof import('../src/format-decoder.ts')['decodeStoredSession'] - decodeStoredSessionHeader: typeof import('../src/format-decoder.ts')['decodeStoredSessionHeader'] - validateHeader: ReturnType -}> { - vi.resetModules() - const validateHeader = vi.fn((sessionId: SessionId, _seed: unknown, meta: unknown) => { - calls.push('validate-header') - const record = meta as Record - if (record['version'] !== currentVersion) { - throw new Error(`current header validator received v${String(record['version'])}`) - } - if (record['id'] !== sessionId) throw new Error('current header validator received the wrong id') - if (!Number.isSafeInteger(record['createdAt'])) { - throw new Error('current header validator received invalid createdAt') - } - return { header: Object.freeze(structuredClone(record)) } - }) - vi.doMock('@deepseek-ai/dsh-session', async () => { - const actual = await vi.importActual( - '@deepseek-ai/dsh-session', - ) - return { - ...actual, - SESSION_FORMAT_VERSION: currentVersion, - Session: { create: validateHeader }, - } - }) - vi.doMock('../src/format-migrations/index.ts', () => ({ - SESSION_FORMAT_MIGRATIONS: migrations, - })) - const decoder = await import('../src/format-decoder.ts') - return { - decodeStoredSession: decoder.decodeStoredSession, - decodeStoredSessionHeader: decoder.decodeStoredSessionHeader, - validateHeader, - } -} - -afterEach(() => { - vi.doUnmock('@deepseek-ai/dsh-session') - vi.doUnmock('../src/format-migrations/index.ts') - vi.resetModules() -}) - -describe('versioned Session format decoder', { concurrent: false }, () => { - it('describes both unsupported format directions', () => { - expect(sessionFormatVersionRefusal(id, 1)).toContain('newer harness') - expect(sessionFormatVersionRefusal(id, -1)).toContain('older than the supported') - }) - - it('runs a single migration lazily and reads the complete old log before slicing', async () => { - const calls: string[] = [] - const step = migration(0, calls) - const { decodeStoredSession, validateHeader } = await configuredDecoder(1, [step], calls) - const originalEvents = eventLog() - const originalSnapshot = structuredClone(originalEvents) - const stored = storedSource(0, originalEvents) - - const decoded = decodeStoredSession(stored.source, id, 1) - expect(decoded.sourceVersion).toBe(0) - expect(decoded.meta.version).toBe(1) - expect(calls).toEqual(['header:0', 'validate-header']) - expect(stored.reads).toEqual([]) - - const migrated = await collectEvents(decoded.events) - await decoded.completed - - expect(stored.reads).toEqual([0]) - expect(calls).toEqual(['header:0', 'validate-header', 'events:0']) - expect(migrated).toEqual([ - { - ...originalEvents[1], - data: { ...originalEvents[1]?.data, migratedFrom0: true, migrationPath: [0] }, - }, - ]) - expect(originalEvents).toEqual(originalSnapshot) - expect(stored.meta).toEqual({ version: 0, id, createdAt: 1 }) - expect(validateHeader).toHaveBeenCalledOnce() - }) - - it('lets an old-format suffix migration use facts from events before fromSeq', async () => { - const step = defineMigration(0, () => { - let previousSeq: number | undefined - return { - header: meta => ({ ...(meta as Record), version: 1 }), - event(value) { - const event = value as SessionEvent - const migrated = previousSeq === undefined - ? event - : { ...event, data: { ...event.data, previousSeq } } - previousSeq = event.seq - return migrated - }, - } - }) - const { decodeStoredSession } = await configuredDecoder(1, [step]) - const stored = storedSource(0, eventLog()) - - const decoded = decodeStoredSession(stored.source, id, 1) - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(stored.reads).toEqual([0]) - expect(events).toEqual([{ - ...eventLog()[1], - data: { ...eventLog()[1]?.data, previousSeq: 0 }, - }]) - }) - - it('streams migrated events with backpressure instead of buffering the complete log', async () => { - const releaseTail = Promise.withResolvers() - const physicalCompletion = Promise.withResolvers>() - const reads: number[] = [] - const source: StoredSessionSource = { - meta: { version: 0, id, createdAt: 1 }, - revision: SessionPersistenceRevision('streaming-source'), - readEvents({ fromSeq = 0 } = {}) { - reads.push(fromSeq) - return { - events: (async function* (): AsyncIterable { - try { - yield structuredClone(eventLog()[0]) - await releaseTail.promise - yield structuredClone(eventLog()[1]) - physicalCompletion.resolve({}) - } catch (error: unknown) { - physicalCompletion.reject(error) - throw error - } - })(), - completed: physicalCompletion.promise, - } - }, - } - const { decodeStoredSession } = await configuredDecoder(1, [migration(0, [])]) - const decoded = decodeStoredSession(source, id) - const iterator = decoded.events[Symbol.asyncIterator]() - - const first = await iterator.next() - expect(first).toMatchObject({ done: false, value: { seq: 0 } }) - expect(reads).toEqual([0]) - let completed = false - void decoded.completed.then(() => { completed = true }) - await Promise.resolve() - expect(completed).toBe(false) - - releaseTail.resolve(undefined) - await expect(iterator.next()).resolves.toMatchObject({ done: false, value: { seq: 1 } }) - await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined }) - await expect(decoded.completed).resolves.toEqual({}) - }) - - it('runs a complete multi-step chain before current header and event validation', async () => { - const calls: string[] = [] - const { decodeStoredSession } = await configuredDecoder( - 2, - [migration(0, calls), migration(1, calls)], - calls, - ) - const stored = storedSource(0, eventLog()) - - const decoded = decodeStoredSession(stored.source, id) - expect(decoded.meta.version).toBe(2) - expect(calls).toEqual(['header:0', 'header:1', 'validate-header']) - - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(calls).toEqual([ - 'header:0', - 'header:1', - 'validate-header', - 'events:0', - 'events:1', - ]) - expect(events[0]?.data).toMatchObject({ migratedFrom0: true, migratedFrom1: true }) - expect(events[0]?.data).toMatchObject({ migrationPath: [0, 1] }) - }) - - it('detaches each migration output before the next migration mutates its input', async () => { - const retained: Array> = [] - const first = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 1 }), - event(value) { - const event = value as SessionEvent - const output = { - ...event, - data: { ...(event.data as Record), first: true }, - } - retained.push(output.data) - return output - }, - })) - const second = defineMigration(1, () => ({ - header: meta => ({ ...(meta as Record), version: 2 }), - event(value) { - const event = value as SessionEvent - const data = event.data as Record - data['second'] = true - return event - }, - })) - const { decodeStoredSession } = await configuredDecoder(2, [first, second]) - - const decoded = decodeStoredSession(storedSource(0, eventLog()).source, id) - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(events.every(event => (event.data as Record)['second'] === true)).toBe(true) - expect(retained.every(data => data['second'] === undefined)).toBe(true) - }) - - it('rejects a non-JSON event output before a later migration can repair it', async () => { - const first = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 1 }), - event(value) { - const event = value as SessionEvent - return { - ...event, - data: { ...(event.data as Record), transient: undefined }, - } - }, - })) - const second = defineMigration(1, () => ({ - header: meta => ({ ...(meta as Record), version: 2 }), - event(value) { - const event = value as SessionEvent - const data = event.data as Record - delete data['transient'] - return event - }, - })) - const { decodeStoredSession } = await configuredDecoder(2, [first, second]) - - const failure = await decodedFailure( - decodeStoredSession(storedSource(0, eventLog()).source, id), - ) - - expect(failure.message).toMatch(/event migration v0 -> v1 failed at seq 0/) - expect((failure.cause as Error).message).toMatch(/not losslessly JSON-serializable/) - }) - - it('plans by version even when registry entries are declared out of order', async () => { - const calls: string[] = [] - const { decodeStoredSession } = await configuredDecoder( - 2, - [migration(1, calls), migration(0, calls)], - calls, - ) - - const decoded = decodeStoredSession(storedSource(0, eventLog()).source, id) - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(calls.slice(0, 3)).toEqual(['header:0', 'header:1', 'validate-header']) - expect(events[0]?.data).toMatchObject({ migrationPath: [0, 1] }) - }) - - it('starts a multi-version registry at the source version', async () => { - const calls: string[] = [] - const { decodeStoredSession } = await configuredDecoder( - 2, - [migration(0, calls), migration(1, calls)], - calls, - ) - const stored = storedSource(1, eventLog()) - - const decoded = decodeStoredSession(stored.source, id, 1) - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(calls).toEqual(['header:1', 'validate-header', 'events:1']) - expect(stored.reads).toEqual([0]) - expect(events[0]?.data).toMatchObject({ migrationPath: [1] }) - }) - - it('retains instance state from the header through events and finishes at EOF', async () => { - const calls: string[] = [] - const Migration = defineMigration(0, () => { - let headerId: SessionId | undefined - let migratedEvents = 0 - return { - header(meta) { - calls.push('header') - headerId = SessionId((meta as Record)['id'] as string) - return { ...(meta as Record), version: 1 } - }, - event(value) { - calls.push(`event:${migratedEvents}`) - migratedEvents += 1 - return { - ...(value as SessionEvent), - data: { ...(value as SessionEvent).data, headerId, migratedEvents }, - } - }, - finish() { - calls.push(`finish:${migratedEvents}`) - }, - } - }) - const { decodeStoredSession } = await configuredDecoder(1, [Migration]) - - const decoded = decodeStoredSession(storedSource(0, eventLog()).source, id) - expect(calls).toEqual(['header']) - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(calls).toEqual(['header', 'event:0', 'event:1', 'finish:2']) - expect(events.map(event => event.data)).toMatchObject([ - { headerId: id, migratedEvents: 1 }, - { headerId: id, migratedEvents: 2 }, - ]) - }) - - it('migrates and validates a header without requiring an event source', async () => { - const calls: string[] = [] - const first = defineMigration(0, () => ({ - header(meta) { - calls.push('header:0') - return { ...(meta as Record), version: 1 } - }, - event: value => value, - finish() { - calls.push('finish:0') - }, - })) - const { decodeStoredSessionHeader } = await configuredDecoder( - 2, - [first, migration(1, calls)], - calls, - ) - - const header = decodeStoredSessionHeader({ version: 0, id, createdAt: 1 }, id) - - expect(header.version).toBe(2) - expect(calls).toEqual(['header:0', 'header:1', 'validate-header']) - }) - - it('allows a migration instance without finish', async () => { - class MigrationWithoutFinish implements SessionFormatMigrationInstance { - static readonly from = 0 - static readonly to = 1 - - header(meta: unknown): unknown { - return { ...(meta as Record), version: 1 } - } - - event(value: unknown): unknown { - return value - } - } - const { decodeStoredSession } = await configuredDecoder(1, [MigrationWithoutFinish]) - - const decoded = decodeStoredSession(storedSource(0, eventLog()).source, id) - - await expect(collectEvents(decoded.events)).resolves.toEqual(eventLog()) - await expect(decoded.completed).resolves.toEqual({}) - }) - - it('applies event migration before the current event vocabulary check', async () => { - const step = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 1 }), - event(value) { - const event = value as Record - return { ...event, type: 'turn/start', data: { turn: 1 } } - }, - })) - const { decodeStoredSession } = await configuredDecoder(1, [step]) - const stored = storedSource(0, [ - { type: 'legacy/turn-begin', seq: 0, time: 1, data: { legacyTurn: 1 } }, - ]) - - const decoded = decodeStoredSession(stored.source, id) - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(events).toEqual([ - { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, - ]) - }) - - it('uses suffix access directly for the current format', async () => { - const { decodeStoredSession } = await configuredDecoder(2, []) - const stored = storedSource(2, eventLog()) - - const decoded = decodeStoredSession(stored.source, id, 1) - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(stored.reads).toEqual([1]) - expect(events).toEqual(eventLog().slice(1)) - }) - - it('buffers a safe current-v0 suffix once without reopening the prefix', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const stored = storedSource(0, eventLog()) - - const decoded = decodeStoredSession(stored.source, id, 1) - expect(await collectEvents(decoded.events)).toEqual(eventLog().slice(1)) - await expect(decoded.completed).resolves.toEqual({}) - - expect(stored.reads).toEqual([1]) - }) - - it('reopens the complete current-v0 log when a legacy suffix record needs its prefix', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const legacy = [ - { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, - { - type: 'steering/message', - seq: 1, - time: 2, - data: { turn: 1, content: [{ type: 'text', text: 'continue' }], source: { kind: 'user' } }, - }, - ] - const stored = storedSource(0, legacy) - - const decoded = decodeStoredSession(stored.source, id, 1) - const events = await collectEvents(decoded.events) - await decoded.completed - - expect(stored.reads).toEqual([1, 0]) - expect(events).toMatchObject([{ type: 'user/message', seq: 1 }]) - }) - - it('observes a failed physical completion after reopening a required v0 prefix', async () => { - const failure = new SessionPersistenceRevisionConflictError('reopened prefix changed') - const fullCompletion = Promise.withResolvers>() - const source: StoredSessionSource = { - meta: { version: 0, id, createdAt: 1 }, - revision: SessionPersistenceRevision('prefix-conflict'), - readEvents({ fromSeq = 0 } = {}) { - if (fromSeq > 0) { - return { - events: (async function* (): AsyncIterable { - yield { - type: 'steering/message', seq: 1, time: 2, - data: { turn: 1, content: [], source: { kind: 'user' } }, - } - })(), - completed: Promise.resolve({}), - } - } - return { - events: (async function* (): AsyncIterable { - fullCompletion.reject(failure) - throw failure - })(), - completed: fullCompletion.promise, - } - }, - } - const { decodeStoredSession } = await configuredDecoder(0, []) - const decoded = decodeStoredSession(source, id, 1) - - await expect(decodedFailure(decoded)).resolves.toBe(failure) - }) - - it('classifies every v0 prefix-independent suffix value without assuming a record', () => { - const compatibility = unversionedFormatCompatibility(0) - if (compatibility === undefined) throw new Error('v0 compatibility must be registered') - - expect(compatibility.requiresPrefix(null)).toBe(false) - expect(compatibility.requiresPrefix({ type: 'turn/end', data: null })).toBe(false) - expect(compatibility.requiresPrefix({ type: 'user/message', data: { id: 'current', content: [] } })).toBe(false) - expect(compatibility.requiresPrefix({ type: 'user/message', data: { content: [] } })).toBe(true) - expect(compatibility.requiresPrefix({ type: 'assistant/message', data: { content: [] } })).toBe(true) - expect(compatibility.requiresPrefix({ type: 'tool/result', data: { callId: 'call' } })).toBe(true) - }) - - it('preserves already-canonical v0 turn-end reasons', async () => { - const compatibility = unversionedFormatCompatibility(0) - if (compatibility === undefined) throw new Error('v0 compatibility must be registered') - const events = [ - { - type: 'turn/end', seq: 0, time: 1, - data: { turn: 1, reason: { kind: 'aborted', reason: { kind: 'disposed' } } }, - }, - { - type: 'turn/end', seq: 1, time: 2, - data: { turn: 2, reason: { kind: 'error', error: { message: 'failed', code: 'UNKNOWN' } } }, - }, - ] - const input = (async function* (): AsyncIterable { - yield* events - })() - const canonical: unknown[] = [] - - for await (const event of compatibility.canonicalizeEvents(input, id)) canonical.push(event) - - expect(canonical).toEqual(events) - }) - - it('canonicalizes every historical compact event name without changing its record', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const events = [ - { - type: 'compact/start', seq: 0, time: 1, - data: { compactionId: 'legacy', turn: 1 }, - surfaceOp: { op: 'retain' }, - }, - { - type: 'compact/summary', seq: 1, time: 2, - data: { summary: 'old summary', shadowedSeqs: [7, 8] }, - durableMetadata: { source: 'historical-v0' }, - }, - { - type: 'compaction/end', seq: 2, time: 3, - data: { compactionId: 'current', turn: 1 }, - }, - { - type: 'compact/end', seq: 3, time: 4, - data: { compactionId: 'legacy', turn: 1 }, - }, - { - type: 'compact/prune', seq: 4, time: 5, - data: { - shadowedRange: { start: 7, end: 8 }, - shadowedSeqs: [7, 8], - shadowedTokenCount: 456, - }, - }, - ] - const stored = storedSource(0, events) - - const decoded = decodeStoredSession(stored.source, id) - const canonical = await collectEvents(decoded.events) - await decoded.completed - - expect(canonical).toEqual(events.map(event => ({ - ...event, - type: event.type.replace(/^compact\//, 'compaction/'), - }))) - expect(stored.reads).toEqual([0]) - }) - - it('still rejects other unknown v0 event names after compaction normalization', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const decoded = decodeStoredSession(storedSource(0, [{ - type: 'compact/future', seq: 0, time: 1, data: {}, - }]).source, id) - - const failure = await decodedFailure(decoded) - expect(failure.message).toMatch(/event type "compact\/future".*not marked ignorable/) - }) - - it('does not run older registered steps for an already-current source', async () => { - const calls: string[] = [] - const { decodeStoredSession } = await configuredDecoder( - 2, - [migration(0, calls), migration(1, calls)], - calls, - ) - const stored = storedSource(2, eventLog()) - - const decoded = decodeStoredSession(stored.source, id, 1) - await collectEvents(decoded.events) - await decoded.completed - - expect(calls).toEqual(['validate-header']) - expect(stored.reads).toEqual([1]) - }) - - it('opens a fresh revision-bound reader for each decode of the same source', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const stored = storedSource(0, eventLog()) - - const first = decodeStoredSession(stored.source, id) - expect(await collectEvents(first.events)).toEqual(eventLog()) - await first.completed - const second = decodeStoredSession(stored.source, id) - expect(await collectEvents(second.events)).toEqual(eventLog()) - await second.completed - - expect(first.revision).toBe(second.revision) - expect(stored.reads).toEqual([0, 0]) - }) - - it('propagates a physical revision conflict unchanged through events and completion', async () => { - const failure = new SessionPersistenceRevisionConflictError('source changed') - const physicalCompletion = Promise.withResolvers>() - const source: StoredSessionSource = { - meta: { version: 0, id, createdAt: 1 }, - revision: SessionPersistenceRevision('conflicting-source'), - readEvents: () => ({ - events: (async function* (): AsyncIterable { - physicalCompletion.reject(failure) - throw failure - })(), - completed: physicalCompletion.promise, - }), - } - const { decodeStoredSession } = await configuredDecoder(0, []) - const decoded = decodeStoredSession(source, id) - const completion = decoded.completed.catch((error: unknown) => error) - const consumption = collectEvents(decoded.events).catch((error: unknown) => error) - - const [streamFailure, completionFailure] = await Promise.all([consumption, completion]) - expect(streamFailure).toBe(failure) - expect(completionFailure).toBe(failure) - }) - - it('propagates an upstream revision conflict unchanged through a migration step', async () => { - const { decodeStoredSession } = await configuredDecoder(1, [migration(0, [])]) - const { SessionPersistenceRevisionConflictError: DecoderRevisionConflictError } = await import('../src/revision.ts') - const failure = new DecoderRevisionConflictError('migrating source changed') - const source: StoredSessionSource = { - meta: { version: 0, id, createdAt: 1 }, - revision: SessionPersistenceRevision('conflicting-migration-source'), - readEvents: () => ({ - events: (async function* (): AsyncIterable { - throw failure - })(), - completed: Promise.reject(failure), - }), - } - await expect(decodedFailure(decodeStoredSession(source, id))).resolves.toBe(failure) - }) - - it('rejects a missing path and a future source in the correct direction', async () => { - const { decodeStoredSession, validateHeader } = await configuredDecoder(2, []) - const old = storedSource(0, []) - const future = storedSource(3, []) - - expect(() => decodeStoredSession(old.source, id)) - .toThrow(/missing v0 -> v1/) - expect(() => decodeStoredSession(future.source, id)) - .toThrow(/newer harness/) - expect(old.reads).toEqual([]) - expect(future.reads).toEqual([]) - expect(validateHeader).not.toHaveBeenCalled() - }) - - it('preserves the raw location in unsupported-format diagnostics', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const stored = storedSource(1, []) - const location = { kind: 'jsonl', path: '/tmp/session.jsonl' } - const source: StoredSessionSource = { ...stored.source, location } - - let failure: unknown - try { - decodeStoredSession(source, id) - } catch (error: unknown) { - failure = error - } - expect(failure).toMatchObject({ - name: 'SessionFormatUnsupportedError', - location, - }) - expect((failure as Error).message).toContain('(raw log: /tmp/session.jsonl)') - }) - - it('rejects an invalid suffix before validating the header or opening events', async () => { - const { decodeStoredSession, validateHeader } = await configuredDecoder(0, []) - const stored = storedSource(0, eventLog()) - - for (const fromSeq of [-1, 1.5, Number.MAX_SAFE_INTEGER + 1]) { - expect(() => decodeStoredSession(stored.source, id, fromSeq)) - .toThrow(/fromSeq must be a non-negative safe integer/) - } - expect(validateHeader).not.toHaveBeenCalled() - expect(stored.reads).toEqual([]) - }) - - it('validates unknown durable header fields before path selection', async () => { - const { decodeStoredSession, validateHeader } = await configuredDecoder(0, []) - const cases: Array<{ meta: unknown; message: RegExp }> = [ - { meta: null, message: /header is not a lossless JSON record/ }, - { meta: { version: '0', id }, message: /invalid format version/ }, - { meta: { version: 0, id: 42 }, message: /has no string id/ }, - ] - let reads = 0 - - for (const entry of cases) { - const source: StoredSessionSource = { - meta: entry.meta, - revision: SessionPersistenceRevision('invalid-header'), - readEvents: () => { - reads += 1 - return { events: (async function* () {})(), completed: Promise.resolve({}) } - }, - } - expect(() => decodeStoredSession(source, id)).toThrow(entry.message) - } - expect(reads).toBe(0) - expect(validateHeader).not.toHaveBeenCalled() - }) - - it('rejects every malformed current event envelope through the stream and completion', async () => { - const { decodeStoredSession } = await configuredDecoder(1, []) - const cases: Array<{ value: unknown; message: RegExp }> = [ - { value: null, message: /non-record event/ }, - { value: { seq: 0, time: 1, data: {} }, message: /without a string type/ }, - { value: { type: 'turn/start', seq: -1, time: 1, data: {} }, message: /invalid seq -1/ }, - { value: { type: 'turn/start', seq: 0, time: 'now', data: {} }, message: /invalid time/ }, - { value: { type: 'turn/start', seq: 0, time: 1 }, message: /without data/ }, - ] - - for (const entry of cases) { - const decoded = decodeStoredSession(storedSource(1, [entry.value]).source, id) - expect((await decodedFailure(decoded)).message).toMatch(entry.message) - } - }) - - it('rejects a stored event that cannot be represented as JSON', async () => { - const { decodeStoredSession } = await configuredDecoder(1, []) - const decoded = decodeStoredSession(storedSource(1, [undefined]).source, id) - - expect((await decodedFailure(decoded)).message).toMatch(/not losslessly JSON-serializable/) - }) - - it('rejects every malformed v0 event before same-version canonicalization', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const cases: Array<{ value: unknown; message: RegExp }> = [ - { value: null, message: /non-record event/ }, - { value: { seq: 0, time: 1, data: {} }, message: /without a string type/ }, - { value: { type: 'turn/start', seq: -1, time: 1, data: {} }, message: /invalid seq -1/ }, - { value: { type: 'turn/start', seq: 0, time: 'now', data: {} }, message: /invalid time/ }, - { value: { type: 'turn/start', seq: 0, time: 1 }, message: /without data/ }, - ] - - for (const entry of cases) { - const decoded = decodeStoredSession(storedSource(0, [entry.value]).source, id) - expect((await decodedFailure(decoded)).message).toMatch(entry.message) - } - }) - - it('lets a v0 turn/end with opaque data reach current validation unchanged', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const decoded = decodeStoredSession(storedSource(0, [ - { type: 'turn/end', seq: 0, time: 1, data: null }, - ]).source, id) - - await expect(collectEvents(decoded.events)).resolves.toEqual([ - { type: 'turn/end', seq: 0, time: 1, data: null }, - ]) - await expect(decoded.completed).resolves.toEqual({}) - }) - - it('rejects a migration that returns the wrong header version', async () => { - const bad = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 0 }), - event: value => value, - })) - const first = await configuredDecoder(1, [bad]) - - expect(() => first.decodeStoredSession(storedSource(0, []).source, id)) - .toThrow(/returned header version 0/) - expect(first.validateHeader).not.toHaveBeenCalled() - - const calls: string[] = [] - const badSecond = defineMigration(1, () => ({ - header: meta => ({ ...(meta as Record), version: 1 }), - event: value => value, - })) - const second = await configuredDecoder(2, [migration(0, calls), badSecond], calls) - const stored = storedSource(0, []) - expect(() => second.decodeStoredSession(stored.source, id)) - .toThrow(/v1 -> v2 returned header version 1/) - expect(calls).toEqual(['header:0']) - expect(second.validateHeader).not.toHaveBeenCalled() - expect(stored.reads).toEqual([]) - }) - - it('rejects a migration that changes the session id or cwd storage identity', async () => { - const changedId = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 1, id: 'other' }), - event: value => value, - })) - const first = await configuredDecoder(1, [changedId]) - expect(() => first.decodeStoredSession(storedSource(0, []).source, id)) - .toThrow(/changed session storage identity/) - - const changedCwd = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 1, cwd: '/other' }), - event: value => value, - })) - const second = await configuredDecoder(1, [changedCwd]) - const stored = storedSource(0, []) - stored.meta['cwd'] = '/work' - expect(() => second.decodeStoredSession(stored.source, id)) - .toThrow(/changed session storage identity/) - }) - - it('wraps a header migration failure with the failing version step', async () => { - const cause = new Error('bad legacy header') - const step = defineMigration(0, () => ({ - header: () => { throw cause }, - event: value => value, - })) - const { decodeStoredSession } = await configuredDecoder(1, [step]) - - let failure: unknown - try { - decodeStoredSession(storedSource(0, []).source, id) - } catch (error: unknown) { - failure = error - } - expect(failure).toMatchObject({ - message: `session "${id}" header migration v0 -> v1 failed`, - cause, - }) - }) - - it('mirrors an event migration failure through the stream and completion promise', async () => { - const cause = new Error('bad legacy event') - const step = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 1 }), - event: () => { throw cause }, - })) - const { decodeStoredSession } = await configuredDecoder(1, [step]) - const decoded = decodeStoredSession(storedSource(0, eventLog()).source, id) - const completion = decoded.completed.catch((error: unknown) => error) - const consumption = collectEvents(decoded.events).catch((error: unknown) => error) - - const [streamFailure, completionFailure] = await Promise.all([consumption, completion]) - expect(streamFailure).toBe(completionFailure) - expect(streamFailure).toMatchObject({ - message: `session "${id}" event migration v0 -> v1 failed at seq 0`, - cause, - }) - }) - - it('mirrors a finish failure through the stream and completion promise', async () => { - const cause = new Error('unclosed legacy state') - const Migration = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 1 }), - event: value => value, - finish: () => { throw cause }, - })) - const { decodeStoredSession } = await configuredDecoder(1, [Migration]) - - const failure = await decodedFailure(decodeStoredSession(storedSource(0, eventLog()).source, id)) - expect(failure).toMatchObject({ - message: `session "${id}" event migration v0 -> v1 failed at EOF`, - cause, - }) - }) - - it('rejects a migration that changes an event sequence number', async () => { - const step = defineMigration(0, () => ({ - header: meta => ({ ...(meta as Record), version: 1 }), - event(value) { - const event = value as SessionEvent - return { ...event, seq: event.seq + 1 } - }, - })) - const { decodeStoredSession } = await configuredDecoder(1, [step]) - const decoded = decodeStoredSession(storedSource(0, eventLog()).source, id) - const completion = decoded.completed.catch((error: unknown) => error) - const consumption = collectEvents(decoded.events).catch((error: unknown) => error) - - const [streamFailure, completionFailure] = await Promise.all([consumption, completion]) - expect(streamFailure).toBe(completionFailure) - expect((streamFailure as Error).message).toMatch(/changed event seq 0 to 1/) - }) - - it('rejects a non-contiguous current-format event sequence', async () => { - const { decodeStoredSession } = await configuredDecoder(0, []) - const stored = storedSource(0, [ - { type: 'turn/start', seq: 1, time: 1, data: { turn: 1 } }, - ]) - - const failure = await decodedFailure(decodeStoredSession(stored.source, id)) - - expect(failure.message).toContain(`session "${id}" event seq mismatch: expected 0, got 1`) - }) - - it('runs current header validation only after the final header step', async () => { - const calls: string[] = [] - const finalStep = defineMigration(1, () => ({ - header(meta) { - calls.push('header:1') - const { createdAt: _createdAt, ...rest } = meta as Record - return { ...rest, version: 2 } - }, - event: value => value, - })) - const { decodeStoredSession } = await configuredDecoder( - 2, - [migration(0, calls), finalStep], - calls, - ) - const stored = storedSource(0, eventLog()) - - expect(() => decodeStoredSession(stored.source, id)) - .toThrow(/current header validator received invalid createdAt/) - expect(calls).toEqual(['header:0', 'header:1', 'validate-header']) - expect(stored.reads).toEqual([]) - }) - - it('detaches stored header and event objects before a mutating migration runs', async () => { - const originalEvents = eventLog() - const eventSnapshot = structuredClone(originalEvents) - const step = defineMigration(0, () => ({ - header(meta) { - const record = meta as Record - record['version'] = 1 - return record - }, - event(value) { - const event = value as SessionEvent - const data = event.data as Record - data['mutated'] = true - return event - }, - })) - const { decodeStoredSession } = await configuredDecoder(1, [step]) - const stored = storedSource(0, originalEvents) - - const decoded = decodeStoredSession(stored.source, id) - const migrated = await collectEvents(decoded.events) - await decoded.completed - - expect(migrated.every(event => (event.data as Record)['mutated'] === true)).toBe(true) - expect(stored.meta).toEqual({ version: 0, id, createdAt: 1 }) - expect(originalEvents).toEqual(eventSnapshot) - }) - - it('rejects duplicate, invalid, and future-targeting static registries at initialization', async () => { - const calls: string[] = [] - await expect(configuredDecoder(1, [migration(0, calls), migration(0, calls)])) - .rejects.toThrow(/duplicate Session format migration/) - - await expect(configuredDecoder(1, [migration(-1, calls)])) - .rejects.toThrow(/adjacent non-negative version/) - - const nonAdjacent = migration(0, calls, 2) - await expect(configuredDecoder(2, [nonAdjacent])) - .rejects.toThrow(/adjacent non-negative version/) - - const fractional = migration(0.5, calls, 1.5) - await expect(configuredDecoder(2, [fractional])) - .rejects.toThrow(/adjacent non-negative version/) - - await expect(configuredDecoder(1, [migration(1, calls)])) - .rejects.toThrow(/targets a version newer than this build/) - }) - - it('initializes with a gapped registry and refuses only sessions at or below the gap', async () => { - const calls: string[] = [] - const { decodeStoredSession } = await configuredDecoder( - 3, - [migration(0, calls), migration(2, calls)], - calls, - ) - const current = storedSource(3, []) - const pastGap = storedSource(2, eventLog()) - const atGap = storedSource(1, eventLog()) - const belowGap = storedSource(0, eventLog()) - - expect(decodeStoredSession(current.source, id).meta.version).toBe(3) - const decoded = decodeStoredSession(pastGap.source, id) - expect(decoded.sourceVersion).toBe(2) - expect(decoded.meta.version).toBe(3) - expect(() => decodeStoredSession(atGap.source, id)) - .toThrow(/missing v1 -> v2/) - expect(() => decodeStoredSession(belowGap.source, id)) - .toThrow(/missing v1 -> v2/) - expect(pastGap.reads).toEqual([]) - }) -}) diff --git a/packages/session/session-persistence/tests/persistence.spec.ts b/packages/session/session-persistence/tests/persistence.spec.ts index 81fe733aeb..a596ed0b11 100644 --- a/packages/session/session-persistence/tests/persistence.spec.ts +++ b/packages/session/session-persistence/tests/persistence.spec.ts @@ -5,13 +5,10 @@ import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' import { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, SessionPersistence, SessionPersistenceRevision, PersistenceCoordinator, - SessionPersistenceRevisionConflictError, - type PersistenceBackend, type SessionPersistenceSnapshot, type StoredEventRead, - type StoredEventReadCompletion, type StoredSessionSource, + type PersistenceBackend, type SessionPersistenceSnapshot, type StoredPrefix, type StoredSuffix, } from '../src/index.ts' import { runPersistenceContract, meta, oneTurnLog } from './contract.ts' import { runCoordinatorContract, type CoordinatorFixture } from './coordinator-contract.ts' -import * as formatDecoder from '../src/format-decoder.ts' /** The durable store shape: materialized sessions only (no lazy entries). */ type MemoryStore = Map @@ -21,45 +18,6 @@ function memoryRevision(entry: { meta: SessionHeader; events: SessionEvent[] }): return SessionPersistenceRevision(JSON.stringify(entry)) } -/** Build one lazy physical read whose completion follows iterator exhaustion. */ -function storedRead( - load: () => Promise<{ events: readonly unknown[]; tornMarker?: TornMarker }>, -): StoredEventRead { - const completed = Promise.withResolvers>() - const events = (async function* (): AsyncIterable { - try { - const loaded = await load() - yield* loaded.events - completed.resolve(loaded.tornMarker === undefined ? {} : { tornMarker: loaded.tornMarker }) - } catch (error: unknown) { - completed.reject(error) - throw error - } - })() - return { events, completed: completed.promise } -} - -/** Materialize an async replacement stream for the map-backed test stores. */ -async function collectReplacement(events: AsyncIterable): Promise { - const collected: SessionEvent[] = [] - for await (const event of events) collected.push(structuredClone(event)) - return collected -} - -async function replaceMemoryStored( - store: MemoryStore, - expectedRevision: SessionPersistenceRevision, - m: SessionHeader, - events: AsyncIterable, -): Promise { - const entry = store.get(m.id) - if (entry === undefined || memoryRevision(entry) !== expectedRevision) { - throw new SessionPersistenceRevisionConflictError(`session "${m.id}" changed before replacement`) - } - if (entry.meta.cwd !== m.cwd) throw new Error(`replacement for session "${m.id}" changes its stored identity`) - store.set(m.id, { meta: structuredClone(m), events: await collectReplacement(events) }) -} - /** An obsolete event fixture that emulates an untyped pre-change producer. */ function legacyHeaderDelta(seq = 0): SessionEvent { return { @@ -124,7 +82,7 @@ class MemoryPersistence extends SessionPersistence implements PersistenceBackend super(ctx) // Assign the store BEFORE constructing the coordinator: the coordinator's // constructor installs the write path and synchronously seeds existing live - // sessions through openStored(), so store must exist first. + // sessions through loadStored(), so store must exist first. this.store = config?.store ?? new Map() this.coordinator = new PersistenceCoordinator(this.ctx, this) } @@ -171,20 +129,13 @@ class MemoryPersistence extends SessionPersistence implements PersistenceBackend // --- PersistenceBackend hooks (the Map storage primitives) --- // A Map-backed store has no torn tails, so `tornMarker` is never set. - async openStored(id: SessionId): Promise | undefined> { + async loadStored(id: SessionId): Promise | undefined> { const entry = this.store.get(id) if (!entry) return undefined - const revision = memoryRevision(entry) return { meta: structuredClone(entry.meta), - revision, - readEvents: ({ fromSeq = 0 } = {}) => storedRead(async () => { - const current = this.store.get(id) - if (current === undefined || memoryRevision(current) !== revision) { - throw new SessionPersistenceRevisionConflictError(`session "${id}" changed during read`) - } - return { events: structuredClone(current.events.filter(event => event.seq >= fromSeq)) } - }), + events: structuredClone(entry.events), + revision: memoryRevision(entry), } } @@ -223,14 +174,6 @@ class MemoryPersistence extends SessionPersistence implements PersistenceBackend if (closers.length > 0) entry.events.push(...structuredClone(closers) as SessionEvent[]) } - async replaceStored( - expectedRevision: SessionPersistenceRevision, - m: SessionHeader, - events: AsyncIterable, - ): Promise { - await replaceMemoryStored(this.store, expectedRevision, m, events) - } - async list(signal?: AbortSignal): Promise { signal?.throwIfAborted() return [...this.store.values()].map(e => structuredClone(e.meta)) @@ -256,36 +199,23 @@ class ControlledBackend implements PersistenceBackend { repairAttempts = 0 beforeAppend?: (attempt: number) => Promise beforeLoadStored?: (attempt: number, signal?: AbortSignal) => Promise - /** Optional physical suffix hook used by readFrom-specific tests. */ - seekHook?: ( - id: SessionId, - fromSeq: number, - signal?: AbortSignal, - ) => Promise<{ meta: SessionHeader; events: SessionEvent[] } | undefined> + /** When set, the declared seek hook delegates here so readFrom exercises it; unset throws (tests set it first). */ + seekHook?: (id: SessionId, fromSeq: number, signal?: AbortSignal) => Promise - async openStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { + loadStoredFrom(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise { + if (this.seekHook === undefined) throw new Error('seekHook not configured for this test') + return this.seekHook(id, fromSeq, signal) + } + + async loadStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { const attempt = ++this.loadAttempts await this.beforeLoadStored?.(attempt, signal) const entry = this.store.get(id) if (entry === undefined) return undefined - const revision = memoryRevision(entry) return { meta: structuredClone(entry.meta), - revision, - readEvents: ({ fromSeq = 0 } = {}) => storedRead(async () => { - signal?.throwIfAborted() - const loaded = this.seekHook === undefined - ? { meta: entry.meta, events: entry.events.filter(event => event.seq >= fromSeq) } - : await this.seekHook(id, fromSeq, signal) - if (loaded === undefined) { - throw new SessionPersistenceRevisionConflictError(`session "${id}" disappeared during read`) - } - const current = this.store.get(id) - if (current === undefined || memoryRevision(current) !== revision) { - throw new SessionPersistenceRevisionConflictError(`session "${id}" changed during read`) - } - return { events: structuredClone(loaded.events) } - }), + events: structuredClone(entry.events), + revision: memoryRevision(entry), } } @@ -313,14 +243,6 @@ class ControlledBackend implements PersistenceBackend { if (entry !== undefined) entry.events.push(...structuredClone(closers) as SessionEvent[]) } - async replaceStored( - expectedRevision: SessionPersistenceRevision, - m: SessionHeader, - events: AsyncIterable, - ): Promise { - await replaceMemoryStored(this.store, expectedRevision, m, events) - } - async list(): Promise { return [...this.store.values()].map(entry => structuredClone(entry.meta)) } @@ -651,11 +573,6 @@ describe('PersistenceCoordinator session preparations', () => { }, { inject: ['sessions'] })) try { - const immediatelyLive = Session.create(prepareId, oneTurnLog(), meta(prepareId)) - const immediateGet = vi.spyOn(ctx.sessions, 'get').mockReturnValue(immediatelyLive) - await expect(coordinator.prepare(prepareId)).rejects.toThrow(/while it is live/) - immediateGet.mockRestore() - const prepareLive = Session.create(prepareId, oneTurnLog(), meta(prepareId)) const prepareGet = vi.spyOn(ctx.sessions, 'get') .mockReturnValueOnce(undefined) @@ -1556,7 +1473,7 @@ describe('PersistenceCoordinator observation cancellation', () => { } }) - it('readFrom via the source reader: serves the suffix, reports absence, and relays reader failures by abort state', async () => { + it('readFrom via the seek hook: serves the suffix, maps undefined to not-found, and relays hook failures by abort state', async () => { const ctx = new Context() await ctx.plugin(SessionStore) const backend = new ControlledBackend() @@ -1577,7 +1494,7 @@ describe('PersistenceCoordinator observation cancellation', () => { } const suffix = await coordinator.readFrom(id, 3) expect(suffix.events).toEqual(log.slice(3)) - // Absence is established while opening the source, before an event read. + // The hook's `undefined` is the backend contract's not-found result. await expect(coordinator.readFrom(SessionId('missing-seek'), 0)).rejects.toThrow('not found') // A hook failure with no cancellation in play propagates as-is. @@ -1585,20 +1502,6 @@ describe('PersistenceCoordinator observation cancellation', () => { backend.seekHook = () => Promise.reject(hookFailure) await expect(coordinator.readFrom(id, 0)).rejects.toBe(hookFailure) - // A revision conflict is retryable because it names no stable source. - let conflictAttempts = 0 - backend.seekHook = async (hookId, fromSeq) => { - conflictAttempts += 1 - if (conflictAttempts === 1) { - throw new SessionPersistenceRevisionConflictError('source changed during readFrom') - } - const entry = backend.store.get(hookId) - if (entry === undefined) return undefined - return { meta: entry.meta, events: entry.events.filter(event => event.seq >= fromSeq) } - } - await expect(coordinator.readFrom(id, 2)).resolves.toMatchObject({ events: log.slice(2) }) - expect(conflictAttempts).toBe(2) - // A hook failure after cancellation surfaces the caller's abort reason, // not the backend's internal teardown error. The abort fires only once // the hook is provably entered, so the failure exercises the catch (not @@ -1728,13 +1631,14 @@ describe('PersistenceCoordinator retirement', () => { }, { inject: ['sessions'] })) await ctx.sessions.flush(first) - // Occupy the per-id serialize chain with a gated source open: + // Occupy the per-id serialize chain with a gated physical read: // inspect() correctly borrows the still-live Session without entering // the backend chain, while both retirements must queue behind readFrom(). const readEntered = Promise.withResolvers() - backend.beforeLoadStored = async () => { + backend.seekHook = async () => { readEntered.resolve(undefined) await readGate.promise + return undefined } const parked = coordinator.readFrom(id, 0).catch((error: unknown) => error) await readEntered.promise @@ -1758,7 +1662,7 @@ describe('PersistenceCoordinator retirement', () => { // delete the successor's entry (exact-entry guard); the successor's own // forget() then clears the map. readGate.resolve(true) - expect(await parked).toBeInstanceOf(Error) // the parked read (not found) is observed + expect(await parked).toBeInstanceOf(Error) // the parked inspect (not found) is observed await firstRetirement await vi.waitFor(() => { expect(internals.retirements.has(id)).toBe(false) }) } finally { @@ -2233,235 +2137,6 @@ describe('SessionPersistence service registration', () => { await Promise.allSettled([fiber.dispose()]) }) - it('rejects obsolete event variants passed directly to the persistence writer', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - const backend = new ControlledBackend() - let coordinator!: PersistenceCoordinator - const fiber = await ctx.plugin(Object.assign((inner: Context) => { - coordinator = new PersistenceCoordinator(inner, backend) - }, { inject: ['sessions'] })) - const id = SessionId('legacy-direct-append') - await coordinator.create(meta(id)) - - try { - await expect(coordinator.append(id, [legacyHeaderDelta()])) - .rejects.toThrow(/unsupported legacy request\/header-delta event/) - await expect(coordinator.append(id, [legacyModeSet()])) - .rejects.toThrow(/unsupported legacy mode\/set event/) - await expect(coordinator.append(id, [legacyFallbackHeader()])) - .rejects.toThrow(/unsupported legacy request\/header reason "fallback"/) - expect(backend.store.has(id)).toBe(false) - } finally { - await fiber.dispose() - await ctx.fiber.dispose() - } - }) - - it('retries cold preparation when its physical source revision changes', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - const backend = new ControlledBackend() - const id = SessionId('prepare-source-conflict') - backend.store.set(id, { meta: meta(id), events: oneTurnLog() }) - let attempts = 0 - backend.seekHook = async (hookId, fromSeq) => { - attempts += 1 - if (attempts === 1) throw new SessionPersistenceRevisionConflictError('prepare source changed') - const entry = backend.store.get(hookId) - if (entry === undefined) return undefined - return { meta: entry.meta, events: entry.events.filter(event => event.seq >= fromSeq) } - } - let coordinator!: PersistenceCoordinator - const fiber = await ctx.plugin(Object.assign((inner: Context) => { - coordinator = new PersistenceCoordinator(inner, backend) - }, { inject: ['sessions'] })) - - try { - await expect(coordinator.inspect(id)).resolves.toMatchObject({ events: oneTurnLog() }) - expect(attempts).toBe(2) - } finally { - await fiber.dispose() - await ctx.fiber.dispose() - } - }) - - it('retries live-prefix adoption when the physical source revision changes', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - const backend = new ControlledBackend() - const id = SessionId('hmr-source-conflict') - const m = meta(id, '/work') - backend.store.set(id, { meta: m, events: oneTurnLog() }) - const session = ctx.sessions.create(id, { seed: oneTurnLog(), meta: { cwd: '/work' } }) - let attempts = 0 - backend.seekHook = async (hookId, fromSeq) => { - attempts += 1 - if (attempts === 1) throw new SessionPersistenceRevisionConflictError('live source changed') - const entry = backend.store.get(hookId) - if (entry === undefined) return undefined - return { meta: entry.meta, events: entry.events.filter(event => event.seq >= fromSeq) } - } - const fiber = await ctx.plugin(Object.assign((inner: Context) => { - new PersistenceCoordinator(inner, backend) - }, { inject: ['sessions'] })) - - try { - await expect(ctx.sessions.flush(session)).resolves.toBe(true) - expect(attempts).toBe(2) - } finally { - await fiber.dispose() - await ctx.fiber.dispose() - } - }) - - it('retries ownerless seed verification when the physical source revision changes', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - const backend = new ControlledBackend() - const id = SessionId('seed-source-conflict') - const m = meta(id, '/work') - backend.store.set(id, { meta: m, events: oneTurnLog() }) - let coordinator!: PersistenceCoordinator - const fiber = await ctx.plugin(Object.assign((inner: Context) => { - coordinator = new PersistenceCoordinator(inner, backend) - }, { inject: ['sessions'] })) - - try { - await coordinator.load(id) - let attempts = 0 - backend.seekHook = async (hookId, fromSeq) => { - attempts += 1 - if (attempts === 1) throw new SessionPersistenceRevisionConflictError('seed source changed') - const entry = backend.store.get(hookId) - if (entry === undefined) return undefined - return { meta: entry.meta, events: entry.events.filter(event => event.seq >= fromSeq) } - } - const session = ctx.sessions.create(id, { seed: oneTurnLog(), meta: { cwd: '/work' } }) - - await expect(ctx.sessions.flush(session)).resolves.toBe(true) - expect(attempts).toBe(2) - } finally { - await fiber.dispose() - await ctx.fiber.dispose() - } - }) - - it('streams an old-format prepared source into replacement and propagates non-conflict failures', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - const backend = new ControlledBackend() - const id = SessionId('prepared-format-replacement') - const m = meta(id) - backend.store.set(id, { meta: m, events: oneTurnLog() }) - let coordinator!: PersistenceCoordinator - const fiber = await ctx.plugin(Object.assign((inner: Context) => { - coordinator = new PersistenceCoordinator(inner, backend) - }, { inject: ['sessions'] })) - const source = { - inspection: Object.freeze({ meta: m, events: Object.freeze(oneTurnLog()) }), - session: Session.create(id, oneTurnLog(), m), - revision: memoryRevision(backend.store.get(id)!), - sourceVersion: -1, - sessionLength: oneTurnLog().length, - tornMarker: undefined, - closers: [], - } - const internals = coordinator as unknown as { - commitPrepared(value: typeof source): Promise - } - const replace = vi.spyOn(backend, 'replaceStored') - - try { - await expect(internals.commitPrepared(source)).resolves.toBeUndefined() - expect(replace).toHaveBeenCalledOnce() - expect(backend.store.get(id)?.events).toEqual(oneTurnLog()) - - const failure = new Error('replacement backend failed') - replace.mockRejectedValueOnce(failure) - source.revision = memoryRevision(backend.store.get(id)!) - await expect(internals.commitPrepared(source)).rejects.toBe(failure) - - replace.mockRejectedValueOnce(new SessionPersistenceRevisionConflictError('replacement raced')) - await expect(internals.commitPrepared(source)).resolves.toBeUndefined() - } finally { - await fiber.dispose() - await ctx.fiber.dispose() - } - }) - - it('routes live adoption of a decoded old format through the same replacement primitive', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - const backend = new ControlledBackend() - const id = SessionId('live-format-replacement') - const m = meta(id, '/work') - const log = oneTurnLog() - backend.store.set(id, { meta: m, events: log }) - let coordinator!: PersistenceCoordinator - const fiber = await ctx.plugin(Object.assign((inner: Context) => { - coordinator = new PersistenceCoordinator(inner, backend) - }, { inject: ['sessions'] })) - const revision = memoryRevision(backend.store.get(id)!) - const stored: StoredSessionSource = { - meta: m, - revision, - readEvents: () => storedRead(async () => ({ events: log })), - } - const decoded = { - meta: m, - sourceVersion: -1, - revision, - events: (async function* (): AsyncIterable { yield* log })(), - completed: Promise.resolve({}), - } - const decode = vi.spyOn(formatDecoder, 'decodeStoredSession').mockReturnValue(decoded) - const replace = vi.spyOn(backend, 'replaceStored') - const internals = coordinator as unknown as { - adoptLivePrefix( - session: Session, - seed: readonly SessionEvent[], - source: StoredSessionSource, - ): Promise - } - - try { - const session = Session.create(id, log, m) - await expect(internals.adoptLivePrefix(session, log, stored)).resolves.toBe(false) - expect(replace).toHaveBeenCalledOnce() - expect(backend.store.get(id)?.events).toEqual(log) - } finally { - decode.mockRestore() - await fiber.dispose() - await ctx.fiber.dispose() - } - }) - - it('propagates a non-conflict failure during ownerless seed verification', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - const backend = new ControlledBackend() - const id = SessionId('seed-source-failure') - const m = meta(id, '/work') - backend.store.set(id, { meta: m, events: oneTurnLog() }) - let coordinator!: PersistenceCoordinator - const fiber = await ctx.plugin(Object.assign((inner: Context) => { - coordinator = new PersistenceCoordinator(inner, backend) - }, { inject: ['sessions'] })) - - try { - await coordinator.load(id) - const failure = new Error('seed reader failed') - backend.seekHook = () => Promise.reject(failure) - const session = ctx.sessions.create(id, { seed: oneTurnLog(), meta: { cwd: '/work' } }) - - await expect(ctx.sessions.flush(session)).rejects.toBe(failure) - } finally { - await Promise.allSettled([fiber.dispose()]) - await ctx.fiber.dispose() - } - }) - it('rejects a stored legacy fallback header during load', async () => { const id = SessionId('legacy-fallback-load') const m = meta(id, '/legacy') diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 86359634bb..01010366cf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4723,9 +4723,6 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session - '@deepseek-ai/dsh-session-persistence': - specifier: workspace:^ - version: link:../../session/session-persistence '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../session/session-persistence-jsonl diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index f1ceab0c43..81a3e124a1 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -556,11 +556,6 @@ "symbol": "SessionLocation", "source": "packages/session/session-persistence/src/index.ts" }, - { - "doc": "docs/subsystems/persistence.md", - "symbol": "SessionFormatMigration", - "source": "packages/session/session-persistence/src/format-decoder.ts" - }, { "doc": "docs/subsystems/persistence.md", "symbol": "SessionRawArtifact",