From 9c3a6a34d40bd88119491d7bfc3b798903d647b5 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 12 Oct 2026 10:30:08 +0800 Subject: [PATCH 01/36] feat(tools): resolve conditional tool admission per request --- apps/cli/tests/fixtures/dsh-badge/snapshot.ts | 1 + docs/agent-lifecycle.i18n.yaml | 4 +- docs/agent-lifecycle.md | 19 +- docs/agent-lifecycle.zh.md | 19 +- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 7 +- docs/architecture.zh.md | 7 +- docs/config-catalog.md | 6 +- docs/config-catalog.zh.md | 6 +- docs/event-producer-consumer.md | 41 +-- docs/event-producer-consumer.zh.md | 41 +-- docs/persistence-catalog.i18n.yaml | 16 +- docs/persistence-catalog.md | 8 +- docs/persistence-catalog.zh.md | 8 +- docs/persistence-schema.json | 6 +- docs/subsystems/core.md | 16 +- docs/subsystems/core.zh.md | 16 +- docs/subsystems/plan.md | 2 +- docs/subsystems/plan.zh.md | 2 +- docs/subsystems/system-prompt.md | 54 ++- docs/subsystems/system-prompt.zh.md | 54 ++- docs/subsystems/tools.md | 20 +- docs/subsystems/tools.zh.md | 20 +- .../conditional-tools/guide.i18n.yaml | 16 + .../v0.2.1-alpha.1/conditional-tools/guide.md | 21 ++ .../conditional-tools/guide.zh.md | 21 ++ .../api/job-controller/tests/host-harness.ts | 1 + .../job-controller/tests/observe.host.spec.ts | 1 + .../tests/archived-session-gate.host.spec.ts | 1 + .../bundle/headless/tests/headless.spec.ts | 1 + .../session-reference/README.i18n.yaml | 8 +- packages/context/session-reference/README.md | 4 +- .../context/session-reference/README.zh.md | 4 +- .../context/session-reference/src/index.ts | 15 +- .../tests/session-reference.spec.ts | 30 +- .../time-context/tests/time-context.spec.ts | 1 + .../tmux-context/tests/tmux-context.spec.ts | 1 + packages/core/agent-loop/README.i18n.yaml | 8 +- packages/core/agent-loop/README.md | 4 +- packages/core/agent-loop/README.zh.md | 4 +- packages/core/agent-loop/src/agent.ts | 312 ++++++++++-------- packages/core/agent-loop/src/tool-calls.ts | 4 + .../tests/contract-regressions.spec.ts | 14 +- packages/core/agent-loop/tests/inbox.spec.ts | 1 + .../agent-loop/tests/request-freeze.spec.ts | 9 +- .../tests/system-prompt-admission.spec.ts | 6 +- .../core/agent-loop/tests/tool-calls.spec.ts | 19 +- .../core/agent-loop/tests/tool-order.spec.ts | 6 +- .../agent-loop/tests/tool-updates.spec.ts | 126 ++++++- packages/core/agent/README.i18n.yaml | 8 +- packages/core/agent/README.md | 6 +- packages/core/agent/README.zh.md | 6 +- packages/core/agent/src/model-selection.ts | 42 +-- packages/core/agent/src/runtime-types.ts | 14 +- packages/core/agent/tests/agent.spec.ts | 1 + .../agent/tests/archive-admission.spec.ts | 1 + .../core/agent/tests/model-selection.spec.ts | 233 ++++--------- packages/core/system-prompt/README.i18n.yaml | 16 +- packages/core/system-prompt/README.md | 8 +- packages/core/system-prompt/README.zh.md | 8 +- packages/core/system-prompt/src/index.ts | 99 ++++-- .../system-prompt/tests/tool-order.spec.ts | 17 +- packages/core/tools/README.i18n.yaml | 3 + packages/core/tools/README.md | 8 + packages/core/tools/README.zh.md | 8 + packages/core/tools/src/index.ts | 172 ++++++++-- packages/core/tools/src/ptc.ts | 3 +- packages/core/tools/tests/activation.spec.ts | 123 +++++++ packages/core/tools/tests/ptc.spec.ts | 51 ++- .../tool-present/tests/present.spec.ts | 1 + .../tests/resources.spec.ts | 1 + .../tests/loader-composition.spec.ts | 1 + .../tool-terminal/tests/tools.spec.ts | 1 + .../experimental/worktree/tests/harness.ts | 1 + .../extensions/tool-cordis/src/api-catalog.ts | 84 +++-- .../tests/command-feedback.spec.ts | 1 + .../tests/loader-composition.spec.ts | 1 + .../tests/tools.spec.ts | 1 + .../command-goal/tests/command-goal.spec.ts | 1 + packages/goal/goal/tests/goal.spec.ts | 1 + packages/goal/goal/tests/projection.spec.ts | 1 + .../goal/tool-goal/tests/tool-goal.spec.ts | 1 + .../tool-ask-user/tests/tool-ask-user.spec.ts | 1 + packages/jobs/jobs-local/tests/events.spec.ts | 1 + packages/jobs/jobs-local/tests/jobs.spec.ts | 1 + packages/plan/plan-mode/README.i18n.yaml | 20 +- packages/plan/plan-mode/README.md | 10 +- packages/plan/plan-mode/README.zh.md | 10 +- packages/plan/plan-mode/src/index.ts | 34 +- .../plan/plan-mode/tests/integration.spec.ts | 10 +- .../plan/plan-mode/tests/plan-mode.spec.ts | 88 +++-- packages/schedule/schedule/tests/harness.ts | 1 + .../working-directory/README.i18n.yaml | 8 +- packages/session/working-directory/README.md | 4 +- .../session/working-directory/README.zh.md | 4 +- .../session/working-directory/src/index.ts | 2 +- .../tests/loader-composition.spec.ts | 1 + .../tool-bash-persistent/tests/tools.spec.ts | 1 + .../shell/tool-bash/tests/background.spec.ts | 2 + .../tests/loader-composition.spec.ts | 1 + .../tool-pwsh-persistent/tests/tools.spec.ts | 1 + .../shell/tool-pwsh/tests/background.spec.ts | 2 + .../skill/tool-skill/tests/tool-skill.spec.ts | 2 + .../subagent/tests/archive-admission.spec.ts | 1 + .../tests/external-activation-helpers.ts | 1 + .../terminal-bash/tests/index.spec.ts | 3 + .../terminal-bash/tests/local.spec.ts | 1 + .../terminal/terminal/tests/service.spec.ts | 1 + .../tests/fixtures/dynamic-tool-updates.ts | 17 +- .../tests/loader-composition.spec.ts | 1 + .../tool-workflow/tests/tool-workflow.spec.ts | 2 + scripts/fixtures/python-sdk-dynamic-tools.mjs | 28 +- scripts/gen-cordis-catalog.ts | 5 + scripts/gen-doc-graphs.ts | 19 +- scripts/smoke-python-runtime.py | 2 + .../dynamic-tools/tool-history.json | 16 +- .../sdk/bash-tool/tool-schemas.expected.json | 16 - .../notifications.expected.jsonl | 6 +- .../sdk/dynamic-tool-updates/session.v4.jsonl | 6 +- .../tool-schemas.1.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../sdk/text-turn/tool-schemas.expected.json | 16 - .../notifications.expected.jsonl | 4 +- .../sdk/tool-error-details/session.v4.jsonl | 4 +- .../system-prompt.expected.md | 8 - .../tool-schemas.expected.json | 16 - .../advanced-toolchain/session.v4.jsonl | 8 +- .../system-prompt.expected.md | 8 - .../tool-schemas.expected.json | 32 -- .../tool-schemas.expected.json | 32 -- .../tool-schemas.expected.json | 16 - .../both-mode-turn/system-prompt.expected.md | 8 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 32 -- .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../cordis-inspect-jsdoc/session.v4.jsonl | 2 +- .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../session.v4.jsonl | 6 +- .../dynamic-tool-updates/session.v4.jsonl | 6 +- .../tool-schemas.expected.json | 48 --- .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../lsp-definition/tool-schemas.expected.json | 16 - .../system-prompt.expected.md | 8 - .../mcp-resources/tool-schemas.expected.json | 16 - .../model-switch-driver.mjs | 33 +- .../tool-schemas.expected.json | 16 - .../office-skills/tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../session.v4.jsonl | 6 +- .../plugin-manager-mcp/session.v4.jsonl | 4 +- .../tool-schemas.expected.json | 32 -- .../plugin-manager/tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../provider-cwd/tool-schemas.expected.json | 16 - .../system-prompt.expected.md | 8 - .../system-prompt.expected.md | 8 - .../ptc-python-turn/system-prompt.expected.md | 10 - .../ptc-read-image/system-prompt.expected.md | 8 - .../ptc-turn/system-prompt.expected.md | 8 - .../tool-schemas.expected.json | 16 - .../ralph-loop/tool-schemas.1.expected.json | 16 - .../ralph-loop/tool-schemas.2.expected.json | 16 - .../ralph-loop/tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../team-targets/tool-schemas.expected.json | 16 - .../text-turn/tool-schemas.expected.json | 16 - .../web-fetch/tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../worktree/tool-schemas.expected.json | 16 - 192 files changed, 1454 insertions(+), 1936 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.md create mode 100644 docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.zh.md create mode 100644 packages/core/tools/tests/activation.spec.ts diff --git a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts index c84912a9f1..87eb1a73b5 100644 --- a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts +++ b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts @@ -27,6 +27,7 @@ try { const agentId = SessionId('dsh-badge-snapshot') const session = ctx.sessions.create(agentId, { meta: { cwd: process.cwd() } }) const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, ctx, id: agentId, options: {}, diff --git a/docs/agent-lifecycle.i18n.yaml b/docs/agent-lifecycle.i18n.yaml index cb75783c9c..3871250205 100644 --- a/docs/agent-lifecycle.i18n.yaml +++ b/docs/agent-lifecycle.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 305a6826a598b96d /agent-turn-and-step-lifecycle: - en: a1389c8ed7e37324 - zh: c2944b9192af4ec9 + en: 8b6b2eff5a5c93b9 + zh: f63a8b82e1888d12 diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 6ffe3c2b47..eceb9229fc 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -25,16 +25,18 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Prompt: system-prompt/assemble waterfall + Driver->>Hooks: agent/request waterfall + Driver->>LLM: prepareCall(config, signal), bind Agent.currentRoute() + Driver->>Prompt: system-prompt/prepare waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) alt proposed step rejected, first batch empty, or pre-step failed Driver-->>Driver: claimed batch stays removed, the open turn spends no step else enter proposed step Driver->>Session: step/start - Driver->>Hooks: agent/request waterfall - Driver->>LLM: prepareCall(config, signal) - Note over Driver,LLM: cancellation during either async phase commits neither system nor users + Driver->>Tools: resolve({ agent, signal }) + Driver->>Prompt: system-prompt/assemble with resolved tool set + Note over Driver,LLM: cancellation during preparation commits neither system nor users Note over Driver,Session: synchronous admission using the prepared call capability Driver->>Session: system/message ordered per-node reconciliation Driver->>Session: user/message per entered message @@ -48,7 +50,7 @@ sequenceDiagram Driver-->>SDK: agent/assistant-stream committed end Driver->>Hooks: agent/request-error waterfall Hooks-->>Driver: return retry action or preserve the original error - Note over Driver,LLM: retry in the open step: prepare and reconcile the same rendered assembly without repeating pre-step or users + Note over Driver,LLM: retry resolves route and tools. Unchanged inputs reuse the prompt without repeating pre-step or users else model request succeeded Driver->>Session: assistant/message Driver-->>SDK: agent/assistant-stream committed end @@ -56,7 +58,7 @@ sequenceDiagram loop barriers and bounded rolling pool, reclassify before start opt call starts Driver->>Session: tool/call - Driver->>Tools: ordered pre, concurrent execute + Driver->>Tools: ordered pre, concurrent execute with request tool set Tools-->>Session: tool-owned events when applicable end opt next model-order result ready @@ -64,13 +66,16 @@ sequenceDiagram Driver->>Session: tool/result end end + Driver->>Tools: dispose request tool set Driver->>Session: step/end + Driver->>Driver: clear bound route opt natural stop and next-step inbox empty Driver->>Hooks: agent/turn-stopping serial terminal checkpoint end opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message + Driver->>Driver: prepare route and runtime context for the next step Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) end @@ -82,7 +87,7 @@ sequenceDiagram The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes, and embeds the exact compact timed stream. Empty content stays out of derived history. A failed, retried, cancelled, or stream-error attempt that reaches settlement without a surface message records its stream as `assistant/attempt`. Live `agent/assistant-stream` chunk frames are transient; replay reads either durable settlement, and a hard process loss before settlement leaves no durable attempt stream. -`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call and reconciles the retained rendered assembly before request derivation, without repeating assembly, pre-step, or user admission. +`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call and resolves tool conditions before request derivation, without repeating pre-step or user admission. Prompt assembly repeats only when the bound route or tool schemas change. 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. diff --git a/docs/agent-lifecycle.zh.md b/docs/agent-lifecycle.zh.md index c4b2fa70db..74b8fb05f6 100644 --- a/docs/agent-lifecycle.zh.md +++ b/docs/agent-lifecycle.zh.md @@ -27,16 +27,18 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Prompt: system-prompt/assemble waterfall + Driver->>Hooks: agent/request waterfall + Driver->>LLM: prepareCall(config, signal), bind Agent.currentRoute() + Driver->>Prompt: system-prompt/prepare waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) alt proposed step rejected, first batch empty, or pre-step failed Driver-->>Driver: claimed batch stays removed, the open turn spends no step else enter proposed step Driver->>Session: step/start - Driver->>Hooks: agent/request waterfall - Driver->>LLM: prepareCall(config, signal) - Note over Driver,LLM: cancellation during either async phase commits neither system nor users + Driver->>Tools: resolve({ agent, signal }) + Driver->>Prompt: system-prompt/assemble with resolved tool set + Note over Driver,LLM: cancellation during preparation commits neither system nor users Note over Driver,Session: synchronous admission using the prepared call capability Driver->>Session: system/message ordered per-node reconciliation Driver->>Session: user/message per entered message @@ -50,7 +52,7 @@ sequenceDiagram Driver-->>SDK: agent/assistant-stream committed end Driver->>Hooks: agent/request-error waterfall Hooks-->>Driver: return retry action or preserve the original error - Note over Driver,LLM: retry in the open step: prepare and reconcile the same rendered assembly without repeating pre-step or users + Note over Driver,LLM: retry resolves route and tools. Unchanged inputs reuse the prompt without repeating pre-step or users else model request succeeded Driver->>Session: assistant/message Driver-->>SDK: agent/assistant-stream committed end @@ -58,7 +60,7 @@ sequenceDiagram loop barriers and bounded rolling pool, reclassify before start opt call starts Driver->>Session: tool/call - Driver->>Tools: ordered pre, concurrent execute + Driver->>Tools: ordered pre, concurrent execute with request tool set Tools-->>Session: tool-owned events when applicable end opt next model-order result ready @@ -66,13 +68,16 @@ sequenceDiagram Driver->>Session: tool/result end end + Driver->>Tools: dispose request tool set Driver->>Session: step/end + Driver->>Driver: clear bound route opt natural stop and next-step inbox empty Driver->>Hooks: agent/turn-stopping serial terminal checkpoint end opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message + Driver->>Driver: prepare route and runtime context for the next step Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) end @@ -84,7 +89,7 @@ sequenceDiagram `assistant/message` 事件会记录每次成功的提供方调用,包括返回空内容或以 `max-tokens` 结束的调用,并嵌入精确的紧凑带时间 stream。空内容不会进入派生历史。失败、重试、取消或 stream error attempt 到达 settlement 时,如果没有 surface message,就会把 stream 记录为 `assistant/attempt`。实时 `agent/assistant-stream` chunk frame 是瞬态数据;回放读取任一种持久 settlement,如果进程在 settlement 前硬中断,则不会留下持久 attempt stream。 -`dsh-compaction-basic` 在派生请求之前通过 `agent/pre-step` 处理压力,而 `agent/request-error` 仅用于规范的上下文溢出。任一触发条件满足后,系统都会先执行可选的工具结果剪枝,再选择摘要。恢复发生在仍打开的步骤内,只有剪枝或摘要生成推进 surface replacement generation 时才重试,否则仍以原始请求错误为准。每次重试都会准备调用,并在派生请求之前协调保留的已渲染组装结果,不重复组装、pre-step 或用户消息准入。 +`dsh-compaction-basic` 在派生请求之前通过 `agent/pre-step` 处理压力,而 `agent/request-error` 仅用于规范的上下文溢出。任一触发条件满足后,系统都会先执行可选的工具结果剪枝,再选择摘要。恢复发生在仍打开的步骤内,只有剪枝或摘要生成推进 surface replacement generation 时才重试,否则仍以原始请求错误为准。每次重试都会在派生请求之前准备调用并解析工具条件,不重复 pre-step 或用户消息准入。只有已绑定路由或工具 schema 变化时才重新组装提示词。 以返回的 `agent/pre-step` 决策为准;通过包装 `next()` 的监听器会保留下游消息与 `startsRequestSeries`,除非有意替换。steering(中途引导)和注入的上下文在后续的认领操作取得其下一步骤批次后,会经过同一 waterfall(瀑布式事件)。 diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 8206f3e6dc..a1eca06e56 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -24,8 +24,8 @@ en: e89802f066e4955d zh: ea2fb4bef94e086d /deepseek-harness-architecture/turn-flow: - en: e6402b28c0ed15fa - zh: 6c07be9047b42056 + en: e7f529503233d805 + zh: f1d1e4a58e44a2ec /deepseek-harness-architecture/session-log: en: a2e35c43438fec6d zh: e27bdac8e9feff32 diff --git a/docs/architecture.md b/docs/architecture.md index 03d88148c7..9157ba13a9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -83,12 +83,13 @@ A **step** is one model request plus the tools it calls. A **turn** is zero or m ```text turn/start claim next-step input plus one queued message - assemble prompt sections + tool schemas + agent/request -> prepareCall -> bind Agent.currentRoute() + prepare variables + runtime context -> agent/pre-step; project runtime context at fallback reject | enter(messages, startsRequestSeries?) reject, or a first enter rewritten empty -> close the turn with no step step/start - agent/request -> prepareCall (cancellation commits neither system nor users) + resolve conditional tools + assemble prompt using that tool set reconcile system/message using the prepared call capability append entered messages as user/message; reconcile retained runtime context log request/header and request/context as needed @@ -107,7 +108,7 @@ turn/end One inbox feeds the driver; injected context waits for a waking message. AgentLoop’s durable `inbox` projection exposes pending input without live Agents. -`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. After assembly and `step/start`, `agent/request` and `prepareCall()` resolve the actual route before the system prompt and accepted users are committed; cancellation during either async phase commits neither. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes registered runtime facts, reconciles the bound prompt, admits users once, and restores removed runtime context, logs header/context as needed, and freezes the request before streaming the bound call. Retries do not repeat assembly or `agent/pre-step`. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). +`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/request` and `prepareCall()` bind the route before context preparation and `agent/pre-step`; cancellation commits no step or messages. Accepted steps resolve tool conditions before final assembly. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming. Retries do not repeat `agent/pre-step`; prompt assembly repeats only when the resolved route or tool schemas change. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). The loop sends immutable requests with live cancellation and reuses freeze evidence for frozen identities; [agent-loop](../packages/core/agent-loop/README.md) owns construction and cancellation causes. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 870fa1c996..58f110c928 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -87,12 +87,13 @@ AgentLoop 在启动已排队工作前等待串行 `agent/created`,初始化失 ```text turn/start claim next-step input plus one queued message - assemble prompt sections + tool schemas + agent/request -> prepareCall -> bind Agent.currentRoute() + prepare variables + runtime context -> agent/pre-step; project runtime context at fallback reject | enter(messages, startsRequestSeries?) reject, or a first enter rewritten empty -> close the turn with no step step/start - agent/request -> prepareCall (cancellation commits neither system nor users) + resolve conditional tools + assemble prompt using that tool set reconcile system/message using the prepared call capability append entered messages as user/message; reconcile retained runtime context log request/header and request/context as needed @@ -111,7 +112,7 @@ turn/end 输入通过同一个 inbox 到达驱动器;注入的上下文等待一条唤醒消息。AgentLoop 的持久 `inbox` 投影使待处理输入在没有活跃 Agent 时仍可读取。 -`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。组装与 `step/start` 之后,`agent/request` 和 `prepareCall()` 先解析实际路由,再提交系统提示词与已接纳用户消息;在任一异步阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求。重试不重复组装或 `agent/pre-step`。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 +`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。组装与 `step/start` 之后,`agent/request` 和 `prepareCall()` 先解析实际路由,再提交系统提示词与已接纳用户消息;在任一异步阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求。重试不重复 `agent/pre-step`;仅在已解析路由或工具 schema 改变时重新组装提示词。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 循环发送不可变请求,同时保持取消有效,仅对完全冻结的对象复用冻结证据;[agent-loop](../packages/core/agent-loop/README.zh.md) 负责请求构建与取消原因。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 17856848d5..28b8224ae3 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2372,7 +2372,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` -- `source`: [`packages/plan/plan-mode/src/index.ts:69`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -3475,7 +3475,7 @@ export interface Config { ## `@deepseek-ai/dsh-system-prompt` -- `source`: [`packages/core/system-prompt/src/index.ts:254`](../packages/core/system-prompt/src/index.ts) +- `source`: [`packages/core/system-prompt/src/index.ts:266`](../packages/core/system-prompt/src/index.ts) ```ts config-catalog /** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */ @@ -4154,7 +4154,7 @@ export interface Config { ## `@deepseek-ai/dsh-tools` - `inject`: `systemPrompt` -- `source`: [`packages/core/tools/src/index.ts:675`](../packages/core/tools/src/index.ts) +- `source`: [`packages/core/tools/src/index.ts:733`](../packages/core/tools/src/index.ts) ```ts config-catalog /** Plugin config: how the registered tools are presented to the model. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c4ab85cdda..1db597f106 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2374,7 +2374,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` -- `source`: [`packages/plan/plan-mode/src/index.ts:69`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -3477,7 +3477,7 @@ export interface Config { ## `@deepseek-ai/dsh-system-prompt` -- `source`: [`packages/core/system-prompt/src/index.ts:254`](../packages/core/system-prompt/src/index.ts) +- `source`: [`packages/core/system-prompt/src/index.ts:266`](../packages/core/system-prompt/src/index.ts) ```ts config-catalog /** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */ @@ -4156,7 +4156,7 @@ export interface Config { ## `@deepseek-ai/dsh-tools` - `inject`: `systemPrompt` -- `source`: [`packages/core/tools/src/index.ts:675`](../packages/core/tools/src/index.ts) +- `source`: [`packages/core/tools/src/index.ts:733`](../packages/core/tools/src/index.ts) ```ts config-catalog /** Plugin config: how the registered tools are presented to the model. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 9691933dda..2702e3b3ec 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -10,18 +10,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:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:363`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:261`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:270`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:393`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:307`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:288`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:320`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:353`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:381`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:369`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:267`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:276`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:305`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:313`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:294`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:326`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:343`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:286`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:387`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:619`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:599`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:626`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | @@ -71,14 +71,15 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:158`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | -| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`agent`](../packages/core/agent), `browser-use-runtime`, [`session-reference`](../packages/context/session-reference), [`working-directory`](../packages/session/working-directory) | -| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | -| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:209`](../packages/core/tools/src/index.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:165`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | -| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:177`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | -| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:154`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:191`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | -| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:199`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | +| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime` | +| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:44`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | +| `system-prompt/prepare` | `waterfall` | [`packages/core/system-prompt/src/index.ts:38`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`working-directory`](../packages/session/working-directory) | +| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:216`](../packages/core/tools/src/index.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:172`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:184`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | +| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:161`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:198`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | +| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:206`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:157`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes` | | `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:39`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index cb8ea84aac..c393e8340c 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -12,18 +12,18 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:363`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:261`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:270`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:393`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:307`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:288`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:320`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:353`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:381`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:369`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:267`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:276`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:305`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:313`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:294`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:326`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:343`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:286`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:387`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:619`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:599`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:626`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | @@ -73,14 +73,15 @@ | `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:158`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | -| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`agent`](../packages/core/agent), `browser-use-runtime`, [`session-reference`](../packages/context/session-reference), [`working-directory`](../packages/session/working-directory) | -| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | -| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:209`](../packages/core/tools/src/index.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:165`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | -| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:177`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | -| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:154`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:191`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | -| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:199`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | +| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime` | +| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:44`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | +| `system-prompt/prepare` | `waterfall` | [`packages/core/system-prompt/src/index.ts:38`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`working-directory`](../packages/session/working-directory) | +| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:216`](../packages/core/tools/src/index.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:172`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:184`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | +| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:161`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:198`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | +| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:206`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present) | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:157`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes` | | `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:39`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index dab112d89b..61fc4845c0 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -144,8 +144,8 @@ en: 4294f78d26ed985b zh: 4294f78d26ed985b /session-persistence-event-catalog/events/plan/plan-mode-log-only: - en: 862175bfe8692ef7 - zh: a8ab123bf674cf77 + en: f23bf0e5e6408adf + zh: a9442b4c5cdeef0b /session-persistence-event-catalog/events/request: en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 @@ -1239,8 +1239,8 @@ en: f43a635a14568780 zh: 8d22226b045122eb /session-persistence-event-catalog/resolved-persistence-types/toolrestriction: - en: d7d3c0238d9b373e - zh: f49d93ee54e7a780 + en: 739d19df365ed5df + zh: b1e41e56995fe238 /session-persistence-event-catalog/resolved-persistence-types/toolresultmessage: en: 2258683c3cfa4ce3 zh: 5663aa76c911761b @@ -1347,8 +1347,8 @@ en: a74e3dfa51c987af zh: 6c3c87974d7a7260 /session-persistence-event-catalog/resolved-persistence-types/active~2: - en: a3de6a6fe9672c7a - zh: a357481e27b3b81f + en: 1bc41f689438a051 + zh: babdc92cc0ad089a /session-persistence-event-catalog/resolved-persistence-types/agentpreset: en: b8a0f8aac9708056 zh: f5f004bd205b41e1 @@ -1779,8 +1779,8 @@ en: 08be4349548406a9 zh: 8e7cf9966198ef78 /session-persistence-event-catalog/resolved-persistence-types/kind-tool-registry: - en: 79db83dd2c430faf - zh: 173f568241f5ce86 + en: bbcefadaa064365a + zh: 0285b8b877d6193d /session-persistence-event-catalog/resolved-persistence-types/kind-user: en: cb5d3fbab4debac6 zh: 72add55254356149 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 6d4c694309..b9be17476b 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -700,7 +700,7 @@ Source: [`packages/interaction/permission-presets/src/index.ts:59`](../packages/ 'plan/mode': { active: boolean } ``` -Source: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +Source: [`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -4996,7 +4996,7 @@ Sources: [`packages/llm/llm/src/types.ts:127`](../packages/llm/llm/src/types.ts) SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -Sources: [`packages/core/tools/src/index.ts:701`](../packages/core/tools/src/index.ts) +Sources: [`packages/core/tools/src/index.ts:759`](../packages/core/tools/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -5556,7 +5556,7 @@ Array of `unknown` (opaque). SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -Sources: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +Sources: [`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -7329,7 +7329,7 @@ SHA-256: `c5228b7a55498d84f529591744a0ab26e0b93ade18a70a26db1377a1ecfa6b49` SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` -Sources: [`packages/core/tools/src/index.ts:35`](../packages/core/tools/src/index.ts) +Sources: [`packages/core/tools/src/index.ts:42`](../packages/core/tools/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 92024676bd..da78fe36f3 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -702,7 +702,7 @@ export type SessionEvent = { 'plan/mode': { active: boolean } ``` -来源:[`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -4998,7 +4998,7 @@ SHA-256: `43e311235aa537df1bacdd92d144df8a952337a76e9ac892cdf670f1a797bad8` SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -来源:[`packages/core/tools/src/index.ts:701`](../packages/core/tools/src/index.ts) +来源:[`packages/core/tools/src/index.ts:759`](../packages/core/tools/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5558,7 +5558,7 @@ SHA-256: `b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7` SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -来源:[`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7331,7 +7331,7 @@ SHA-256: `c5228b7a55498d84f529591744a0ab26e0b93ade18a70a26db1377a1ecfa6b49` SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` -来源:[`packages/core/tools/src/index.ts:35`](../packages/core/tools/src/index.ts) +来源:[`packages/core/tools/src/index.ts:42`](../packages/core/tools/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index e9046242ff..2467ac78ef 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -22518,7 +22518,7 @@ "digest": "20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5", "names": [], "sources": [ - "packages/plan/plan-mode/src/index.ts:52" + "packages/plan/plan-mode/src/index.ts:51" ] }, { @@ -22908,7 +22908,7 @@ "packages/core/tools/src/index.ts#ToolRestriction" ], "sources": [ - "packages/core/tools/src/index.ts:701" + "packages/core/tools/src/index.ts:759" ] }, { @@ -24142,7 +24142,7 @@ "digest": "8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543", "names": [], "sources": [ - "packages/core/tools/src/index.ts:35" + "packages/core/tools/src/index.ts:42" ] }, { diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index c6c02c6c42..882e8d364b 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -61,8 +61,14 @@ Source: [`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types interface Agent { /** Session-backed Agent identity. */ readonly id: SessionId - /** The provider route and model this agent's requests use. */ + /** Initial request options; currentRoute() reports the bound request route. */ readonly options: AgentOptions + /** + * Read the immutable route bound to this request and its tool batch. + * @returns the actual provider and model selected by prepareCall(). + * @throws when no main request is prepared; never falls back to prior requests. + */ + currentRoute(): Readonly> /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -952,16 +958,16 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/request` — waterfall -Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs after assembly and `step/start`, before the system prompt and accepted user batch are committed. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. +Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs before context preparation and `agent/pre-step`. Cancellation here or during subsequent `prepareCall()` resolution opens no step and commits no system prompt or user batch. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. ```ts cordis-catalog /** * Replace the frozen call configuration. `await next()` yields the config * the machine would use (agent options on the first request, the logged * header afterwards); return a replacement to switch. On step admission, - * this runs after assembly and `step/start`, before the system prompt and - * accepted user batch are committed. Cancellation here or during subsequent - * `prepareCall()` resolution commits neither. The prepared call capability + * this runs before context preparation and `agent/pre-step`. Cancellation + * here or during subsequent `prepareCall()` resolution opens no step and + * commits no system prompt or user batch. The prepared call capability * governs prompt admission. Model-visible content must use logged channels; * this waterfall cannot mutate messages. * @param payload.agent - the agent making the model call. diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 582a817f1f..2e9bf255f3 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -65,8 +65,14 @@ interface AgentHandle { interface Agent { /** Session-backed Agent identity. */ readonly id: SessionId - /** The provider route and model this agent's requests use. */ + /** Initial request options; currentRoute() reports the bound request route. */ readonly options: AgentOptions + /** + * Read the immutable route bound to this request and its tool batch. + * @returns the actual provider and model selected by prepareCall(). + * @throws when no main request is prepared; never falls back to prior requests. + */ + currentRoute(): Readonly> /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -962,16 +968,16 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/request` — waterfall -Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs after assembly and `step/start`, before the system prompt and accepted user batch are committed. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. +Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs before context preparation and `agent/pre-step`. Cancellation here or during subsequent `prepareCall()` resolution opens no step and commits no system prompt or user batch. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. ```ts cordis-catalog /** * Replace the frozen call configuration. `await next()` yields the config * the machine would use (agent options on the first request, the logged * header afterwards); return a replacement to switch. On step admission, - * this runs after assembly and `step/start`, before the system prompt and - * accepted user batch are committed. Cancellation here or during subsequent - * `prepareCall()` resolution commits neither. The prepared call capability + * this runs before context preparation and `agent/pre-step`. Cancellation + * here or during subsequent `prepareCall()` resolution opens no step and + * commits no system prompt or user batch. The prepared call capability * governs prompt admission. Model-visible content must use logged channels; * this waterfall cannot mutate messages. * @param payload.agent - the agent making the model call. diff --git a/docs/subsystems/plan.md b/docs/subsystems/plan.md index 1c29a87851..bf19460d13 100644 --- a/docs/subsystems/plan.md +++ b/docs/subsystems/plan.md @@ -50,7 +50,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.planMode` — `PlanModeController` -`ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, the `plan:policy` section, the `/plan` command, and the stable exit tool. Client carriers expose the projection's cropped `{ active, pending }` view. +`ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, the `plan:policy` section, the `/plan` command, and the conditional exit tool. Client carriers expose the projection's cropped `{ active, pending }` view. ```ts cordis-catalog /** diff --git a/docs/subsystems/plan.zh.md b/docs/subsystems/plan.zh.md index db2a7e1c2b..11cc861a1f 100644 --- a/docs/subsystems/plan.zh.md +++ b/docs/subsystems/plan.zh.md @@ -50,7 +50,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.planMode` — `PlanModeController` -`ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, the `plan:policy` section, the `/plan` command, and the stable exit tool. Client carriers expose the projection's cropped `{ active, pending }` view. +`ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, the `plan:policy` section, the `/plan` command, and the conditional exit tool. Client carriers expose the projection's cropped `{ active, pending }` view. ```ts cordis-catalog /** diff --git a/docs/subsystems/system-prompt.md b/docs/subsystems/system-prompt.md index c529c150bb..76d9fed53e 100644 --- a/docs/subsystems/system-prompt.md +++ b/docs/subsystems/system-prompt.md @@ -184,23 +184,29 @@ variable(name: string, provider: (context: AssembleContext) => string | undefine * added only by the assembly waterfall retain their accepted values. Current * suppression removes optional contexts, and missing required registrations * are restored in registry order. Sections, tools, and interpolation variables - * retain the accepted assembly; their providers and waterfall do not rerun. + * retain their accepted values during this refresh. * @param assembly - accepted assembly for this scope and step. * @param context - the same scope and current plugin-defined assembly fields. * @returns the accepted assembly with current runtime-context provider text. */ -refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly +refreshContext(assembly: T, context: AssembleContext = {}): T /** - * Assemble global and scoped providers, detach tool parameters, apply - * canonical ordering, then run the assembly waterfall. Scoped sections and - * variables shadow globals. The returned waterfall value is authoritative - * except that an effective complete section is restored afterwards as the - * sole prompt section. - * @param context - the optional scope and plugin-defined assembly fields. - * @returns the post-waterfall assembly with any complete prompt enforced. + * Prepare variables and runtime facts before accepting a step. No tool + * conditions or prompt sections are evaluated in this phase. + * @param context - calling scope and request cancellation. + * @returns prepared inputs after the preparation waterfall. */ -async assemble(context: AssembleContext = {}): Promise +async prepare(context: AssembleContext = {}): Promise + +/** + * Assemble prompt sections and tool declarations after request preparation. + * The presentation waterfall cannot replace provider-owned tools. + * @param context - calling scope, route-bound agent, and resolved tools. + * @param preparation - accepted variables and runtime facts; prepared here when omitted. + * @returns the complete assembly with ordered tool declarations. + */ +async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise ``` Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) @@ -213,13 +219,13 @@ Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system- #### `system-prompt/assemble` — waterfall -Expert waterfall over the assembled sections, contexts, tools, and variables. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners receive only that scope's assemblies. The returned value is authoritative. A supplied signal controls only this explicit assembly request and must not be retained to control later turns. A registered complete section is restored after this waterfall, so listeners cannot add to or replace that scope's system prompt. +Presentation waterfall over assembled sections, contexts, and variables. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners receive only that scope's assemblies. The returned text is authoritative; tool declarations remain provider-owned. A supplied signal controls only this explicit assembly request and must not be retained to control later turns. A registered complete section is restored after this waterfall, so listeners cannot add to or replace that scope's system prompt. ```ts cordis-catalog /** - * Expert waterfall over the assembled sections, contexts, tools, and variables. + * Presentation waterfall over assembled sections, contexts, and variables. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners - * receive only that scope's assemblies. The returned value is authoritative. + * receive only that scope's assemblies. The returned text is authoritative; tool declarations remain provider-owned. * A supplied signal controls only this explicit assembly request and must not * be retained to control later turns. A registered complete section is * restored after this waterfall, so listeners cannot add to or replace @@ -228,7 +234,7 @@ Expert waterfall over the assembled sections, contexts, tools, and variables. Sc * @param context - the caller's per-assembly context. * @mode waterfall */ -'system-prompt/assemble'(this: Scoped, assembly: PromptAssembly, context: AssembleContext, next: () => Promise): Promise +'system-prompt/assemble'(this: Scoped, assembly: PromptPresentation, context: AssembleContext, next: () => Promise): Promise ``` Types: [Scoped](scope.md) @@ -250,5 +256,25 @@ Emitted when any prompt provider changes. This registry notification is unfilter 'system-prompt/change'(): void ``` +Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) + + + +#### `system-prompt/prepare` — waterfall + +Prepare variables and runtime context before step admission. + +```ts cordis-catalog +/** + * Prepare variables and runtime context before step admission. + * @param preparation - registered variables and context contributions. + * @param context - calling scope and cancellation. + * @mode waterfall + */ +'system-prompt/prepare'(this: Scoped, preparation: PromptPreparation, context: AssembleContext, next: () => Promise): Promise +``` + +Types: [Scoped](scope.md) + Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) diff --git a/docs/subsystems/system-prompt.zh.md b/docs/subsystems/system-prompt.zh.md index a805c1d771..12ce785206 100644 --- a/docs/subsystems/system-prompt.zh.md +++ b/docs/subsystems/system-prompt.zh.md @@ -184,23 +184,29 @@ variable(name: string, provider: (context: AssembleContext) => string | undefine * added only by the assembly waterfall retain their accepted values. Current * suppression removes optional contexts, and missing required registrations * are restored in registry order. Sections, tools, and interpolation variables - * retain the accepted assembly; their providers and waterfall do not rerun. + * retain their accepted values during this refresh. * @param assembly - accepted assembly for this scope and step. * @param context - the same scope and current plugin-defined assembly fields. * @returns the accepted assembly with current runtime-context provider text. */ -refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly +refreshContext(assembly: T, context: AssembleContext = {}): T /** - * Assemble global and scoped providers, detach tool parameters, apply - * canonical ordering, then run the assembly waterfall. Scoped sections and - * variables shadow globals. The returned waterfall value is authoritative - * except that an effective complete section is restored afterwards as the - * sole prompt section. - * @param context - the optional scope and plugin-defined assembly fields. - * @returns the post-waterfall assembly with any complete prompt enforced. + * Prepare variables and runtime facts before accepting a step. No tool + * conditions or prompt sections are evaluated in this phase. + * @param context - calling scope and request cancellation. + * @returns prepared inputs after the preparation waterfall. */ -async assemble(context: AssembleContext = {}): Promise +async prepare(context: AssembleContext = {}): Promise + +/** + * Assemble prompt sections and tool declarations after request preparation. + * The presentation waterfall cannot replace provider-owned tools. + * @param context - calling scope, route-bound agent, and resolved tools. + * @param preparation - accepted variables and runtime facts; prepared here when omitted. + * @returns the complete assembly with ordered tool declarations. + */ +async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise ``` Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) @@ -213,13 +219,13 @@ Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system- #### `system-prompt/assemble` — waterfall -Expert waterfall over the assembled sections, contexts, tools, and variables. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners receive only that scope's assemblies. The returned value is authoritative. A supplied signal controls only this explicit assembly request and must not be retained to control later turns. A registered complete section is restored after this waterfall, so listeners cannot add to or replace that scope's system prompt. +Presentation waterfall over assembled sections, contexts, and variables. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners receive only that scope's assemblies. The returned text is authoritative; tool declarations remain provider-owned. A supplied signal controls only this explicit assembly request and must not be retained to control later turns. A registered complete section is restored after this waterfall, so listeners cannot add to or replace that scope's system prompt. ```ts cordis-catalog /** - * Expert waterfall over the assembled sections, contexts, tools, and variables. + * Presentation waterfall over assembled sections, contexts, and variables. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners - * receive only that scope's assemblies. The returned value is authoritative. + * receive only that scope's assemblies. The returned text is authoritative; tool declarations remain provider-owned. * A supplied signal controls only this explicit assembly request and must not * be retained to control later turns. A registered complete section is * restored after this waterfall, so listeners cannot add to or replace @@ -228,7 +234,7 @@ Expert waterfall over the assembled sections, contexts, tools, and variables. Sc * @param context - the caller's per-assembly context. * @mode waterfall */ -'system-prompt/assemble'(this: Scoped, assembly: PromptAssembly, context: AssembleContext, next: () => Promise): Promise +'system-prompt/assemble'(this: Scoped, assembly: PromptPresentation, context: AssembleContext, next: () => Promise): Promise ``` Types: [Scoped](scope.zh.md) @@ -250,5 +256,25 @@ Emitted when any prompt provider changes. This registry notification is unfilter 'system-prompt/change'(): void ``` +Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) + + + +#### `system-prompt/prepare` — waterfall + +Prepare variables and runtime context before step admission. + +```ts cordis-catalog +/** + * Prepare variables and runtime context before step admission. + * @param preparation - registered variables and context contributions. + * @param context - calling scope and cancellation. + * @mode waterfall + */ +'system-prompt/prepare'(this: Scoped, preparation: PromptPreparation, context: AssembleContext, next: () => Promise): Promise +``` + +Types: [Scoped](scope.zh.md) + Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index 585ce1582a..c9e0a46a73 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -206,6 +206,8 @@ interface ToolExecutionInput { readonly arguments: unknown /** The agent on whose behalf the call runs (set by the agent loop). */ readonly agent?: Agent + /** Request admission shared by Native and PTC dispatch. Conditional tools require it. */ + readonly toolSet?: ResolvedToolSet /** * Opaque token of the enclosing transport execution, when one exists. PTC * mode sets this on SDK sub-dispatches so commit-style observers can wait for @@ -525,9 +527,10 @@ presentAs(mode: ToolPresentationMode): () => void * Register globally or in the calling agent scope. Scoped tools shadow * globals; duplicates within one layer and the reserved `run_code` name fail. * @param definition - tool schema, execution, and optional finalization/presentation callbacks. + * @param options - optional request-time activation condition. * @returns the exact disposer that unregisters the tool. */ -register(definition: ToolDefinition): () => void +register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void /** * Restrict global tools for the calling agent scope. Empty filters, unknown @@ -557,17 +560,28 @@ guard(guard: ToolGuard): () => void * actually executed. * @param name - the tool name as registered. * @param scope - the viewing scope (the agent); omitted = the global view. + * @param toolSet - request admission; omit only to inspect registered definitions. * @returns the definition the scope resolves, or undefined when none is visible. */ -get(name: string, scope?: ScopeKey): ToolDefinition | undefined +get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined + +/** + * Resolve conditions once for this request without changing shared registrations. + * Cancellation or a rejected condition publishes no partial selection. Removed + * registrations cannot be restored by a late condition result. + * @param context - agent with a bound route and request cancellation. + * @returns the complete selection; the caller disposes it after its tool batch settles. + */ +async resolve(context: ToolActivationContext): Promise /** * Project visible definitions onto the allowlisted model-facing schema fields, * excluding execution and presentation callbacks. * @param scope - the viewing scope (the agent); omitted = the global view. + * @param toolSet - request admission, or omitted for registered-definition inspection. * @returns one deep-cloned schema per visible tool. */ -schemas(scope?: ScopeKey): ToolSchema[] +schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[] /** * Classify a pending call through the caller's visible tool definition. Only diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 4ee27fcb4d..81a1408320 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -206,6 +206,8 @@ interface ToolExecutionInput { readonly arguments: unknown /** The agent on whose behalf the call runs (set by the agent loop). */ readonly agent?: Agent + /** Request admission shared by Native and PTC dispatch. Conditional tools require it. */ + readonly toolSet?: ResolvedToolSet /** * Opaque token of the enclosing transport execution, when one exists. PTC * mode sets this on SDK sub-dispatches so commit-style observers can wait for @@ -525,9 +527,10 @@ presentAs(mode: ToolPresentationMode): () => void * Register globally or in the calling agent scope. Scoped tools shadow * globals; duplicates within one layer and the reserved `run_code` name fail. * @param definition - tool schema, execution, and optional finalization/presentation callbacks. + * @param options - optional request-time activation condition. * @returns the exact disposer that unregisters the tool. */ -register(definition: ToolDefinition): () => void +register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void /** * Restrict global tools for the calling agent scope. Empty filters, unknown @@ -557,17 +560,28 @@ guard(guard: ToolGuard): () => void * actually executed. * @param name - the tool name as registered. * @param scope - the viewing scope (the agent); omitted = the global view. + * @param toolSet - request admission; omit only to inspect registered definitions. * @returns the definition the scope resolves, or undefined when none is visible. */ -get(name: string, scope?: ScopeKey): ToolDefinition | undefined +get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined + +/** + * Resolve conditions once for this request without changing shared registrations. + * Cancellation or a rejected condition publishes no partial selection. Removed + * registrations cannot be restored by a late condition result. + * @param context - agent with a bound route and request cancellation. + * @returns the complete selection; the caller disposes it after its tool batch settles. + */ +async resolve(context: ToolActivationContext): Promise /** * Project visible definitions onto the allowlisted model-facing schema fields, * excluding execution and presentation callbacks. * @param scope - the viewing scope (the agent); omitted = the global view. + * @param toolSet - request admission, or omitted for registered-definition inspection. * @returns one deep-cloned schema per visible tool. */ -schemas(scope?: ScopeKey): ToolSchema[] +schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[] /** * Classify a pending call through the caller's visible tool definition. Only diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.i18n.yaml new file mode 100644 index 0000000000..94da8216ed --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.md +/: + en: 0a9569f33806d6bf + zh: 3bd885a0d518aad8 +/update-conditional-tools-and-prompt-hooks: + en: a292521a564f5f0b + zh: 2e15d7b96d966b29 +/update-conditional-tools-and-prompt-hooks/change: + en: 018c4ade3568fbc5 + zh: e2f0f9c1467250be +/update-conditional-tools-and-prompt-hooks/migration: + en: abe994f27c41f65e + zh: 106d04a591a0faa2 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.md new file mode 100644 index 0000000000..b9cc48a160 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Custom tool and prompt plugins must use request-owned tool admission and the earlier route preparation stage." +--- + +# Update conditional tools and prompt hooks + +English | [中文](guide.zh.md) + +## Change + +`agent/request` and `prepareCall()` bind the route before `agent/pre-step`. Runtime context preparation uses `system-prompt/prepare`; `system-prompt/assemble` receives presentation fields without a tool array. Tool declarations remain owned by registered providers. Conditional tools require a resolved request set for execution, including nested PTC calls. Replacing a registration does not authorize an outstanding call to run the replacement. + +`exit_plan_mode` is offered only while committed plan mode is active. A failed plan-state write stops step admission and keeps the pending selection. Existing Sessions require no format migration. + +## Migration + +1. Declare tool conditions with `ctx.tools.register(definition, { when })`. Read the bound route through `agent.currentRoute()`; never infer it from initial options or the preceding Session header. +2. Move runtime-context preparation listeners to `system-prompt/prepare`. Keep presentation changes in `system-prompt/assemble` and stop replacing its tool list. +3. For programmatic conditional calls, resolve `{ agent, signal }` through `ctx.tools.resolve()`, pass the resulting `toolSet` to assembly and execution, and dispose it after the batch settles. AgentLoop does this for model calls. Pass `context.toolSet` when tool guidance queries `ctx.tools.get()` or `schemas()`. +4. Update custom Agent implementations with `currentRoute()`, valid only while a main request is bound. Verify that inactive tools are absent from declarations and that a historical name returns `UNKNOWN_TOOL` without reaching the implementation. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.zh.md new file mode 100644 index 0000000000..1d4b35bca4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-alpha.1/conditional-tools/guide.zh.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "自定义工具和提示词插件必须使用请求拥有的工具准入集合以及提前的路由准备阶段。" +--- + +# 更新条件工具与提示词钩子 + +[English](guide.md) | 中文 + +## 变更 + +`agent/request` 与 `prepareCall()` 在 `agent/pre-step` 之前绑定路由。运行时上下文准备使用 `system-prompt/prepare`;`system-prompt/assemble` 接收不含工具数组的展示字段。工具声明仍由已注册提供方持有。条件工具执行需要已解析的请求集合,包括嵌套 PTC 调用。替换注册不会授权尚未执行的旧调用使用新实现。 + +`exit_plan_mode` 只在已提交的计划模式启用时提供。计划状态写入失败会停止步骤接纳并保留待提交选择。现有 Session 无需格式迁移。 + +## 迁移 + +1. 使用 `ctx.tools.register(definition, { when })` 声明工具条件。通过 `agent.currentRoute()` 读取已绑定路由,不从初始选项或先前 Session 请求头推断。 +2. 将运行时上下文准备监听器迁移到 `system-prompt/prepare`。展示变更留在 `system-prompt/assemble`,停止替换它的工具列表。 +3. 程序化调用条件工具时,通过 `ctx.tools.resolve()` 解析 `{ agent, signal }`,将返回的 `toolSet` 传给组装与执行,并在批次结束后释放。AgentLoop 会为模型调用完成这些操作。工具指导查询 `ctx.tools.get()` 或 `schemas()` 时传入 `context.toolSet`。 +4. 为自定义 Agent 实现补充 `currentRoute()`,仅在主请求已绑定期间可用。验证未启用工具不出现在声明中,且使用历史名称调用会返回 `UNKNOWN_TOOL`,不会进入实现。 diff --git a/packages/api/job-controller/tests/host-harness.ts b/packages/api/job-controller/tests/host-harness.ts index 85609166b0..79776efbd9 100644 --- a/packages/api/job-controller/tests/host-harness.ts +++ b/packages/api/job-controller/tests/host-harness.ts @@ -21,6 +21,7 @@ export async function registerAgent(ctx: Context, rawId: string): Promise Promise } = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/api/job-controller/tests/observe.host.spec.ts b/packages/api/job-controller/tests/observe.host.spec.ts index 583862eeac..51b24ff063 100644 --- a/packages/api/job-controller/tests/observe.host.spec.ts +++ b/packages/api/job-controller/tests/observe.host.spec.ts @@ -226,6 +226,7 @@ describe('JobController', () => { async function liveOwner(ctx: Context, rawId: string): Promise { const session = ctx.sessions.create(SessionId(rawId)) const owner: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/api/session-controller/tests/archived-session-gate.host.spec.ts b/packages/api/session-controller/tests/archived-session-gate.host.spec.ts index 79bad41b7c..8209040d68 100644 --- a/packages/api/session-controller/tests/archived-session-gate.host.spec.ts +++ b/packages/api/session-controller/tests/archived-session-gate.host.spec.ts @@ -26,6 +26,7 @@ async function harness(): Promise { /** A registered idle Agent double: the gate reads only its Session header. */ async function liveAgent(ctx: Context, session: Session): Promise { const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index cc73507d5f..e290f7a342 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -149,6 +149,7 @@ async function bench(script: Script, options: BenchOptions = {}): Promise<{ let idle = Promise.resolve() let running = false const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: createOptions.agentOptions ?? {}, session, diff --git a/packages/context/session-reference/README.i18n.yaml b/packages/context/session-reference/README.i18n.yaml index 51063bf115..3b7443317e 100644 --- a/packages/context/session-reference/README.i18n.yaml +++ b/packages/context/session-reference/README.i18n.yaml @@ -27,14 +27,14 @@ en: 169f100ba62f2120 zh: 3fd4fc0bd73b2370 /deepseek-ai-dsh-session-reference/use-this-package/configuration: - en: d9abc1b28c3feb40 - zh: ac85539027b37130 + en: 5dfb1f0c52d300bf + zh: ae731dd6fcd93027 /deepseek-ai-dsh-session-reference/understand-the-implementation: en: db349483e453caf7 zh: 70035c291e1efe84 /deepseek-ai-dsh-session-reference/understand-the-implementation/design-concept: - en: 5c7712ca91eaae1c - zh: 2d923b605afa7a88 + en: d7ff10eae41712ad + zh: 2b91a16dee11808e /deepseek-ai-dsh-session-reference/understand-the-implementation/source-map: en: 7c7b413082507150 zh: 0229eb73d441b305 diff --git a/packages/context/session-reference/README.md b/packages/context/session-reference/README.md index 4c594635b5..79221efeec 100644 --- a/packages/context/session-reference/README.md +++ b/packages/context/session-reference/README.md @@ -50,7 +50,7 @@ For a truncated reference, an optional spill backend saves the full captured tex | `maxReferenceBytes` | automatic | Explicit maximum serialized JSON bytes per source; overrides the automatic budget exactly | | `referenceContextFraction` | `0.2` | Context-window fraction per source, from `0` to `1` | -The automatic budget is `max(65536, floor(contextWindow × 4 × referenceContextFraction))` bytes per source. Model context capacity is measured in tokens; four bytes per token is a sizing heuristic, not an exact token conversion. A missing route, LLM service, adapter, or capacity uses 64 KiB; other model metadata lookup errors and cancellation fail preparation. +The automatic budget is `max(65536, floor(contextWindow × 4 × referenceContextFraction))` bytes per source. Model context capacity is measured in tokens; four bytes per token is a sizing heuristic, not an exact token conversion. A missing LLM service, adapter, or capacity uses 64 KiB; other model metadata lookup errors and cancellation fail preparation. The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-reference) is the exhaustive source for every accepted field and its JSDoc. @@ -70,7 +70,7 @@ Preparation reads each referenced session's current surface exactly once, when t The resolver discovers optional storage through `ctx.get("spillStore")` and saves only truncated references. Storage ownership is the target session; the source descriptor identifies the referenced session and label, without a fabricated tool call. Cancellation is checked after the asynchronous save and prevents publication even if an artifact was written. Artifact expiry remains the backend's existing policy. -The budget uses the provider and model captured after `system-prompt/assemble` completes for the target agent. Direct `prepare` calls before any assembly use agent options; session headers do not select the budget model. Diagnostic assemblies without an agent do not affect captured routes. +The budget uses `agent.currentRoute()`, bound before step input preparation. The agent must have a prepared main request when a model-relative budget is needed; initial options and stored headers do not select the budget model. ### Source map diff --git a/packages/context/session-reference/README.zh.md b/packages/context/session-reference/README.zh.md index c1f8b58d59..edd4e673b4 100644 --- a/packages/context/session-reference/README.zh.md +++ b/packages/context/session-reference/README.zh.md @@ -50,7 +50,7 @@ kind: "package-reference" | `maxReferenceBytes` | 自动 | 每个来源的最大序列化 JSON 字节数;显式设置时精确覆盖自动预算 | | `referenceContextFraction` | `0.2` | 每个来源的上下文窗口比例,范围为 `0` 到 `1` | -自动预算为每个来源 `max(65536, floor(contextWindow × 4 × referenceContextFraction))` 字节。模型上下文容量以 token 计量;每个 token 四字节是容量估算,不是精确的 token 换算。缺少路由、LLM(大语言模型)服务、适配器或容量时使用 64 KiB;其他模型元数据查询错误与取消会使准备失败。 +自动预算为每个来源 `max(65536, floor(contextWindow × 4 × referenceContextFraction))` 字节。模型上下文容量以 token 计量;每个 token 四字节是容量估算,不是精确的 token 换算。缺少 LLM(大语言模型)服务、适配器或容量时使用 64 KiB;其他模型元数据查询错误与取消会使准备失败。 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-reference)是每个受支持字段及其 JSDoc 的穷尽式真源。 @@ -70,7 +70,7 @@ kind: "package-reference" 解析器通过 `ctx.get("spillStore")` 获取可选存储,只保存被截断的引用。存储归目标会话所有;来源信息标识被引用的源会话与标签,不伪造工具调用。异步保存后会检查取消,即使产物已写入,也会阻止发布。产物过期仍遵循后端既有策略。 -预算使用目标 agent 的 `system-prompt/assemble` 完成后捕获的提供方与模型。首次组装前直接调用 `prepare` 时使用 agent 选项;会话头不决定预算模型。不带 agent 的诊断组装不会影响已捕获路由。 +预算使用步骤输入准备前绑定的 `agent.currentRoute()`。需要模型相对预算时,agent 必须已有准备完成的主请求;初始选项与已存储请求头不决定预算模型。 ### 源码地图 diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index f2082d85e2..df9a66e850 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -92,7 +92,6 @@ export class SessionReferenceResolver extends TypertRemoteService { }) private readonly config: Required> & { maxReferenceBytes: number | undefined } - private readonly assembledRoutes = new WeakMap() constructor(ctx: Context, config: Config = {}) { super(ctx, 'sessionReferenceResolver') @@ -123,15 +122,6 @@ export class SessionReferenceResolver extends TypertRemoteService { 'SESSION_REFERENCE_INVALID_CONFIG', ) } - // Prepend observes model-selection overrides after downstream assembly completes. - ctx.on('system-prompt/assemble', async (_assembly, context, next) => { - const assembly = await next() - if (context.agent !== undefined) { - const { provider, model } = assembly.variables - this.assembledRoutes.set(context.agent, { provider, model }) - } - return assembly - }, { prepend: true }) ctx.on('agent/pre-step', async ({ agent, signal }, next): Promise => { const decision = await next() if (decision.kind === 'reject') return decision @@ -359,10 +349,9 @@ export class SessionReferenceResolver extends TypertRemoteService { private async referenceBudget(agent: Agent, signal: AbortSignal | undefined): Promise { if (this.config.maxReferenceBytes !== undefined) return this.config.maxReferenceBytes - // Options seed direct preparation; an assembled route owns model-step preparation. - const { provider, model } = this.assembledRoutes.get(agent) ?? agent.options + const { provider, model } = agent.currentRoute() const llm = this.ctx.get('llm') - if (provider === undefined || model === undefined || llm === undefined) return DEFAULT_MAX_REFERENCE_BYTES + if (llm === undefined) return DEFAULT_MAX_REFERENCE_BYTES let info: LlmResolvedModelInfo try { info = await settleWithCancellation(llm.resolveModelInfo(provider, model, signal), signal) diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index efc8447e90..b7af57466d 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { agentEvents, installModelSelection, type Agent, type ModelSelectionRef } from '@deepseek-ai/dsh-agent' +import { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { CompactionId, compactCheckpointSource } from '@deepseek-ai/dsh-compaction' import LlmRuntime, { createDeveloperMessage, createMessage, createSystemMessage, createToolResultMessage, createUserMessage, LlmError, ToolCallId } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' @@ -86,7 +86,8 @@ function withProjectionCache( } function fakeAgent(session: Session): Agent { - return { id: session.id, session, options: {} } as Agent + const options: Agent['options'] = {} + return { id: session.id, session, options, currentRoute: () => ({ provider: options.provider ?? 'seed', model: options.model ?? 'seed' }) } as Agent } function expectCode(code: SessionReferenceErrorCode): Error { @@ -533,12 +534,10 @@ describe('model-relative reference budgets', () => { else expect(resolve).toHaveBeenCalledWith('seed', 'seed', undefined) }) - it('uses the assembled selection, not the header, seed, or next selected model', async () => { + it('uses the bound request route independently of stored and initial routes', async () => { const { ctx, agent, source, resolve } = await setup() - const selection: ModelSelectionRef = { current: { provider: 'selected', model: 'large' }, assembled: undefined } - installModelSelection(ctx, selection) - await ctx.systemPrompt.assemble({ agent, scope: agent }) - selection.current = { provider: 'selected', model: 'small' } + let route = { provider: 'selected', model: 'large' } + vi.spyOn(agent, 'currentRoute').mockImplementation(() => route) const message = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const signal = new AbortController().signal const enter = () => agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, signal }, @@ -551,6 +550,7 @@ describe('model-relative reference budgets', () => { expect(bytes({ content: [], additionalContext: firstContext })).toBe(160_000) expect(resolve).toHaveBeenLastCalledWith('selected', 'large', signal) await ctx.systemPrompt.assemble({ agent, scope: agent }) + route = { provider: 'selected', model: 'small' } resolve.mockResolvedValue({ provider: 'selected', id: 'small', name: 'small', context: { contextWindow: 8_000 } }) const second = await enter() if (second.kind !== 'enter' || second.messages[1] === undefined) throw new Error('expected reference context') @@ -558,23 +558,13 @@ describe('model-relative reference budgets', () => { expect(resolve).toHaveBeenLastCalledWith('selected', 'small', signal) }) - it('uses the floor for absent metadata, service, or assembled route and ignores diagnostic assemblies', async () => { + it('uses the floor for absent metadata or service', async () => { const { ctx, agent, resolve, prepare, llmFiber } = await setup() - await ctx.systemPrompt.assemble() resolve.mockResolvedValue({ provider: 'seed', id: 'seed', name: 'seed' }) expect(bytes(await prepare())).toBe(65_536) expect(resolve).toHaveBeenCalledOnce() - await ctx.systemPrompt.assemble({ agent, scope: agent }) - expect(bytes(await prepare())).toBe(65_536) - expect(resolve).toHaveBeenCalledOnce() - delete agent.options.model - const other = fakeAgent(agent.session) - other.options.provider = 'seed' - await ctx.sessionReferenceResolver.prepare(other, [], [{ sessionId: SessionId('source') }]) - expect(resolve).toHaveBeenCalledOnce() await llmFiber.dispose() - other.options.model = 'seed' - expect(bytes(await ctx.sessionReferenceResolver.prepare(other, [], [{ sessionId: SessionId('source') }]))).toBe(65_536) + expect(bytes(await ctx.sessionReferenceResolver.prepare(agent, [], [{ sessionId: SessionId('source') }]))).toBe(65_536) }) it('uses the floor when the real LLM runtime has no adapter for the route', async () => { @@ -619,7 +609,7 @@ describe('model-relative reference budgets', () => { expect(read).not.toHaveBeenCalled() }) - it('removes both listeners when the resolver fiber is disposed', async () => { + it('removes the preparation listener when the resolver fiber is disposed', async () => { const { ctx, agent, source, resolve, resolverFiber } = await setup() const resolver = ctx.sessionReferenceResolver await resolverFiber.dispose() diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index 92499007d1..f5b28c96ef 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -47,6 +47,7 @@ async function mount(config: Config = {}) { function sessionAgent(session: Session, id = 'agent'): Agent { const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: SessionId(id), options: {}, session, diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index ae15f20a46..b895f139db 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -106,6 +106,7 @@ async function mount( function sessionAgent(session: Session, id = 'agent'): Agent { const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: SessionId(id), options: {}, session, diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 0bbdb05d37..5c19f9b0b8 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -45,8 +45,8 @@ en: 3c5721bc00a0bbf4 zh: 711f832343ffbb75 /deepseek-ai-dsh-agent-loop/understand-the-implementation/turn-and-step-flow: - en: 28939261ccc7defe - zh: 9d157a321307ebd4 + en: 29c33bc92b4a8db6 + zh: d1152a6656bb772d /deepseek-ai-dsh-agent-loop/understand-the-implementation/failure-and-cancellation: en: eea56903c4ff82f5 zh: c0d5abb5767780ed @@ -63,8 +63,8 @@ en: ed0e841bed26a836 zh: f30d91bc5a64fa20 /deepseek-ai-dsh-agent-loop/model-experience/complete-conversation-request/token-effect: - en: ad93d8d61968a25d - zh: 268ff858b0fa96e8 + en: 3862d03b3b4d6ec4 + zh: 164c6ecc8a21fdb1 /deepseek-ai-dsh-agent-loop/model-experience/complete-conversation-request/kv-cache-effect: en: c002d27c825d04e8 zh: b0dbdd95d3b3b6b5 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 62dcd35a92..7ff895ef11 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -117,7 +117,7 @@ The loop is the production acquisition point for session write handles. When `ct ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver assembles the prompt and tools and runs `agent/pre-step`; the fallback projects runtime context after listeners run. A rejected decision or empty first batch opens no step. On the first attempt after acceptance, `step/start` precedes the `agent/request` waterfall and `prepareCall()`; neither async phase sees the pending system prompt or accepted users committed to history, and cancellation during either commits neither. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts without reassembling the bound prompt or tools, appends the accepted `user/message` batch only on the first attempt with its owned context candidate replaced in place, and restores removed runtime context, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the same rendered assembly without repeating assembly, `agent/pre-step`, or user admission. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver binds the route through `agent/request` and `prepareCall()`, prepares variables and runtime context, then runs `agent/pre-step`; its fallback projects that context. A rejected decision or empty first batch opens no step. Cancellation during route preparation commits neither a system prompt nor users. After acceptance, `step/start` precedes asynchronous tool activation and final prompt assembly. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt with its owned context candidate replaced in place, and restores removed runtime context, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries resolve tool conditions against their bound route without repeating `agent/pre-step` or user admission. An unchanged route and tool schema set reuse the accepted prompt; a changed route or tool set assembles the corresponding prompt again. The request-owned tool set is closed after dispatch settles, and the bound Agent route is cleared when the step ends. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) Prompt admission uses the actual `prepareCall()` result, not the preceding `request/context`. With no system node, even an empty prompt is appended (reserving node 0 without a wire message). On an incapable route or at a new request series, a non-empty rendering is consolidated at the first system node: each non-empty later system node receives a logged per-node empty replacement, then the head is rewritten if needed. Dormant empty tails need no replacement and do not determine the effective text. Consolidation applies even when the latest effective text is unchanged. On a continuing `in-history` series, an unchanged effective prompt produces no event and a non-empty change appends. An empty rendering clears every non-empty later system node through a logged per-node empty replacement, then empties the head if needed, regardless of route or series state. No older instructions remain model-visible. An empty head with no active later system node means no prompt; repeated clears and resume leave it empty. A restored non-empty prompt follows the same route/series rule: a continuing capable route may append it, while an incapable route or new series refills the head. A step starts a series when the pre-step decision declares `startsRequestSeries` or `session.surface.contentGeneration` changed since attachment or the last request (a replacement or image-offload decision). Visible tool-schema changes force prompt consolidation only when the prepared route lacks `toolUpdate`. Routes supporting both tool and system-prompt updates can append a changed prompt and activate added tools without rewriting earlier messages. If another admission condition replaces a system node, the request starts a new series with current tool declarations. Resume and a provider or model swap alone continue the series; the prepared route still governs admission. Per-node empty replacements preserve intervening history without a surface delete operation. @@ -157,7 +157,7 @@ For each step, the loop sends the session's derived messages and visible tool sc #### Token effect -System text and schemas are paid again on every step, and on an `in-history` route every retained prompt version is paid until compaction shadows it or prompt reconciliation empties it. Per-agent scoping chooses the contributions, while the authoritative assembly waterfall can alter the final request and makes its listener responsible for protocol coherence. +System text and schemas are paid again on every step, and on an `in-history` route every retained prompt version is paid until compaction shadows it or prompt reconciliation empties it. Per-agent scoping chooses the contributions, while the presentation waterfall can alter prompt text but cannot replace provider-owned tool declarations. #### KV Cache effect diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index ee355a328d..daf4663ac9 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -117,7 +117,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器组装提示词与工具,并运行 `agent/pre-step`;fallback 在监听器执行后投影运行时上下文。被拒绝的决定或空的首批输入不打开步骤。接纳后的首次尝试先记录 `step/start`,再运行 `agent/request` waterfall 与 `prepareCall()`;这两个异步阶段都看不到待提交的系统提示词与已接纳用户消息进入历史,在任一阶段取消都不会提交这两者。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实而不重新组装绑定的提示词或工具、仅在首次尝试追加已接纳的 `user/message` 批次并原位替换循环自有上下文候选、恢复被移除的运行时上下文、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试复用同一份已渲染组装结果,不重复组装、`agent/pre-step` 或用户消息准入。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器通过 `agent/request` 与 `prepareCall()` 绑定路由,准备变量和运行时上下文,然后运行 `agent/pre-step`;fallback 投影该上下文。被拒绝的决定或空的首批输入不打开步骤。路由准备期间取消不会提交系统提示词或用户消息。接纳后,`step/start` 先于异步工具激活与最终提示词组装。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次并原位替换循环自有上下文候选、恢复被移除的运行时上下文、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试按其绑定路由重新解析工具条件,不重复 `agent/pre-step` 或用户消息接纳。路由与工具 schema 集合未变时复用已接纳提示词;任一变化时重新组装对应提示词。请求拥有的工具集合在分派结束后关闭,Agent 的绑定路由在步骤结束时清除。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 提示词准入依据实际的 `prepareCall()` 结果,而非先前的 `request/context`。没有系统节点时,即使提示词为空也追加(预留第 0 号节点,但不产生协议消息)。在不具备能力的路由上或新请求序列开始时,非空渲染文本归并到首个系统节点:每个非空的后续系统节点分别收到有日志记录的空内容替换,随后按需重写头节点。未生效的空尾节点无需替换,也不决定有效文本。即使最新有效文本未变,也执行归并。延续中的 `in-history` 序列在有效提示词不变时不产生事件,非空变更则追加。无论路由或序列状态如何,空渲染文本都会通过有日志记录的逐节点空内容替换清除每个非空的后续系统节点,再按需清空头节点。模型不会继续看到旧指令。空头节点且没有生效的后续系统节点表示没有提示词;重复清除与恢复会话都保持为空。重新提供的非空提示词遵循同一路由/序列规则:延续中的具备能力路由可以追加它,不具备能力的路由或新序列则重新填充头节点。以下情况开启序列:pre-step 决定声明 `startsRequestSeries`,或 `session.surface.contentGeneration` 自附接或上次请求以来发生变化(替换或图片省略决定)。仅当已准备路由未声明 `toolUpdate` 时,可见工具 schema 变化才强制归并提示词。同时支持工具和系统提示词更新的路由可以追加变更后的提示词并激活新增工具,无需改写此前消息。如果其他准入条件替换系统节点,请求会以当前工具声明开启新序列。恢复与单纯的提供方或模型切换都延续序列;准入仍由已准备的路由决定。逐节点的空内容替换保留其间历史,无需 surface 删除操作。 @@ -157,7 +157,7 @@ const handle = await ctx.agents.create({ #### Token 影响 -系统文本与 schema 在每个步骤都会再次计入,在 `in-history` 路由上,每个保留的提示词版本都会持续计入,直到压缩将其遮蔽或提示词协调将其清空。逐 agent 作用域决定贡献,而权威组装 waterfall 可以改变最终请求,并使其监听器负责保持协议连贯。 +系统文本与 schema 在每个步骤都会再次计入,在 `in-history` 路由上,每个保留的提示词版本都会持续计入,直到压缩将其遮蔽或提示词协调将其清空。逐 agent 作用域决定贡献;展示 waterfall 可以修改提示词文本,但不能替换提供方拥有的工具声明。 #### KV Cache 影响 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index adf2e33ddc..d473dc5d23 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -30,7 +30,7 @@ import { createScope } from '@deepseek-ai/dsh-scope' import type { EpochHeader, RequestContext, Session, SessionId, SessionSeq, TurnEndReason, UserMessage } from '@deepseek-ai/dsh-session' import { canonicalHeader, headerEquals, ToolCallRecovery } from '@deepseek-ai/dsh-session' import { joinContextSections, renderContextSections, renderPrompt } from '@deepseek-ai/dsh-system-prompt' -import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt' +import type { PromptAssembly, PromptPreparation } from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-session-projection' import type { Context } from '@deepseek-ai/cordis' import { ReactLoopInbox } from './inbox.ts' @@ -38,6 +38,7 @@ import { RuntimeContextProjection } from './runtime-context.ts' import { AssistantStreamAttempt } from './assistant-stream.ts' import { SystemPromptProjection } from './runtime-context.ts' import { executeToolCalls } from './tool-calls.ts' +import { ToolActivationError } from '@deepseek-ai/dsh-tools' type Phase = | { kind: 'idle'; lastTurn: number } @@ -51,13 +52,19 @@ type Phase = type StepEndReason = Extract +interface PreparedRequest { + config: LlmCallConfig + preparedCall?: PreparedLlmCall +} + type PreparedStep = | { kind: 'reject' } | { kind: 'enter' messages: UserMessage[] startsRequestSeries?: true - assembly: PromptAssembly + preparation: PromptPreparation + request: PreparedRequest } /** Remove adapter-derived values before plugins propose the next request config. */ @@ -97,6 +104,7 @@ function abortedCancelCause(signal: AbortSignal): AgentCancelCause | undefined { /** Drives one session through turn and step boundaries. */ export class ReactLoopAgent implements Agent { readonly inbox: ReactLoopInbox + private requestRoute: Readonly> | undefined private phase: Phase private activityDone: Promise = Promise.resolve() @@ -137,6 +145,11 @@ export class ReactLoopAgent implements Agent { this.systemPrompt = new SystemPromptProjection(session) } + currentRoute(): Readonly> { + if (this.requestRoute === undefined) throw new Error('agent has no prepared model request') + return this.requestRoute + } + get status(): AgentStatus { return this.phase.kind === 'idle' || this.phase.kind === 'maintenance' ? 'idle' : 'running' } @@ -269,12 +282,14 @@ export class ReactLoopAgent implements Agent { if (this.phase.kind !== 'running') throw new Error(`agent "${this.id}": pre-step outside running phase`) const signal = this.phase.abort.signal const claimed = this.inbox.claim(target, position.turn) - const assembly = await this.loopCtx.systemPrompt.assemble(assembleContextFor(this, signal)) + const request = await this.prepareRequest(position.turn, position.step, signal) + const preparation = await this.loopCtx.systemPrompt.prepare(assembleContextFor(this, signal)) + preparation.variables = { ...preparation.variables, ...this.currentRoute() } signal.throwIfAborted() const decision = await this.dispatch.waterfall( 'agent/pre-step', { messages: claimed, ...position, signal }, (): Promise => { - const sections = renderContextSections(assembly) + const sections = renderContextSections(preparation) const context = this.runtimeContext.project(joinContextSections(sections), sections) return Promise.resolve({ kind: 'enter', @@ -284,7 +299,7 @@ export class ReactLoopAgent implements Agent { ) signal.throwIfAborted() if (decision.kind === 'reject') return decision - return { ...decision, assembly } + return { ...decision, preparation, request } } /** Whether the assembled tool schemas differ from the logged request header's. */ @@ -313,6 +328,7 @@ export class ReactLoopAgent implements Agent { let target: InboxTarget = 'next-turn' try { while (true) { + this.requestRoute = undefined signal.throwIfAborted() const step = phase.step + 1 const decision = await this.preStep(target, { turn, step }) @@ -356,6 +372,7 @@ export class ReactLoopAgent implements Agent { } finally { stopRecovery() this.session.append('step/end', { turn, step }) + this.requestRoute = undefined } signal.throwIfAborted() if (turnEnds && this.inbox.nextStep.length === 0) { @@ -372,16 +389,15 @@ export class ReactLoopAgent implements Agent { turnEnds = { kind: 'aborted', reason: cause } throw error } - // Every failure is structured: an `LlmError` keeps its facts, anything - // else flattens to `errorChain` text under the `UNKNOWN` code. turnEnds = { kind: 'error', error: error instanceof LlmError ? error.failure - : { message: errorChain(error), code: 'UNKNOWN' }, + : { message: errorChain(error), code: error instanceof ToolActivationError ? error.code : 'UNKNOWN' }, } this.throwError(error) } finally { + this.requestRoute = undefined try { // oxlint-disable-next-line typescript/no-non-null-assertion -- every exit assigns a turn ending this.session.append('turn/end', { turn, reason: turnEnds! }) @@ -403,159 +419,175 @@ export class ReactLoopAgent implements Agent { const { turn, step, abort: { signal } } = this.phase signal.throwIfAborted() - const { assembly } = decision - const renderedPrompt = renderPrompt(assembly) let firstAttempt = true + let acceptedAssembly: { provider: string; model: string; schemas: string; assembly: PromptAssembly } | undefined while (true) { - const { config, preparedCall } = await this.prepareRequest(turn, step, signal) - const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, assembleContextFor(this, signal)) - const sections = renderContextSections(currentContext) - const context = this.runtimeContext.project(joinContextSections(sections), sections) - signal.throwIfAborted() - const startsRequestSeries = firstAttempt && decision.startsRequestSeries === true - const commits = this.systemPrompt.project(renderedPrompt, { - inHistory: preparedCall?.systemPromptUpdate === 'in-history', - startsSeries: startsRequestSeries - || this.requestSurfaceGeneration !== this.session.surface.contentGeneration - || (preparedCall?.toolUpdate === undefined && this.toolsChanged(assembly.tools)), - }) - for (const { message, intent } of commits) { - this.session.append('system/message', { turn, step, message }, intent) - } - let contextAdmitted = false - if (firstAttempt) { - for (const message of decision.messages) { - if (message.source.kind === 'runtime-context') { - if (context !== undefined && !contextAdmitted) { - this.session.append('user/message', context, { surfaceOp: 'append' }) - contextAdmitted = true + const { config, preparedCall } = firstAttempt ? decision.request : await this.prepareRequest(turn, step, signal) + const toolSet = await this.loopCtx.tools.resolve({ agent: this, signal }) + try { + const schemas = JSON.stringify(this.loopCtx.tools.schemas(this, toolSet)) + if (acceptedAssembly === undefined || acceptedAssembly.provider !== config.provider + || acceptedAssembly.model !== config.model || acceptedAssembly.schemas !== schemas) { + const assembly = await this.loopCtx.systemPrompt.assemble( + { ...assembleContextFor(this, signal), toolSet }, + { ...decision.preparation, variables: { ...decision.preparation.variables, ...this.currentRoute() } }, + ) + acceptedAssembly = { provider: config.provider, model: config.model, schemas, assembly } + } + const { assembly } = acceptedAssembly + const renderedPrompt = renderPrompt(assembly) + const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, assembleContextFor(this, signal)) + const sections = renderContextSections(currentContext) + const context = this.runtimeContext.project(joinContextSections(sections), sections) + signal.throwIfAborted() + const startsRequestSeries = firstAttempt && decision.startsRequestSeries === true + const commits = this.systemPrompt.project(renderedPrompt, { + inHistory: preparedCall?.systemPromptUpdate === 'in-history', + startsSeries: startsRequestSeries + || this.requestSurfaceGeneration !== this.session.surface.contentGeneration + || (preparedCall?.toolUpdate === undefined && this.toolsChanged(assembly.tools)), + }) + for (const { message, intent } of commits) { + this.session.append('system/message', { turn, step, message }, intent) + } + let contextAdmitted = false + if (firstAttempt) { + for (const message of decision.messages) { + if (message.source.kind === 'runtime-context') { + if (context !== undefined && !contextAdmitted) { + this.session.append('user/message', context, { surfaceOp: 'append' }) + contextAdmitted = true + } + } else { + this.session.append('user/message', message, { surfaceOp: 'append' }) } - } else { - this.session.append('user/message', message, { surfaceOp: 'append' }) } } - } - if (context !== undefined && !contextAdmitted) { - this.session.append('user/message', context, { surfaceOp: 'append' }) - } - firstAttempt = false - const request = this.buildRequest(config, preparedCall, assembly.tools, { turn, step }, startsRequestSeries, signal) - const live = new AssistantStreamAttempt( - this.session.id, - ++this.assistantAttemptCounter, - () => ++this.assistantStreamRevision, - turn, - step, - (frame) => { this.dispatch.emit('agent/assistant-stream', { frame }) }, - ) - let started = false - try { - const stream = preparedCall?.stream(request) ?? this.loopCtx.llm.stream(request) - signal.throwIfAborted() - live.start() - started = true - for await (const chunk of stream) { - signal.throwIfAborted() - live.push(chunk) + if (context !== undefined && !contextAdmitted) { + this.session.append('user/message', context, { surfaceOp: 'append' }) } - signal.throwIfAborted() - } catch (error: unknown) { - if (!started) throw error + firstAttempt = false + const request = this.buildRequest(config, preparedCall, assembly.tools, { turn, step }, startsRequestSeries, signal) + const live = new AssistantStreamAttempt( + this.session.id, + ++this.assistantAttemptCounter, + () => ++this.assistantStreamRevision, + turn, + step, + (frame) => { this.dispatch.emit('agent/assistant-stream', { frame }) }, + ) + let started = false try { - if (signal.aborted) { - const content = live.interruptedBlocks() - if (content.length > 0) { - live.settle('assistant/message', () => this.session.append('assistant/message', { - turn, - step, - message: createAssistantMessage({ - content, - source: { - provider: request.provider, - model: request.model, - ...live.replayState === undefined ? {} : { replayState: live.replayState }, - }, - }), - interrupted: true, - ...live.usage === undefined ? {} : { usage: live.usage }, - stream: live.stream, - }, { surfaceOp: 'append' }).seq) + const stream = preparedCall?.stream(request) ?? this.loopCtx.llm.stream(request) + signal.throwIfAborted() + live.start() + started = true + for await (const chunk of stream) { + signal.throwIfAborted() + live.push(chunk) + } + signal.throwIfAborted() + } catch (error: unknown) { + if (!started) throw error + try { + if (signal.aborted) { + const content = live.interruptedBlocks() + if (content.length > 0) { + live.settle('assistant/message', () => this.session.append('assistant/message', { + turn, + step, + message: createAssistantMessage({ + content, + source: { + provider: request.provider, + model: request.model, + ...live.replayState === undefined ? {} : { replayState: live.replayState }, + }, + }), + interrupted: true, + ...live.usage === undefined ? {} : { usage: live.usage }, + stream: live.stream, + }, { surfaceOp: 'append' }).seq) + } else { + live.settle( + 'assistant/attempt', + () => this.session.append('assistant/attempt', { turn, step, stream: live.stream }).seq, + ) + } } else { live.settle( 'assistant/attempt', () => this.session.append('assistant/attempt', { turn, step, stream: live.stream }).seq, ) } - } else { + } catch (settlementError: unknown) { + throw new AggregateError( + [error, settlementError], + 'Assistant stream failed and its durable settlement was rejected', + { cause: error }, + ) + } + throw error + } + try { + const finish = live.finish + if (finish.kind === 'error' || finish.kind === 'aborted') { live.settle( 'assistant/attempt', () => this.session.append('assistant/attempt', { turn, step, stream: live.stream }).seq, ) + const action = await this.dispatch.waterfall( + 'agent/request-error', { + turn, + step, + provider: request.provider, + failure: finish.failure, + retryPolicy: preparedCall?.retryPolicy, + signal, + }, + () => Promise.resolve(undefined), + ) + signal.throwIfAborted() + if (action?.kind !== 'retry') { + throw new LlmError(finish.failure.message, finish.failure.code, finish.failure) + } + continue } - } catch (settlementError: unknown) { - throw new AggregateError( - [error, settlementError], - 'Assistant stream failed and its durable settlement was rejected', - { cause: error }, - ) - } - throw error - } - try { - const finish = live.finish - if (finish.kind === 'error' || finish.kind === 'aborted') { + + const message = createAssistantMessage({ + content: live.blocks(), + source: { + provider: request.provider, + model: request.model, + ...live.replayState !== undefined ? { replayState: live.replayState } : {}, + }, + }) live.settle( - 'assistant/attempt', - () => this.session.append('assistant/attempt', { turn, step, stream: live.stream }).seq, - ) - const action = await this.dispatch.waterfall( - 'agent/request-error', { + 'assistant/message', + () => this.session.append('assistant/message', { turn, step, - provider: request.provider, - failure: finish.failure, - retryPolicy: preparedCall?.retryPolicy, - signal, - }, - () => Promise.resolve(undefined), + message, + ...live.usage === undefined ? {} : { usage: live.usage }, + stream: live.stream, + }, { surfaceOp: 'append' }).seq, ) - signal.throwIfAborted() - if (action?.kind !== 'retry') { - throw new LlmError(finish.failure.message, finish.failure.code, finish.failure) - } - continue + if (finish.kind === 'max-tokens') return { kind: 'max-tokens' } + + const toolCalls = message.content.filter(block => block.type === 'tool-call') + if (toolCalls.length === 0) return { kind: 'completed' } + const { concluded } = await executeToolCalls( + this.loopCtx, turn, step, toolCalls, signal, + context => this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context]), + toolSet, + ) + return concluded ? { kind: 'completed' } : null + } catch (error: unknown) { + if (!live.ended) live.abandon() + throw error } - - const message = createAssistantMessage({ - content: live.blocks(), - source: { - provider: request.provider, - model: request.model, - ...live.replayState !== undefined ? { replayState: live.replayState } : {}, - }, - }) - live.settle( - 'assistant/message', - () => this.session.append('assistant/message', { - turn, - step, - message, - ...live.usage === undefined ? {} : { usage: live.usage }, - stream: live.stream, - }, { surfaceOp: 'append' }).seq, - ) - if (finish.kind === 'max-tokens') return { kind: 'max-tokens' } - - const toolCalls = message.content.filter(block => block.type === 'tool-call') - if (toolCalls.length === 0) return { kind: 'completed' } - const { concluded } = await executeToolCalls( - this.loopCtx, turn, step, toolCalls, signal, - context => this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context]), - ) - return concluded ? { kind: 'completed' } : null - } catch (error: unknown) { - if (!live.ended) live.abandon() - throw error + } finally { + toolSet.dispose() } } } @@ -565,7 +597,8 @@ export class ReactLoopAgent implements Agent { turn: number, step: number, signal: AbortSignal, - ): Promise<{ config: LlmCallConfig; preparedCall?: PreparedLlmCall }> { + ): Promise { + this.requestRoute = undefined const { session } = this // A loop instance starts from its declared route, restoring only an explicit @@ -609,6 +642,7 @@ export class ReactLoopAgent implements Agent { config = proposedConfig } signal.throwIfAborted() + this.requestRoute = Object.freeze({ provider: config.provider, model: config.model }) return { config, ...preparedCall === undefined ? {} : { preparedCall } } } diff --git a/packages/core/agent-loop/src/tool-calls.ts b/packages/core/agent-loop/src/tool-calls.ts index c12de68d19..7424a57931 100644 --- a/packages/core/agent-loop/src/tool-calls.ts +++ b/packages/core/agent-loop/src/tool-calls.ts @@ -11,6 +11,7 @@ * @module dsh-agent-loop/tool-calls */ +import type { ResolvedToolSet } from '@deepseek-ai/dsh-tools' import type { Context } from '@deepseek-ai/cordis' import { createToolResultMessage, type ToolCallBlock } from '@deepseek-ai/dsh-llm' import type { Session, SessionSeq, UserMessage } from '@deepseek-ai/dsh-session' @@ -56,6 +57,7 @@ interface GroupOutcome { * @param toolCalls - assistant calls in model order. * @param signal - abort signal shared by the step. * @param acceptContext - accepts committed result context for the next step boundary. + * @param toolSet - request-owned admission propagated into every Native dispatch. */ export async function executeToolCalls( ctx: Context, @@ -64,6 +66,7 @@ export async function executeToolCalls( toolCalls: ToolCallBlock[], signal: AbortSignal, acceptContext: (context: UserMessage) => void, + toolSet?: ResolvedToolSet, ): Promise<{ concluded: boolean }> { const agent = ctx.agents.requireInitiator() const { session } = agent @@ -77,6 +80,7 @@ export async function executeToolCalls( arguments: parseArguments(block.arguments), agent, signal, + ...toolSet === undefined ? {} : { toolSet }, }, })) diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index 0213c38060..f6a887eea3 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -1280,8 +1280,8 @@ describe('tool result call identity', () => { }) }) -describe('disposal and cancellation during pre-step assembly', () => { - it('disposal during system-prompt assembly closes a no-step turn', { timeout: 30000 }, async () => { +describe('disposal and cancellation during prompt assembly', () => { + it('disposal during system-prompt assembly closes an admitted step without model output', { timeout: 30000 }, async () => { // Start disposal, then release assembly. Do not await disposal first: it // waits for the blocked driver to exit. const adapter = new MockAdapter(['hang']) @@ -1327,13 +1327,13 @@ describe('disposal and cancellation during pre-step assembly', () => { const e = agent.session.snapshotEvents() expect(e.filter(x => x.type === 'turn/start' || x.type === 'turn/end').map(x => x.type)) .toEqual(['turn/start', 'turn/end']) - expect(e.some(x => x.type === 'step/start')).toBe(false) - expect(e.some(x => x.type === 'step/end')).toBe(false) + expect(e.some(x => x.type === 'step/start')).toBe(true) + expect(e.some(x => x.type === 'step/end')).toBe(true) expect(e.some(x => x.type === 'assistant/attempt')).toBe(false) expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'disposed' } }]) }) - it('cancel during system-prompt assembly closes a no-step turn', { timeout: 30000 }, async () => { + it('cancel during system-prompt assembly closes an admitted step without model output', { timeout: 30000 }, async () => { const adapter = new MockAdapter([textResponse('should not appear')]) let releaseAssemble!: () => void const blocker = new Promise(r => void (releaseAssemble = r)) @@ -1374,8 +1374,8 @@ describe('disposal and cancellation during pre-step assembly', () => { const e = agent.session.snapshotEvents() expect(e.filter(x => x.type === 'turn/start' || x.type === 'turn/end').map(x => x.type)) .toEqual(['turn/start', 'turn/end']) - expect(e.some(x => x.type === 'step/start')).toBe(false) - expect(e.some(x => x.type === 'step/end')).toBe(false) + expect(e.some(x => x.type === 'step/start')).toBe(true) + expect(e.some(x => x.type === 'step/end')).toBe(true) expect(e.some(x => x.type === 'assistant/attempt')).toBe(false) expect(e.some(x => x.type === 'assistant/message')).toBe(false) expect(adapter.requests).toHaveLength(0) diff --git a/packages/core/agent-loop/tests/inbox.spec.ts b/packages/core/agent-loop/tests/inbox.spec.ts index 739d18b990..8f1ac7eeef 100644 --- a/packages/core/agent-loop/tests/inbox.spec.ts +++ b/packages/core/agent-loop/tests/inbox.spec.ts @@ -22,6 +22,7 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { const session = overrides.session ?? Session.create(id) const ctx = overrides.ctx ?? new Context() return { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/core/agent-loop/tests/request-freeze.spec.ts b/packages/core/agent-loop/tests/request-freeze.spec.ts index 560be88627..a74891ca45 100644 --- a/packages/core/agent-loop/tests/request-freeze.spec.ts +++ b/packages/core/agent-loop/tests/request-freeze.spec.ts @@ -164,13 +164,12 @@ describe('loop-owned request freezing', () => { const { ctx } = await harness(adapter) const schemas: ToolSchema[][] = [] const stops: string[][] = [] - ctx.on('system-prompt/assemble', async (_assembly, _context, next) => { - const assembly = await next() + ctx.systemPrompt.tools(() => { const tools: ToolSchema[] = [{ name: 'nested', description: 'test', parameters: { type: 'object', properties: { value: { type: 'array', items: { type: 'string', enum: ['a', 'b'] } } }, } }] schemas.push(tools) - return { ...assembly, tools } + return { schemas: tools } }) ctx.on('agent/request', async (_payload, next) => { const config = await next() @@ -193,8 +192,8 @@ describe('loop-owned request freezing', () => { expect(errors).toEqual([]) expect(requests).toHaveLength(2) for (const [index, request] of requests.entries()) { - expect(request.tools).toBe(schemas[index]) - expectFrozen(schemas[index]) + expect(request.tools).toEqual(schemas[index]) + expectFrozen(request.tools) expect(() => request.stop!.push('mutate')).toThrow(TypeError) if (!registered) expect(request.stop).toBe(stops[index]) } diff --git a/packages/core/agent-loop/tests/system-prompt-admission.spec.ts b/packages/core/agent-loop/tests/system-prompt-admission.spec.ts index 01543b64df..47390d938b 100644 --- a/packages/core/agent-loop/tests/system-prompt-admission.spec.ts +++ b/packages/core/agent-loop/tests/system-prompt-admission.spec.ts @@ -369,13 +369,13 @@ describe('prepared-route prompt admission', () => { expect(resumed.session.snapshotEvents().filter(event => event.type === 'request/header').at(-1)?.data.reason).toBe('resume') }) - it.each(['request', 'prepare'] as const)('cancels during %s with a balanced empty step before input admission', async (stage) => { + it.each(['request', 'prepare'] as const)('cancels during %s before step and input admission', async (stage) => { const h = await harness() const entered = Promise.withResolvers() const release = Promise.withResolvers() const observe = async () => { const types = h.agent.session.snapshotEvents().map(event => event.type) - expect(types).toContain('step/start') + expect(types).not.toContain('step/start') expect(types).not.toContain('system/message') expect(types).not.toContain('user/message') expect(types).not.toContain('request/header') @@ -394,7 +394,7 @@ describe('prepared-route prompt admission', () => { await h.agent.whenIdle() expect(h.capable.requests).toHaveLength(0) const types = h.agent.session.snapshotEvents().map(event => event.type) - expect(types.filter(type => type === 'step/start' || type === 'step/end')).toEqual(['step/start', 'step/end']) + expect(types.filter(type => type === 'step/start' || type === 'step/end')).toEqual([]) expect(types.filter(type => ['system/message', 'user/message', 'request/header'].includes(type))).toEqual([]) }) diff --git a/packages/core/agent-loop/tests/tool-calls.spec.ts b/packages/core/agent-loop/tests/tool-calls.spec.ts index 8aa74cec2d..c84a10e06e 100644 --- a/packages/core/agent-loop/tests/tool-calls.spec.ts +++ b/packages/core/agent-loop/tests/tool-calls.spec.ts @@ -150,7 +150,7 @@ describe('tool-call scheduler: grouping and barriers', () => { expect(order).toEqual(['r-start-A1', 'r-end-A1', 'w-A2', 'r-start-A3', 'r-end-A3']) }) - it('reclassifies pending calls after an exclusive barrier replaces their tool', async () => { + it('rejects pending calls whose original registration was replaced', async () => { const adapter = new MockAdapter([ multiCall([ { id: 'c1', name: 'replace', args: { id: '0' } }, @@ -181,17 +181,13 @@ describe('tool-call scheduler: grouping and barriers', () => { const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })) - await until(() => replacement.started.length === 1) - await new Promise(r => setTimeout(r, 5)) - expect(replacement.started).toEqual(['1']) - replacement.release('1') - await until(() => replacement.started.length === 2) - expect(replacement.started).toEqual(['1', '2']) - replacement.release('2') await waitForIdle(ctx, agent) + expect(replacement.started).toEqual([]) + expect(events(agent).filter(event => event.type === 'tool/result').slice(1).map(event => event.data.error?.code)) + .toEqual(['UNKNOWN_TOOL', 'UNKNOWN_TOOL']) }) - it('stops replenishing when a result observer makes the next call exclusive', async () => { + it('drains started calls and rejects unstarted calls after replacement', async () => { const adapter = new MockAdapter([ multiCall([ { id: 'c1', name: 'x', args: { id: '1' } }, @@ -219,10 +215,9 @@ describe('tool-call scheduler: grouping and barriers', () => { await new Promise(r => setTimeout(r, 5)) expect(replacement.started).toEqual([]) initial.release('2') - await until(() => replacement.started.length === 1) - expect(replacement.started).toEqual(['3']) - replacement.release('3') await waitForIdle(ctx, agent) + expect(replacement.started).toEqual([]) + expect(events(agent).filter(event => event.type === 'tool/result').at(-1)?.data.error?.code).toBe('UNKNOWN_TOOL') }) }) diff --git a/packages/core/agent-loop/tests/tool-order.spec.ts b/packages/core/agent-loop/tests/tool-order.spec.ts index 287f5fe761..688be207cd 100644 --- a/packages/core/agent-loop/tests/tool-order.spec.ts +++ b/packages/core/agent-loop/tests/tool-order.spec.ts @@ -95,7 +95,7 @@ describe('loop-level canonical tool order', () => { expect(Object.isFrozen(adapter.requests[0])).toBe(true) }) - it('closes a no-step turn when toolOrder names an unregistered tool', async () => { + it('closes the admitted step without a request when toolOrder names an unregistered tool', async () => { const adapter = new MockAdapter([textResponse('never sent')]) const ctx = await harness(adapter, ['ghost', TOOL_ORDER_REST]) registerNamed(ctx, 'alpha') @@ -106,7 +106,7 @@ describe('loop-level canonical tool order', () => { expect(foldRequestHeader(agent.session.snapshotEvents())).toBeUndefined() expect(agent.session.snapshotEvents().some(e => e.type === 'turn/start')).toBe(true) expect(agent.session.snapshotEvents().some(e => e.type === 'turn/end')).toBe(true) - expect(agent.session.snapshotEvents().some(e => e.type === 'step/start')).toBe(false) - expect(agent.session.snapshotEvents().some(e => e.type === 'step/end')).toBe(false) + expect(agent.session.snapshotEvents().some(e => e.type === 'step/start')).toBe(true) + expect(agent.session.snapshotEvents().some(e => e.type === 'step/end')).toBe(true) }) }) diff --git a/packages/core/agent-loop/tests/tool-updates.spec.ts b/packages/core/agent-loop/tests/tool-updates.spec.ts index 6eca806085..bd0542cc74 100644 --- a/packages/core/agent-loop/tests/tool-updates.spec.ts +++ b/packages/core/agent-loop/tests/tool-updates.spec.ts @@ -9,7 +9,7 @@ import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools' -import { MockAdapter, textResponse } from './mock-adapter.ts' +import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts' const contexts: Context[] = [] afterEach(async () => { @@ -112,3 +112,127 @@ describe('tool update emission', () => { expect(agent.session.requestHeader()?.tools?.map(schema => schema.name)).toEqual(['search']) }) }) + + +describe('request-time tool activation', () => { + it('uses the bound route for asynchronous conditions and rejects a historical name after removal', async () => { + const adapter = new MockAdapter([ + toolCallResponse('allowed', 'conditional', {}), textResponse('done'), + toolCallResponse('removed', 'conditional', {}), textResponse('done'), + ]) + const { ctx, agent } = await harness(adapter) + const routed: string[] = [] + let calls = 0 + let model = 'enabled' + ctx.on('agent/request', async (_payload, next) => ({ ...await next(), model })) + ctx.tools.register(defineContentToolFixture({ + name: 'conditional', description: 'Available on one route.', parameters: {}, + async execute(_args, exec) { + expect(exec.agent?.currentRoute()).toEqual({ provider: 'mock', model: 'enabled' }) + calls++ + return [{ type: 'text', text: 'done' }] + }, + }), { when: async ({ agent: subject }) => { + const route = subject.currentRoute() + expect(Object.isFrozen(route)).toBe(true) + routed.push(route.model) + await Promise.resolve() + return route.model === 'enabled' + } }) + expect(() => agent.currentRoute()).toThrow('no prepared model request') + await send(agent, 'enabled') + model = 'disabled' + await send(agent, 'try the historical name') + expect(calls).toBe(1) + expect(routed).toEqual(['enabled', 'enabled', 'disabled', 'disabled']) + expect(developerEvents(agent).at(-1)?.data.message.content) + .toEqual([{ type: 'tool-removal', toolName: 'conditional' }]) + expect(agent.session.snapshotEvents().find(event => event.type === 'tool/result' && event.data.message.toolCallId === 'removed')?.data) + .toMatchObject({ error: { code: 'UNKNOWN_TOOL' } }) + expect(() => agent.currentRoute()).toThrow('no prepared model request') + }) + + it('cancels an asynchronous condition without committing the proposed request', async () => { + const adapter = new MockAdapter([textResponse('unused')]) + const { ctx, agent } = await harness(adapter) + const entered = Promise.withResolvers() + const settle = Promise.withResolvers() + ctx.tools.register(defineContentToolFixture({ + name: 'conditional', description: 'A pending condition.', parameters: {}, + execute: async () => [{ type: 'text', text: 'unused' }], + }), { when: () => { entered.resolve(undefined); return settle.promise } }) + const running = send(agent, 'cancel during activation') + await entered.promise + agent.cancel({ kind: 'user' }) + settle.resolve(true) + await running + expect(adapter.requests).toEqual([]) + expect(agent.session.snapshotEvents().filter(event => ['request/header', 'system/message', 'user/message'].includes(event.type))).toEqual([]) + expect(() => agent.currentRoute()).toThrow('no prepared model request') + }) + + it.each(['condition', 'route'])('reassembles on a retry after the %s changes without admitting users again', async (change) => { + const adapter = new MockAdapter([ + [{ type: 'finish', reason: { kind: 'error', failure: { code: 'SERVER', message: 'retry', status: 503 } } }], + textResponse('done'), + ]) + const { ctx, agent } = await harness(adapter) + let retried = false + let admissions = 0 + ctx.on('agent/pre-step', (_input, next) => { admissions++; return next() }) + ctx.on('agent/request', async (_input, next) => ({ + ...await next(), model: change === 'route' && retried ? 'second' : 'first', + })) + ctx.on('agent/request-error', async (_input, next) => { + await next() + retried = true + return { kind: 'retry' } + }) + ctx.tools.register(defineContentToolFixture({ + name: 'conditional', description: 'Retry-dependent availability.', parameters: {}, + execute: async () => [{ type: 'text', text: 'unused' }], + }), { when: () => change === 'route' || retried }) + ctx.systemPrompt.section({ + name: 'retry:guidance', order: 0, complete: true, + text: context => `${agent.currentRoute().model}:${ctx.tools.schemas(agent, context.toolSet).map(tool => tool.name).join(',')}`, + }) + await send(agent, 'retry once') + const prompts = adapter.requests.map(request => request.messages.find(message => message.role === 'system')?.content) + expect(prompts[0]).toEqual([{ type: 'text', text: change === 'route' ? 'first:conditional' : 'first:' }]) + expect(prompts[1]).toEqual([{ type: 'text', text: change === 'route' ? 'second:conditional' : 'first:conditional' }]) + expect(admissions).toBe(1) + expect(agent.session.snapshotEvents().filter(event => event.type === 'user/message' && event.data.source.kind === 'user')).toHaveLength(1) + expect(() => agent.currentRoute()).toThrow('no prepared model request') + }) + + it('reports condition failures without admitting a partial request', async () => { + const adapter = new MockAdapter([textResponse('unused')]) + const { ctx, agent } = await harness(adapter) + ctx.tools.register(defineContentToolFixture({ + name: 'conditional', description: 'An unavailable activation dependency.', parameters: {}, + execute: async () => [{ type: 'text', text: 'unused' }], + }), { when: async () => { throw new Error('credential storage unavailable') } }) + await send(agent, 'inspect') + expect(adapter.requests).toEqual([]) + expect(agent.session.snapshotEvents().filter(event => ['request/header', 'system/message', 'user/message'].includes(event.type))).toEqual([]) + expect(agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data) + .toMatchObject({ reason: { kind: 'error', error: { code: 'TOOL_ACTIVATION_FAILED' } } }) + expect(() => agent.currentRoute()).toThrow('no prepared model request') + }) + + it('shares the selected set with prompt guidance', async () => { + const adapter = new MockAdapter([textResponse('done')]) + const { ctx, agent } = await harness(adapter) + ctx.tools.register(defineContentToolFixture({ + name: 'conditional', description: 'Disabled.', parameters: {}, + execute: async () => [{ type: 'text', text: 'unused' }], + }), { when: () => false }) + ctx.systemPrompt.section({ + name: 'conditional:guidance', order: 0, + text: context => ctx.tools.get('conditional', context.scope, context.toolSet) === undefined ? '' : 'Conditional guidance', + }) + await send(agent, 'inspect') + expect(adapter.requests[0]?.tools ?? []).toEqual([]) + expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('Conditional guidance') + }) +}) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index befdc09642..1502bd30aa 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -36,14 +36,14 @@ en: 7c850051d2857bfa zh: 4cab817553114e15 /deepseek-ai-dsh-agent/understand-the-implementation/step-admission: - en: 348b9ecd0890c585 - zh: d0f73d28d0d2c6f1 + en: 5bba803d6c23370a + zh: 0e5e3c037a111141 /deepseek-ai-dsh-agent/understand-the-implementation/durable-inbox: en: f6802c7f94f623b3 zh: cc3885db80765970 /deepseek-ai-dsh-agent/understand-the-implementation/source-map: - en: 7e09b94c79dc97ca - zh: 3f9c5455c4dc563a + en: 8efa6e74d4dbe28e + zh: 6126170ac464703f /deepseek-ai-dsh-agent/understand-the-implementation/registry-and-lifecycle: en: df92e97cedd0d02e zh: f6040c145bffd933 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 9da1f06f64..d2255afddb 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -82,7 +82,9 @@ The package is built on one separation: the public `Agent` surface and registry ### Step admission -`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. Acceptance does not commit it: after assembly and `step/start`, `agent/request` and `prepareCall()` resolve the route before the loop commits the system prompt and user batch. Cancellation during either async phase commits neither. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. +`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. Route preparation runs before `agent/pre-step`. Acceptance does not commit the batch: tool conditions and prompt assembly must also succeed before system and user messages are logged. Cancellation during route preparation opens no step and commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. + +`agent.currentRoute()` returns the immutable provider/model bound by request preparation, through the corresponding tool batch. It throws before preparation and after the batch ends; initial options and previous Session headers are not fallbacks. Auxiliary model calls do not replace the main request route. ### Durable inbox @@ -99,7 +101,7 @@ The package is built on one separation: the public `Agent` surface and registry | [`src/types.ts`](src/types.ts) | `AgentOptions`, cancellation causes, and inbox projection vocabulary | | [`src/dispatch.ts`](src/dispatch.ts) | `agentEvents` fused dispatcher and `assembleContextFor(agent)` | | [`src/consumed-work.ts`](src/consumed-work.ts) | `foldConsumedWork(events)`: what the log's consumed work became | -| [`src/model-selection.ts`](src/model-selection.ts) | `installModelSelection`: coupling one selection to assembly and routing | +| [`src/model-selection.ts`](src/model-selection.ts) | `installModelSelection`: capturing a selection for step routing | | [`src/archive-admission.ts`](src/archive-admission.ts) | The `turn` family of the Workspace registry's archive admission: a running turn and its user-cause cancel | ### Registry and lifecycle diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index 0166f96a80..722b9edd45 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -82,7 +82,9 @@ await handle.agent.whenIdle() ### 步骤准入 -`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。接纳不等于提交:组装与 `step/start` 之后,`agent/request` 和 `prepareCall()` 先解析路由,循环随后才提交系统提示词与用户批次。在任一异步阶段取消都不会提交这两者。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 +`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。路由准备在 `agent/pre-step` 之前执行。接纳不等于提交:工具条件与提示词组装也必须成功,随后才记录系统提示词与用户批次。在路由准备期间取消不会打开步骤,也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 + +`agent.currentRoute()` 返回请求准备绑定的不可变提供方与模型,持续到对应工具批次结束。准备前和批次结束后调用会抛错,不回退到初始选项或先前 Session 请求头。辅助模型调用不会替换主请求路由。 ### 持久 inbox @@ -99,7 +101,7 @@ await handle.agent.whenIdle() | [`src/types.ts`](src/types.ts) | `AgentOptions`、取消原因与收件箱投影词汇 | | [`src/dispatch.ts`](src/dispatch.ts) | `agentEvents` 融合分发器与 `assembleContextFor(agent)` | | [`src/consumed-work.ts`](src/consumed-work.ts) | `foldConsumedWork(events)`:日志消费掉的工作最终怎样了 | -| [`src/model-selection.ts`](src/model-selection.ts) | `installModelSelection`:把一个选择耦合到组装与路由 | +| [`src/model-selection.ts`](src/model-selection.ts) | `installModelSelection`:为步骤路由捕获模型选择 | | [`src/archive-admission.ts`](src/archive-admission.ts) | Workspace 注册表归档准入中的 `turn` 族:运行中的回合及其用户原因取消 | ### 注册表与生命周期 diff --git a/packages/core/agent/src/model-selection.ts b/packages/core/agent/src/model-selection.ts index 8921bc12a4..d5801e30b7 100644 --- a/packages/core/agent/src/model-selection.ts +++ b/packages/core/agent/src/model-selection.ts @@ -30,9 +30,9 @@ export interface ModelSelection { /** Mutable model selection plus the value captured for the current step. */ export interface ModelSelectionRef { - /** Model selected for the next step that enters prompt assembly. */ + /** Model selected for the next step entering route preparation. */ current: ModelSelection | undefined - /** Selection captured when the current step entered prompt assembly. */ + /** Selection captured by the first route preparation of the current step. */ assembled: ModelSelection | undefined } @@ -61,15 +61,13 @@ function modelSwitchNotice(previous: ModelSelection, selected: ModelSelection) { } /** - * Couple one mutable selection to Agent-scoped prompt assembly and request routing. - * Prompt assembly snapshots the selected model before delegating, then applies - * its provider/model pair and effort to request config so a - * concurrent switch takes effect on a later step instead of splitting the two - * surfaces. An absent selected effort clears any inherited effort, restoring - * the selected model's provider/default behavior. + * Couple one mutable selection to Agent-scoped request routing. The first + * request preparation in a step captures the selection before delegating; + * retries retain it, and concurrent selections apply to later steps. An absent + * selected effort clears inherited effort, restoring the model's provider default. * * A provider/model change appends a durable user-role notice to the next - * admitted request. It compares the assembled selection with the latest + * admitted request. It compares the bound request route with the latest * request header; effort-only changes and empty no-request decisions add no * notice. Failure before header persistence repeats the notice on the next * request. @@ -79,23 +77,14 @@ function modelSwitchNotice(previous: ModelSelection, selected: ModelSelection) { * @returns Disposer for all scoped waterfall listeners. */ export function installModelSelection(agentCtx: Context, selection: ModelSelectionRef): () => void { - const disposeAssembly = agentCtx.on('system-prompt/assemble', async (_assembly, _context, next) => { - const selected = selection.current - const assembled = await next() - selection.assembled = selected - if (selected === undefined) return assembled - return { - ...assembled, - variables: { - ...assembled.variables, - provider: selected.provider, - model: selected.model, - }, - } - }) + let capturedStep: { turn: number; step: number } | undefined const disposeRequest = agentCtx.on( 'agent/request', - async (_payload, next): Promise => { + async ({ turn, step }, next): Promise => { + if (capturedStep?.turn !== turn || capturedStep.step !== step) { + capturedStep = { turn, step } + selection.assembled = selection.current === undefined ? undefined : { ...selection.current } + } const resolved = await next() const selected = selection.assembled if (selected === undefined) return resolved @@ -117,15 +106,14 @@ export function installModelSelection(agentCtx: Context, selection: ModelSelecti if (decision.kind === 'reject' || signal.aborted) return decision // The loop skips an empty first step and an emptied offered continuation. if (decision.messages.length === 0 && (step === 1 || messages.length > 0)) return decision - const selected = selection.assembled + const selected = agent.currentRoute() const previous = agent.session.requestHeader()?.config - if (selected === undefined || previous === undefined || sameRoute(selected, previous)) return decision + if (previous === undefined || sameRoute(selected, previous)) return decision return { ...decision, messages: [...decision.messages, modelSwitchNotice(previous, selected)] } }, { prepend: true }, ) return () => { - disposeAssembly() disposeRequest() disposeNotice() } diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 0fa89afc05..9501b45841 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -162,8 +162,14 @@ export type AssistantStreamFrame = declare module './types.ts' { interface Agent { - /** The provider route and model this agent's requests use. */ + /** Initial request options; currentRoute() reports the bound request route. */ readonly options: AgentOptions + /** + * Read the immutable route bound to this request and its tool batch. + * @returns the actual provider and model selected by prepareCall(). + * @throws when no main request is prepared; never falls back to prior requests. + */ + currentRoute(): Readonly> /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -322,9 +328,9 @@ declare module '@deepseek-ai/cordis' { * Replace the frozen call configuration. `await next()` yields the config * the machine would use (agent options on the first request, the logged * header afterwards); return a replacement to switch. On step admission, - * this runs after assembly and `step/start`, before the system prompt and - * accepted user batch are committed. Cancellation here or during subsequent - * `prepareCall()` resolution commits neither. The prepared call capability + * this runs before context preparation and `agent/pre-step`. Cancellation + * here or during subsequent `prepareCall()` resolution opens no step and + * commits no system prompt or user batch. The prepared call capability * governs prompt admission. Model-visible content must use logged channels; * this waterfall cannot mutate messages. * @param payload.agent - the agent making the model call. diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index c31acf5c66..282c942dd6 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -18,6 +18,7 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { const session = overrides.session ?? Session.create(id) const ctx = overrides.ctx ?? new Context() const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/core/agent/tests/archive-admission.spec.ts b/packages/core/agent/tests/archive-admission.spec.ts index 0f84de4fe0..40556764c7 100644 --- a/packages/core/agent/tests/archive-admission.spec.ts +++ b/packages/core/agent/tests/archive-admission.spec.ts @@ -15,6 +15,7 @@ async function liveAgent(ctx: Context, rawId: string, initial: AgentStatus): Pro const cancels: CancelCall[] = [] let status = initial const agent: LiveAgent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session: Session.create(id), diff --git a/packages/core/agent/tests/model-selection.spec.ts b/packages/core/agent/tests/model-selection.spec.ts index 27b2a7bffd..7dddee1b9a 100644 --- a/packages/core/agent/tests/model-selection.spec.ts +++ b/packages/core/agent/tests/model-selection.spec.ts @@ -1,191 +1,88 @@ -import { describe, expect, it } from 'vitest' +/** Model selection is captured before route preparation and remains stable within a step. */ +import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import { - agentEvents, - installModelSelection, - type Agent, - type ModelSelection, - type ModelSelectionRef, -} from '../src/index.ts' -import { - createUserMessage, - ReasoningEffortId, - type LlmCallConfig, - type UserMessage, -} from '@deepseek-ai/dsh-llm' +import { agentEvents, installModelSelection, type Agent, type ModelSelection, type ModelSelectionRef } from '../src/index.ts' +import { createUserMessage, ReasoningEffortId, type LlmCallConfig } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -const SIGNAL = new AbortController().signal -const INPUT = createUserMessage({ - content: [{ type: 'text', text: 'continue' }], - source: { kind: 'user' }, +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() }) +const signal = new AbortController().signal +const input = createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'user' } }) -function createAgent(): Agent { - return { session: Session.create(SessionId('model-selection')) } as Agent -} - -function expectedNotice(from: string, to: string) { - return { - content: [{ - type: 'text', - text: `[model changed: assistant turns above this point were generated by ${from}; the session continues with ${to}]`, - }], - source: { kind: 'model-selection', form: 'notice', summary: `${from} → ${to}` }, - } -} - -async function switchHarness(current: ModelSelection, previous?: ModelSelection) { +function harness(current?: ModelSelection, previous?: ModelSelection) { const ctx = new Context() - await ctx.plugin(SystemPrompt) + contexts.push(ctx) const selection: ModelSelectionRef = { current, assembled: undefined } const dispose = installModelSelection(ctx, selection) - const agent = createAgent() - if (previous !== undefined) { - agent.session.append('request/header', { header: { config: previous }, reason: 'initial' }) + let route: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 } + const agent = { session: Session.create(SessionId('model-selection')), currentRoute: () => route } as Agent + if (previous) agent.session.append('request/header', { header: { config: previous }, reason: 'initial' }) + const request = async (step: number, seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 }) => { + route = await agentEvents(ctx, agent).waterfall('agent/request', { turn: 1, step, signal }, () => Promise.resolve(seed)) + return route } - await ctx.systemPrompt.assemble() - return { agent, ctx, dispose, selection } + const preStep = (messages = [input], offered = [input], step = 1, requestSignal = signal) => + agentEvents(ctx, agent).waterfall('agent/pre-step', { turn: 1, step, messages: offered, signal: requestSignal }, + () => Promise.resolve({ kind: 'enter' as const, messages })) + return { ctx, agent, selection, dispose, request, preStep } } -async function preStep( - ctx: Context, - agent: Agent, - { - messages = [INPUT], - offered = [INPUT], - step = 1, - signal = SIGNAL, - }: { - messages?: UserMessage[] - offered?: UserMessage[] - step?: number - signal?: AbortSignal - } = {}, -) { - return agentEvents(ctx, agent).waterfall( - 'agent/pre-step', - { turn: 1, step, messages: offered, signal }, - () => Promise.resolve({ kind: 'enter' as const, messages }), - ) +function notice(from: string, to: string) { + return { content: [{ type: 'text', text: `[model changed: assistant turns above this point were generated by ${from}; the session continues with ${to}]` }] } } describe('installModelSelection()', () => { - it('snapshots prompt variables and request routing together, then disposes its listeners', async () => { - const ctx = new Context() - await ctx.plugin(SystemPrompt) - const selection: ModelSelectionRef = { current: undefined, assembled: undefined } - const dispose = installModelSelection(ctx, selection) - const agent = createAgent() + it('captures selection per step, preserves retries, and disposes routing', async () => { + const h = harness() const seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 } - const signal = new AbortController().signal - - expect((await ctx.systemPrompt.assemble()).variables).toEqual({}) - await expect(agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 1, step: 0, signal }, () => Promise.resolve(seed), - )).resolves.toBe(seed) - - selection.current = { - provider: 'alpha', - model: 'a1', - reasoningEffort: ReasoningEffortId('high'), - } - expect((await ctx.systemPrompt.assemble()).variables).toMatchObject({ provider: 'alpha', model: 'a1' }) - selection.current = { provider: 'beta', model: 'b1' } - await expect(agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 1, step: 0, signal }, () => Promise.resolve(seed), - )).resolves.toEqual({ - provider: 'alpha', - model: 'a1', - reasoningEffort: ReasoningEffortId('high'), - temperature: 0.2, - }) - - expect((await ctx.systemPrompt.assemble()).variables).toMatchObject({ provider: 'beta', model: 'b1' }) - const inherited: LlmCallConfig = { - provider: 'alpha', - model: 'a1', - reasoningEffort: ReasoningEffortId('max'), - temperature: 0.2, - } - await expect(agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve(inherited), - )).resolves.toEqual({ provider: 'beta', model: 'b1', temperature: 0.2 }) - - dispose() - expect((await ctx.systemPrompt.assemble()).variables).toEqual({}) - await expect(agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 2, step: 0, signal }, () => Promise.resolve(seed), - )).resolves.toBe(seed) - await ctx.fiber.dispose() + expect(await h.request(0, seed)).toBe(seed) + h.selection.current = { provider: 'alpha', model: 'a1', reasoningEffort: ReasoningEffortId('high') } + expect(await h.request(1)).toEqual({ ...seed, ...h.selection.current }) + h.selection.current = { provider: 'beta', model: 'b1' } + expect(await h.request(1)).toMatchObject({ provider: 'alpha', model: 'a1' }) + expect(await h.request(2, { ...seed, reasoningEffort: ReasoningEffortId('max') })).toEqual({ ...seed, ...h.selection.current }) + h.dispose() + expect(await h.request(3, seed)).toBe(seed) }) - it('announces same-provider and cross-provider route changes from the assembled selection', async () => { - const { agent, ctx, dispose, selection } = await switchHarness( - { provider: 'alpha', model: 'a1' }, - { provider: 'alpha', model: 'a0' }, - ) - await expect(preStep(ctx, agent)).resolves.toMatchObject({ - messages: [INPUT, expectedNotice('a0', 'a1')], - }) - - selection.current = { provider: 'beta', model: 'b1' } - await ctx.systemPrompt.assemble() - selection.current = { provider: 'alpha', model: 'a2' } - await expect(preStep(ctx, agent)).resolves.toMatchObject({ - messages: [INPUT, expectedNotice('alpha/a0', 'beta/b1')], - }) - await ctx.systemPrompt.assemble() - await expect(preStep(ctx, agent)).resolves.toMatchObject({ - messages: [INPUT, expectedNotice('a0', 'a2')], - }) - - dispose() - await ctx.fiber.dispose() + it('announces the bound same-provider and cross-provider routes', async () => { + const h = harness({ provider: 'alpha', model: 'a1' }, { provider: 'alpha', model: 'a0' }) + await h.request(1) + await expect(h.preStep()).resolves.toMatchObject({ messages: [input, notice('a0', 'a1')] }) + h.selection.current = { provider: 'beta', model: 'b1' } + await h.request(2) + h.selection.current = { provider: 'alpha', model: 'a2' } + await expect(h.preStep()).resolves.toMatchObject({ messages: [input, notice('alpha/a0', 'beta/b1')] }) + await h.request(3) + await expect(h.preStep()).resolves.toMatchObject({ messages: [input, notice('a0', 'a2')] }) }) - it('does not announce initial, same-route, effort-only, rejected, aborted, or disposed steps', async () => { - const { agent, ctx, dispose, selection } = await switchHarness({ provider: 'alpha', model: 'a0' }) - await expect(preStep(ctx, agent)).resolves.toMatchObject({ kind: 'enter', messages: [INPUT] }) - agent.session.append('request/header', { - header: { config: { provider: 'alpha', model: 'a0' } }, reason: 'initial', - }) - selection.current = { - provider: 'alpha', - model: 'a0', - reasoningEffort: ReasoningEffortId('high'), - } - await ctx.systemPrompt.assemble() - await expect(preStep(ctx, agent)).resolves.toMatchObject({ kind: 'enter', messages: [INPUT] }) - - selection.current = { provider: 'alpha', model: 'a1' } - await ctx.systemPrompt.assemble() - const rejected = await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', - { turn: 1, step: 1, messages: [], signal: SIGNAL }, - () => Promise.resolve({ kind: 'reject' as const }), - ) - expect(rejected).toEqual({ kind: 'reject' }) - const aborted = new AbortController() - aborted.abort() - await expect(preStep(ctx, agent, { signal: aborted.signal })).resolves.toMatchObject({ messages: [INPUT] }) - - dispose() - await expect(preStep(ctx, agent)).resolves.toMatchObject({ kind: 'enter', messages: [INPUT] }) - await ctx.fiber.dispose() + it('preserves initial, unchanged, rejected, cancelled, and disposed decisions', async () => { + const h = harness({ provider: 'alpha', model: 'a0' }) + await h.request(1) + await expect(h.preStep()).resolves.toEqual({ kind: 'enter', messages: [input] }) + h.agent.session.append('request/header', { header: { config: h.agent.currentRoute() }, reason: 'initial' }) + h.selection.current = { provider: 'alpha', model: 'a0', reasoningEffort: ReasoningEffortId('high') } + await h.request(2) + await expect(h.preStep()).resolves.toEqual({ kind: 'enter', messages: [input] }) + h.selection.current = { provider: 'alpha', model: 'a1' } + await h.request(3) + await expect(agentEvents(h.ctx, h.agent).waterfall('agent/pre-step', { turn: 1, step: 3, messages: [], signal }, + () => Promise.resolve({ kind: 'reject' as const }))).resolves.toEqual({ kind: 'reject' }) + const aborted = AbortSignal.abort() + await expect(h.preStep([input], [input], 3, aborted)).resolves.toEqual({ kind: 'enter', messages: [input] }) + h.dispose() + await expect(h.preStep()).resolves.toEqual({ kind: 'enter', messages: [input] }) }) - it('preserves empty no-call decisions and announces an empty tool continuation', async () => { - const { agent, ctx } = await switchHarness( - { provider: 'alpha', model: 'a1' }, - { provider: 'alpha', model: 'a0' }, - ) - await expect(preStep(ctx, agent, { messages: [] })).resolves.toEqual({ kind: 'enter', messages: [] }) - await expect(preStep(ctx, agent, { messages: [], step: 2 })).resolves.toEqual({ kind: 'enter', messages: [] }) - await expect(preStep(ctx, agent, { messages: [], offered: [], step: 2 })).resolves.toMatchObject({ - messages: [{ source: { summary: 'a0 → a1' } }], - }) - await ctx.fiber.dispose() + it('preserves empty claims and announces an empty tool continuation', async () => { + const h = harness({ provider: 'alpha', model: 'a1' }, { provider: 'alpha', model: 'a0' }) + await h.request(1) + await expect(h.preStep([])).resolves.toEqual({ kind: 'enter', messages: [] }) + await expect(h.preStep([], [input], 2)).resolves.toEqual({ kind: 'enter', messages: [] }) + await expect(h.preStep([], [], 2)).resolves.toMatchObject({ messages: [notice('a0', 'a1')] }) }) }) diff --git a/packages/core/system-prompt/README.i18n.yaml b/packages/core/system-prompt/README.i18n.yaml index a5c3f5913c..18bb14f61c 100644 --- a/packages/core/system-prompt/README.i18n.yaml +++ b/packages/core/system-prompt/README.i18n.yaml @@ -21,8 +21,8 @@ en: 87e28893e6cf58d7 zh: 06f476b38c4d2038 /deepseek-ai-dsh-system-prompt/use-this-package/contribute-a-prompt-section: - en: 165fecb5329b00b6 - zh: a7c595d1787916c9 + en: db364cc533949015 + zh: a6e8a12d9a661b60 /deepseek-ai-dsh-system-prompt/use-this-package/contribute-a-prompt-variable: en: b3e4c9b4ced59488 zh: d80c791e72bd5821 @@ -42,8 +42,8 @@ en: d9575bcb07a1145b zh: 0f1a388780d055b1 /deepseek-ai-dsh-system-prompt/understand-the-implementation/assembly-and-rendering: - en: 54977e6c431f851e - zh: ef60007054b97ff0 + en: d51940213af9b87f + zh: f3a2540010624a79 /deepseek-ai-dsh-system-prompt/understand-the-implementation/scoping: en: 1100ab1dfe961631 zh: c510275c893951b4 @@ -57,8 +57,8 @@ en: cf78b9dd5596495f zh: bd44560f8c2435e8 /deepseek-ai-dsh-system-prompt/model-experience/system-prompt/what-the-model-sees: - en: 0aaabee3a9883eea - zh: 13e6ead5b455fa30 + en: 622e83de7772dc1f + zh: 7b3c54f08a317e93 /deepseek-ai-dsh-system-prompt/model-experience/system-prompt/what-the-model-sees/harness-identity: en: 40effd71cb503319 zh: 9969356237a4f398 @@ -72,8 +72,8 @@ en: 3039bc5e7a796b21 zh: 6b7a9eaf69c9ea53 /deepseek-ai-dsh-system-prompt/model-experience/tool-schemas/what-the-model-sees: - en: a983ef220593cf73 - zh: 28770612ffc1be60 + en: b3873ff844d91e34 + zh: 5cccd2afda37af9a /deepseek-ai-dsh-system-prompt/model-experience/tool-schemas/token-effect: en: f3a7d374c55e1720 zh: 0ee48af678cb875f diff --git a/packages/core/system-prompt/README.md b/packages/core/system-prompt/README.md index 6c9d7338ec..d6a37baa85 100644 --- a/packages/core/system-prompt/README.md +++ b/packages/core/system-prompt/README.md @@ -67,6 +67,8 @@ Set `interpolate: false` on a section or dynamic context to preserve its text li `refreshContext(assembly, context)` refreshes registered runtime facts after pre-step and route preparation. It preserves accepted sections, tools, variables, and contexts contributed only by the assembly waterfall, applies current optional-context suppression, and restores missing required entries. Put changing facts in context providers; registered context text is read again before admission. +`prepare(context)` resolves variables and runtime facts through `system-prompt/prepare` before step admission. After the loop binds the route and commits step selections, `assemble(context, preparation)` resolves sections and tool declarations. Presentation listeners receive sections, contexts, and variables; tools remain provider-owned. Tool-aware section callbacks use `context.toolSet` to inspect the same request selection as execution. + ### Contribute a prompt variable Variables are referenced from section or context text as `{{name}}` and resolved at each assembly; scoped variables shadow a same-named global for that agent. The loop supplies `provider` and `model`; plugins can register the facts they own. The working-directory service supplies directory text as literal user context. @@ -107,7 +109,7 @@ The package is a registry plus a cooperative assembly pipeline. One `assemble()` ### Assembly and rendering -Assembly resolves and renders in two stages: `assemble()` returns sections with resolved-but-uninterpolated text, the ordered tool schemas, and every registered variable resolved against the context, while `renderPrompt()` interpolates `{{variable}}` references unless a section sets `interpolate: false`, drops empty sections, and joins with blank lines — strictly, an unknown reference, a registered-but-valueless reference, or a malformed complete group throws, because a malformed prompt is worse than a loud failure. `toolOrder` canonicalizes the collected tools before the waterfall (registration order is a plugin-load artifact); a waterfall listener that mutates the list owns the determinism of what it emits. +Assembly resolves and renders in two stages: `assemble()` returns sections with resolved-but-uninterpolated text, the ordered tool schemas, and every registered variable resolved against the context, while `renderPrompt()` interpolates `{{variable}}` references unless a section sets `interpolate: false`, drops empty sections, and joins with blank lines — strictly, an unknown reference, a registered-but-valueless reference, or a malformed complete group throws, because a malformed prompt is worse than a loud failure. `toolOrder` canonicalizes the collected tools before the waterfall (registration order is a plugin-load artifact); the presentation waterfall receives no tool array and cannot replace provider-owned declarations. ### Scoping @@ -137,7 +139,7 @@ The package-level contract is enough for most consumers; read these when you nee #### What the model sees -First-party sections render the harness identity, deployment persona prefix (including the model-name introduction), reusable instructions (including the generated tools SDK and structured-output guidance), then the environment-bearing suffix: harness source (`10000`), Web surface (`10100`), and deployment persona suffix (`10200`). External section orders and assembly listeners remain authoritative. `includeHarnessIdentity: false` omits only that fixed opener. Empty sections disappear; scoped sections and variables can shadow globals for one agent. The `system-prompt/assemble` waterfall determines the delivered prompt and tool schemas unless one effective section declares itself complete — that exact section then becomes the whole system prompt while the waterfall's contexts, tools, and variables remain. The rendered prompt reaches the model as a system-role message of derived history — surface node 0, or the latest system node after an in-history update — neither the loop request nor `request/header` carries a separate `system` field. If the complete rendering is empty, the loop clears every active system node through logged empty replacements, so no older prompt remains in model history. Ordered dynamic contexts are separate from sections and become sourced user-role snapshots only when present; `includeRuntimeContext: false` or a scoped suppressor removes optional contributions while required operational context remains. +First-party sections render the harness identity, deployment persona prefix (including the model-name introduction), reusable instructions (including the generated tools SDK and structured-output guidance), then the environment-bearing suffix: harness source (`10000`), Web surface (`10100`), and deployment persona suffix (`10200`). External section orders and assembly listeners remain authoritative. `includeHarnessIdentity: false` omits only that fixed opener. Empty sections disappear; scoped sections and variables can shadow globals for one agent. The `system-prompt/assemble` waterfall determines the delivered prompt unless one effective section declares itself complete — that exact section then becomes the whole system prompt while the waterfall's contexts and variables remain. Tool declarations stay provider-owned. The rendered prompt reaches the model as a system-role message of derived history — surface node 0, or the latest system node after an in-history update — neither the loop request nor `request/header` carries a separate `system` field. If the complete rendering is empty, the loop clears every active system node through logged empty replacements, so no older prompt remains in model history. Ordered dynamic contexts are separate from sections and become sourced user-role snapshots only when present; `includeRuntimeContext: false` or a scoped suppressor removes optional contributions while required operational context remains. ##### Harness identity @@ -157,7 +159,7 @@ Prefix-stable while identity, persona, variables, section text, and order render #### What the model sees -For shipped tools, the model receives the per-agent-visible subset of the [generated tool schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tools), ordered by configuration or lexicographically after restrictions and assembly interception. Extensions can contribute additional definitions through the same registry. Sections and schema providers are separate assembly inputs. A restriction does not remove a section registration: tool-guidance plugins use `text({ scope })` and `ctx.tools.get(name, scope)` to return empty text or select applicable fragments. Arbitrary static sections are not automatically rewritten. +For shipped tools, the model receives the per-agent-visible subset of the [generated tool schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tools), ordered by configuration or lexicographically after restrictions and request-time activation. Extensions can contribute additional definitions through the same registry. Sections and schema providers are separate assembly inputs. A restriction does not remove a section registration: tool-guidance plugins use `text({ scope, toolSet })` and `ctx.tools.get(name, scope, toolSet)` to return empty text or select applicable fragments. Arbitrary static sections are not automatically rewritten. #### Token effect diff --git a/packages/core/system-prompt/README.zh.md b/packages/core/system-prompt/README.zh.md index 1807bf0411..117ba86ffc 100644 --- a/packages/core/system-prompt/README.zh.md +++ b/packages/core/system-prompt/README.zh.md @@ -67,6 +67,8 @@ ctx.systemPrompt.section({ `refreshContext(assembly, context)` 在 pre-step 与路由准备之后刷新已注册的运行时事实。它保留已接纳的段、工具、变量及仅由组装 waterfall 添加的上下文,应用当前的可选上下文抑制,并恢复缺失的必需条目。将变化的事实放在上下文 provider 中;已注册上下文的文本会在准入前再次读取。 +`prepare(context)` 在步骤接纳前通过 `system-prompt/prepare` 解析变量与运行时事实。循环绑定路由并提交步骤选择后,`assemble(context, preparation)` 解析段落与工具声明。展示监听器接收段落、上下文与变量;工具声明仍由提供方持有。依赖工具的段落回调通过 `context.toolSet` 读取与执行相同的请求集合。 + ### 贡献提示词变量 变量从段或上下文文本中以 `{{name}}` 引用,每次组装时解析;带作用域的变量会为该 agent 遮蔽同名全局变量。循环提供 `provider` 和 `model`;插件可注册自己拥有的事实。工作目录服务通过不执行插值的用户上下文提供目录文本。 @@ -107,7 +109,7 @@ ctx.systemPrompt.variable('response_language', () => 'English') ### 组装与渲染 -组装分两阶段完成求值与渲染:`assemble()` 返回文本已求值但尚未插值的段、有序工具 schema,以及每个已注册变量按当前上下文求得的值;`renderPrompt()` 对未设置 `interpolate: false` 的段插值 `{{variable}}` 引用、删除空段并用空行连接——严格规则:未知引用、已注册但无值的引用或格式错误的完整组都会抛出,因为格式错误的提示词比明确失败更糟。`toolOrder` 在 waterfall 分发前规范化收集到的工具(注册顺序只是插件加载产物);修改列表的 waterfall 监听器对其输出的确定性负责。 +组装分两阶段完成求值与渲染:`assemble()` 返回文本已求值但尚未插值的段、有序工具 schema,以及每个已注册变量按当前上下文求得的值;`renderPrompt()` 对未设置 `interpolate: false` 的段插值 `{{variable}}` 引用、删除空段并用空行连接——严格规则:未知引用、已注册但无值的引用或格式错误的完整组都会抛出,因为格式错误的提示词比明确失败更糟。`toolOrder` 在 waterfall 分发前规范化收集到的工具(注册顺序只是插件加载产物);展示 waterfall 不接收工具数组,也不能替换提供方持有的声明。 ### 作用域 @@ -137,7 +139,7 @@ ctx.systemPrompt.variable('response_language', () => 'English') #### 模型看到什么 -第一方段落依次渲染 harness 身份、部署 persona 前缀(含模型名称介绍)、可复用指令(包括生成的工具 SDK 和结构化输出指导),最后是携带环境信息的后缀:harness 源码(`10000`)、Web 表层(`10100`)和部署 persona 后缀(`10200`)。外部段落的顺序与组装监听器仍决定其最终结果。`includeHarnessIdentity: false` 仅省略这个固定开场白。空段会消失;带作用域的段与变量可以为一个 agent 遮蔽全局项。`system-prompt/assemble` waterfall 决定交付的提示词与工具 schema,除非一个有效段声明自身为 complete——此时该确切段会成为完整的系统提示词,而 waterfall 得到的上下文、工具与变量保持不变。渲染后的提示词作为派生历史中的 system 角色消息——surface 第 0 号节点,或历史内更新之后最新的系统节点——到达模型;循环请求与 `request/header` 均不含单独的 `system` 字段。完整渲染结果为空时,循环通过有日志记录的空内容替换清除所有生效的系统节点,模型历史不再保留任何旧提示词。有序动态上下文与段分离,只在存在时才会成为带来源的 user 角色快照;`includeRuntimeContext: false` 或带作用域的抑制器会移除可选贡献;必需的操作上下文仍然保留。 +第一方段落依次渲染 harness 身份、部署 persona 前缀(含模型名称介绍)、可复用指令(包括生成的工具 SDK 和结构化输出指导),最后是携带环境信息的后缀:harness 源码(`10000`)、Web 表层(`10100`)和部署 persona 后缀(`10200`)。外部段落的顺序与组装监听器仍决定其最终结果。`includeHarnessIdentity: false` 仅省略这个固定开场白。空段会消失;带作用域的段与变量可以为一个 agent 遮蔽全局项。`system-prompt/assemble` waterfall 决定交付的提示词,除非一个有效段声明自身为 complete——此时该确切段会成为完整的系统提示词,而 waterfall 得到的上下文与变量保持不变。工具声明仍由提供方持有。渲染后的提示词作为派生历史中的 system 角色消息——surface 第 0 号节点,或历史内更新之后最新的系统节点——到达模型;循环请求与 `request/header` 均不含单独的 `system` 字段。完整渲染结果为空时,循环通过有日志记录的空内容替换清除所有生效的系统节点,模型历史不再保留任何旧提示词。有序动态上下文与段分离,只在存在时才会成为带来源的 user 角色快照;`includeRuntimeContext: false` 或带作用域的抑制器会移除可选贡献;必需的操作上下文仍然保留。 ##### harness 身份 @@ -157,7 +159,7 @@ You are an AI agent powered by DeepSeek Harness. #### 模型看到什么 -对于已交付工具,模型会收到[生成工具 schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tools)中对每个 agent 可见的子集;限制与组装拦截完成后,按配置或字典序排列。扩展可以通过同一注册表贡献其他定义。段与 schema 提供方是独立的组装输入。限制不会移除段落注册:工具指导插件通过 `text({ scope })` 与 `ctx.tools.get(name, scope)` 返回空文本或选择适用片段。任意静态段落不会被自动改写。 +对于已交付工具,模型会收到[生成工具 schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tools)中对每个 agent 可见的子集;限制与请求时激活完成后,按配置或字典序排列。扩展可以通过同一注册表贡献其他定义。段与 schema 提供方是独立的组装输入。限制不会移除段落注册:工具指导插件通过 `text({ scope, toolSet })` 与 `ctx.tools.get(name, scope, toolSet)` 返回空文本或选择适用片段。任意静态段落不会被自动改写。 #### Token 影响 diff --git a/packages/core/system-prompt/src/index.ts b/packages/core/system-prompt/src/index.ts index 2f027dfaf9..57eb475eab 100644 --- a/packages/core/system-prompt/src/index.ts +++ b/packages/core/system-prompt/src/index.ts @@ -17,9 +17,9 @@ declare module '@deepseek-ai/cordis' { interface Events { /** - * Expert waterfall over the assembled sections, contexts, tools, and variables. + * Presentation waterfall over assembled sections, contexts, and variables. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners - * receive only that scope's assemblies. The returned value is authoritative. + * receive only that scope's assemblies. The returned text is authoritative; tool declarations remain provider-owned. * A supplied signal controls only this explicit assembly request and must not * be retained to control later turns. A registered complete section is * restored after this waterfall, so listeners cannot add to or replace @@ -28,7 +28,14 @@ declare module '@deepseek-ai/cordis' { * @param context - the caller's per-assembly context. * @mode waterfall */ - 'system-prompt/assemble'(this: Scoped, assembly: PromptAssembly, context: AssembleContext, next: () => Promise): Promise + 'system-prompt/assemble'(this: Scoped, assembly: PromptPresentation, context: AssembleContext, next: () => Promise): Promise + /** + * Prepare variables and runtime context before step admission. + * @param preparation - registered variables and context contributions. + * @param context - calling scope and cancellation. + * @mode waterfall + */ + 'system-prompt/prepare'(this: Scoped, preparation: PromptPreparation, context: AssembleContext, next: () => Promise): Promise /** * Emitted when any prompt provider changes. This registry notification is * unfiltered because a global change affects every scope. @@ -117,17 +124,22 @@ export interface ToolProviderResult { readonly knownNames?: readonly string[] } -/** - * Merge-extensible assembled model input. Sections and contexts remain - * uninterpolated until rendered; tools are already in canonical order. - */ -export interface PromptAssembly { - sections: AssembledSection[] +/** Prepared runtime facts and variables; context text remains uninterpolated. */ +export interface PromptPreparation { contexts: AssembledContext[] - tools: ToolSchema[] variables: Record } +/** Prompt text contributions; tool declarations are owned by their providers. */ +export interface PromptPresentation extends PromptPreparation { + sections: AssembledSection[] +} + +/** Completed model inputs, including provider-owned tool declarations. */ +export interface PromptAssembly extends PromptPresentation { + tools: ToolSchema[] +} + const SECTION_ORDERS = { HARNESS_IDENTITY: -1000, DEPLOYMENT_PERSONA_PREFIX: 0, @@ -323,7 +335,7 @@ export function joinContextSections(sections: readonly ContextSnapshotSection[]) * @param assembly - the assembly whose contexts and variables to render. * @returns one entry per contributing context that rendered to non-empty text. */ -export function renderContextSections(assembly: PromptAssembly): ContextSnapshotSection[] { +export function renderContextSections(assembly: PromptPreparation): ContextSnapshotSection[] { return assembly.contexts .map(context => ({ name: context.name, @@ -570,12 +582,12 @@ export class SystemPrompt extends Service { * added only by the assembly waterfall retain their accepted values. Current * suppression removes optional contexts, and missing required registrations * are restored in registry order. Sections, tools, and interpolation variables - * retain the accepted assembly; their providers and waterfall do not rerun. + * retain their accepted values during this refresh. * @param assembly - accepted assembly for this scope and step. * @param context - the same scope and current plugin-defined assembly fields. * @returns the accepted assembly with current runtime-context provider text. */ - refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly { + refreshContext(assembly: T, context: AssembleContext = {}): T { const providers = this.layers.merge(context.scope, layer => layer.contexts) const suppressed = !this.layers.global.runtimeContextSuppressors.isEmpty() || this.layers.chainLayers(context.scope).some(layer => !layer.runtimeContextSuppressors.isEmpty()) @@ -598,16 +610,12 @@ export class SystemPrompt extends Service { } /** - * Assemble global and scoped providers, detach tool parameters, apply - * canonical ordering, then run the assembly waterfall. Scoped sections and - * variables shadow globals. The returned waterfall value is authoritative - * except that an effective complete section is restored afterwards as the - * sole prompt section. - * @param context - the optional scope and plugin-defined assembly fields. - * @returns the post-waterfall assembly with any complete prompt enforced. + * Prepare variables and runtime facts before accepting a step. No tool + * conditions or prompt sections are evaluated in this phase. + * @param context - calling scope and request cancellation. + * @returns prepared inputs after the preparation waterfall. */ - // Keep configuration failures on the declared asynchronous error path. - async assemble(context: AssembleContext = {}): Promise { + async prepare(context: AssembleContext = {}): Promise { const scope = context.scope const scopeLayers = this.layers.chainLayers(scope) const runtimeContextSuppressed = !this.layers.global.runtimeContextSuppressors.isEmpty() @@ -623,6 +631,28 @@ export class SystemPrompt extends Service { variables[name] = provider(context) } } + const contexts = [...this.layers.merge(scope, layer => layer.contexts).values()] + .filter(entry => !runtimeContextSuppressed || entry.required === true) + .sort((a, b) => a.order - b.order) + .map(entry => resolveContext(entry, context)) + const preparation = { contexts, variables } + return this.ctx.waterfall(scopeTarget(this, scope), 'system-prompt/prepare', preparation, context, + () => Promise.resolve(preparation)) + } + + /** + * Assemble prompt sections and tool declarations after request preparation. + * The presentation waterfall cannot replace provider-owned tools. + * @param context - calling scope, route-bound agent, and resolved tools. + * @param preparation - accepted variables and runtime facts; prepared here when omitted. + * @returns the complete assembly with ordered tool declarations. + */ + async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise { + const prepared = preparation ?? await this.prepare(context) + const scope = context.scope + const scopeLayers = this.layers.chainLayers(scope) + const runtimeContextSuppressed = !this.layers.global.runtimeContextSuppressors.isEmpty() + || scopeLayers.some(layer => !layer.runtimeContextSuppressors.isEmpty()) // Scoped sections shadow globals before the deterministic order sort. const sectionByName = this.layers.merge(scope, layer => layer.sections) const contextByName = this.layers.merge(scope, layer => layer.contexts) @@ -661,25 +691,28 @@ export class SystemPrompt extends Service { if (section.complete === true) completeSection = { ...assembled } return assembled }) - const assembly: PromptAssembly = { - sections, - contexts: [...contextByName.values()] - .filter(entry => !runtimeContextSuppressed || entry.required === true) - .sort((a, b) => a.order - b.order) - .map(entry => resolveContext(entry, context)), - tools: orderTools(collected, this.toolOrder, knownNames), - variables, - } + const tools = orderTools(collected, this.toolOrder, knownNames) + const assembly: PromptPresentation = { ...prepared, sections } const transformed = await this.ctx.waterfall( scopeTarget(this, scope), 'system-prompt/assemble', assembly, context, () => Promise.resolve(assembly), ) - if (completeSection === undefined && !runtimeContextSuppressed) return transformed const requiredContexts = new Set([...contextByName.values()].filter(entry => entry.required === true).map(entry => entry.name)) + const contexts = runtimeContextSuppressed + ? transformed.contexts.filter(entry => requiredContexts.has(entry.name)) : [...transformed.contexts] + for (const provider of contextByName.values()) { + if (provider.required !== true) continue + const name = provider.name + const value = resolveContext(provider, context) + const existing = contexts.findIndex(entry => entry.name === name) + if (existing >= 0) contexts[existing] = value + else contexts.push(value) + } return { ...transformed, + tools, sections: completeSection === undefined ? transformed.sections : [completeSection], - contexts: runtimeContextSuppressed ? transformed.contexts.filter(entry => requiredContexts.has(entry.name)) : transformed.contexts, + contexts, } } } diff --git a/packages/core/system-prompt/tests/tool-order.spec.ts b/packages/core/system-prompt/tests/tool-order.spec.ts index b716feae16..9218dab72a 100644 --- a/packages/core/system-prompt/tests/tool-order.spec.ts +++ b/packages/core/system-prompt/tests/tool-order.spec.ts @@ -78,21 +78,14 @@ describe('SystemPrompt tool order', () => { expect(assembly.tools.map(t => t.description)).toEqual(['anchor', 'first', 'second']) }) - it('canonicalizes BEFORE the assemble waterfall: listeners see the ordered list and own their own edits', async () => { + it('keeps ordered provider declarations outside presentation transforms', async () => { const ctx = await mount() ctx.systemPrompt.tools(() => ({ schemas: [tool('zulu'), tool('alpha')] })) - let seen: string[] | undefined - ctx.on('system-prompt/assemble', function (assembly, _context, next) { - seen = assembly.tools.map(t => t.name) - // A listener-appended tool is NOT re-sorted — same contract as sections: - // canonicalization applies to what the registry contributed, and a - // listener owns the determinism of what it emits. - assembly.tools.push(tool('aardvark')) - return next() + ctx.on('system-prompt/assemble', async (assembly, _context, next) => { + expect(assembly).not.toHaveProperty('tools') + return { ...await next(), tools: [tool('aardvark')] } }) - const assembly = await ctx.systemPrompt.assemble() - expect(seen).toEqual(['alpha', 'zulu']) - expect(names(assembly)).toEqual(['alpha', 'zulu', 'aardvark']) + expect(names(await ctx.systemPrompt.assemble())).toEqual(['alpha', 'zulu']) }) it.each([ diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index 739e42cb05..0103da13ae 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -20,6 +20,9 @@ /deepseek-ai-dsh-tools/use-this-package/register-a-tool: en: 9d2e6caa39c53d62 zh: 096a777f828c7565 +/deepseek-ai-dsh-tools/use-this-package/conditional-tools: + en: 93008deced28d5fe + zh: 09fe2f8693c5f147 /deepseek-ai-dsh-tools/use-this-package/configure-the-presentation-mode: en: 19a752864651fc41 zh: 48e20c3cdc867428 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index bbf221031b..8360559504 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -63,6 +63,14 @@ ctx.tools.register(defineTool({ The unified schema DSL supports `string`, `number`, `integer`, `boolean`, `null`, `array`, `object`, author-only `json`, and exact-one `oneOf`; `InferValue` preserves exact types through 16 container levels before widening to `JsonValue`. A raw JSON Schema (`JsonSchemaNode`) is the wire-level counterpart shared with subagents, workflows, and MCP. +### Conditional tools + +`register(definition, { when })` evaluates a synchronous or asynchronous condition for each model request. The condition receives `{ agent, signal }`; `agent.currentRoute()` reports the resolved provider/model. False omits the tool from Native declarations, PTC bindings, and execution. A thrown condition fails request preparation as `TOOL_ACTIVATION_FAILED`; it is not treated as ordinary unavailability. Conditions must observe cancellation and must not change registrations or perform tool work. + +`resolve({ agent, signal })` returns a request-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and every Native or PTC execution, then dispose it after the batch settles. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, cancellation, or same-name replacement prevent unstarted calls from using it. Started operations retain their cooperative cancellation obligations. Conditional calls without a resolved set return `UNKNOWN_TOOL`. + +`get(name, scope, toolSet)` and `schemas(scope, toolSet)` inspect an admitted set; omitting `toolSet` inspects registered definitions without evaluating conditions. Tool guidance receives the same selection as `AssembleContext.toolSet`. A presentation transform cannot add or remove callable tools. + ### Configure the presentation mode The `mode` config decides what the model sees: `native` (every visible schema) or `ptc` (only `run_code` plus a generated SDK). diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index a3e9989874..8ea7f82f5e 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -63,6 +63,14 @@ ctx.tools.register(defineTool({ 统一 schema DSL 支持 `string`、`number`、`integer`、`boolean`、`null`、`array`、`object`、仅供作者使用的 `json` 与恰好匹配一个分支的 `oneOf`;`InferValue` 在 16 层容器内保留精确类型,之后加宽为 `JsonValue`。原始 JSON Schema(`JsonSchemaNode`)是与 subagent、工作流和 MCP 共享的协议级对应类型。 +### 条件工具 + +`register(definition, { when })` 为每次模型请求计算同步或异步条件。条件接收 `{ agent, signal }`;`agent.currentRoute()` 返回已解析的提供方与模型。返回 false 会从原生声明、PTC 绑定和执行集合中排除工具。条件抛错会以 `TOOL_ACTIVATION_FAILED` 中止请求准备,不会被当成正常不可用。条件必须响应取消,不得改变注册或执行工具操作。 + +`resolve({ agent, signal })` 返回请求拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及每次原生或 PTC 执行,批次结束后释放。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制、取消或同名替换会阻止尚未开始的调用继续使用它。已经开始的操作保留协作取消义务。没有已解析集合的条件工具调用返回 `UNKNOWN_TOOL`。 + +`get(name, scope, toolSet)` 和 `schemas(scope, toolSet)` 读取已准入集合;省略 `toolSet` 时只查看已注册定义,不计算条件。工具指导文本通过 `AssembleContext.toolSet` 接收同一集合。展示变换不能增删可调用工具。 + ### 配置呈现模式 `mode` 配置决定模型看到什么:`native`(每个可见 schema)或 `ptc`(只有 `run_code` 加一份生成 SDK)。 diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index e506d99da0..b79fa6daf5 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -29,6 +29,13 @@ import { renderToolsSdk } from './ts-types.ts' import type { ToolSdkSchema } from './ts-types.ts' import { renderToolsSdkPy } from './py-types.ts' +declare module '@deepseek-ai/dsh-system-prompt' { + interface AssembleContext { + /** Request-owned tool selection; absent when inspecting registered definitions. */ + toolSet?: ResolvedToolSet + } +} + declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { /** Tool availability changes supplied by the tool registry. */ @@ -220,6 +227,55 @@ export interface ToolOutputDefinition { presentationMeta?(args: unknown, value: JsonValue): JsonValue } +/** Inputs for a tool's request-time activation condition. */ +export interface ToolActivationContext { + /** Agent whose currentRoute() is bound to the request being prepared. */ + readonly agent: Agent + /** Cancellation of request preparation; asynchronous conditions must observe it. */ + readonly signal: AbortSignal +} + +/** Lifecycle-owned conditions for a registered tool. */ +export interface ToolRegistrationOptions { + /** + * Decide whether this request may call the tool. Omission enables it. False + * excludes it from both declarations and dispatch; rejection fails request + * preparation. Conditions must not mutate registrations or start tool work. + * @param context - requesting agent and cancellation signal. + * @returns whether the tool participates in this request. + */ + readonly when?: (context: ToolActivationContext) => boolean | Promise +} + +/** One request's admitted registrations, also used by nested PTC calls. */ +export interface ResolvedToolSet { + /** Close request admission after its tool batch settles. */ + dispose(): void + /** + * Read admitted registrations that remain visible in their original scope. + * @param scope - exact requesting agent; another scope is never admitted. + * @returns original definitions excluding removed or restricted registrations. + */ + view(scope: ScopeKey | undefined): ReadonlyMap +} + +/** Failure to determine a tool's request-time availability. */ +export class ToolActivationError extends HarnessError { + /** + * Preserve a condition failure without treating it as normal unavailability. + * @param name - tool whose condition rejected. + * @param cause - underlying condition failure. + */ + constructor(name: string, cause: unknown) { + super(`cannot resolve availability of tool "${name}": ${errorMessage(cause)}`, 'TOOL_ACTIVATION_FAILED', { cause }) + } +} + +interface ToolRegistration { + readonly definition: ToolDefinition + readonly when: ToolRegistrationOptions['when'] +} + /** A registered tool: its schema plus the execution function. */ export interface ToolDefinition extends ToolSchema { /** Mandatory canonical output declaration. */ @@ -338,6 +394,8 @@ export interface ToolExecutionInput { readonly arguments: unknown /** The agent on whose behalf the call runs (set by the agent loop). */ readonly agent?: Agent + /** Request admission shared by Native and PTC dispatch. Conditional tools require it. */ + readonly toolSet?: ResolvedToolSet /** * Opaque token of the enclosing transport execution, when one exists. PTC * mode sets this on SDK sub-dispatches so commit-style observers can wait for @@ -715,6 +773,7 @@ interface CompiledToolRestriction { interface ToolView { /** Visible definitions after restrictions, scoped shadowing, and transport insertion. */ readonly visible: ReadonlyMap + readonly registrations: ReadonlyMap /** Pre-restriction capability names used by prompt-order validation. */ readonly knownNames: ReadonlySet /** Current global names that a scoped restriction may name. */ @@ -733,7 +792,7 @@ export type ToolGuard = (execution: Readonly) => string | undefin /** One scope's complete tool-registry contribution. */ class ToolLayer implements ScopeLayer { - readonly tools: NamedEntries + readonly tools: NamedEntries readonly restrictions = new AnonymousEntries() readonly guards = new AnonymousEntries() /** @@ -852,7 +911,7 @@ export class ToolRuntime extends Service { // optional-input type for direct (non-Loader) construction in tests. this.defaultMode = config.mode ?? 'native' this.maxParallelSubCalls = resolveMaxParallelSubCalls(config.maxParallelSubCalls) - ctx.systemPrompt.tools(context => this.wireSchemas(context.scope)) + ctx.systemPrompt.tools(context => this.wireSchemas(context.scope, context.toolSet)) if (this.defaultMode !== 'native') { ctx.systemPrompt.section(this.collapseSection()) ctx.systemPrompt.section(this.sdkSection()) @@ -909,7 +968,7 @@ export class ToolRuntime extends Service { const render = SDK_RENDERERS[runtime.language] /* v8 ignore next -- requirePtcRuntime rejects an unknown language before this runs. */ if (render === undefined) throw new Error(`dsh-tools: no SDK renderer for ${runtime.language}`) - return render(this.sdkSchemas(context.scope)) + return render(this.sdkSchemas(context.scope, context.toolSet)) }, } } @@ -1014,11 +1073,11 @@ export class ToolRuntime extends Service { * Build one scope's wire schemas and names for prompt-order validation. * Restrictions do not make known tools invalid, but a mode collapse does. */ - private wireSchemas(scope?: ScopeKey): ToolProviderResult { + private wireSchemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolProviderResult { const view = this.view(scope) const mode = this.modeFor(scope) if (mode === 'native') { - const schemas = [...view.visible.values()].map(definition => this.schemaOf(definition, false)) + const schemas = this.definitions(scope, toolSet).map(definition => this.schemaOf(definition, false)) return { schemas, knownNames: [...view.knownNames] } } // Validate the runtime language BEFORE projecting schemas: schemaOf reads @@ -1027,7 +1086,7 @@ export class ToolRuntime extends Service { // renderer-table rejection the canonical assembly-time error for a // language with no SDK renderer. this.requirePtcRuntime(mode) - const schemas = [...view.visible.values()].map(definition => this.schemaOf(definition, false)) + const schemas = this.definitions(scope, toolSet).map(definition => this.schemaOf(definition, false)) return { schemas: schemas.filter(schema => schema.name === RUN_CODE_NAME), knownNames: [RUN_CODE_NAME], @@ -1064,9 +1123,10 @@ export class ToolRuntime extends Service { * Register globally or in the calling agent scope. Scoped tools shadow * globals; duplicates within one layer and the reserved `run_code` name fail. * @param definition - tool schema, execution, and optional finalization/presentation callbacks. + * @param options - optional request-time activation condition. * @returns the exact disposer that unregisters the tool. */ - register(definition: ToolDefinition): () => void { + register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void { const name = definition.name const output = (definition as Partial).output if (output === undefined || typeof output !== 'object' @@ -1088,7 +1148,7 @@ export class ToolRuntime extends Service { } return this.layers.effect( this.ctx, - layer => layer.tools.insert(name, definition), + layer => layer.tools.insert(name, { definition, when: options.when }), { label: 'tools.register()' }, ) } @@ -1190,27 +1250,32 @@ export class ToolRuntime extends Service { const own = this.layers.peek(scope) // Inherited surface, nearest ancestor last: a nearer scope's same-name // entry shadows a farther one, and the global layer is the farthest. - const inherited = new Map(this.layers.global.tools.entries()) + const inherited = new Map(this.layers.global.tools.entries()) for (const layer of layers) { if (layer === own) continue for (const [name, definition] of layer.tools.entries()) inherited.set(name, definition) } const visible = new Map() + const registrations = new Map() const knownNames = new Set() const restrictableNames = new Set() - for (const [name, definition] of inherited) { + for (const [name, registration] of inherited) { knownNames.add(name) restrictableNames.add(name) // Restrictions intersect across the whole chain: any scope on it may // mask an inherited name for everything nested inside it. - if (layers.every(layer => layer.admits(name))) visible.set(name, definition) + if (layers.every(layer => layer.admits(name))) { + visible.set(name, registration.definition) + registrations.set(name, registration) + } } // The scope's own registrations last, shadowing an inherited name and // outside the filter above. if (own !== undefined) { - for (const [name, definition] of own.tools.entries()) { + for (const [name, registration] of own.tools.entries()) { knownNames.add(name) - visible.set(name, definition) + visible.set(name, registration.definition) + registrations.set(name, registration) } } // Presentation infrastructure is resolved last and outside capability @@ -1221,7 +1286,7 @@ export class ToolRuntime extends Service { if (this.modeFor(scope) !== 'native') { visible.set(RUN_CODE_NAME, this.requirePtcTransport()) } - return { visible, knownNames, restrictableNames } + return { visible, registrations, knownNames, restrictableNames } } /** @@ -1231,10 +1296,58 @@ export class ToolRuntime extends Service { * actually executed. * @param name - the tool name as registered. * @param scope - the viewing scope (the agent); omitted = the global view. + * @param toolSet - request admission; omit only to inspect registered definitions. * @returns the definition the scope resolves, or undefined when none is visible. */ - get(name: string, scope?: ScopeKey): ToolDefinition | undefined { - return this.view(scope).visible.get(name) + get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined { + return toolSet === undefined ? this.view(scope).visible.get(name) : toolSet.view(scope).get(name) + } + + /** + * Resolve conditions once for this request without changing shared registrations. + * Cancellation or a rejected condition publishes no partial selection. Removed + * registrations cannot be restored by a late condition result. + * @param context - agent with a bound route and request cancellation. + * @returns the complete selection; the caller disposes it after its tool batch settles. + */ + async resolve(context: ToolActivationContext): Promise { + const { agent, signal } = context + signal.throwIfAborted() + const view = this.view(agent) + const admitted = new Map() + for (const [name, definition] of view.visible) { + const registration = view.registrations.get(name) + let enabled: boolean + try { + enabled = registration?.when === undefined || await registration.when(context) + } catch (cause: unknown) { + signal.throwIfAborted() + throw new ToolActivationError(name, cause) + } + signal.throwIfAborted() + if (enabled) admitted.set(name, definition) + } + let closed = false + return Object.freeze({ + dispose: () => { closed = true }, + view: (scope: ScopeKey | undefined): ReadonlyMap => { + const visible = new Map() + if (closed || scope !== agent || signal.aborted) return visible + const current = this.view(agent) + for (const [name, definition] of admitted) { + if (current.visible.get(name) === definition + && current.registrations.get(name) === view.registrations.get(name)) { + visible.set(name, definition) + } + } + return visible + }, + }) + } + + private definitions(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition[] { + if (toolSet === undefined) return [...this.view(scope).visible.values()] + return [...toolSet.view(scope).values()] } /** @@ -1250,8 +1363,11 @@ export class ToolRuntime extends Service { * @param nested - whether the call is a transport sub-dispatch, not a model-direct call. * @returns the definition that may run, or undefined when the call must be rejected. */ - private resolveExecution(name: string, scope: ScopeKey | undefined, nested: boolean): ToolDefinition | undefined { - const tool = this.get(name, scope) + private resolveExecution( + name: string, scope: ScopeKey | undefined, nested: boolean, toolSet?: ResolvedToolSet, + ): ToolDefinition | undefined { + if (toolSet === undefined && this.view(scope).registrations.get(name)?.when !== undefined) return undefined + const tool = this.get(name, scope, toolSet) if (tool === undefined) return undefined if (this.collapses(name, scope, nested)) return undefined return tool @@ -1261,15 +1377,16 @@ export class ToolRuntime extends Service { * Project visible definitions onto the allowlisted model-facing schema fields, * excluding execution and presentation callbacks. * @param scope - the viewing scope (the agent); omitted = the global view. + * @param toolSet - request admission, or omitted for registered-definition inspection. * @returns one deep-cloned schema per visible tool. */ - schemas(scope?: ScopeKey): ToolSchema[] { - return [...this.view(scope).visible.values()].map(definition => this.schemaOf(definition, true)) + schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[] { + return this.definitions(scope, toolSet).map(definition => this.schemaOf(definition, true)) } /** Project visible callable tools onto the generated PTC mode SDK contract. */ - private sdkSchemas(scope?: ScopeKey): ToolSdkSchema[] { - return [...this.view(scope).visible.values()] + private sdkSchemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSdkSchema[] { + return this.definitions(scope, toolSet) .filter(definition => definition.name !== RUN_CODE_NAME) .map((definition): ToolSdkSchema => { const output = snapshotJsonValue(definition.output.schema) @@ -1307,7 +1424,7 @@ export class ToolRuntime extends Service { * @returns the fail-closed scheduling mode. */ executionMode(exec: ToolExecutionInput): ToolExecutionMode { - const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== undefined) + const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== undefined, exec.toolSet) if (!tool?.isConcurrencySafe) return { kind: 'exclusive' } try { const concurrencySafe: unknown = tool.isConcurrencySafe(exec.arguments) @@ -1410,7 +1527,7 @@ export class ToolRuntime extends Service { // observe — or worse, approve — a call that can only fail. An unknown tool // keeps the historical dispatch-stage `UNKNOWN_TOOL` path so policy // listeners still see every name that reaches the registry. - const visible = this.get(name, agent) + const visible = this.get(name, agent, exec.toolSet) const collapsed = visible !== undefined && this.collapses(name, agent, parent !== undefined) const concludingExecutions = this.concludingExecutions const base = { @@ -1420,6 +1537,7 @@ export class ToolRuntime extends Service { name, signal, ...agent !== undefined ? { agent } : {}, + ...exec.toolSet !== undefined ? { toolSet: exec.toolSet } : {}, ...parent !== undefined ? { parent } : {}, ...exec.schema !== undefined ? { schema: exec.schema } : {}, deferContext(context: UserMessage): void { @@ -1581,7 +1699,7 @@ export class ToolRuntime extends Service { } exec.signal = signal try { - const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== undefined) + const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== undefined, exec.toolSet) if (!tool) throw new ToolNotFoundError(exec.name) state.bodyInvoked = true const returned = await tool.execute(exec.arguments, exec) @@ -1810,7 +1928,7 @@ export class ToolRuntime extends Service { if (result.isError) { throw new TypeError('tools/post-execute cannot replace the value of a failed result') } - const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== undefined) + const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== undefined, exec.toolSet) if (tool === undefined) throw new ToolNotFoundError(exec.name) const replaced = this.createSuccessResult(exec, tool, decision.value) return this.markCanonical(exec, { @@ -1879,7 +1997,7 @@ export class ToolRuntime extends Service { ...result.additionalContexts !== undefined ? { additionalContexts: result.additionalContexts } : {}, }) } - const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== undefined) + const tool = this.resolveExecution(exec.name, exec.agent, exec.parent !== undefined, exec.toolSet) if (tool === undefined) throw new ToolNotFoundError(exec.name) const normalized = this.createSuccessResult(exec, tool, result.value) return this.markCanonical(exec, { diff --git a/packages/core/tools/src/ptc.ts b/packages/core/tools/src/ptc.ts index 9d3bea545b..815af25971 100644 --- a/packages/core/tools/src/ptc.ts +++ b/packages/core/tools/src/ptc.ts @@ -554,6 +554,7 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO schema, arguments: normalized.dispatched, ...exec.agent ? { agent: exec.agent } : {}, + ...exec.toolSet !== undefined ? { toolSet: exec.toolSet } : {}, parent: exec.token, signal: runController.signal, } @@ -691,7 +692,7 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO // restricted globals vanish) — the same view the SDK section declared, // so a program can bind exactly what its prompt promised; sub-dispatch // re-resolves per call through the same view (exec.agent threads down). - for (const schema of registry.schemas(exec.agent)) { + for (const schema of registry.schemas(exec.agent, exec.toolSet)) { if (schema.name === RUN_CODE_NAME) continue Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(deepFreeze(schema)) }) } diff --git a/packages/core/tools/tests/activation.spec.ts b/packages/core/tools/tests/activation.spec.ts new file mode 100644 index 0000000000..5b052468d0 --- /dev/null +++ b/packages/core/tools/tests/activation.spec.ts @@ -0,0 +1,123 @@ +/** Conditional registrations share request admission with direct and nested execution. */ +import { afterEach, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { createScope, type Scope } from '@deepseek-ai/dsh-scope' +import { SessionId } from '@deepseek-ai/dsh-session' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime, { defineTool, ToolActivationError } from '@deepseek-ai/dsh-tools' + +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() +}) + +async function setup() { + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + const agent = { id: SessionId('activation'), currentRoute: () => ({ provider: 'test', model: 'test' }) } as Agent + let scope!: Scope + await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, { inject: ['tools'] })) + const controller = new AbortController() + let calls = 0 + const tool = defineTool({ + name: 'conditional', description: 'A conditional operation.', parameters: {}, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute() { calls++; return 'done' }, + }) + const input = { agent, name: tool.name, arguments: {}, callId: ToolCallId('call'), signal: controller.signal } + const resolve = () => ctx.tools.resolve({ agent, signal: controller.signal }) + return { ctx, agent, scope, controller, tool, input, resolve, calls: () => calls } +} + +it('activates and deactivates a registered tool without allowing historical calls', async () => { + const h = await setup() + let enabled = false + h.ctx.tools.register(h.tool, { when: () => enabled }) + const unavailable = await h.resolve() + expect(h.ctx.tools.schemas(h.agent, unavailable)).toEqual([]) + enabled = true + expect((await h.ctx.tools.execute({ ...h.input, toolSet: unavailable })).error?.info?.code).toBe('UNKNOWN_TOOL') + expect((await h.ctx.tools.execute(h.input)).error?.info?.code).toBe('UNKNOWN_TOOL') + const available = await h.resolve() + expect(h.ctx.tools.schemas(h.agent, available).map(tool => tool.name)).toEqual(['conditional']) + expect((await h.ctx.tools.execute({ ...h.input, toolSet: available })).isError).toBe(false) + enabled = false + const disabled = await h.resolve() + expect((await h.ctx.tools.execute({ ...h.input, toolSet: disabled })).error?.info?.code).toBe('UNKNOWN_TOOL') + expect(h.calls()).toBe(1) +}) + +it('keeps admissions specific to the requesting agent', async () => { + const h = await setup() + h.ctx.tools.register(h.tool, { when: () => true }) + const toolSet = await h.resolve() + const other = { id: SessionId('other') } as Agent + expect((await h.ctx.tools.execute({ ...h.input, agent: other, toolSet })).error?.info?.code).toBe('UNKNOWN_TOOL') + expect(h.calls()).toBe(0) +}) + +it('applies live restrictions and closes request admission permanently', async () => { + const h = await setup() + h.ctx.tools.register(h.tool, { when: () => true }) + const toolSet = await h.resolve() + const lift = h.scope.ctx.tools.restrict({ deny: ['conditional'] }) + expect((await h.ctx.tools.execute({ ...h.input, toolSet })).error?.info?.code).toBe('UNKNOWN_TOOL') + lift() + expect((await h.ctx.tools.execute({ ...h.input, toolSet })).isError).toBe(false) + toolSet.dispose() + expect(h.ctx.tools.schemas(h.agent, toolSet)).toEqual([]) + expect((await h.ctx.tools.execute({ ...h.input, toolSet })).error?.info?.code).toBe('UNKNOWN_TOOL') + expect(h.calls()).toBe(1) +}) + +it('does not substitute a same-name registration after admission', async () => { + const h = await setup() + const unregister = h.ctx.tools.register(h.tool, { when: () => true }) + const old = await h.resolve() + unregister() + h.ctx.tools.register(h.tool, { when: () => true }) + expect((await h.ctx.tools.execute({ ...h.input, toolSet: old })).error?.info?.code).toBe('UNKNOWN_TOOL') + expect((await h.ctx.tools.execute({ ...h.input, toolSet: await h.resolve() })).isError).toBe(false) + expect(h.calls()).toBe(1) +}) + +it('does not restore a registration removed during its asynchronous condition', async () => { + const h = await setup() + const condition = Promise.withResolvers() + const entered = Promise.withResolvers() + const unregister = h.ctx.tools.register(h.tool, { when: () => { entered.resolve(undefined); return condition.promise } }) + const pending = h.resolve() + await entered.promise + unregister() + condition.resolve(true) + const toolSet = await pending + expect(h.ctx.tools.schemas(h.agent, toolSet)).toEqual([]) + expect((await h.ctx.tools.execute({ ...h.input, toolSet })).error?.info?.code).toBe('UNKNOWN_TOOL') + expect(h.calls()).toBe(0) +}) + +it('propagates cancellation after an asynchronous condition settles', async () => { + const h = await setup() + const condition = Promise.withResolvers() + h.ctx.tools.register(h.tool, { when: ({ signal }) => { expect(signal).toBe(h.controller.signal); return condition.promise } }) + const pending = h.resolve() + const rejection = expect(pending).rejects.toMatchObject({ name: 'AbortError' }) + h.controller.abort() + condition.resolve(true) + await rejection + expect(h.calls()).toBe(0) +}) + +it('reports condition failures without treating them as disabled tools', async () => { + const h = await setup() + const cause = new Error('credential storage unavailable') + h.ctx.tools.register(h.tool, { when: () => { throw cause } }) + await expect(h.resolve()).rejects.toMatchObject({ + name: ToolActivationError.name, code: 'TOOL_ACTIVATION_FAILED', cause, + }) + expect(h.calls()).toBe(0) +}) diff --git a/packages/core/tools/tests/ptc.spec.ts b/packages/core/tools/tests/ptc.spec.ts index aa18a99f0f..a968ea0be8 100644 --- a/packages/core/tools/tests/ptc.spec.ts +++ b/packages/core/tools/tests/ptc.spec.ts @@ -169,6 +169,51 @@ it('logs detached frozen nested metadata without changing the binding value or l }) describe('mode-aware wire contribution', () => { + it('shares conditional admission with SDK bindings and rejects a replaced cached binding', async () => { + const { ctx, runtime, systemPrompt } = await setup({ mode: 'ptc' }) + try { + const agent = { session: Session.create(SessionId('conditional-ptc')) } as Agent + let active = false + const execute = vi.fn(async () => 'done') + const definition = defineTool({ + name: 'conditional', description: 'Available on selected requests.', parameters: {}, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + execute, + }) + const unregister = ctx.tools.register(definition, { when: () => active }) + for (const enabled of [false, true]) { + active = enabled + const toolSet = await ctx.tools.resolve({ agent, signal: testToolSignal }) + try { + const assembly = await systemPrompt.assemble({ scope: agent, agent, toolSet }) + const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? '' + expect(sdk.includes('conditional:')).toBe(enabled) + runtime.behavior = async (request) => { + const functions = request.bindings[0]!.functions + expect(Object.keys(functions)).toEqual(enabled ? ['conditional'] : []) + if (enabled) { + expect(await functions.conditional!({})).toBe('done') + unregister() + ctx.tools.register(definition, { when: () => true }) + await expect(functions.conditional!({})).rejects.toThrow('unknown tool "conditional"') + } + return { logs: [] } + } + const result = await ctx.tools.execute({ + agent, toolSet, signal: testToolSignal, callId: ToolCallId('conditional-program'), + name: RUN_CODE_NAME, arguments: { code: 'program', description: 'Check conditional bindings' }, + }) + expect(result.isError).toBe(false) + } finally { + toolSet.dispose() + } + } + expect(execute).toHaveBeenCalledTimes(1) + } finally { + await ctx.fiber.dispose() + } + }) + it('rejects an unsupported presentation mode in configuration', () => { expect(() => ToolRuntime.Config({ mode: 'both' } as never)).toThrow() }) @@ -267,7 +312,7 @@ describe('mode-aware wire contribution', () => { expect(sdk).toContain('deep_output: string | null') }) - it('treats expert assembly output as authoritative in mode ptc', async () => { + it('keeps PTC declarations owned by the registry during presentation transforms', async () => { const mode = 'ptc' const { ctx, systemPrompt } = await setup({ mode }) registerEcho(ctx) @@ -276,13 +321,13 @@ describe('mode-aware wire contribution', () => { return { ...assembly, sections: assembly.sections.filter(section => section.name !== 'tools:sdk'), - tools: assembly.tools.filter(tool => tool.name !== RUN_CODE_NAME), + tools: [], } }, { prepend: true }) const assembly = await systemPrompt.assemble() expect(assembly.sections.some(section => section.name === 'tools:sdk')).toBe(false) - expect(assembly.tools.some(tool => tool.name === RUN_CODE_NAME)).toBe(false) + expect(assembly.tools.some(tool => tool.name === RUN_CODE_NAME)).toBe(true) }) it('lets one scope shadow the default SDK section in mode ptc', async () => { diff --git a/packages/deliverables/tool-present/tests/present.spec.ts b/packages/deliverables/tool-present/tests/present.spec.ts index afbbf5958a..0583f21f1d 100644 --- a/packages/deliverables/tool-present/tests/present.spec.ts +++ b/packages/deliverables/tool-present/tests/present.spec.ts @@ -31,6 +31,7 @@ async function agent(ctx: Context, cwd: string | undefined): Promise { version: SESSION_FORMAT_VERSION, id, createdAt: 0, ...cwd === undefined ? {} : { cwd }, isSeeded: false, }) const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/experimental/browser-use-runtime/tests/resources.spec.ts b/packages/experimental/browser-use-runtime/tests/resources.spec.ts index f838191d44..285394c448 100644 --- a/packages/experimental/browser-use-runtime/tests/resources.spec.ts +++ b/packages/experimental/browser-use-runtime/tests/resources.spec.ts @@ -16,6 +16,7 @@ async function fixture() { const fiber = ctx.plugin(() => {}) const session = Session.create(SessionId(id)) const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, session, ctx: fiber.ctx, options: {}, status: 'idle', inbox: unsupportedInbox(), send() {}, followup() {}, inject() {}, cancel() {}, steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }), diff --git a/packages/experimental/tool-terminal/tests/loader-composition.spec.ts b/packages/experimental/tool-terminal/tests/loader-composition.spec.ts index 9d2db58481..1a624d6d04 100644 --- a/packages/experimental/tool-terminal/tests/loader-composition.spec.ts +++ b/packages/experimental/tool-terminal/tests/loader-composition.spec.ts @@ -43,6 +43,7 @@ async function agent(ctx: Context): Promise { const id = SessionId('pty-loader-agent') const session = Session.create(id) const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, diff --git a/packages/experimental/tool-terminal/tests/tools.spec.ts b/packages/experimental/tool-terminal/tests/tools.spec.ts index 8f6f3a5897..e00ba3542e 100644 --- a/packages/experimental/tool-terminal/tests/tools.spec.ts +++ b/packages/experimental/tool-terminal/tests/tools.spec.ts @@ -20,6 +20,7 @@ async function fakeAgent(ctx: Context, rawId: string): Promise { const id = SessionId(rawId) const session = Session.create(id) const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, diff --git a/packages/experimental/worktree/tests/harness.ts b/packages/experimental/worktree/tests/harness.ts index c38be4d57c..f425987975 100644 --- a/packages/experimental/worktree/tests/harness.ts +++ b/packages/experimental/worktree/tests/harness.ts @@ -42,6 +42,7 @@ export function testAgent(ctx: Context, cwd: string, name = 'worktree-test'): Ag const id = SessionId(name) const session = Session.create(id, [], { version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false, cwd }) const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, session, options: {}, status: 'idle', ctx: scope.ctx, inbox: unsupportedInbox(), send() {}, followup() {}, steer() {}, inject() {}, cancel() {}, whenIdle: async () => {}, runMaintenance: task => task(new AbortController().signal), diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index cac34cc692..c2f549d957 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1655,8 +1655,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { key: 'planMode', - summary: '`ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, the `plan:policy` section, the `/plan` command, and the stable exit tool.', - description: '`ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, the `plan:policy` section, the `/plan` command, and the stable exit tool. Client carriers expose the projection\'s cropped `{ active, pending }` view.', + summary: '`ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, the `plan:policy` section, the `/plan` command, and the conditional exit tool.', + description: '`ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, the `plan:policy` section, the `/plan` command, and the conditional exit tool. Client carriers expose the projection\'s cropped `{ active, pending }` view.', methods: [ { signature: 'get(agent: Agent): { active: boolean; pending?: boolean }', @@ -3088,16 +3088,22 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the exact Cordis effect disposer.', }, { - signature: 'refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly', - description: 'Refresh accepted registered runtime facts for request admission. Contexts added only by the assembly waterfall retain their accepted values. Current suppression removes optional contexts, and missing required registrations are restored in registry order. Sections, tools, and interpolation variables retain the accepted assembly; their providers and waterfall do not rerun.', + signature: 'refreshContext(assembly: T, context: AssembleContext = {}): T', + description: 'Refresh accepted registered runtime facts for request admission. Contexts added only by the assembly waterfall retain their accepted values. Current suppression removes optional contexts, and missing required registrations are restored in registry order. Sections, tools, and interpolation variables retain their accepted values during this refresh.', parameters: [{ name: 'assembly', description: 'accepted assembly for this scope and step.' }, { name: 'context', description: 'the same scope and current plugin-defined assembly fields.' }], returns: 'the accepted assembly with current runtime-context provider text.', }, { - signature: 'async assemble(context: AssembleContext = {}): Promise', - description: 'Assemble global and scoped providers, detach tool parameters, apply canonical ordering, then run the assembly waterfall. Scoped sections and variables shadow globals. The returned waterfall value is authoritative except that an effective complete section is restored afterwards as the sole prompt section.', - parameters: [{ name: 'context', description: 'the optional scope and plugin-defined assembly fields.' }], - returns: 'the post-waterfall assembly with any complete prompt enforced.', + signature: 'async prepare(context: AssembleContext = {}): Promise', + description: 'Prepare variables and runtime facts before accepting a step. No tool conditions or prompt sections are evaluated in this phase.', + parameters: [{ name: 'context', description: 'calling scope and request cancellation.' }], + returns: 'prepared inputs after the preparation waterfall.', + }, + { + signature: 'async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise', + description: 'Assemble prompt sections and tool declarations after request preparation. The presentation waterfall cannot replace provider-owned tools.', + parameters: [{ name: 'context', description: 'calling scope, route-bound agent, and resolved tools.' }, { name: 'preparation', description: 'accepted variables and runtime facts; prepared here when omitted.' }], + returns: 'the complete assembly with ordered tool declarations.', }, ], }, @@ -3327,9 +3333,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the exact disposer that restores the deployment default.', }, { - signature: 'register(definition: ToolDefinition): () => void', + signature: 'register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void', description: 'Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.', - parameters: [{ name: 'definition', description: 'tool schema, execution, and optional finalization/presentation callbacks.' }], + parameters: [{ name: 'definition', description: 'tool schema, execution, and optional finalization/presentation callbacks.' }, { name: 'options', description: 'optional request-time activation condition.' }], returns: 'the exact disposer that unregisters the tool.', }, { @@ -3345,15 +3351,21 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the exact disposer that unregisters the guard.', }, { - signature: 'get(name: string, scope?: ScopeKey): ToolDefinition | undefined', + signature: 'get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined', description: 'Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.', - parameters: [{ name: 'name', description: 'the tool name as registered.' }, { name: 'scope', description: 'the viewing scope (the agent); omitted = the global view.' }], + parameters: [{ name: 'name', description: 'the tool name as registered.' }, { name: 'scope', description: 'the viewing scope (the agent); omitted = the global view.' }, { name: 'toolSet', description: 'request admission; omit only to inspect registered definitions.' }], returns: 'the definition the scope resolves, or undefined when none is visible.', }, { - signature: 'schemas(scope?: ScopeKey): ToolSchema[]', + signature: 'async resolve(context: ToolActivationContext): Promise', + description: 'Resolve conditions once for this request without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.', + parameters: [{ name: 'context', description: 'agent with a bound route and request cancellation.' }], + returns: 'the complete selection; the caller disposes it after its tool batch settles.', + }, + { + signature: 'schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]', description: 'Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.', - parameters: [{ name: 'scope', description: 'the viewing scope (the agent); omitted = the global view.' }], + parameters: [{ name: 'scope', description: 'the viewing scope (the agent); omitted = the global view.' }, { name: 'toolSet', description: 'request admission, or omitted for registered-definition inspection.' }], returns: 'one deep-cloned schema per visible tool.', }, { @@ -3966,7 +3978,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ mode: 'waterfall', signature: '\'agent/request\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', summary: 'Replace the frozen call configuration.', - description: 'Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs after assembly and `step/start`, before the system prompt and accepted user batch are committed. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages.', + description: 'Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs before context preparation and `agent/pre-step`. Cancellation here or during subsequent `prepareCall()` resolution opens no step and commits no system prompt or user batch. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages.', parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, { @@ -4388,9 +4400,9 @@ export const EVENT_API: readonly EventApiEntry[] = [ { name: 'system-prompt/assemble', mode: 'waterfall', - signature: '\'system-prompt/assemble\'(this: Scoped, assembly: PromptAssembly, context: AssembleContext, next: () => Promise): Promise', - summary: 'Expert waterfall over the assembled sections, contexts, tools, and variables.', - description: 'Expert waterfall over the assembled sections, contexts, tools, and variables. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners receive only that scope\'s assemblies. The returned value is authoritative. A supplied signal controls only this explicit assembly request and must not be retained to control later turns. A registered complete section is restored after this waterfall, so listeners cannot add to or replace that scope\'s system prompt.', + signature: '\'system-prompt/assemble\'(this: Scoped, assembly: PromptPresentation, context: AssembleContext, next: () => Promise): Promise', + summary: 'Presentation waterfall over assembled sections, contexts, and variables.', + description: 'Presentation waterfall over assembled sections, contexts, and variables. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): scoped listeners receive only that scope\'s assemblies. The returned text is authoritative; tool declarations remain provider-owned. A supplied signal controls only this explicit assembly request and must not be retained to control later turns. A registered complete section is restored after this waterfall, so listeners cannot add to or replace that scope\'s system prompt.', parameters: [{ name: 'assembly', description: 'the mutable assembly built from registered providers.' }, { name: 'context', description: 'the caller\'s per-assembly context.' }], }, { @@ -4401,6 +4413,14 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Emitted when any prompt provider changes. This registry notification is unfiltered because a global change affects every scope.', parameters: [], }, + { + name: 'system-prompt/prepare', + mode: 'waterfall', + signature: '\'system-prompt/prepare\'(this: Scoped, preparation: PromptPreparation, context: AssembleContext, next: () => Promise): Promise', + summary: 'Prepare variables and runtime context before step admission.', + description: 'Prepare variables and runtime context before step admission.', + parameters: [{ name: 'preparation', description: 'registered variables and context contributions.' }, { name: 'context', description: 'calling scope and cancellation.' }], + }, { name: 'tools/change', mode: 'emit', @@ -6315,7 +6335,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'PromptAssembly', - declaration: 'export interface PromptAssembly {\n sections: AssembledSection[];\n contexts: AssembledContext[];\n tools: ToolSchema[];\n variables: Record;\n}', + declaration: 'export interface PromptAssembly extends PromptPresentation {\n tools: ToolSchema[];\n}', }, { name: 'PromptContext', @@ -6333,6 +6353,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'PromptOrigin', declaration: 'export type PromptOrigin = {\n kind: \'composer\';\n} | {\n kind: \'plugin\';\n name: string;\n};', }, + { + name: 'PromptPreparation', + declaration: 'export interface PromptPreparation {\n contexts: AssembledContext[];\n variables: Record;\n}', + }, + { + name: 'PromptPresentation', + declaration: 'export interface PromptPresentation extends PromptPreparation {\n sections: AssembledSection[];\n}', + }, { name: 'PromptSection', declaration: 'export interface PromptSection {\n readonly name: string;\n readonly order: number;\n readonly text: string | ((context: AssembleContext) => string);\n readonly interpolate?: boolean;\n readonly complete?: boolean;\n}', @@ -6521,6 +6549,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ResolvedSubagentStartRequest', declaration: 'export interface ResolvedSubagentStartRequest extends SubagentStartRequest {\n readonly cwd: string;\n}', }, + { + name: 'ResolvedToolSet', + declaration: 'export interface ResolvedToolSet {\n dispose(): void;\n view(scope: ScopeKey | undefined): ReadonlyMap;\n}', + }, { name: 'RestoredSessionOptions', declaration: 'export interface RestoredSessionOptions {\n readonly seed: SessionEvent[];\n readonly meta: SessionHeader;\n readonly inheritedEventCount: SessionLogOffset;\n readonly eventState: SessionSeedEventState;\n}', @@ -7707,7 +7739,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SystemPrompt', - declaration: 'export class SystemPrompt extends Service {\n static Config: z;\n constructor(ctx: Context, config: Config);\n section(section: PromptSection): () => void;\n getSectionOrder(name: PromptSectionOrderName): number;\n getContextOrder(name: PromptContextOrderName): number;\n context(context: PromptContext): () => void;\n suppressRuntimeContext(): () => void;\n tools(provider: (context: AssembleContext) => ToolProviderResult): () => void;\n variable(name: string, provider: (context: AssembleContext) => string | undefined): () => void;\n refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly;\n async assemble(context: AssembleContext = {}): Promise;\n}', + declaration: 'export class SystemPrompt extends Service {\n static Config: z;\n constructor(ctx: Context, config: Config);\n section(section: PromptSection): () => void;\n getSectionOrder(name: PromptSectionOrderName): number;\n getContextOrder(name: PromptContextOrderName): number;\n context(context: PromptContext): () => void;\n suppressRuntimeContext(): () => void;\n tools(provider: (context: AssembleContext) => ToolProviderResult): () => void;\n variable(name: string, provider: (context: AssembleContext) => string | undefined): () => void;\n refreshContext(assembly: T, context: AssembleContext = {}): T;\n async prepare(context: AssembleContext = {}): Promise;\n async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise;\n}', }, { name: 'SystemPromptMessageSource', @@ -7893,6 +7925,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'TokenUsage', declaration: 'export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n totalTokens?: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n}', }, + { + name: 'ToolActivationContext', + declaration: 'export interface ToolActivationContext {\n readonly agent: Agent;\n readonly signal: AbortSignal;\n}', + }, { name: 'ToolAdditionBlock', declaration: 'export interface ToolAdditionBlock {\n type: \'tool-addition\';\n toolName: string;\n tool?: never;\n}', @@ -7943,7 +7979,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolExecutionInput', - declaration: 'export interface ToolExecutionInput {\n readonly callId: ToolCallId;\n readonly rootCallId?: ToolCallId;\n readonly name: string;\n readonly schema?: ToolSchema;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n}', + declaration: 'export interface ToolExecutionInput {\n readonly callId: ToolCallId;\n readonly rootCallId?: ToolCallId;\n readonly name: string;\n readonly schema?: ToolSchema;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly toolSet?: ResolvedToolSet;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n}', }, { name: 'ToolExecutionMode', @@ -7993,6 +8029,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ToolProviderResult', declaration: 'export interface ToolProviderResult {\n readonly schemas: readonly ToolSchema[];\n readonly knownNames?: readonly string[];\n}', }, + { + name: 'ToolRegistrationOptions', + declaration: 'export interface ToolRegistrationOptions {\n readonly when?: (context: ToolActivationContext) => boolean | Promise;\n}', + }, { name: 'ToolRemovalBlock', declaration: 'export interface ToolRemovalBlock {\n type: \'tool-removal\';\n toolName: string;\n}', @@ -8019,7 +8059,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolRuntime', - declaration: 'export class ToolRuntime extends Service {\n static inject;\n static Config: z;\n readonly [TOOL_RUNTIME_SCHEDULER]: ToolRuntimeScheduler;\n constructor(ctx: Context, config: Config = {});\n presentAs(mode: ToolPresentationMode): () => void;\n register(definition: ToolDefinition): () => void;\n restrict(filter: ToolRestriction): () => void;\n guard(guard: ToolGuard): () => void;\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined;\n schemas(scope?: ScopeKey): ToolSchema[];\n executionMode(exec: ToolExecutionInput): ToolExecutionMode;\n async execute(exec: ToolExecutionInput): Promise;\n}', + declaration: 'export class ToolRuntime extends Service {\n static inject;\n static Config: z;\n readonly [TOOL_RUNTIME_SCHEDULER]: ToolRuntimeScheduler;\n constructor(ctx: Context, config: Config = {});\n presentAs(mode: ToolPresentationMode): () => void;\n register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void;\n restrict(filter: ToolRestriction): () => void;\n guard(guard: ToolGuard): () => void;\n get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined;\n async resolve(context: ToolActivationContext): Promise;\n schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[];\n executionMode(exec: ToolExecutionInput): ToolExecutionMode;\n async execute(exec: ToolExecutionInput): Promise;\n}', }, { name: 'ToolRuntimeScheduler', diff --git a/packages/feedback/command-feedback/tests/command-feedback.spec.ts b/packages/feedback/command-feedback/tests/command-feedback.spec.ts index 4e5401c09e..680a1e87f0 100644 --- a/packages/feedback/command-feedback/tests/command-feedback.spec.ts +++ b/packages/feedback/command-feedback/tests/command-feedback.spec.ts @@ -33,6 +33,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } const session = ctx.sessions.create(SessionId(id)) let status: AgentStatus = 'idle' const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/feedback/command-feedback/tests/loader-composition.spec.ts b/packages/feedback/command-feedback/tests/loader-composition.spec.ts index 273657e579..bf2090a66c 100644 --- a/packages/feedback/command-feedback/tests/loader-composition.spec.ts +++ b/packages/feedback/command-feedback/tests/loader-composition.spec.ts @@ -32,6 +32,7 @@ async function agent(ctx: Context): Promise { const session = ctx.sessions.create(id) let status: AgentStatus = 'idle' const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts index 74b8ce5dd6..8e2855bd45 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -34,6 +34,7 @@ async function agent(ctx: Context, cwd: string): Promise { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false, }) const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 1e4e65c7a1..0329d2eea1 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -25,6 +25,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } const inbox = createInboxStub() let status: AgentStatus = 'idle' const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/goal/goal/tests/goal.spec.ts b/packages/goal/goal/tests/goal.spec.ts index fe9c2d0030..9f98194d2a 100644 --- a/packages/goal/goal/tests/goal.spec.ts +++ b/packages/goal/goal/tests/goal.spec.ts @@ -54,6 +54,7 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent } const inbox = createInboxStub() const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index 227da38ad8..b2f6491192 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -39,6 +39,7 @@ interface Bench { async function liveAgent(ctx: Context, session: Session): Promise { const status: AgentStatus = 'idle' const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index ecc7822bce..65fcdc64fc 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -54,6 +54,7 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St const inbox = createInboxStub() let status: AgentStatus = 'running' const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts index 5ba9c7f544..c6af01c97b 100644 --- a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts +++ b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts @@ -80,6 +80,7 @@ async function setup(config: toolAskUser.Config = { mode: 'timed', timeout: -1 } function stubAgent(id: string, delegationDepth = 0): Agent { const agentId = SessionId(id) const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: agentId, options: {}, session: Session.create(agentId, [], { diff --git a/packages/jobs/jobs-local/tests/events.spec.ts b/packages/jobs/jobs-local/tests/events.spec.ts index 5a653569b9..89e629dd65 100644 --- a/packages/jobs/jobs-local/tests/events.spec.ts +++ b/packages/jobs/jobs-local/tests/events.spec.ts @@ -19,6 +19,7 @@ function agentIn(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { } const session = Session.create(id) return { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/jobs/jobs-local/tests/jobs.spec.ts b/packages/jobs/jobs-local/tests/jobs.spec.ts index 0c409049b9..3d24152a0f 100644 --- a/packages/jobs/jobs-local/tests/jobs.spec.ts +++ b/packages/jobs/jobs-local/tests/jobs.spec.ts @@ -35,6 +35,7 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { } const session = Session.create(id) const agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index 534d4abb49..e4c32250f2 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -39,14 +39,14 @@ en: 0acc88b042a99380 zh: e4cf66b77f2fc7ae /deepseek-ai-dsh-plan-mode/understand-the-implementation/durable-state-and-step-boundary-appends: - en: ff946ab59a7b4a0f - zh: b1c79937770f57ad + en: 6d0adadc354f211e + zh: 86fa49a9f4377368 /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-plan-command: en: a7bf35c2a9da52bc zh: dea9f4b3a41f1a6d /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-exit-tool: - en: 56798d0f45fb5775 - zh: 282e4a522ce6dae0 + en: 86b26413acb2e835 + zh: a84d876efefa5bea /deepseek-ai-dsh-plan-mode/understand-the-implementation/session-projection-unit: en: 74cd6bdf50af51f5 zh: 67609cf7202ececb @@ -90,14 +90,14 @@ en: 9622e96bdc01276d zh: 53801e68a49f3d1d /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/what-the-model-sees: - en: 3768d0189f9f13af - zh: 2168a9b24551b7c6 + en: 76ba584f0225cc7f + zh: f8b010dbc909e4ac /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/token-effect: - en: d1b1418f20ee119d - zh: c2b89ea3cae57175 + en: a1a020eb7ba26e7c + zh: a99208693d331a31 /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/kv-cache-effect: - en: 6b1404ea11f1e60d - zh: 348d0579de218652 + en: f640fc33aa30602f + zh: e0925a15d01141e9 /deepseek-ai-dsh-plan-mode/known-limitations-and-deferred-work: en: a87aabfede0087fd zh: 201e9b3766980005 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 6cbcbf2632..428c53d7f7 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -82,7 +82,7 @@ Plan mode is a product package, not a capability seam: there is no swappable bac ### Durable state and step-boundary appends -The package persists one log-only whole-value event, `plan/mode`, and the last logged value is the state. A mode change appends immediately when no turn is open; during an open turn it stays pending until the next accepted in-turn pre-step — the only append point while an agent runs — and an append failure cannot block the turn. The `set`/`get` service methods and their exact return states live in [`src/index.ts`](src/index.ts) and read the registered `plan` projection; the first dependent access fails explicitly when the registry or key is absent. +The package persists one log-only whole-value event, `plan/mode`, and the last logged value is the state. A mode change appends immediately when no turn is open; during an open turn it stays pending until the next accepted in-turn pre-step — the only append point while an agent runs — and an append failure stops step admission while retaining the pending selection. The `set`/`get` service methods and their exact return states live in [`src/index.ts`](src/index.ts) and read the registered `plan` projection; the first dependent access fails explicitly when the registry or key is absent. ### The `/plan` command @@ -90,7 +90,7 @@ The command child activates only when a commands service is composed. It maps ba ### The exit tool -`exit_plan_mode` stays registered while plan mode is inactive, so entering or leaving changes only the prompt section, never the request tool catalog. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. +`exit_plan_mode` is conditionally admitted only while the committed plan state is active. Entering or leaving changes the tool declarations and plan guidance together; Native and PTC execution use the same admitted set. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. ### Session projection unit @@ -164,15 +164,15 @@ The user block is append-only conversation growth. Entering or leaving plan mode #### What the model sees -The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) remains available in both states; execution outside plan mode fails, while an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call carrying review feedback, and a dismissed review a failed call naming the user's takeover. +The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered only in plan mode; calls outside its admitted set return `UNKNOWN_TOOL`, while an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call carrying review feedback, and a dismissed review a failed call naming the user's takeover. #### Token effect -The stable schema is paid according to ToolRuntime mode, and each plan argument and review result remains in conversation history. +The schema is paid only while active, according to ToolRuntime mode, and each plan argument and review result remains in conversation history. #### KV Cache effect -Mode transitions do not change the tool catalog; plan arguments and review results extend the conversation normally. +Mode transitions add or remove the exit tool through the route’s tool-update protocol; plan arguments and review results extend the conversation normally. ## Known Limitations and Deferred Work diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index 8ecb60b1db..40cb116121 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -82,7 +82,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 持久状态与步骤边界追加 -本包持久化一条仅记日志、整值替换的事件 `plan/mode`,最后一条已记录值即为状态。没有轮次开启时,模式变更会立即追加;轮次开启期间,它保持待生效,直到下一个被接受的轮内 pre-step——agent 运行时唯一的追加点——且追加失败不能阻塞轮次。`set`/`get` 服务方法及其确切返回状态见 [`src/index.ts`](src/index.ts),并读取已注册的 `plan` 投影;注册表或 key 缺失时,第一次依赖它们的访问会显式失败。 +本包持久化一条仅记日志、整值替换的事件 `plan/mode`,最后一条已记录值即为状态。没有打开的轮次时立即记录模式变化;轮次内则等待下一个被接纳的 pre-step。写入失败会停止步骤接纳并保留待提交选择。`set`/`get` 的精确返回状态见 [`src/index.ts`](src/index.ts);它们读取已注册的 `plan` 投影,缺少注册表或投影键时在首次依赖访问处明确失败。 ### `/plan` 命令 @@ -90,7 +90,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 退出工具 -`exit_plan_mode` 在计划模式未激活时仍保持注册,因此进入或离开只改变提示词段落,绝不改变请求的工具目录。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道,或评审等待期间服务重载,调用都会以拒绝方式失败,`/plan off` 仍是手动退路。 +`exit_plan_mode` 只在已提交的计划状态为 active 时准入。进入或离开会同时改变工具声明与计划指导;原生和 PTC 执行使用同一准入集合。批准评审后记录静默的待退出选择,由下一个被接纳的轮次内 pre-step 提交,当前工具批次的剩余调用保留计划指导。没有用户问答通道,或评审期间服务重载时,调用失败;`/plan off` 仍可手动退出。 ### 会话投影单元 @@ -164,15 +164,15 @@ You are in plan mode. Explore and design before presenting the complete plan thr #### 模型看到什么 -[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 在两种状态下均可用;在计划模式之外执行会失败,而计划模式内经批准的评审返回规范的 `{ approved: true }` 值,并渲染既有的确认文本。拒绝仍是携带评审反馈的失败调用,放弃评审则是一次指明用户接手的失败调用。 +[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 只在计划模式中提供;不在准入集合中的调用返回 `UNKNOWN_TOOL`。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是携带评审反馈的失败调用;关闭评审则报告用户接管对话。 #### Token 影响 -稳定 schema 的成本取决于 ToolRuntime 模式,每次传入的 plan 参数与评审结果都会保留在对话历史中。 +schema 仅在启用时按 ToolRuntime 模式计入开销;每份计划参数与评审结果保留在对话历史中。 #### KV Cache 影响 -模式转换不改变工具目录;plan 参数与评审结果按常规方式扩展对话。 +模式转换通过路由的工具更新协议新增或移除退出工具;计划参数与评审结果正常扩展对话。 ## 已知限制与延期工作 diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index e711607da8..a4fa5cf12e 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -8,13 +8,12 @@ * * The `plan` projection folds the session log, so resume and fork restore the * state. User selections remain pending until the next accepted in-turn - * pre-step. The service includes the selected state in the proposed step - * assembly, then appends `plan/mode` from `agent/pre-step` only when the step - * is accepted. Same-step request retries reuse their assembly. + * pre-step. The service appends `plan/mode` from `agent/pre-step` before + * request-time tool conditions and plan guidance read that committed state. + * Same-step retries do not commit pending selections. * - * The exit tool remains registered while plan mode is inactive, so entering - * or leaving plan mode changes only the prompt section, not the request tool - * catalog. + * The exit tool is admitted only for requests whose committed plan state is + * active. Native declarations, PTC bindings, and execution share that selection. * * See packages/plan/plan-mode/README.md. * @@ -60,8 +59,7 @@ declare module '@deepseek-ai/cordis' { } /** - * The model-facing exit tool's name. It stays registered while plan mode is - * inactive so the request tool catalog is stable across transitions. + * The model-facing exit tool's name, admitted only while plan mode is active. */ export const EXIT_PLAN_MODE = 'exit_plan_mode' @@ -169,7 +167,7 @@ export const planProjectionDefinition = { /** * `ctx.planMode`: owns logged plan state, applies and narrates selected state at step start, - * the `plan:policy` section, the `/plan` command, and the stable exit tool. + * the `plan:policy` section, the `/plan` command, and the conditional exit tool. * Client carriers expose the projection's cropped `{ active, pending }` view. */ export class PlanModeController extends Service { @@ -191,8 +189,8 @@ export class PlanModeController extends Service { let disposed = false // Pre-step is outside Session.append publication, so it can append the // log-only mode event inside an open turn without re-entering the session. - // A failed append remains pending for a later accepted in-turn pre-step, - // and policy cannot block the step. + // A failed append remains pending and stops admission before guidance or + // tool availability could describe an uncommitted state. ctx.on('agent/pre-step', async ( { agent, signal }, next, @@ -201,12 +199,7 @@ export class PlanModeController extends Service { const pending = this.pendingIntents.get(agent.session) if (decision.kind === 'reject' || signal.aborted || pending === undefined) return decision const narration = this.narration(agent.session, pending.active) - try { - this.onBoundary(agent.session) - } catch (error) { - ctx.logger.warn('dsh-plan-mode: failed to append selected plan mode at step start: %o', error) - return decision - } + this.onBoundary(agent.session) return !pending.narrate || narration === undefined ? decision : { ...decision, messages: [...decision.messages, narration] } @@ -218,8 +211,7 @@ export class PlanModeController extends Service { order: ctx.systemPrompt.getSectionOrder('PLAN_POLICY'), text: (context) => { if (context.agent === undefined) return '' - const pending = this.pendingIntents.get(context.agent.session) - return (pending?.active ?? this.loggedActive(context.agent.session)) ? this.section : '' + return this.loggedActive(context.agent.session) ? this.section : '' }, }) @@ -347,7 +339,7 @@ export class PlanModeController extends Service { } // Keep plan guidance for the rest of this assistant tool batch. The // silent selection is appended at the next accepted in-turn pre-step, - // before its request assembly. + // before its tool and prompt assembly. this.pendingIntents.set(agent.session, { active: false, narrate: false }) return { approved: true } }, @@ -362,7 +354,7 @@ export class PlanModeController extends Service { title: 'Plan review', content: result.content, }), - })) + }), { when: ({ agent }) => this.loggedActive(agent.session) }) } private loggedActive(session: Session): boolean { diff --git a/packages/plan/plan-mode/tests/integration.spec.ts b/packages/plan/plan-mode/tests/integration.spec.ts index b1742a1ba2..80d843c577 100644 --- a/packages/plan/plan-mode/tests/integration.spec.ts +++ b/packages/plan/plan-mode/tests/integration.spec.ts @@ -127,7 +127,7 @@ describe('plan mode through the agent loop', () => { expect(log.some(event => event.type === 'user/message' && event.data.source.kind !== 'user')).toBe(false) }) - it('a user flip between turns lands at the boundary: one notice and a replaced system node with stable tool schemas', async () => { + it('a user flip between turns lands at the boundary: one notice and an added exit tool', async () => { const adapter = new MockAdapter([ textResponse('First turn, default mode.'), textResponse('Second turn, plan mode.'), @@ -139,7 +139,7 @@ describe('plan mode through the agent loop', () => { await waitForIdle(ctx, agent) expect(planActive(ctx, agent)).toBe(false) const first = findEvent(agent.session.snapshotEvents(), 'request/header') - expect(first.data.header.tools?.map(tool => tool.name)).toEqual(['exit_plan_mode', 'read', 'write']) + expect(first.data.header.tools?.map(tool => tool.name)).toEqual(['read', 'write']) const firstSystem = findEvent(agent.session.snapshotEvents(), 'system/message') expect(systemText(agent)).not.toContain(PLAN_CONFIG.section) @@ -163,10 +163,10 @@ describe('plan mode through the agent loop', () => { expect(second?.sourceEventSeqs).toEqual([firstSystem.seq]) expect(agent.session.surface.nodes[0]).toBe(second?.seq) expect(systemText(agent)).toContain('plan mode') - expect(log.filter(event => event.type === 'request/header').map(event => event.data.reason)).toEqual(['initial', 'series']) + expect(log.filter(event => event.type === 'request/header').map(event => event.data.reason)).toEqual(['initial', 'change']) const secondHeader = findEvent(log, 'request/header', 'last') expect(secondHeader.data.header.tools?.map(tool => tool.name)).toEqual(['exit_plan_mode', 'read', 'write']) - expect(secondHeader.data.header.tools).toEqual(first.data.header.tools) + expect(secondHeader.data.header.tools).not.toEqual(first.data.header.tools) }) it('a mode flip at error settlement waits until the step after a same-step retry', async () => { @@ -204,7 +204,7 @@ describe('plan mode through the agent loop', () => { expect(adapter.requests).toHaveLength(3) expect(requestSystem(adapter.requests[2])).toContain(PLAN_CONFIG.section) - expect(adapter.requests[2]?.tools).toEqual(adapter.requests[0]?.tools) + expect(adapter.requests[2]?.tools?.map(tool => tool.name)).toEqual(['exit_plan_mode', 'read', 'write']) const log = agent.session.snapshotEvents() const planMode = findEvent(log, 'plan/mode') const firstEnd = log.find(event => event.type === 'step/end' diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index bf97cc789c..7c58740292 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -1,4 +1,6 @@ import { describe, expect, it, vi } from 'vitest' + +const testToolSignal = new AbortController().signal import { Context } from '@deepseek-ai/cordis' import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' @@ -72,8 +74,9 @@ async function agentWithSession( return agent } -function assembleFor(ctx: Context, agent: Agent) { - return ctx.systemPrompt.assemble({ agent, scope: agent }) +async function assembleFor(ctx: Context, agent: Agent) { + const toolSet = await ctx.tools.resolve({ agent, signal: testToolSignal }) + return ctx.systemPrompt.assemble({ agent, scope: agent, toolSet }) } function foldPlanMode(events: readonly SessionEvent[], end = events.length): boolean { @@ -159,7 +162,7 @@ function registerNamedTools(ctx: Context, names: string[]): void { } } -/** Assert the mapped PTC mode SDK includes the stable plan exit binding and test tools. */ +/** Assert the mapped PTC mode SDK includes the active plan exit binding and test tools. */ function expectPlanPtcSdkBindings(sdk: string): void { expect(sdk).toContain('interface ToolArgsMap {') expect(sdk).toContain('read: Record;') @@ -409,7 +412,7 @@ describe('the boundary flush', () => { }) - it('contains an append failure instead of blocking the prompt or the turn', async () => { + it('stops admission on append failure and retries the pending selection', async () => { const ctx = await setup() const warn = vi.fn() ctx.logger.warn = warn as never @@ -423,8 +426,8 @@ describe('the boundary flush', () => { if (type === 'plan/mode') throw new Error('backend gone') return (original as (...args: unknown[]) => unknown)(type, ...rest) }) as unknown) as typeof agent.session.append - await boundary(ctx, agent, 'step-start') - expect(warn).toHaveBeenCalledOnce() + await expect(boundary(ctx, agent, 'step-start')).rejects.toThrow('backend gone') + expect(warn).not.toHaveBeenCalled() // The failed flush re-parks the intent (cleared only after a landed // append), so the next healthy boundary converges the log with the // picker's optimistic state instead of dropping the switch forever. @@ -435,7 +438,7 @@ describe('the boundary flush', () => { expect(ctx.planMode.get(agent).pending).toBeUndefined() }) - it('contains a pre-step append failure and keeps the intent pending', async () => { + it('rejects a pre-step append failure and keeps the intent pending', async () => { const ctx = await setup() const warn = vi.fn() ctx.logger.warn = warn as never @@ -447,24 +450,24 @@ describe('the boundary flush', () => { if (type === 'plan/mode') throw new Error('backend gone') return (original as (...args: unknown[]) => unknown)(type, ...rest) }) as unknown) as typeof agent.session.append - await boundary(ctx, agent, 'pre-step') - expect(warn).toHaveBeenCalledOnce() + await expect(boundary(ctx, agent, 'pre-step')).rejects.toThrow('backend gone') + expect(warn).not.toHaveBeenCalled() expect(ctx.planMode.get(agent)).toEqual({ active: false, pending: true }) }) }) describe('the soft layer', () => { - it('keeps the tool schemas identical across default and plan mode', async () => { + it('adds the exit schema together with plan guidance', async () => { const ctx = await setup() registerNamedTools(ctx, ['read', 'write']) const agent = await agentWithSession(ctx) const defaultAssembly = await assembleFor(ctx, agent) - expect(defaultAssembly.tools.map(tool => tool.name)).toEqual([EXIT_PLAN_MODE, 'read', 'write']) + expect(defaultAssembly.tools.map(tool => tool.name)).toEqual(['read', 'write']) expect(defaultAssembly.sections.find(section => section.name === 'plan:policy')?.text).toBe('') agent.session.append('plan/mode', { active: true }) const planAssembly = await assembleFor(ctx, agent) - expect(planAssembly.tools).toEqual(defaultAssembly.tools) + expect(planAssembly.tools.map(tool => tool.name)).toEqual([EXIT_PLAN_MODE, 'read', 'write']) expect(planAssembly.sections.find(section => section.name === 'plan:policy')?.text).toBe(TEST_PLAN_SECTION) }) @@ -485,25 +488,15 @@ describe('the soft layer', () => { expect(assembly.sections.find(section => section.name === 'plan:policy')?.text).toBe(TEST_PLAN_SECTION) }) - it('leaves foreign assemble additions alone (no assemble-layer filtering)', async () => { - // Plan guidance does not filter the registry or later assembly additions. - const ctx = new Context() - await ctx.plugin(SystemPrompt) - await ctx.plugin(ToolRuntime) - await mountProjectionSeam(ctx) - ctx.on('system-prompt/assemble', async (_assembly, _context, next) => { - const final = await next() - final.tools = [...final.tools, { name: 'added-later', description: 'added after next()', parameters: {} }] - return final - }) - await ctx.plugin(PlanModeController, PLAN_CONFIG) - registerNamedTools(ctx, ['read']) + it('keeps independently registered tools available across plan changes', async () => { + const ctx = await setup() + registerNamedTools(ctx, ['read', 'added-later']) const planning = await agentWithSession(ctx, 'planning', { active: true }) expect((await assembleFor(ctx, planning)).tools.map(tool => tool.name)) - .toEqual(['exit_plan_mode', 'read', 'added-later']) + .toEqual(['added-later', 'exit_plan_mode', 'read']) const defaulted = await agentWithSession(ctx, 'defaulted') expect((await assembleFor(ctx, defaulted)).tools.map(tool => tool.name)) - .toEqual(['exit_plan_mode', 'read', 'added-later']) + .toEqual(['added-later', 'read']) }) it('keeps run_code the only wire tool in plan mode under the registry PTC mode; the SDK gains the exit binding', async () => { @@ -532,7 +525,7 @@ describe('the soft layer', () => { expectPlanPtcSdkBindings(sdk) }) - it('keeps the PTC mode SDK byte-identical across mode switches', async () => { + it('includes the PTC exit binding only while plan mode is active', async () => { class FakeRuntime extends PtcRuntime { resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } @@ -549,13 +542,11 @@ describe('the soft layer', () => { registerNamedTools(withPlanMode, ['read', 'write']) const agent = await agentWithSession(withPlanMode) const defaultSdk = (await assembleFor(withPlanMode, agent)).sections.find(section => section.name === 'tools:sdk')?.text ?? '' - expectPlanPtcSdkBindings(defaultSdk) + expect(defaultSdk).not.toContain('exit_plan_mode:') agent.session.append('plan/mode', { active: true }) const planSdk = (await assembleFor(withPlanMode, agent)).sections.find(section => section.name === 'tools:sdk')?.text ?? '' - expect(planSdk).toBe(defaultSdk) + expectPlanPtcSdkBindings(planSdk) - // Loading the plan-mode plugin deliberately adds one stable binding compared - // with a deployment that does not compose plan mode at all. const bare = new Context() await bare.plugin(SystemPrompt) await bare.plugin(ToolRuntime, { mode: 'ptc' }) @@ -563,7 +554,7 @@ describe('the soft layer', () => { registerNamedTools(bare, ['read', 'write']) const bareSdk = (await bare.systemPrompt.assemble({ agent })).sections.find(section => section.name === 'tools:sdk')?.text ?? '' expect(bareSdk).not.toContain('exit_plan_mode:') - expect(defaultSdk).not.toBe(bareSdk) + expect(defaultSdk).toBe(bareSdk) }) }) @@ -804,8 +795,11 @@ describe('exit_plan_mode', () => { return { ctx, agent, asked } } - function callExit(ctx: Context, agent: Agent | undefined, plan = '# The plan\n\ndo things') { + async function callExit(ctx: Context, agent: Agent | undefined, plan = '# The plan\n\ndo things') { + const signal = new AbortController().signal + const toolSet = agent === undefined ? undefined : await ctx.tools.resolve({ agent, signal }) return ctx.tools.execute({ + ...toolSet === undefined ? {} : { toolSet }, callId: ToolCallId(`call-exit-${++callCounter}`), name: EXIT_PLAN_MODE, arguments: { plan }, @@ -827,16 +821,16 @@ describe('exit_plan_mode', () => { const ctx = await setup() const result = await callExit(ctx, undefined) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode requires a calling agent (no session to switch)' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: unknown tool "exit_plan_mode"' }]) }) - it('rejects a call outside plan mode while remaining advertised', async () => { + it('omits and rejects the exit tool outside plan mode', async () => { const ctx = await setup() const agent = await agentWithSession(ctx) - expect(ctx.tools.schemas().map(tool => tool.name)).toContain(EXIT_PLAN_MODE) + expect((await assembleFor(ctx, agent)).tools.map(tool => tool.name)).not.toContain(EXIT_PLAN_MODE) const result = await callExit(ctx, agent) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: unknown tool "exit_plan_mode"' }]) }) it('rejects an empty or heading-less plan before asking the reviewer', async () => { @@ -938,6 +932,7 @@ describe('exit_plan_mode', () => { const agent = await agentWithSession(ctx, 'ptc-exit', { active: true }) const result = await ctx.tools.execute({ + toolSet: await ctx.tools.resolve({ agent, signal: testToolSignal }), callId: ToolCallId(`call-exit-${++callCounter}`), name: RUN_CODE_NAME, arguments: { code: `return await tools.${EXIT_PLAN_MODE}({ plan: ${JSON.stringify(plan)} })`, description: 'Submit the plan for review' }, @@ -960,21 +955,19 @@ describe('exit_plan_mode', () => { expect(ctx.planMode.get(agent)).toEqual({ active: true, pending: false }) }) - it('an approved exit projects the next assembly before the boundary and never removes the tool', async () => { + it('removes the exit tool and plan guidance together after the accepted boundary', async () => { const { ctx, agent } = await setupWithReview({ selected: ['Approve'] }) const approved = await callExit(ctx, agent) expect(approved.isError).toBe(false) - // Calls of the SAME assistant response were requested under the existing - // plan-shaped header. Pending state shapes only the proposed next - // assembly; the accepted boundary then commits the matching durable fold. + // Calls from the same assistant response retain the committed plan state. expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) - const assembly = await ctx.systemPrompt.assemble({ agent }) + const assembly = await assembleFor(ctx, agent) expect(assembly.tools.some(tool => tool.name === EXIT_PLAN_MODE)).toBe(true) - expect(assembly.sections.find(section => section.name === 'plan:policy')?.text).toBe('') + expect(assembly.sections.find(section => section.name === 'plan:policy')?.text).toBe(TEST_PLAN_SECTION) await boundary(ctx, agent, 'step-start') expect(foldPlanMode(agent.session.snapshotEvents())).toBe(false) - const afterExit = await ctx.systemPrompt.assemble({ agent }) - expect(afterExit.tools).toEqual(assembly.tools) + const afterExit = await assembleFor(ctx, agent) + expect(afterExit.tools.some(tool => tool.name === EXIT_PLAN_MODE)).toBe(false) expect(afterExit.sections.find(section => section.name === 'plan:policy')?.text).toBe('') }) @@ -1088,6 +1081,7 @@ describe('exit_plan_mode', () => { const { ctx, agent, asked } = await setupWithReview({ selected: ['Approve'] }) const controller = new AbortController() const result = await ctx.tools.execute({ + toolSet: await ctx.tools.resolve({ agent, signal: testToolSignal }), callId: ToolCallId(`call-exit-${++callCounter}`), name: EXIT_PLAN_MODE, arguments: { plan: '# P' }, @@ -1163,7 +1157,7 @@ describe('exit_plan_mode', () => { }) describe('HMR disposal', () => { - it('unregisters the service, listeners, prompt section, and stable exit tool with the plugin fiber', async () => { + it('unregisters the service, listeners, prompt section, and exit tool with the plugin fiber', async () => { const ctx = new Context() await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) diff --git a/packages/schedule/schedule/tests/harness.ts b/packages/schedule/schedule/tests/harness.ts index bf152ad187..f6c9794a32 100644 --- a/packages/schedule/schedule/tests/harness.ts +++ b/packages/schedule/schedule/tests/harness.ts @@ -125,6 +125,7 @@ export interface HarnessAgent extends Agent { export function agentFor(ctx: Context, id = 'original', meta?: CreateSessionOptions['meta']): HarnessAgent { const session = ctx.sessions.create(SessionId(id), meta === undefined ? undefined : { meta }) return { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, session, ctx: ctx.extend(), options: {}, status: 'idle', inbox: unsupportedInbox(), send() {}, followup: vi.fn<(message: UserMessage) => void>(), steer() {}, inject() {}, cancel() {}, whenIdle: async () => {}, runMaintenance: operation => operation(new AbortController().signal), diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index a593c37b80..cee7dbc5ed 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -18,8 +18,8 @@ en: 0cd615b8f987f950 zh: ccf4964df789011c /deepseek-ai-dsh-working-directory/understand-the-implementation: - en: f0458147d29631b1 - zh: 6a288670dd084ffb + en: 6f7b264aef175243 + zh: e2798c0aab0eb21b /deepseek-ai-dsh-working-directory/further-exploration: en: eabff683146786c8 zh: 7997dec17802ef64 @@ -39,8 +39,8 @@ en: f5a095acef81df3b zh: 758796edbc4337fc /deepseek-ai-dsh-working-directory/known-limitations-and-deferred-work: - en: a0f7bcd972f4a4fb - zh: 051ec0eb0fa92bea + en: 7f93a8dd08c52ac5 + zh: 38f35141d2e7eb6d /deepseek-ai-dsh-working-directory/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: a4b126f9a4eaca6f diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 1f54ad8c92..19f00941aa 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -39,7 +39,7 @@ Mount alongside `fs`, `sessionProjections`, and `systemPrompt`. `defaultDirector
Implementation internals — click to expand -The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. +The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. `system-prompt/prepare` validates the current directory before step admission and before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. No runtime invariant companion is published because the service reads its only directory state from the Session projection and checks filesystem validity at use. @@ -77,7 +77,7 @@ Directory transitions append context without replacing the stable system-prompt -- **Missing original project** — when the current directory and the original project are both unavailable, prompt assembly rejects every model turn, including chat-only turns. The service does not choose or recreate a repository. Restore the original directory, or use SDK `setWorkingDirectory` (`set_working_directory` in Python) or `ctx.workingDirectory.set` to select an existing absolute directory before retrying. Existing shells retain their process-local directories. +- **Missing original project** — when the current directory and the original project are both unavailable, request preparation rejects every model turn, including chat-only turns. The service does not choose or recreate a repository. Restore the original directory, or use SDK `setWorkingDirectory` (`set_working_directory` in Python) or `ctx.workingDirectory.set` to select an existing absolute directory before retrying. Existing shells retain their process-local directories. ### Dev Note diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index ad92f21b59..b656f1e835 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -39,7 +39,7 @@ kind: "package-reference"
实现细节 — 点击展开 -Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 +Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。`system-prompt/prepare` 在步骤接纳以及发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。 @@ -77,7 +77,7 @@ Session 投影拥有当前目录,并通过 Session observation 暴露它,因 -- **原始项目缺失** — 当前目录与原始项目均不可用时,提示词组装会拒绝每个模型轮次,包括纯聊天轮次。服务不会另选或重建仓库。请先恢复原始目录,或通过 SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`)或 `ctx.workingDirectory.set` 选择现有的绝对目录,再重试。已有 shell 保留各自进程的目录。 +- **原始项目缺失** — 当前目录与原始项目均不可用时,请求准备会拒绝每个模型轮次,包括纯聊天轮次。服务不会另选或重建仓库。请先恢复原始目录,或通过 SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`)或 `ctx.workingDirectory.set` 选择现有的绝对目录,再重试。已有 shell 保留各自进程的目录。 ### 开发备注 diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index 7346feb274..90156169ed 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -94,7 +94,7 @@ export class WorkingDirectoryService extends Service { interpolate: false, text: context => context.agent === undefined ? '' : this.contextText(context.agent.session), }) - ctx.on('system-prompt/assemble', async (_assembly, context, next) => { + ctx.on('system-prompt/prepare', async (_assembly, context, next) => { if (context.agent === undefined) return next() await this.ensure(context.agent, context.signal) const assembly = await next() 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 f30e87b978..d8644dbc62 100644 --- a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts @@ -45,6 +45,7 @@ async function agent(ctx: Context, cwd: string): Promise { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false, }) const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/shell/tool-bash-persistent/tests/tools.spec.ts b/packages/shell/tool-bash-persistent/tests/tools.spec.ts index d3507373c7..ab9967bfd9 100644 --- a/packages/shell/tool-bash-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/tools.spec.ts @@ -39,6 +39,7 @@ async function agent(ctx: Context, cwd: string | undefined): Promise { ...cwd === undefined ? {} : { cwd }, }) const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/shell/tool-bash/tests/background.spec.ts b/packages/shell/tool-bash/tests/background.spec.ts index 3a1fbff9bb..35e6b566ba 100644 --- a/packages/shell/tool-bash/tests/background.spec.ts +++ b/packages/shell/tool-bash/tests/background.spec.ts @@ -352,6 +352,7 @@ describe('foreground commands as jobs', () => { const ctx = await setup() const ownerId = SessionId('promote-owner') const owner: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: ownerId, options: {}, session: Session.create(ownerId, undefined, { @@ -468,6 +469,7 @@ describe('owned background output', () => { const ctx = await setup() const ownerId = SessionId('background-owner') const owner: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: ownerId, options: {}, session: Session.create(ownerId, undefined, { diff --git a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts index 90c29923a0..f48241d964 100644 --- a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts @@ -80,6 +80,7 @@ async function agent(ctx: Context, cwd: string): Promise { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false, }) const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts index b2b6d96137..6c0f41fe57 100644 --- a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts @@ -39,6 +39,7 @@ async function agent(ctx: Context, cwd: string | undefined): Promise { ...cwd === undefined ? {} : { cwd }, }) const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/shell/tool-pwsh/tests/background.spec.ts b/packages/shell/tool-pwsh/tests/background.spec.ts index 8a1d46addc..3382c91132 100644 --- a/packages/shell/tool-pwsh/tests/background.spec.ts +++ b/packages/shell/tool-pwsh/tests/background.spec.ts @@ -204,6 +204,7 @@ describe('owned background output (pwsh)', () => { const { ctx, pwsh } = await setup() const ownerId = SessionId('pwsh-background-owner') const owner: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: ownerId, options: {}, session: Session.create(ownerId, undefined, { @@ -404,6 +405,7 @@ describe('foreground commands as jobs (pwsh)', () => { const { ctx, pwsh } = await setup() const ownerId = SessionId('pwsh-promote-owner') const owner: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: ownerId, options: {}, session: Session.create(ownerId, undefined, { diff --git a/packages/skill/tool-skill/tests/tool-skill.spec.ts b/packages/skill/tool-skill/tests/tool-skill.spec.ts index e3362cda0a..21253e2cac 100644 --- a/packages/skill/tool-skill/tests/tool-skill.spec.ts +++ b/packages/skill/tool-skill/tests/tool-skill.spec.ts @@ -69,6 +69,7 @@ function agentForCwd(cwd: string): Agent { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false, }) return { + currentRoute() { throw new Error('no prepared model request in this fixture') }, ctx: new Context(), id, options: {}, @@ -87,6 +88,7 @@ function agentForCwd(cwd: string): Agent { function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent { const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: SessionId(id), options: {}, session, diff --git a/packages/subagent/subagent/tests/archive-admission.spec.ts b/packages/subagent/subagent/tests/archive-admission.spec.ts index 9e8c1b2b12..9aba8f2235 100644 --- a/packages/subagent/subagent/tests/archive-admission.spec.ts +++ b/packages/subagent/subagent/tests/archive-admission.spec.ts @@ -31,6 +31,7 @@ async function liveAgent(ctx: Context, session: Session, initial: AgentStatus): const cancels: CancelCall[] = [] let status = initial const agent: LiveAgent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/subagent/subagent/tests/external-activation-helpers.ts b/packages/subagent/subagent/tests/external-activation-helpers.ts index 389ce804d6..21f53b0e22 100644 --- a/packages/subagent/subagent/tests/external-activation-helpers.ts +++ b/packages/subagent/subagent/tests/external-activation-helpers.ts @@ -33,6 +33,7 @@ export async function externalTestParent(ctx: Context, cwd?: string): Promise { const session = ctx.sessions.create(SessionId('mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: ownerFiber.ctx, @@ -726,6 +728,7 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('pending-mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: ownerFiber.ctx, diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index e5a53123d0..0d11094467 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -40,6 +40,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { const scope = ctx.plugin(() => {}) const session = Session.create(id) const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index 11da341945..b14e47b3ab 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -24,6 +24,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { const scopeFiber = ctx.plugin(() => {}) const session = Session.create(id) const agent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/test-support/session-snapshot/tests/fixtures/dynamic-tool-updates.ts b/packages/test-support/session-snapshot/tests/fixtures/dynamic-tool-updates.ts index 5ff044af6b..f85e947ad9 100644 --- a/packages/test-support/session-snapshot/tests/fixtures/dynamic-tool-updates.ts +++ b/packages/test-support/session-snapshot/tests/fixtures/dynamic-tool-updates.ts @@ -6,24 +6,23 @@ import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' export const name = 'snapshot-dynamic-tool-updates' export const inject = ['tools'] -/** Register a tool after reading, then remove it after use without changing prompt text. */ +/** Activate a tool after reading, then disable it after use without changing prompt text. */ export function apply(ctx: Context): void { - let removeTool: (() => void) | undefined + let active = false + ctx.tools.register(defineContentToolFixture({ + name: 'snapshot_ping', description: 'Return pong once.', parameters: {}, + async execute() { return [{ type: 'text', text: 'pong' }] }, + }), { when: async () => active }) let requests = 0 ctx.on('tools/post-execute', async (exec, result, next) => { const downstream = await next() if (result.isError) return downstream switch (exec.name) { case 'read': - removeTool = ctx.tools.register(defineContentToolFixture({ - name: 'snapshot_ping', - description: 'Return pong once.', - parameters: {}, - async execute() { return [{ type: 'text', text: 'pong' }] }, - })) + active = true break case 'snapshot_ping': - removeTool?.() + active = false break } return downstream diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index 3642d8485f..11a8cdbc9e 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -34,6 +34,7 @@ async function agent(ctx: Context): Promise { const id = SessionId('todo-loader-agent') const session = Session.create(id) const value: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, followup: () => {}, steer: () => {}, inject: () => {}, send: () => {}, cancel() {}, diff --git a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts index 7c7f819072..bc39c173eb 100644 --- a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts +++ b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts @@ -457,6 +457,7 @@ describe('dsh-tool-workflow', () => { const engine = ctx.workflowEngine as StubEngine const session = Session.create(SessionId('caller')) const parent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx, send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), @@ -670,6 +671,7 @@ describe('dsh-tool-workflow', () => { await ctx.plugin(toolWorkflow, {}) const session = Session.create(SessionId('caller')) const parent: Agent = { + currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx, send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), diff --git a/scripts/fixtures/python-sdk-dynamic-tools.mjs b/scripts/fixtures/python-sdk-dynamic-tools.mjs index e21829c33d..f64930c327 100644 --- a/scripts/fixtures/python-sdk-dynamic-tools.mjs +++ b/scripts/fixtures/python-sdk-dynamic-tools.mjs @@ -1,27 +1,27 @@ -/** Add a native tool after a file read and unregister it after its first execution. */ +/** Activate a native tool after a file read and disable it after its first execution. */ export const name = 'python-sdk-dynamic-tools' export const inject = ['tools'] /** @param {import('@deepseek-ai/cordis').Context} ctx - Scenario-owned tool registry. */ export function apply(ctx) { - let removeTool + let active = false + ctx.tools.register({ + name: 'snapshot_ping', + description: 'Return pong once.', + parameters: { type: 'object', properties: {}, additionalProperties: false }, + output: { + schema: { type: 'string' }, + render(_args, value) { return [{ type: 'text', text: value }] }, + }, + async execute() { return 'pong' }, + }, { when: async ({ agent }) => active && agent.currentRoute().provider === 'deepseek-official' }) ctx.on('tools/post-execute', async (exec, result, next) => { const downstream = await next() if (result.isError) return downstream if (exec.name === 'read' && exec.arguments.file_path === 'dynamic-tool-task.txt') { - removeTool = ctx.effect(() => ctx.tools.register({ - name: 'snapshot_ping', - description: 'Return pong once.', - parameters: { type: 'object', properties: {}, additionalProperties: false }, - output: { - schema: { type: 'string' }, - render(_args, value) { return [{ type: 'text', text: value }] }, - }, - async execute() { return 'pong' }, - })) + active = true } else if (exec.name === 'snapshot_ping') { - removeTool?.() - removeTool = undefined + active = false } return downstream }) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 2c012bde12..a08fbcb5a9 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -933,7 +933,12 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { 'upgrade route registration contract is owned by packages/host/webserver/src/index.ts', JsonValue: 'JSON value union is owned by packages/core/session/src/json.ts', KnobState: 'projection unit state fields are owned by packages/interaction/permission-presets/README.md', + ToolActivationContext: 'conditional activation inputs are owned by packages/core/tools/README.md', + ToolRegistrationOptions: 'conditional registration options are owned by packages/core/tools/README.md', + ResolvedToolSet: 'request-owned admission is owned by packages/core/tools/README.md', PromptAssembly: 'assembly result is owned by packages/core/system-prompt/README.md', + PromptPreparation: 'preparation inputs are owned by packages/core/system-prompt/README.md', + PromptPresentation: 'presentation inputs are owned by packages/core/system-prompt/README.md', RequestRunId: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts', RpcReceipt: 'carrier-layer receipt is owned by packages/client/connection/src/rpc.ts', SessionForkSource: 'service-local fork input is owned by packages/core/session/src/index.ts', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index e161b0452c..8df91243ce 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1540,16 +1540,18 @@ function renderLifecycle(): string { ' Note over Agent,Driver: claim pending next-step input plus one queued prompt', ` Driver-->>SDK: ${mermaidCode('agent/inbox/spliced')} pure deletion`, ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, - ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`, + ` Driver->>Hooks: ${mermaidCode('agent/request')} waterfall`, + ' Driver->>LLM: prepareCall(config, signal), bind Agent.currentRoute()', + ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall`, ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`, ' Hooks-->>Driver: authoritative reject or enter(messages)', ' alt proposed step rejected, first batch empty, or pre-step failed', ' Driver-->>Driver: claimed batch stays removed, the open turn spends no step', ' else enter proposed step', ` Driver->>Session: ${mermaidCode('step/start')}`, - ` Driver->>Hooks: ${mermaidCode('agent/request')} waterfall`, - ' Driver->>LLM: prepareCall(config, signal)', - ' Note over Driver,LLM: cancellation during either async phase commits neither system nor users', + ' Driver->>Tools: resolve({ agent, signal })', + ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} with resolved tool set`, + ' Note over Driver,LLM: cancellation during preparation commits neither system nor users', ' Note over Driver,Session: synchronous admission using the prepared call capability', ` Driver->>Session: ${mermaidCode('system/message')} ordered per-node reconciliation`, ` Driver->>Session: ${mermaidCode('user/message')} per entered message`, @@ -1563,7 +1565,7 @@ function renderLifecycle(): string { ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`, ` Driver->>Hooks: ${mermaidCode('agent/request-error')} waterfall`, ' Hooks-->>Driver: return retry action or preserve the original error', - ' Note over Driver,LLM: retry in the open step: prepare and reconcile the same rendered assembly without repeating pre-step or users', + ' Note over Driver,LLM: retry resolves route and tools. Unchanged inputs reuse the prompt without repeating pre-step or users', ' else model request succeeded', ` Driver->>Session: ${mermaidCode('assistant/message')}`, ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`, @@ -1571,7 +1573,7 @@ function renderLifecycle(): string { ' loop barriers and bounded rolling pool, reclassify before start', ' opt call starts', ` Driver->>Session: ${mermaidCode('tool/call')}`, - ' Driver->>Tools: ordered pre, concurrent execute', + ' Driver->>Tools: ordered pre, concurrent execute with request tool set', ' Tools-->>Session: tool-owned events when applicable', ' end', ' opt next model-order result ready', @@ -1579,13 +1581,16 @@ function renderLifecycle(): string { ` Driver->>Session: ${mermaidCode('tool/result')}`, ' end', ' end', + ' Driver->>Tools: dispose request tool set', ` Driver->>Session: ${mermaidCode('step/end')}`, + ' Driver->>Driver: clear bound route', ' opt natural stop and next-step inbox empty', ` Driver->>Hooks: ${mermaidCode('agent/turn-stopping')} serial terminal checkpoint`, ' end', ' opt next-step input is pending', ' Driver-->>Driver: claim pending next-step input', ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, + ' Driver->>Driver: prepare route and runtime context for the next step', ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`, ' Hooks-->>Driver: authoritative reject or enter(messages)', ' end', @@ -1597,7 +1602,7 @@ function renderLifecycle(): string { '', 'The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes, and embeds the exact compact timed stream. Empty content stays out of derived history. A failed, retried, cancelled, or stream-error attempt that reaches settlement without a surface message records its stream as `assistant/attempt`. Live `agent/assistant-stream` chunk frames are transient; replay reads either durable settlement, and a hard process loss before settlement leaves no durable attempt stream.', '', - '`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call and reconciles the retained rendered assembly before request derivation, without repeating assembly, pre-step, or user admission.', + '`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call and resolves tool conditions before request derivation, without repeating pre-step or user admission. Prompt assembly repeats only when the bound route or tool schemas change.', '', '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.', '', diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index d79a0a3f88..2a6235b233 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -1334,6 +1334,8 @@ def smoke_sdk_dynamic_tools(base_url: str, executable: Path, update_snapshots: b dsh_bin=str(executable), dsh_home=str(dsh_home), patches=(str(patch),), env={ "DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1", + # This scenario owns tool changes independently of bundled office assets. + "DSH_PRIMARY_RUNTIME": "", "HOME": str(user_home), "USERPROFILE": str(user_home), "DSH_AGENTS_HOME": str(user_home / ".agents"), }, diff --git a/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json b/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json index 7a8a75aa85..4c56b5a792 100644 --- a/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json +++ b/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json @@ -47,7 +47,6 @@ "tools": [ "create_goal", "edit", - "exit_plan_mode", "get_goal", "glob", "grep", @@ -56,7 +55,6 @@ "job_list", "job_output", "list_agents", - "load_workspace_dependencies", "read", "read_image", "send_message", @@ -87,7 +85,7 @@ }, { "type": "request/header", - "seq": 20, + "seq": 19, "time": 0, "data": { "header": { @@ -104,7 +102,6 @@ "tools": [ "create_goal", "edit", - "exit_plan_mode", "get_goal", "glob", "grep", @@ -113,7 +110,6 @@ "job_list", "job_output", "list_agents", - "load_workspace_dependencies", "read", "read_image", "send_message", @@ -135,7 +131,7 @@ }, { "type": "developer/message", - "seq": 21, + "seq": 20, "time": 0, "data": { "turn": 1, @@ -153,13 +149,13 @@ "role": "developer", "id": "{{messageId}}" }, - "headerSeq": 20 + "headerSeq": 19 }, "surfaceOp": "append" }, { "type": "request/header", - "seq": 28, + "seq": 26, "time": 0, "data": { "header": { @@ -176,7 +172,6 @@ "tools": [ "create_goal", "edit", - "exit_plan_mode", "get_goal", "glob", "grep", @@ -185,7 +180,6 @@ "job_list", "job_output", "list_agents", - "load_workspace_dependencies", "read", "read_image", "send_message", @@ -206,7 +200,7 @@ }, { "type": "developer/message", - "seq": 29, + "seq": 27, "time": 0, "data": { "turn": 1, diff --git a/snapshots/sdk/bash-tool/tool-schemas.expected.json b/snapshots/sdk/bash-tool/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/sdk/bash-tool/tool-schemas.expected.json +++ b/snapshots/sdk/bash-tool/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/dynamic-tool-updates/notifications.expected.jsonl b/snapshots/sdk/dynamic-tool-updates/notifications.expected.jsonl index bfec6f1e36..cca4e59344 100644 --- a/snapshots/sdk/dynamic-tool-updates/notifications.expected.jsonl +++ b/snapshots/sdk/dynamic-tool-updates/notifications.expected.jsonl @@ -6,7 +6,7 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":13,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}}} @@ -14,14 +14,14 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":15,"time":0,"data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_task_read"},"toolCallId":"call_task_read","content":[{"type":"text","text":"{{cwd}}/task.txt\nfile\n\n1: Reply with the single word DONE after reading this file.\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{sessionId}}"},"meta":{"path":"{{cwd}}/task.txt","offset":1,"lines":[{"number":1,"text":"Reply with the single word DONE after reading this file."}],"totalLines":1}},"sourceEventSeqs":[14],"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":16,"time":0,"data":{"turn":1,"step":1}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":17,"time":0,"data":{"turn":1,"step":2}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":18,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":18,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"developer/message","seq":19,"time":0,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":21,"time":0,"data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":22,"time":0,"data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[21],"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":23,"time":0,"data":{"turn":1,"step":2}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":24,"time":0,"data":{"turn":1,"step":3}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":25,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":25,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"developer/message","seq":26,"time":0,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{sessionId}}"}},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":27,"time":0,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":28,"time":0,"data":{"turn":1,"step":3}}}} diff --git a/snapshots/sdk/dynamic-tool-updates/session.v4.jsonl b/snapshots/sdk/dynamic-tool-updates/session.v4.jsonl index aee79405da..03befefbea 100644 --- a/snapshots/sdk/dynamic-tool-updates/session.v4.jsonl +++ b/snapshots/sdk/dynamic-tool-updates/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1790049391235,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790049391235,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1790049391235,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1790049391235,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1790049391235,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -17,14 +17,14 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_task_read"},"toolCallId":"call_task_read","content":[{"type":"text","text":"{{cwd}}/task.txt\nfile\n\n1: Reply with the single word DONE after reading this file.\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:5}}"},"meta":{"path":"{{cwd}}/task.txt","offset":1,"lines":[{"number":1,"text":"Reply with the single word DONE after reading this file."}],"totalLines":1}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:6}}"},"headerSeq":18},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1790049391255,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790049391255,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1790049391255,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1790049391255,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[21],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:9}}"}},"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:10}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1790049391270,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1790049391270,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790049391270,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790049391270,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1790049391270,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/sdk/subagent-activation-limit/tool-schemas.1.expected.json b/snapshots/sdk/subagent-activation-limit/tool-schemas.1.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/sdk/subagent-activation-limit/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-activation-limit/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/subagent-continuable-inheritance/tool-schemas.1.expected.json b/snapshots/sdk/subagent-continuable-inheritance/tool-schemas.1.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/sdk/subagent-continuable-inheritance/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-continuable-inheritance/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/subagent-continuable/tool-schemas.1.expected.json b/snapshots/sdk/subagent-continuable/tool-schemas.1.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/sdk/subagent-continuable/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-continuable/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/subagent-dsh-sdk-diagnostic/tool-schemas.expected.json b/snapshots/sdk/subagent-dsh-sdk-diagnostic/tool-schemas.expected.json index ed6f50a025..e21bdfc94e 100644 --- a/snapshots/sdk/subagent-dsh-sdk-diagnostic/tool-schemas.expected.json +++ b/snapshots/sdk/subagent-dsh-sdk-diagnostic/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.1.expected.json b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.1.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.expected.json b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.expected.json index ce1cf8dfd5..f19dc369b8 100644 --- a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.expected.json +++ b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/subagent-list-agents/tool-schemas.1.expected.json b/snapshots/sdk/subagent-list-agents/tool-schemas.1.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/sdk/subagent-list-agents/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-list-agents/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/subagent-send-message/tool-schemas.1.expected.json b/snapshots/sdk/subagent-send-message/tool-schemas.1.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/sdk/subagent-send-message/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-send-message/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/text-turn/tool-schemas.expected.json b/snapshots/sdk/text-turn/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/sdk/text-turn/tool-schemas.expected.json +++ b/snapshots/sdk/text-turn/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/sdk/tool-error-details/notifications.expected.jsonl b/snapshots/sdk/tool-error-details/notifications.expected.jsonl index e6d6e7fde2..255a064363 100644 --- a/snapshots/sdk/tool-error-details/notifications.expected.jsonl +++ b/snapshots/sdk/tool-error-details/notifications.expected.jsonl @@ -6,7 +6,7 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Exercise a native denial and a caught PTC inner denial, then reply ERROR_DETAILS_OK."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"Exercise a native denial and","messageSeqs":[8],"source":{"kind":"fallback"}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":13,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"denied-native","name":"bash","arguments":"{\"command\":\"echo AUTO_DENIED\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"denied-native","name":"bash","args":["{\"command\":\"echo AUTO_DENIED\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"denied-native","name":"bash","arguments":"{\"command\":\"echo AUTO_DENIED\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}}} @@ -16,7 +16,7 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":17,"time":0,"data":{"turn":1,"step":2}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"system/message","seq":18,"time":0,"data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":19,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["run_code"]},"reason":"change","startsSeries":true}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"developer/message","seq":20,"time":0,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"exit_plan_mode"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":19},"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"developer/message","seq":20,"time":0,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":19},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":21,"time":0,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"denied-code","name":"run_code","args":["{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":22,"time":0,"data":{"turn":1,"step":2,"callId":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/ptc-dispatch-start","seq":23,"time":0,"data":{"rootCallId":"denied-code","parentCallId":"denied-code","subCallId":"denied-code:ptc:1","name":"bash","arguments":{"command":"echo AUTO_DENIED"}}}}} diff --git a/snapshots/sdk/tool-error-details/session.v4.jsonl b/snapshots/sdk/tool-error-details/session.v4.jsonl index 871095019b..e88e55d31a 100644 --- a/snapshots/sdk/tool-error-details/session.v4.jsonl +++ b/snapshots/sdk/tool-error-details/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Exercise a native denial and a caught PTC inner denial, then reply ERROR_DETAILS_OK."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Exercise a native denial and","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"denied-native","name":"bash","arguments":"{\"command\":\"echo AUTO_DENIED\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1791315723125,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315723125,"index":0,"dt":[],"id":"denied-native","name":"bash","args":["{\"command\":\"echo AUTO_DENIED\"}"]},{"type":"chunk","time":1791315723125,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"denied-native","name":"bash","arguments":"{\"command\":\"echo AUTO_DENIED\"}"}}},{"type":"chunk","time":1791315723125,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -19,7 +19,7 @@ {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["run_code"]},"reason":"change","startsSeries":true}} -{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"exit_plan_mode"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} +{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1791315723151,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315723151,"index":0,"dt":[],"id":"denied-code","name":"run_code","args":["{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"]},{"type":"chunk","time":1791315723151,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}}},{"type":"chunk","time":1791315723151,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"denied-code","parentCallId":"denied-code","subCallId":"denied-code:ptc:1","name":"bash","arguments":{"command":"echo AUTO_DENIED"}}} diff --git a/snapshots/sdk/tool-error-details/system-prompt.expected.md b/snapshots/sdk/tool-error-details/system-prompt.expected.md index 9070405e5b..ad38551639 100644 --- a/snapshots/sdk/tool-error-details/system-prompt.expected.md +++ b/snapshots/sdk/tool-error-details/system-prompt.expected.md @@ -122,11 +122,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -359,9 +354,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/snapshots/sdk/tool-error-details/tool-schemas.expected.json b/snapshots/sdk/tool-error-details/tool-schemas.expected.json index e150d82593..4d0a928cb7 100644 --- a/snapshots/sdk/tool-error-details/tool-schemas.expected.json +++ b/snapshots/sdk/tool-error-details/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/advanced-toolchain/session.v4.jsonl b/snapshots/session/advanced-toolchain/session.v4.jsonl index c0f1a22b8d..add1f65e1f 100644 --- a/snapshots/session/advanced-toolchain/session.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Run this advanced flow exactly once: list runtime inspect providers; discover providers through run_code when available; delegate once to a direct spawn child; run one workflow that delegates to another spawn child; list providers again; then reply with exactly ADVANCED_HEADLESS_OK."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["bash","cordis_inspect_list","cordis_inspect_query","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["bash","cordis_inspect_list","cordis_inspect_query","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Run this advanced flow exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-inspect-before","name":"cordis_inspect_list","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715021,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715022,"index":0,"dt":[],"id":"advanced-inspect-before","name":"cordis_inspect_list","args":["{}"]},{"type":"chunk","time":1791315715022,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-inspect-before","name":"cordis_inspect_list","arguments":"{}"}}},{"type":"chunk","time":1791315715022,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715022,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -19,7 +19,7 @@ {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["run_code"]},"reason":"change","startsSeries":true}} -{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"cordis_inspect_list"},{"type":"tool-removal","toolName":"cordis_inspect_query"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"exit_plan_mode"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} +{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"cordis_inspect_list"},{"type":"tool-removal","toolName":"cordis_inspect_query"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect_list({}); return inspected.providers.map(provider => provider.id);\",\"description\":\"Discover runtime APIs through PTC\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715055,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715055,"index":0,"dt":[],"id":"advanced-code","name":"run_code","args":["{\"code\":\"const inspected = await tools.cordis_inspect_list({}); return inspected.providers.map(provider => provider.id);\",\"description\":\"Discover runtime APIs through PTC\"}"]},{"type":"chunk","time":1791315715055,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect_list({}); return inspected.providers.map(provider => provider.id);\",\"description\":\"Discover runtime APIs through PTC\"}"}}},{"type":"chunk","time":1791315715055,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715055,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect_list({}); return inspected.providers.map(provider => provider.id);\",\"description\":\"Discover runtime APIs through PTC\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:ptc:1","name":"cordis_inspect_list","arguments":{}}} @@ -28,8 +28,8 @@ {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"system/message","data":{"turn":1,"step":3,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"sourceEventSeqs":[18],"surfaceOp":{"op":"replace","startSeq":18,"endSeq":18}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["bash","cordis_inspect_list","cordis_inspect_query","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} -{"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"cordis_inspect_list"},{"type":"tool-addition","toolName":"cordis_inspect_query"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"exit_plan_mode"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"},{"type":"tool-removal","toolName":"run_code"}],"role":"developer","id":"{{message:11}}"},"headerSeq":29},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["bash","cordis_inspect_list","cordis_inspect_query","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} +{"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"cordis_inspect_list"},{"type":"tool-addition","toolName":"cordis_inspect_query"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"},{"type":"tool-removal","toolName":"run_code"}],"role":"developer","id":"{{message:11}}"},"headerSeq":29},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715200,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715200,"index":0,"dt":[],"id":"advanced-direct-child","name":"subagent","args":["{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"]},{"type":"chunk","time":1791315715200,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"}}},{"type":"chunk","time":1791315715200,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715200,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"advanced-direct-child","name":"subagent","arguments":"{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"}} {"type":"subagent/catalog","data":{"version":0,"childId":"{{session:2}}","childCreatedAt":1791315715221,"mode":"continuable","label":"Check direct child"}} diff --git a/snapshots/session/advanced-toolchain/system-prompt.expected.md b/snapshots/session/advanced-toolchain/system-prompt.expected.md index cf4dcd9c3f..1f8ae75e47 100644 --- a/snapshots/session/advanced-toolchain/system-prompt.expected.md +++ b/snapshots/session/advanced-toolchain/system-prompt.expected.md @@ -135,11 +135,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -374,9 +369,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/snapshots/session/advanced-toolchain/tool-schemas.expected.json b/snapshots/session/advanced-toolchain/tool-schemas.expected.json index cb349d3ca4..c1869ed807 100644 --- a/snapshots/session/advanced-toolchain/tool-schemas.expected.json +++ b/snapshots/session/advanced-toolchain/tool-schemas.expected.json @@ -148,22 +148,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", @@ -861,22 +845,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/agent-instructions/tool-schemas.expected.json b/snapshots/session/agent-instructions/tool-schemas.expected.json index 00e71002a7..f6aebf6daf 100644 --- a/snapshots/session/agent-instructions/tool-schemas.expected.json +++ b/snapshots/session/agent-instructions/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", @@ -740,22 +724,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/background-confinement-failure/tool-schemas.expected.json b/snapshots/session/background-confinement-failure/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/background-confinement-failure/tool-schemas.expected.json +++ b/snapshots/session/background-confinement-failure/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/both-mode-turn/system-prompt.expected.md b/snapshots/session/both-mode-turn/system-prompt.expected.md index 329e451ce8..e0bdbd4e54 100644 --- a/snapshots/session/both-mode-turn/system-prompt.expected.md +++ b/snapshots/session/both-mode-turn/system-prompt.expected.md @@ -89,11 +89,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -326,9 +321,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/snapshots/session/browser-use-chrome-devtools-mcp/tool-schemas.expected.json b/snapshots/session/browser-use-chrome-devtools-mcp/tool-schemas.expected.json index cd473bea70..cc51623a5b 100644 --- a/snapshots/session/browser-use-chrome-devtools-mcp/tool-schemas.expected.json +++ b/snapshots/session/browser-use-chrome-devtools-mcp/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/browser-use-playwright-mcp/tool-schemas.expected.json b/snapshots/session/browser-use-playwright-mcp/tool-schemas.expected.json index 2d24d7c17d..43d2d085bd 100644 --- a/snapshots/session/browser-use-playwright-mcp/tool-schemas.expected.json +++ b/snapshots/session/browser-use-playwright-mcp/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/browser-use-stagehand-native/tool-schemas.expected.json b/snapshots/session/browser-use-stagehand-native/tool-schemas.expected.json index e1acbc8206..b4bd87c655 100644 --- a/snapshots/session/browser-use-stagehand-native/tool-schemas.expected.json +++ b/snapshots/session/browser-use-stagehand-native/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/claude-code-mods/tool-schemas.expected.json b/snapshots/session/claude-code-mods/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/claude-code-mods/tool-schemas.expected.json +++ b/snapshots/session/claude-code-mods/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/compaction-recovery/tool-schemas.expected.json b/snapshots/session/compaction-recovery/tool-schemas.expected.json index 00e71002a7..f6aebf6daf 100644 --- a/snapshots/session/compaction-recovery/tool-schemas.expected.json +++ b/snapshots/session/compaction-recovery/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", @@ -740,22 +724,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/computer-use-cua-driver-mcp/tool-schemas.expected.json b/snapshots/session/computer-use-cua-driver-mcp/tool-schemas.expected.json index 4b839adb31..e1d4a256e3 100644 --- a/snapshots/session/computer-use-cua-driver-mcp/tool-schemas.expected.json +++ b/snapshots/session/computer-use-cua-driver-mcp/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/computer-use-cua-driver-native/tool-schemas.expected.json b/snapshots/session/computer-use-cua-driver-native/tool-schemas.expected.json index 802ed2fe0d..078ba05d26 100644 --- a/snapshots/session/computer-use-cua-driver-native/tool-schemas.expected.json +++ b/snapshots/session/computer-use-cua-driver-native/tool-schemas.expected.json @@ -153,22 +153,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl b/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl index a165bcdee1..ac1bcf8418 100644 --- a/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl +++ b/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Inspect the exact tools service","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788778145981,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788778145981,"index":0,"dt":[],"id":"inspect-tools-api","name":"cordis_inspect_query","args":["{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"]},{"type":"chunk","time":1788778145981,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}}},{"type":"chunk","time":1788778145981,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788778145981,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"inspect-tools-api"},"toolCallId":"inspect-tools-api","content":[{"type":"text","text":"{\n \"platform\": \"host\",\n \"provider\": \"Service\",\n \"method\": \"listService\",\n \"data\": {\n \"mode\": \"service\",\n \"service\": {\n \"key\": \"tools\",\n \"description\": \"Tool registry and execution pipeline. Scoped registrations shadow globals; one visibility resolver feeds presentation, lookup, and dispatch.\",\n \"access\": {\n \"optional\": {\n \"expression\": \"ctx.get(\\\"tools\\\")\",\n \"requiresUndefinedCheck\": true\n },\n \"hardDependency\": {\n \"inject\": [\n \"tools\"\n ],\n \"expression\": \"ctx.tools\"\n }\n },\n \"methods\": [\n {\n \"signature\": \"presentAs(mode: ToolPresentationMode): () => void\",\n \"description\": \"Present the calling scope's tools in `mode` instead of the deployment default. Nearest scope on the chain wins, so a preset's standing declaration covers every agent joined under it.\\n\\nScoped only, and one declaration per scope: this is how an agent preset composes PTC mode agents beside native ones in the same process, and a process-global override would be the `mode` config field instead.\",\n \"parameters\": [\n {\n \"name\": \"mode\",\n \"description\": \"the presentation the covered agents' models see.\"\n }\n ],\n \"returns\": \"the exact disposer that restores the deployment default.\"\n },\n {\n \"signature\": \"register(definition: ToolDefinition): () => void\",\n \"description\": \"Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.\",\n \"parameters\": [\n {\n \"name\": \"definition\",\n \"description\": \"tool schema, execution, and optional finalization/presentation callbacks.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the tool.\"\n },\n {\n \"signature\": \"restrict(filter: ToolRestriction): () => void\",\n \"description\": \"Restrict global tools for the calling agent scope. Empty filters, unknown names, scope-local names, and reserved transport names fail. Restrictions intersect; scoped registrations remain visible.\",\n \"parameters\": [\n {\n \"name\": \"filter\",\n \"description\": \"global-tool mask: `allow` (keep only) and/or `deny` (remove).\"\n }\n ],\n \"returns\": \"the exact disposer that lifts this restriction.\"\n },\n {\n \"signature\": \"guard(guard: ToolGuard): () => void\",\n \"description\": \"Register a monotonic guard after the extensible `tools/pre-execute` waterfall. A plain-context guard applies globally; one registered through `agent.ctx` applies only to that agent. Any matching guard may deny by returning a reason, while no guard can force-allow a call another guard denied. The exact effect disposer is returned for ordered ownership and HMR cleanup.\",\n \"parameters\": [\n {\n \"name\": \"guard\",\n \"description\": \"synchronous check; a returned string denies the execution.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the guard.\"\n },\n {\n \"signature\": \"get(name: string, scope?: ScopeKey): ToolDefinition | undefined\",\n \"description\": \"Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.\",\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the tool name as registered.\"\n },\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n }\n ],\n \"returns\": \"the definition the scope resolves, or undefined when none is visible.\"\n },\n {\n \"signature\": \"schemas(scope?: ScopeKey): ToolSchema[]\",\n \"description\": \"Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.\",\n \"parameters\": [\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n }\n ],\n \"returns\": \"one deep-cloned schema per visible tool.\"\n },\n {\n \"signature\": \"executionMode(exec: ToolExecutionInput): ToolExecutionMode\",\n \"description\": \"Classify a pending call through the caller's visible tool definition. Only an exact `true` is parallel; unknown, hidden, undeclared, invalid, or throwing classifiers are exclusive.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"call name, parsed arguments, and optional agent scope.\"\n }\n ],\n \"returns\": \"the fail-closed scheduling mode.\"\n },\n {\n \"signature\": \"async execute(exec: ToolExecutionInput): Promise\",\n \"description\": \"Execute through pre-policy, guards, around-dispatch, post-policy, definition-owned content finalization, and final notification. Tool and listener failures resolve as materialized error results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen snapshot final observers receive. Cancellation arriving after entry and before final result materialization skips a not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a successful started outcome with `ABORTED`; already-started work is still drained and may retain a tool-owned structured error.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"the typed same-process call input. The registry assigns its correlation token before policy begins.\"\n }\n ],\n \"returns\": \"the materialized final result.\"\n }\n ]\n },\n \"referencedTypes\": [\n {\n \"name\": \"Agent\",\n \"declaration\": \"export interface Agent {\\n readonly id: SessionId;\\n}\"\n },\n {\n \"name\": \"Branded\",\n \"declaration\": \"export type Branded = string & {\\n readonly [BRAND]: B;\\n};\"\n },\n {\n \"name\": \"DiffCallView\",\n \"declaration\": \"export interface DiffCallView {\\n card: 'diff';\\n title: string;\\n diffs: FileDiff[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"DiffResultView\",\n \"declaration\": \"export interface DiffResultView {\\n card: 'diff';\\n title?: string;\\n diffs: FileDiff[];\\n}\"\n },\n {\n \"name\": \"FileDiff\",\n \"declaration\": \"export interface FileDiff {\\n path: string;\\n oldText: string | null;\\n newText: string;\\n}\"\n },\n {\n \"name\": \"FileLocation\",\n \"declaration\": \"export interface FileLocation {\\n path: string;\\n line?: number;\\n}\"\n },\n {\n \"name\": \"GenericCallView\",\n \"declaration\": \"export interface GenericCallView {\\n card: 'generic';\\n title: string;\\n kind?: ToolCallKind;\\n rawInput?: unknown;\\n content?: ContentBlock[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"GenericResultView\",\n \"declaration\": \"export interface GenericResultView {\\n card: 'generic';\\n title?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"JsonSchemaNode\",\n \"declaration\": \"export interface JsonSchemaNode {\\n type?: JsonSchemaType;\\n oneOf?: JsonSchemaNode[];\\n properties?: Record;\\n required?: string[];\\n additionalProperties?: boolean;\\n items?: JsonSchemaNode;\\n enum?: JsonSchemaScalar[];\\n const?: JsonSchemaScalar;\\n description?: string;\\n title?: string;\\n default?: JsonValue;\\n examples?: JsonValue;\\n}\"\n },\n {\n \"name\": \"JsonSchemaScalar\",\n \"declaration\": \"export type JsonSchemaScalar = string | number | boolean | null;\"\n },\n {\n \"name\": \"JsonSchemaType\",\n \"declaration\": \"export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\"\n },\n {\n \"name\": \"JsonValue\",\n \"declaration\": \"export type JsonValue = null | boolean | number | string | JsonValue[] | {\\n [key: string]: JsonValue;\\n};\"\n },\n {\n \"name\": \"ReadFileLine\",\n \"declaration\": \"export interface ReadFileLine {\\n number: number;\\n text: string;\\n}\"\n },\n {\n \"name\": \"ReadResultView\",\n \"declaration\": \"export interface ReadResultView {\\n card: 'read';\\n title?: string;\\n path: string;\\n offset: number;\\n lines: ReadFileLine[];\\n totalLines: number;\\n lang?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"ScopeKey\",\n \"declaration\": \"export type ScopeKey = object;\"\n },\n {\n \"name\": \"SearchFileMatches\",\n \"declaration\": \"export interface SearchFileMatches {\\n path: string;\\n matches: SearchLineMatch[];\\n}\"\n },\n {\n \"name\": \"SearchLineMatch\",\n \"declaration\": \"export interface SearchLineMatch {\\n lineNumber: number;\\n line: string;\\n}\"\n },\n {\n \"name\": \"SearchMatchesResultView\",\n \"declaration\": \"export interface SearchMatchesResultView {\\n card: 'search';\\n shape: 'matches';\\n title?: string;\\n files: SearchFileMatches[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchPathsResultView\",\n \"declaration\": \"export interface SearchPathsResultView {\\n card: 'search';\\n shape: 'paths';\\n title?: string;\\n paths: string[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchResultView\",\n \"declaration\": \"export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;\"\n },\n {\n \"name\": \"SessionId\",\n \"declaration\": \"export type SessionId = Branded<'SessionId'>;\"\n },\n {\n \"name\": \"TerminalCallView\",\n \"declaration\": \"export interface TerminalCallView {\\n card: 'terminal';\\n title: string;\\n description?: string;\\n cwd?: string;\\n}\"\n },\n {\n \"name\": \"TerminalResultView\",\n \"declaration\": \"export interface TerminalResultView {\\n card: 'terminal';\\n title?: string;\\n output?: string;\\n exitCode?: number;\\n signal?: string;\\n}\"\n },\n {\n \"name\": \"ToolCallId\",\n \"declaration\": \"export type ToolCallId = Branded<'ToolCallId'>;\"\n },\n {\n \"name\": \"ToolCallKind\",\n \"declaration\": \"export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\"\n },\n {\n \"name\": \"ToolCallView\",\n \"declaration\": \"export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\"\n },\n {\n \"name\": \"ToolDefinition\",\n \"declaration\": \"export interface ToolDefinition extends ToolSchema {\\n readonly output: ToolOutputDefinition;\\n execute(args: unknown, exec: ToolRunContext): Promise;\\n projectContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n timeoutMs?: number;\\n isConcurrencySafe?(args: unknown): boolean;\\n presentCall?(args: unknown): ToolCallView | undefined;\\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\\n}\"\n },\n {\n \"name\": \"ToolErrorInfo\",\n \"declaration\": \"export interface ToolErrorInfo {\\n name: string;\\n code: string;\\n reason?: string;\\n}\"\n },\n {\n \"name\": \"ToolExecution\",\n \"declaration\": \"export interface ToolExecution extends ToolExecutionInput {\\n readonly rootCallId: ToolCallId;\\n readonly token: ToolExecutionToken;\\n}\"\n },\n {\n \"name\": \"ToolExecutionFailure\",\n \"declaration\": \"export interface ToolExecutionFailure {\\n readonly isError: true;\\n readonly error: ToolFailure;\\n readonly value?: never;\\n readonly content: ContentBlock[];\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: never;\\n}\"\n },\n {\n \"name\": \"ToolExecutionInput\",\n \"declaration\": \"export interface ToolExecutionInput {\\n readonly callId: ToolCallId;\\n readonly rootCallId?: ToolCallId;\\n readonly name: string;\\n readonly schema?: ToolSchema;\\n readonly arguments: unknown;\\n readonly agent?: Agent;\\n readonly parent?: ToolExecutionToken;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolExecutionMode\",\n \"declaration\": \"export type ToolExecutionMode = {\\n kind: 'parallel';\\n} | {\\n kind: 'exclusive';\\n};\"\n },\n {\n \"name\": \"ToolExecutionResult\",\n \"declaration\": \"export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\"\n },\n {\n \"name\": \"ToolExecutionSuccess\",\n \"declaration\": \"export interface ToolExecutionSuccess {\\n readonly isError: false;\\n readonly value: JsonValue;\\n readonly content: ContentBlock[];\\n readonly error?: never;\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: true;\\n}\"\n },\n {\n \"name\": \"ToolExecutionToken\",\n \"declaration\": \"export type ToolExecutionToken = symbol & {\\n readonly [toolExecutionTokenBrand]: true;\\n};\"\n },\n {\n \"name\": \"ToolFailure\",\n \"declaration\": \"export interface ToolFailure {\\n message: string;\\n info?: ToolErrorInfo;\\n}\"\n },\n {\n \"name\": \"ToolGuard\",\n \"declaration\": \"export type ToolGuard = (execution: Readonly) => string | undefined;\"\n },\n {\n \"name\": \"ToolOutputDefinition\",\n \"declaration\": \"export interface ToolOutputDefinition {\\n readonly schema: JsonSchemaNode;\\n render(args: unknown, value: JsonValue): ContentBlock[];\\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolPresentationMode\",\n \"declaration\": \"export type ToolPresentationMode = 'native' | 'ptc';\"\n },\n {\n \"name\": \"ToolRestriction\",\n \"declaration\": \"export interface ToolRestriction {\\n readonly allow?: readonly string[];\\n readonly deny?: readonly string[];\\n}\"\n },\n {\n \"name\": \"ToolResult\",\n \"declaration\": \"export interface ToolResult {\\n content: ContentBlock[];\\n isError: boolean;\\n meta?: JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolResultView\",\n \"declaration\": \"export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | SearchResultView | ReadResultView | WebResultView;\"\n },\n {\n \"name\": \"ToolRunContext\",\n \"declaration\": \"export interface ToolRunContext extends ToolExecution {\\n deferContext(context: UserMessage): void;\\n concludeTurn(): void;\\n}\"\n },\n {\n \"name\": \"ToolSchema\",\n \"declaration\": \"export interface ToolSchema {\\n deferLoading?: true;\\n name: string;\\n description: string;\\n parameters: Record;\\n}\"\n },\n {\n \"name\": \"UserMessage\",\n \"declaration\": \"export interface UserMessage extends MessageBase {\\n readonly role: 'user';\\n}\"\n },\n {\n \"name\": \"WebFetchResultView\",\n \"declaration\": \"export interface WebFetchResultView {\\n card: 'web';\\n kind: 'fetch';\\n title?: string;\\n url: string;\\n statusCode: number;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebResultView\",\n \"declaration\": \"export type WebResultView = WebSearchResultView | WebFetchResultView;\"\n },\n {\n \"name\": \"WebSearchResultView\",\n \"declaration\": \"export interface WebSearchResultView {\\n card: 'web';\\n kind: 'search';\\n title?: string;\\n sources: WebSource[];\\n answer?: string;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebSource\",\n \"declaration\": \"export interface WebSource {\\n url: string;\\n title?: string;\\n snippet?: string;\\n publishedAt?: string;\\n}\"\n }\n ]\n }\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"inspect-tools-api"},"toolCallId":"inspect-tools-api","content":[{"type":"text","text":"{\n \"platform\": \"host\",\n \"provider\": \"Service\",\n \"method\": \"listService\",\n \"data\": {\n \"mode\": \"service\",\n \"service\": {\n \"key\": \"tools\",\n \"description\": \"Tool registry and execution pipeline. Scoped registrations shadow globals; one visibility resolver feeds presentation, lookup, and dispatch.\",\n \"access\": {\n \"optional\": {\n \"expression\": \"ctx.get(\\\"tools\\\")\",\n \"requiresUndefinedCheck\": true\n },\n \"hardDependency\": {\n \"inject\": [\n \"tools\"\n ],\n \"expression\": \"ctx.tools\"\n }\n },\n \"methods\": [\n {\n \"signature\": \"presentAs(mode: ToolPresentationMode): () => void\",\n \"description\": \"Present the calling scope's tools in `mode` instead of the deployment default. Nearest scope on the chain wins, so a preset's standing declaration covers every agent joined under it.\\n\\nScoped only, and one declaration per scope: this is how an agent preset composes PTC mode agents beside native ones in the same process, and a process-global override would be the `mode` config field instead.\",\n \"parameters\": [\n {\n \"name\": \"mode\",\n \"description\": \"the presentation the covered agents' models see.\"\n }\n ],\n \"returns\": \"the exact disposer that restores the deployment default.\"\n },\n {\n \"signature\": \"register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void\",\n \"description\": \"Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.\",\n \"parameters\": [\n {\n \"name\": \"definition\",\n \"description\": \"tool schema, execution, and optional finalization/presentation callbacks.\"\n },\n {\n \"name\": \"options\",\n \"description\": \"optional request-time activation condition.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the tool.\"\n },\n {\n \"signature\": \"restrict(filter: ToolRestriction): () => void\",\n \"description\": \"Restrict global tools for the calling agent scope. Empty filters, unknown names, scope-local names, and reserved transport names fail. Restrictions intersect; scoped registrations remain visible.\",\n \"parameters\": [\n {\n \"name\": \"filter\",\n \"description\": \"global-tool mask: `allow` (keep only) and/or `deny` (remove).\"\n }\n ],\n \"returns\": \"the exact disposer that lifts this restriction.\"\n },\n {\n \"signature\": \"guard(guard: ToolGuard): () => void\",\n \"description\": \"Register a monotonic guard after the extensible `tools/pre-execute` waterfall. A plain-context guard applies globally; one registered through `agent.ctx` applies only to that agent. Any matching guard may deny by returning a reason, while no guard can force-allow a call another guard denied. The exact effect disposer is returned for ordered ownership and HMR cleanup.\",\n \"parameters\": [\n {\n \"name\": \"guard\",\n \"description\": \"synchronous check; a returned string denies the execution.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the guard.\"\n },\n {\n \"signature\": \"get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined\",\n \"description\": \"Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.\",\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the tool name as registered.\"\n },\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"request admission; omit only to inspect registered definitions.\"\n }\n ],\n \"returns\": \"the definition the scope resolves, or undefined when none is visible.\"\n },\n {\n \"signature\": \"async resolve(context: ToolActivationContext): Promise\",\n \"description\": \"Resolve conditions once for this request without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.\",\n \"parameters\": [\n {\n \"name\": \"context\",\n \"description\": \"agent with a bound route and request cancellation.\"\n }\n ],\n \"returns\": \"the complete selection; the caller disposes it after its tool batch settles.\"\n },\n {\n \"signature\": \"schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]\",\n \"description\": \"Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.\",\n \"parameters\": [\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"request admission, or omitted for registered-definition inspection.\"\n }\n ],\n \"returns\": \"one deep-cloned schema per visible tool.\"\n },\n {\n \"signature\": \"executionMode(exec: ToolExecutionInput): ToolExecutionMode\",\n \"description\": \"Classify a pending call through the caller's visible tool definition. Only an exact `true` is parallel; unknown, hidden, undeclared, invalid, or throwing classifiers are exclusive.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"call name, parsed arguments, and optional agent scope.\"\n }\n ],\n \"returns\": \"the fail-closed scheduling mode.\"\n },\n {\n \"signature\": \"async execute(exec: ToolExecutionInput): Promise\",\n \"description\": \"Execute through pre-policy, guards, around-dispatch, post-policy, definition-owned content finalization, and final notification. Tool and listener failures resolve as materialized error results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen snapshot final observers receive. Cancellation arriving after entry and before final result materialization skips a not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a successful started outcome with `ABORTED`; already-started work is still drained and may retain a tool-owned structured error.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"the typed same-process call input. The registry assigns its correlation token before policy begins.\"\n }\n ],\n \"returns\": \"the materialized final result.\"\n }\n ]\n },\n \"referencedTypes\": [\n {\n \"name\": \"Agent\",\n \"declaration\": \"export interface Agent {\\n readonly id: SessionId;\\n}\"\n },\n {\n \"name\": \"Branded\",\n \"declaration\": \"export type Branded = string & {\\n readonly [BRAND]: B;\\n};\"\n },\n {\n \"name\": \"DiffCallView\",\n \"declaration\": \"export interface DiffCallView {\\n card: 'diff';\\n title: string;\\n diffs: FileDiff[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"DiffResultView\",\n \"declaration\": \"export interface DiffResultView {\\n card: 'diff';\\n title?: string;\\n diffs: FileDiff[];\\n}\"\n },\n {\n \"name\": \"FileDiff\",\n \"declaration\": \"export interface FileDiff {\\n path: string;\\n oldText: string | null;\\n newText: string;\\n}\"\n },\n {\n \"name\": \"FileLocation\",\n \"declaration\": \"export interface FileLocation {\\n path: string;\\n line?: number;\\n}\"\n },\n {\n \"name\": \"GenericCallView\",\n \"declaration\": \"export interface GenericCallView {\\n card: 'generic';\\n title: string;\\n kind?: ToolCallKind;\\n rawInput?: unknown;\\n content?: ContentBlock[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"GenericResultView\",\n \"declaration\": \"export interface GenericResultView {\\n card: 'generic';\\n title?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"JsonSchemaNode\",\n \"declaration\": \"export interface JsonSchemaNode {\\n type?: JsonSchemaType;\\n oneOf?: JsonSchemaNode[];\\n properties?: Record;\\n required?: string[];\\n additionalProperties?: boolean;\\n items?: JsonSchemaNode;\\n enum?: JsonSchemaScalar[];\\n const?: JsonSchemaScalar;\\n description?: string;\\n title?: string;\\n default?: JsonValue;\\n examples?: JsonValue;\\n}\"\n },\n {\n \"name\": \"JsonSchemaScalar\",\n \"declaration\": \"export type JsonSchemaScalar = string | number | boolean | null;\"\n },\n {\n \"name\": \"JsonSchemaType\",\n \"declaration\": \"export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\"\n },\n {\n \"name\": \"JsonValue\",\n \"declaration\": \"export type JsonValue = null | boolean | number | string | JsonValue[] | {\\n [key: string]: JsonValue;\\n};\"\n },\n {\n \"name\": \"ReadFileLine\",\n \"declaration\": \"export interface ReadFileLine {\\n number: number;\\n text: string;\\n}\"\n },\n {\n \"name\": \"ReadResultView\",\n \"declaration\": \"export interface ReadResultView {\\n card: 'read';\\n title?: string;\\n path: string;\\n offset: number;\\n lines: ReadFileLine[];\\n totalLines: number;\\n lang?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"ResolvedToolSet\",\n \"declaration\": \"export interface ResolvedToolSet {\\n dispose(): void;\\n view(scope: ScopeKey | undefined): ReadonlyMap;\\n}\"\n },\n {\n \"name\": \"ScopeKey\",\n \"declaration\": \"export type ScopeKey = object;\"\n },\n {\n \"name\": \"SearchFileMatches\",\n \"declaration\": \"export interface SearchFileMatches {\\n path: string;\\n matches: SearchLineMatch[];\\n}\"\n },\n {\n \"name\": \"SearchLineMatch\",\n \"declaration\": \"export interface SearchLineMatch {\\n lineNumber: number;\\n line: string;\\n}\"\n },\n {\n \"name\": \"SearchMatchesResultView\",\n \"declaration\": \"export interface SearchMatchesResultView {\\n card: 'search';\\n shape: 'matches';\\n title?: string;\\n files: SearchFileMatches[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchPathsResultView\",\n \"declaration\": \"export interface SearchPathsResultView {\\n card: 'search';\\n shape: 'paths';\\n title?: string;\\n paths: string[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchResultView\",\n \"declaration\": \"export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;\"\n },\n {\n \"name\": \"SessionId\",\n \"declaration\": \"export type SessionId = Branded<'SessionId'>;\"\n },\n {\n \"name\": \"TerminalCallView\",\n \"declaration\": \"export interface TerminalCallView {\\n card: 'terminal';\\n title: string;\\n description?: string;\\n cwd?: string;\\n}\"\n },\n {\n \"name\": \"TerminalResultView\",\n \"declaration\": \"export interface TerminalResultView {\\n card: 'terminal';\\n title?: string;\\n output?: string;\\n exitCode?: number;\\n signal?: string;\\n}\"\n },\n {\n \"name\": \"ToolActivationContext\",\n \"declaration\": \"export interface ToolActivationContext {\\n readonly agent: Agent;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolCallId\",\n \"declaration\": \"export type ToolCallId = Branded<'ToolCallId'>;\"\n },\n {\n \"name\": \"ToolCallKind\",\n \"declaration\": \"export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\"\n },\n {\n \"name\": \"ToolCallView\",\n \"declaration\": \"export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\"\n },\n {\n \"name\": \"ToolDefinition\",\n \"declaration\": \"export interface ToolDefinition extends ToolSchema {\\n readonly output: ToolOutputDefinition;\\n execute(args: unknown, exec: ToolRunContext): Promise;\\n projectContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n timeoutMs?: number;\\n isConcurrencySafe?(args: unknown): boolean;\\n presentCall?(args: unknown): ToolCallView | undefined;\\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\\n}\"\n },\n {\n \"name\": \"ToolErrorInfo\",\n \"declaration\": \"export interface ToolErrorInfo {\\n name: string;\\n code: string;\\n reason?: string;\\n}\"\n },\n {\n \"name\": \"ToolExecution\",\n \"declaration\": \"export interface ToolExecution extends ToolExecutionInput {\\n readonly rootCallId: ToolCallId;\\n readonly token: ToolExecutionToken;\\n}\"\n },\n {\n \"name\": \"ToolExecutionFailure\",\n \"declaration\": \"export interface ToolExecutionFailure {\\n readonly isError: true;\\n readonly error: ToolFailure;\\n readonly value?: never;\\n readonly content: ContentBlock[];\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: never;\\n}\"\n },\n {\n \"name\": \"ToolExecutionInput\",\n \"declaration\": \"export interface ToolExecutionInput {\\n readonly callId: ToolCallId;\\n readonly rootCallId?: ToolCallId;\\n readonly name: string;\\n readonly schema?: ToolSchema;\\n readonly arguments: unknown;\\n readonly agent?: Agent;\\n readonly toolSet?: ResolvedToolSet;\\n readonly parent?: ToolExecutionToken;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolExecutionMode\",\n \"declaration\": \"export type ToolExecutionMode = {\\n kind: 'parallel';\\n} | {\\n kind: 'exclusive';\\n};\"\n },\n {\n \"name\": \"ToolExecutionResult\",\n \"declaration\": \"export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\"\n },\n {\n \"name\": \"ToolExecutionSuccess\",\n \"declaration\": \"export interface ToolExecutionSuccess {\\n readonly isError: false;\\n readonly value: JsonValue;\\n readonly content: ContentBlock[];\\n readonly error?: never;\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: true;\\n}\"\n },\n {\n \"name\": \"ToolExecutionToken\",\n \"declaration\": \"export type ToolExecutionToken = symbol & {\\n readonly [toolExecutionTokenBrand]: true;\\n};\"\n },\n {\n \"name\": \"ToolFailure\",\n \"declaration\": \"export interface ToolFailure {\\n message: string;\\n info?: ToolErrorInfo;\\n}\"\n },\n {\n \"name\": \"ToolGuard\",\n \"declaration\": \"export type ToolGuard = (execution: Readonly) => string | undefined;\"\n },\n {\n \"name\": \"ToolOutputDefinition\",\n \"declaration\": \"export interface ToolOutputDefinition {\\n readonly schema: JsonSchemaNode;\\n render(args: unknown, value: JsonValue): ContentBlock[];\\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolPresentationMode\",\n \"declaration\": \"export type ToolPresentationMode = 'native' | 'ptc';\"\n },\n {\n \"name\": \"ToolRegistrationOptions\",\n \"declaration\": \"export interface ToolRegistrationOptions {\\n readonly when?: (context: ToolActivationContext) => boolean | Promise;\\n}\"\n },\n {\n \"name\": \"ToolRestriction\",\n \"declaration\": \"export interface ToolRestriction {\\n readonly allow?: readonly string[];\\n readonly deny?: readonly string[];\\n}\"\n },\n {\n \"name\": \"ToolResult\",\n \"declaration\": \"export interface ToolResult {\\n content: ContentBlock[];\\n isError: boolean;\\n meta?: JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolResultView\",\n \"declaration\": \"export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | SearchResultView | ReadResultView | WebResultView;\"\n },\n {\n \"name\": \"ToolRunContext\",\n \"declaration\": \"export interface ToolRunContext extends ToolExecution {\\n deferContext(context: UserMessage): void;\\n concludeTurn(): void;\\n}\"\n },\n {\n \"name\": \"ToolSchema\",\n \"declaration\": \"export interface ToolSchema {\\n deferLoading?: true;\\n name: string;\\n description: string;\\n parameters: Record;\\n}\"\n },\n {\n \"name\": \"UserMessage\",\n \"declaration\": \"export interface UserMessage extends MessageBase {\\n readonly role: 'user';\\n}\"\n },\n {\n \"name\": \"WebFetchResultView\",\n \"declaration\": \"export interface WebFetchResultView {\\n card: 'web';\\n kind: 'fetch';\\n title?: string;\\n url: string;\\n statusCode: number;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebResultView\",\n \"declaration\": \"export type WebResultView = WebSearchResultView | WebFetchResultView;\"\n },\n {\n \"name\": \"WebSearchResultView\",\n \"declaration\": \"export interface WebSearchResultView {\\n card: 'web';\\n kind: 'search';\\n title?: string;\\n sources: WebSource[];\\n answer?: string;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebSource\",\n \"declaration\": \"export interface WebSource {\\n url: string;\\n title?: string;\\n snippet?: string;\\n publishedAt?: string;\\n}\"\n }\n ]\n }\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-subprocess-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788778146017,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788778146017,"index":0,"dt":[],"id":"inspect-subprocess-api","name":"cordis_inspect_query","args":["{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"]},{"type":"chunk","time":1788778146017,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"inspect-subprocess-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"}}},{"type":"chunk","time":1788778146017,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788778146017,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/cordis-inspect-jsdoc/tool-schemas.expected.json b/snapshots/session/cordis-inspect-jsdoc/tool-schemas.expected.json index 5d880fdde7..f33d4e7c51 100644 --- a/snapshots/session/cordis-inspect-jsdoc/tool-schemas.expected.json +++ b/snapshots/session/cordis-inspect-jsdoc/tool-schemas.expected.json @@ -148,22 +148,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/deepseek-messages-system-prompt/tool-schemas.expected.json b/snapshots/session/deepseek-messages-system-prompt/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/deepseek-messages-system-prompt/tool-schemas.expected.json +++ b/snapshots/session/deepseek-messages-system-prompt/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/deepseek-protocol-system-prompt/tool-schemas.expected.json b/snapshots/session/deepseek-protocol-system-prompt/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/deepseek-protocol-system-prompt/tool-schemas.expected.json +++ b/snapshots/session/deepseek-protocol-system-prompt/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/dynamic-tool-prompt-updates/session.v4.jsonl b/snapshots/session/dynamic-tool-prompt-updates/session.v4.jsonl index cff0e5a329..7532f7f79d 100644 --- a/snapshots/session/dynamic-tool-prompt-updates/session.v4.jsonl +++ b/snapshots/session/dynamic-tool-prompt-updates/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","systemPromptUpdate":"in-history"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1790149644504,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790149644504,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1790149644504,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1790149644504,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1790149644504,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -18,14 +18,14 @@ {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1790149644534,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790149644534,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1790149644534,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1790149644535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:10}}"}},"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":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1790149644557,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1790149644557,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790149644557,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790149644557,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1790149644557,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/session/dynamic-tool-updates/session.v4.jsonl b/snapshots/session/dynamic-tool-updates/session.v4.jsonl index aee79405da..03befefbea 100644 --- a/snapshots/session/dynamic-tool-updates/session.v4.jsonl +++ b/snapshots/session/dynamic-tool-updates/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1790049391235,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790049391235,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1790049391235,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1790049391235,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1790049391235,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -17,14 +17,14 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_task_read"},"toolCallId":"call_task_read","content":[{"type":"text","text":"{{cwd}}/task.txt\nfile\n\n1: Reply with the single word DONE after reading this file.\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:5}}"},"meta":{"path":"{{cwd}}/task.txt","offset":1,"lines":[{"number":1,"text":"Reply with the single word DONE after reading this file."}],"totalLines":1}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:6}}"},"headerSeq":18},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1790049391255,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790049391255,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1790049391255,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1790049391255,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[21],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:9}}"}},"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:10}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1790049391270,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1790049391270,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790049391270,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790049391270,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1790049391270,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/session/dynamic-tool-updates/tool-schemas.expected.json b/snapshots/session/dynamic-tool-updates/tool-schemas.expected.json index 87bccafb3f..6a6b432083 100644 --- a/snapshots/session/dynamic-tool-updates/tool-schemas.expected.json +++ b/snapshots/session/dynamic-tool-updates/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", @@ -740,22 +724,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", @@ -1380,22 +1348,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/foreground-confinement-timeout/tool-schemas.expected.json b/snapshots/session/foreground-confinement-timeout/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/foreground-confinement-timeout/tool-schemas.expected.json +++ b/snapshots/session/foreground-confinement-timeout/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/fs-glob-sampling/tool-schemas.expected.json b/snapshots/session/fs-glob-sampling/tool-schemas.expected.json index 3fb3980c3b..5b4d780009 100644 --- a/snapshots/session/fs-glob-sampling/tool-schemas.expected.json +++ b/snapshots/session/fs-glob-sampling/tool-schemas.expected.json @@ -87,22 +87,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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": "glob", "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 4 paths in modification-time order; a larger result is sampled across top-level entries and reports where the complete list was saved.", diff --git a/snapshots/session/lsp-definition/tool-schemas.expected.json b/snapshots/session/lsp-definition/tool-schemas.expected.json index 76087bb96f..9b31b5eb2c 100644 --- a/snapshots/session/lsp-definition/tool-schemas.expected.json +++ b/snapshots/session/lsp-definition/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/mcp-resources-ptc/system-prompt.expected.md b/snapshots/session/mcp-resources-ptc/system-prompt.expected.md index a6b0b07911..88d3f9beac 100644 --- a/snapshots/session/mcp-resources-ptc/system-prompt.expected.md +++ b/snapshots/session/mcp-resources-ptc/system-prompt.expected.md @@ -97,11 +97,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -355,9 +350,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/snapshots/session/mcp-resources/tool-schemas.expected.json b/snapshots/session/mcp-resources/tool-schemas.expected.json index 4e5e9d557c..f47e927b07 100644 --- a/snapshots/session/mcp-resources/tool-schemas.expected.json +++ b/snapshots/session/mcp-resources/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/model-switch-notice/model-switch-driver.mjs b/snapshots/session/model-switch-notice/model-switch-driver.mjs index 508e1ec8bf..072dc673af 100644 --- a/snapshots/session/model-switch-notice/model-switch-driver.mjs +++ b/snapshots/session/model-switch-notice/model-switch-driver.mjs @@ -1,46 +1,23 @@ /** Test-only driver that selects another model after the first step's tool call. */ -import { installModelSelection } from '@deepseek-ai/dsh-agent' - const SELECTED = { provider: 'deepseek-official', model: 'deepseek-v4-pro' } -const selections = new WeakMap() +const switched = new WeakSet() export const name = 'model-switch-driver' export const inject = ['agents'] /** - * Install the real selection helper and change its input after `todo_write`. + * Change the request route after `todo_write`; headless owns the selection notice. * @param {import('@deepseek-ai/cordis').Context} ctx - composition context. */ export function apply(ctx) { - ctx.on('agent/created', ({ agent }) => { - const selection = { current: undefined, assembled: undefined } - selections.set(agent.session, selection) - installModelSelection(agent.ctx, selection) - }) ctx.on('session/event', (session, event) => { - if (event.type !== 'todo/write') return - const selection = selections.get(session) - if (selection === undefined) throw new Error('model-switch driver requires an installed selection') - selection.current = SELECTED - }) - // Headless also fixes the original selection. These root waterfalls make the - // driver authoritative; ending after step two avoids a reverse notice. - ctx.on('system-prompt/assemble', async (_assembly, context, next) => { - const assembled = await next() - if (context.agent === undefined) return assembled - const selected = selections.get(context.agent.session)?.assembled - if (selected === undefined) return assembled - return { - ...assembled, - variables: { ...assembled.variables, provider: selected.provider, model: selected.model }, - } + if (event.type === 'todo/write') switched.add(session) }) ctx.on('agent/request', async ({ agent }, next) => { const resolved = await next() - const selected = selections.get(agent.session)?.assembled - if (selected === undefined) return resolved + if (!switched.has(agent.session)) return resolved const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved - return { ...withoutInheritedEffort, ...selected } + return { ...withoutInheritedEffort, ...SELECTED } }) } diff --git a/snapshots/session/multimodal-spill-ends/tool-schemas.expected.json b/snapshots/session/multimodal-spill-ends/tool-schemas.expected.json index 637c069b74..3a003efa6c 100644 --- a/snapshots/session/multimodal-spill-ends/tool-schemas.expected.json +++ b/snapshots/session/multimodal-spill-ends/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/office-skills/tool-schemas.expected.json b/snapshots/session/office-skills/tool-schemas.expected.json index 79d6891abc..b9c653bab9 100644 --- a/snapshots/session/office-skills/tool-schemas.expected.json +++ b/snapshots/session/office-skills/tool-schemas.expected.json @@ -62,22 +62,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/persistent-pwsh-tool-turn/tool-schemas.expected.json b/snapshots/session/persistent-pwsh-tool-turn/tool-schemas.expected.json index d1b4eef213..925f644478 100644 --- a/snapshots/session/persistent-pwsh-tool-turn/tool-schemas.expected.json +++ b/snapshots/session/persistent-pwsh-tool-turn/tool-schemas.expected.json @@ -42,22 +42,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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": "glob", "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", diff --git a/snapshots/session/pi-ai-conversation-updates/session.v4.jsonl b/snapshots/session/pi-ai-conversation-updates/session.v4.jsonl index 843a75e88d..3c238c7228 100644 --- a/snapshots/session/pi-ai-conversation-updates/session.v4.jsonl +++ b/snapshots/session/pi-ai-conversation-updates/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"moonshotai","model":"kimi-k3","contextWindow":1048576,"systemPromptUpdate":"in-history"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"moonshotai","model":"kimi-k3"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1790149644504,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790149644504,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1790149644504,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1790149644504,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1790149644504,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -18,14 +18,14 @@ {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"moonshotai","model":"kimi-k3"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1790149644534,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790149644534,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1790149644534,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1790149644535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"moonshotai","model":"kimi-k3"},"id":"{{message:11}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1790149644557,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1790149644557,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790149644557,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790149644557,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1790149644557,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/session/plugin-manager-mcp/session.v4.jsonl b/snapshots/session/plugin-manager-mcp/session.v4.jsonl index 794d19b23f..af8d95fc88 100644 --- a/snapshots/session/plugin-manager-mcp/session.v4.jsonl +++ b/snapshots/session/plugin-manager-mcp/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use plugin_manager with action set_plugin, target include:demo, enabled true to activate the configured MCP entry. Then call its newly discovered mcp__demo__ping tool and report the result. Do not use other tools."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","plugin_manager","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","plugin_manager","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}} {"type":"session/title","data":{"title":"Use plugin_manager with action set_plugi","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to activate a plugin via plugin_manager, then call an MCP tool. Let me do the plugin_manager call first.\n\nNote: they say \"Do not use other tools\" other than plugin_manager and the mcp tool. But I need to first enable it. Let's call plugin_manager set_plugin.\n\nLet me also list plugins first? The instruction says use plugin_manager with action set_plugin, target include:demo, enabled true. Let's just do that."},{"type":"tool-call","id":"call_00_xLhr9wia3A5m7wuSRWwD0436","name":"plugin_manager","arguments":"{\"action\": \"set_plugin\", \"target\": \"include:demo\", \"enabled\": true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"reasoning","signature":"75d99e21-1d47-4a33-bb88-340a1e84b749"},{"type":"tool-call"}]}},"id":"{{message:4}}"},"usage":{"inputTokens":7220,"outputTokens":174,"cacheReadTokens":0,"cacheWriteTokens":0,"totalTokens":7394},"stream":[{"type":"chunk","time":1789984418848,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1789984418848,"index":0,"dt":[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,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],"texts":["The"," user"," wants"," me"," to"," activate"," a"," plugin"," via"," plugin","_manager",","," then"," call"," an"," M","CP"," tool","."," Let"," me"," do"," the"," plugin","_manager"," call"," first",".\n\n","Note",":"," they"," say"," \"","Do"," not"," use"," other"," tools","\""," other"," than"," plugin","_manager"," and"," the"," m","cp"," tool","."," But"," I"," need"," to"," first"," enable"," it","."," Let","'s"," call"," plugin","_manager"," set","_","plugin",".\n\n","Let"," me"," also"," list"," plugins"," first","?"," The"," instruction"," says"," use"," plugin","_manager"," with"," action"," set","_","plugin",","," target"," include",":","demo",","," enabled"," true","."," Let","'s"," just"," do"," that","."]},{"type":"chunk","time":1789984418849,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to activate a plugin via plugin_manager, then call an MCP tool. Let me do the plugin_manager call first.\n\nNote: they say \"Do not use other tools\" other than plugin_manager and the mcp tool. But I need to first enable it. Let's call plugin_manager set_plugin.\n\nLet me also list plugins first? The instruction says use plugin_manager with action set_plugin, target include:demo, enabled true. Let's just do that."}}},{"type":"chunk","time":1789984418849,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789984418849,"index":1,"dt":[],"id":"call_00_xLhr9wia3A5m7wuSRWwD0436","name":"plugin_manager","args":[""]},{"type":"tool-call-chunks","time0":1789984418849,"index":1,"dt":[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],"id":"call_00_xLhr9wia3A5m7wuSRWwD0436","args":["{","\"","action","\"",": ","\"","set","_","plugin","\"",", ","\"","target","\"",": ","\"","include",":","demo","\"",", ","\"","en","abled","\"",": ","true","}"]},{"type":"chunk","time":1789984418849,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_xLhr9wia3A5m7wuSRWwD0436","name":"plugin_manager","arguments":"{\"action\": \"set_plugin\", \"target\": \"include:demo\", \"enabled\": true}"}}},{"type":"chunk","time":1789984418849,"chunk":{"type":"usage","usage":{"inputTokens":7220,"outputTokens":174,"cacheReadTokens":0,"cacheWriteTokens":0,"totalTokens":7394}}},{"type":"chunk","time":1789984418849,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"reasoning","signature":"75d99e21-1d47-4a33-bb88-340a1e84b749"},{"type":"tool-call"}]}}}]},"surfaceOp":"append"} @@ -18,7 +18,7 @@ {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_mcp_resource_templates","list_mcp_resources","mcp__demo__ping","plugin_manager","read","read_image","read_mcp_resource","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_mcp_resource_templates","list_mcp_resources","mcp__demo__ping","plugin_manager","read","read_image","read_mcp_resource","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"list_mcp_resource_templates"},{"type":"tool-addition","toolName":"list_mcp_resources"},{"type":"tool-addition","toolName":"mcp__demo__ping"},{"type":"tool-addition","toolName":"read_mcp_resource"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The plugin was enabled. Now call mcp__demo__ping.\n\nWait — the tool was already listed in my tools before enabling. Let's call it anyway."},{"type":"tool-call","id":"call_00_miuKfLCTz5Cb38gdp8kK5186","name":"mcp__demo__ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"reasoning","signature":"b1ec1efe-4be6-4836-a10c-e5d6bfdce520"},{"type":"tool-call"}]}},"id":"{{message:8}}"},"usage":{"inputTokens":7035,"outputTokens":59,"cacheReadTokens":768,"cacheWriteTokens":0,"totalTokens":7862},"stream":[{"type":"chunk","time":1789984418998,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1789984418998,"index":0,"dt":[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":["The"," plugin"," was"," enabled","."," Now"," call"," m","cp","__","demo","__","ping",".\n\n","Wait"," —"," the"," tool"," was"," already"," listed"," in"," my"," tools"," before"," enabling","."," Let","'s"," call"," it"," anyway","."]},{"type":"chunk","time":1789984418998,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The plugin was enabled. Now call mcp__demo__ping.\n\nWait — the tool was already listed in my tools before enabling. Let's call it anyway."}}},{"type":"chunk","time":1789984418998,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789984418998,"index":1,"dt":[],"id":"call_00_miuKfLCTz5Cb38gdp8kK5186","name":"mcp__demo__ping","args":[""]},{"type":"tool-call-chunks","time0":1789984418998,"index":1,"dt":[],"id":"call_00_miuKfLCTz5Cb38gdp8kK5186","args":["{}"]},{"type":"chunk","time":1789984418998,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_miuKfLCTz5Cb38gdp8kK5186","name":"mcp__demo__ping","arguments":"{}"}}},{"type":"chunk","time":1789984418998,"chunk":{"type":"usage","usage":{"inputTokens":7035,"outputTokens":59,"cacheReadTokens":768,"cacheWriteTokens":0,"totalTokens":7862}}},{"type":"chunk","time":1789984418998,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"reasoning","signature":"b1ec1efe-4be6-4836-a10c-e5d6bfdce520"},{"type":"tool-call"}]}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_00_miuKfLCTz5Cb38gdp8kK5186","name":"mcp__demo__ping","arguments":"{}"}} diff --git a/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json b/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json index f44f52640a..31ec55c6a1 100644 --- a/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json +++ b/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", @@ -801,22 +785,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/plugin-manager/tool-schemas.expected.json b/snapshots/session/plugin-manager/tool-schemas.expected.json index 4596dae7a1..692d89f859 100644 --- a/snapshots/session/plugin-manager/tool-schemas.expected.json +++ b/snapshots/session/plugin-manager/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/product-subagent-both/tool-schemas.expected.json b/snapshots/session/product-subagent-both/tool-schemas.expected.json index 2b36308f92..1b05d09fe2 100644 --- a/snapshots/session/product-subagent-both/tool-schemas.expected.json +++ b/snapshots/session/product-subagent-both/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/product-subagent-codex/tool-schemas.expected.json b/snapshots/session/product-subagent-codex/tool-schemas.expected.json index d9f3cfa9d0..1c48e82c80 100644 --- a/snapshots/session/product-subagent-codex/tool-schemas.expected.json +++ b/snapshots/session/product-subagent-codex/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/product-subagent-result-diagnostic/tool-schemas.expected.json b/snapshots/session/product-subagent-result-diagnostic/tool-schemas.expected.json index 11f07197a2..da2d9314ae 100644 --- a/snapshots/session/product-subagent-result-diagnostic/tool-schemas.expected.json +++ b/snapshots/session/product-subagent-result-diagnostic/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/provider-cwd/tool-schemas.expected.json b/snapshots/session/provider-cwd/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/provider-cwd/tool-schemas.expected.json +++ b/snapshots/session/provider-cwd/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/ptc-node-read-only/system-prompt.expected.md b/snapshots/session/ptc-node-read-only/system-prompt.expected.md index 39529ce115..33387c0251 100644 --- a/snapshots/session/ptc-node-read-only/system-prompt.expected.md +++ b/snapshots/session/ptc-node-read-only/system-prompt.expected.md @@ -89,11 +89,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -330,9 +325,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/snapshots/session/ptc-node-workspace/system-prompt.expected.md b/snapshots/session/ptc-node-workspace/system-prompt.expected.md index 39529ce115..33387c0251 100644 --- a/snapshots/session/ptc-node-workspace/system-prompt.expected.md +++ b/snapshots/session/ptc-node-workspace/system-prompt.expected.md @@ -89,11 +89,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -330,9 +325,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/snapshots/session/ptc-python-turn/system-prompt.expected.md b/snapshots/session/ptc-python-turn/system-prompt.expected.md index 23dc2e1494..2f30fb8164 100644 --- a/snapshots/session/ptc-python-turn/system-prompt.expected.md +++ b/snapshots/session/ptc-python-turn/system-prompt.expected.md @@ -152,14 +152,6 @@ class EditOutput(TypedDict): before: str after: str -class ExitPlanModeArgs(TypedDict): - # The complete plan, as markdown, starting with a # heading that names it. - plan: str - # Additional keys beyond those declared are allowed. - -class ExitPlanModeOutput(TypedDict): - approved: Literal[True] - class GetGoalOutput1(TypedDict): goal: None @@ -517,8 +509,6 @@ class Tools(Protocol): """Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.""" async def edit(self, args: EditArgs) -> EditOutput: """Edit an existing UTF-8 text file by replacing literal text.""" - async def exit_plan_mode(self, args: ExitPlanModeArgs) -> ExitPlanModeOutput: - """Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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.""" async def get_goal(self, args: dict[str, Any]) -> GetGoalOutput1 | GetGoalOutput2: """Read the current session goal, including the id and revision that update_goal requires.""" async def glob(self, args: GlobArgs) -> GlobOutput: diff --git a/snapshots/session/ptc-read-image/system-prompt.expected.md b/snapshots/session/ptc-read-image/system-prompt.expected.md index f0a3c2426f..a8ac831e43 100644 --- a/snapshots/session/ptc-read-image/system-prompt.expected.md +++ b/snapshots/session/ptc-read-image/system-prompt.expected.md @@ -89,11 +89,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -326,9 +321,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/snapshots/session/ptc-turn/system-prompt.expected.md b/snapshots/session/ptc-turn/system-prompt.expected.md index 39529ce115..33387c0251 100644 --- a/snapshots/session/ptc-turn/system-prompt.expected.md +++ b/snapshots/session/ptc-turn/system-prompt.expected.md @@ -89,11 +89,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -330,9 +325,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: true; - }; get_goal: { goal: null; } | { diff --git a/snapshots/session/pty-tools-sandbox-backend/tool-schemas.expected.json b/snapshots/session/pty-tools-sandbox-backend/tool-schemas.expected.json index 95ffc0255b..bf0cb36d10 100644 --- a/snapshots/session/pty-tools-sandbox-backend/tool-schemas.expected.json +++ b/snapshots/session/pty-tools-sandbox-backend/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/ralph-loop/tool-schemas.1.expected.json b/snapshots/session/ralph-loop/tool-schemas.1.expected.json index 02ebdc4baf..404eb6dc87 100644 --- a/snapshots/session/ralph-loop/tool-schemas.1.expected.json +++ b/snapshots/session/ralph-loop/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/ralph-loop/tool-schemas.2.expected.json b/snapshots/session/ralph-loop/tool-schemas.2.expected.json index 02ebdc4baf..404eb6dc87 100644 --- a/snapshots/session/ralph-loop/tool-schemas.2.expected.json +++ b/snapshots/session/ralph-loop/tool-schemas.2.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/ralph-loop/tool-schemas.expected.json b/snapshots/session/ralph-loop/tool-schemas.expected.json index deabaf4a0d..49057f142e 100644 --- a/snapshots/session/ralph-loop/tool-schemas.expected.json +++ b/snapshots/session/ralph-loop/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/session-query-spill/tool-schemas.expected.json b/snapshots/session/session-query-spill/tool-schemas.expected.json index 9d66381297..986c2c612b 100644 --- a/snapshots/session/session-query-spill/tool-schemas.expected.json +++ b/snapshots/session/session-query-spill/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/subagent-acp-diagnostic/tool-schemas.expected.json b/snapshots/session/subagent-acp-diagnostic/tool-schemas.expected.json index 46abe32771..9b0246b8c1 100644 --- a/snapshots/session/subagent-acp-diagnostic/tool-schemas.expected.json +++ b/snapshots/session/subagent-acp-diagnostic/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/subagent-child-question-rejection/tool-schemas.expected.json b/snapshots/session/subagent-child-question-rejection/tool-schemas.expected.json index b8dc7c20a8..2d0622de05 100644 --- a/snapshots/session/subagent-child-question-rejection/tool-schemas.expected.json +++ b/snapshots/session/subagent-child-question-rejection/tool-schemas.expected.json @@ -170,22 +170,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/subagent-no-message-tool/tool-schemas.1.expected.json b/snapshots/session/subagent-no-message-tool/tool-schemas.1.expected.json index e48983205c..892f4a6d05 100644 --- a/snapshots/session/subagent-no-message-tool/tool-schemas.1.expected.json +++ b/snapshots/session/subagent-no-message-tool/tool-schemas.1.expected.json @@ -65,22 +65,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/subagent-structured-parent/tool-schemas.1.expected.json b/snapshots/session/subagent-structured-parent/tool-schemas.1.expected.json index d217c78441..fd65fad3b9 100644 --- a/snapshots/session/subagent-structured-parent/tool-schemas.1.expected.json +++ b/snapshots/session/subagent-structured-parent/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/subagent-structured-parent/tool-schemas.expected.json b/snapshots/session/subagent-structured-parent/tool-schemas.expected.json index 25793c1cd4..32e1b67539 100644 --- a/snapshots/session/subagent-structured-parent/tool-schemas.expected.json +++ b/snapshots/session/subagent-structured-parent/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/subagent-tool-filter/tool-schemas.1.expected.json b/snapshots/session/subagent-tool-filter/tool-schemas.1.expected.json index 45ab57c7c0..b7041366f4 100644 --- a/snapshots/session/subagent-tool-filter/tool-schemas.1.expected.json +++ b/snapshots/session/subagent-tool-filter/tool-schemas.1.expected.json @@ -65,22 +65,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/system-prompt-in-history/tool-schemas.expected.json b/snapshots/session/system-prompt-in-history/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/system-prompt-in-history/tool-schemas.expected.json +++ b/snapshots/session/system-prompt-in-history/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/team-targets/tool-schemas.expected.json b/snapshots/session/team-targets/tool-schemas.expected.json index 4926edb120..d33b95f8d9 100644 --- a/snapshots/session/team-targets/tool-schemas.expected.json +++ b/snapshots/session/team-targets/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/text-turn/tool-schemas.expected.json b/snapshots/session/text-turn/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/text-turn/tool-schemas.expected.json +++ b/snapshots/session/text-turn/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/web-fetch/tool-schemas.expected.json b/snapshots/session/web-fetch/tool-schemas.expected.json index 5ef902c18a..ef6c62a3fb 100644 --- a/snapshots/session/web-fetch/tool-schemas.expected.json +++ b/snapshots/session/web-fetch/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/workflow-confinement/tool-schemas.expected.json b/snapshots/session/workflow-confinement/tool-schemas.expected.json index 2b4b1f069f..1949c7d605 100644 --- a/snapshots/session/workflow-confinement/tool-schemas.expected.json +++ b/snapshots/session/workflow-confinement/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/workspace-dependencies/tool-schemas.expected.json b/snapshots/session/workspace-dependencies/tool-schemas.expected.json index 4d3db178b9..c930eafbdc 100644 --- a/snapshots/session/workspace-dependencies/tool-schemas.expected.json +++ b/snapshots/session/workspace-dependencies/tool-schemas.expected.json @@ -62,22 +62,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/worktree/tool-schemas.expected.json b/snapshots/session/worktree/tool-schemas.expected.json index 6641f8f0b2..652502f14c 100644 --- a/snapshots/session/worktree/tool-schemas.expected.json +++ b/snapshots/session/worktree/tool-schemas.expected.json @@ -124,22 +124,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", From 3ce7312b751851b1e8897554e129a05add1c1627 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 12 Oct 2026 11:09:00 +0800 Subject: [PATCH 02/36] fix(tools): align conditional activation tests and snapshots --- packages/api/session-controller/src/agent.ts | 4 ++-- .../tests/session-fork.host.spec.ts | 7 +------ .../tests/session-models.host.spec.ts | 21 ++++++++++++------- packages/core/agent-loop/src/tool-calls.ts | 4 ++-- packages/plan/plan-mode/src/index.ts | 7 ++----- .../tests/working-directory.spec.ts | 10 ++++++--- .../pwsh-tool-turn/tool-schemas.expected.json | 16 -------------- .../tool-schemas.expected.json | 16 -------------- .../system-prompt.expected.md | 8 ------- .../system-prompt.expected.md | 8 ------- .../plan-review/approved-expanded.expected.md | 1 + snapshots/web/plan-review/session.v4.jsonl | 9 ++++---- .../web/ptc-round/system-prompt.expected.md | 8 ------- 13 files changed, 33 insertions(+), 86 deletions(-) diff --git a/packages/api/session-controller/src/agent.ts b/packages/api/session-controller/src/agent.ts index 3f0fa77944..7523ea6c8d 100644 --- a/packages/api/session-controller/src/agent.ts +++ b/packages/api/session-controller/src/agent.ts @@ -276,7 +276,7 @@ export class ApiSessionAgentController { } /** - * Install or return the Session-local model selection used by prompt assembly. + * Install or return the Session-local model selection used by request preparation. * @param agent - live Agent that owns the selection. * @returns the installed mutable selection reference. */ @@ -326,7 +326,7 @@ export class ApiSessionAgentController { } /** - * Commit and cache one validated selection for the next prompt assembly. + * Commit and cache one validated selection for the next step's request preparation. * @param agent - live Agent that owns the selection. * @param selection - validated selection to record and apply. */ diff --git a/packages/api/session-controller/tests/session-fork.host.spec.ts b/packages/api/session-controller/tests/session-fork.host.spec.ts index e6ba8321ce..d94b156d1d 100644 --- a/packages/api/session-controller/tests/session-fork.host.spec.ts +++ b/packages/api/session-controller/tests/session-fork.host.spec.ts @@ -662,14 +662,9 @@ describe('sessions.fork', () => { const child = ctx.agents.get(response.value.sessionId) if (child === undefined) throw new Error('fork did not publish the child agent') expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount)).toEqual(inherited) - const assembly = await child.ctx.systemPrompt.assemble() - expect(assembly.variables).toMatchObject({ - provider: 'inherited-provider', - model: 'inherited-model', - }) const fallback: LlmCallConfig = { provider: 'default-provider', model: 'default-model' } await expect(agentEvents(child.ctx, child).waterfall( - 'agent/request', { turn: 1, step: 0, signal: new AbortController().signal }, () => Promise.resolve(fallback), + 'agent/request', { turn: 1, step: 1, signal: new AbortController().signal }, () => Promise.resolve(fallback), )).resolves.toMatchObject({ provider: 'inherited-provider', model: 'inherited-model', 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 e852460e93..3ebc903a03 100644 --- a/packages/api/session-controller/tests/session-models.host.spec.ts +++ b/packages/api/session-controller/tests/session-models.host.spec.ts @@ -1,7 +1,7 @@ /** * Session Controller model-directory and selection behavior: dynamic provider grouping, * provider-local catalog failures, logged-selection restoration without stale - * catalog injection, unavailable-model refusals, and the prompt-assembly + * catalog injection, unavailable-model refusals, and the request-preparation * boundary for a running selection change. */ @@ -486,7 +486,7 @@ describe('Web session model selection', () => { await ctx.fiber.dispose() }) - it('rejects unlisted models and switches available models only after the next assembly', async () => { + it('rejects unlisted models and applies a selection when the next step prepares its request', async () => { const { ctx, agent, sessionId } = await harness() const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' }) const seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 } @@ -494,6 +494,14 @@ describe('Web session model selection', () => { expect(currentSelection(ctx, sessionId)) .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' }) + expectValue(await remote.selectModel(request({ + sessionId, + provider: 'deepseek-official', + model: 'deepseek-chat', + }))) + await expect(agentEvents(ctx, agent).waterfall( + 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve(seed), + )).resolves.toEqual({ ...seed, provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' }) const selected = expectValue(await remote.selectModel(request({ sessionId, @@ -506,14 +514,11 @@ describe('Web session model selection', () => { model: 'deepseek-reasoner', reasoningEffort: 'max', }) - await expect(agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 1, step: 0, signal }, () => Promise.resolve(seed), - )).resolves.toEqual(seed) - - expect((await ctx.systemPrompt.assemble()).variables) - .toMatchObject({ provider: 'deepseek-official', model: 'deepseek-reasoner' }) await expect(agentEvents(ctx, agent).waterfall( 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve(seed), + )).resolves.toEqual({ ...seed, provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' }) + await expect(agentEvents(ctx, agent).waterfall( + 'agent/request', { turn: 1, step: 2, signal }, () => Promise.resolve(seed), )).resolves.toMatchObject({ provider: 'deepseek-official', model: 'deepseek-reasoner', diff --git a/packages/core/agent-loop/src/tool-calls.ts b/packages/core/agent-loop/src/tool-calls.ts index 7424a57931..72bbc08f8e 100644 --- a/packages/core/agent-loop/src/tool-calls.ts +++ b/packages/core/agent-loop/src/tool-calls.ts @@ -66,7 +66,7 @@ export async function executeToolCalls( toolCalls: ToolCallBlock[], signal: AbortSignal, acceptContext: (context: UserMessage) => void, - toolSet?: ResolvedToolSet, + toolSet: ResolvedToolSet, ): Promise<{ concluded: boolean }> { const agent = ctx.agents.requireInitiator() const { session } = agent @@ -80,7 +80,7 @@ export async function executeToolCalls( arguments: parseArguments(block.arguments), agent, signal, - ...toolSet === undefined ? {} : { toolSet }, + toolSet, }, })) diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index a1bd146af5..05df478183 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -288,11 +288,8 @@ export class PlanModeController extends Service { }], }, execute: async (args, exec) => { - const agent = exec.agent - if (agent === undefined) throw new Error(`${EXIT_PLAN_MODE} requires a calling agent (no session to switch)`) - if (!this.loggedActive(agent.session)) { - throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`) - } + // oxlint-disable-next-line typescript/no-non-null-assertion -- conditional admission requires a Plan-mode Agent + const agent = exec.agent! if (!/^#\s+\S/.test(args.plan.trim())) { throw new Error(`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`) } diff --git a/packages/session/working-directory/tests/working-directory.spec.ts b/packages/session/working-directory/tests/working-directory.spec.ts index dbd6775312..a3fd4281b5 100644 --- a/packages/session/working-directory/tests/working-directory.spec.ts +++ b/packages/session/working-directory/tests/working-directory.spec.ts @@ -9,7 +9,7 @@ import WorkingDirectory, { type Config as WorkingDirectoryConfig } from '@deepse import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' import { SessionId } from '@deepseek-ai/dsh-session' import { ToolCallId } from '@deepseek-ai/dsh-llm' -import { renderContextSnapshot, renderPrompt } from '@deepseek-ai/dsh-system-prompt' +import { renderContextSnapshot, renderPrompt, type AssembleContext, type PromptPreparation } from '@deepseek-ai/dsh-system-prompt' import * as WorkingDirectoryTool from '@deepseek-ai/dsh-tool-working-directory' async function fixture(config?: (root: string) => WorkingDirectoryConfig) { @@ -177,9 +177,13 @@ describe('Session working directories', () => { })]) }) - it.each(['remove', 'replace'] as const)('retains required current-directory context after an assembly transform can %s it', async (change) => { + it.each((['system-prompt/prepare', 'system-prompt/assemble'] as const).flatMap(event => + (['remove', 'replace'] as const).map(change => ({ event, change })), + ))('retains required current-directory context after $event can $change it', async ({ event, change }) => { await using f = await fixture() - f.ctx.on('system-prompt/assemble', async (_assembly, _context, next) => { + f.ctx.on(event, async ( + _assembly: Assembly, _context: AssembleContext, next: () => Promise, + ) => { const assembled = await next() return { ...assembled, diff --git a/snapshots/session/pwsh-tool-turn/tool-schemas.expected.json b/snapshots/session/pwsh-tool-turn/tool-schemas.expected.json index d1a1729417..95be0857e0 100644 --- a/snapshots/session/pwsh-tool-turn/tool-schemas.expected.json +++ b/snapshots/session/pwsh-tool-turn/tool-schemas.expected.json @@ -42,22 +42,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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": "glob", "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", diff --git a/snapshots/web/fresh-round-trip/tool-schemas.expected.json b/snapshots/web/fresh-round-trip/tool-schemas.expected.json index 557f8adc57..dbd2640bc1 100644 --- a/snapshots/web/fresh-round-trip/tool-schemas.expected.json +++ b/snapshots/web/fresh-round-trip/tool-schemas.expected.json @@ -170,22 +170,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/web/official-subagent-bundle/system-prompt.expected.md b/snapshots/web/official-subagent-bundle/system-prompt.expected.md index 9e8e56f62b..c390edc00a 100644 --- a/snapshots/web/official-subagent-bundle/system-prompt.expected.md +++ b/snapshots/web/official-subagent-bundle/system-prompt.expected.md @@ -107,11 +107,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -428,9 +423,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: boolean; - }; get_goal: { goal: null; } | { diff --git a/snapshots/web/optional-string-editor/system-prompt.expected.md b/snapshots/web/optional-string-editor/system-prompt.expected.md index f5e4347e82..b60fdcee95 100644 --- a/snapshots/web/optional-string-editor/system-prompt.expected.md +++ b/snapshots/web/optional-string-editor/system-prompt.expected.md @@ -107,11 +107,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -436,9 +431,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: boolean; - }; get_goal: { goal: null; } | { diff --git a/snapshots/web/plan-review/approved-expanded.expected.md b/snapshots/web/plan-review/approved-expanded.expected.md index a9ab6bccfa..02642606ac 100644 --- a/snapshots/web/plan-review/approved-expanded.expected.md +++ b/snapshots/web/plan-review/approved-expanded.expected.md @@ -17,6 +17,7 @@ - text: . - button "Called tools" [expanded] - 'button "Tool call exit_plan_mode · # Add `--greeting` flag to CLI"' +- text: "Tool removed: exit_plan_mode" - '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."' - paragraph: DONE - 'button "Open plan: Add `--greeting` flag to CLI"': "Add `--greeting` flag to CLI Plan · Markdown Open" diff --git a/snapshots/web/plan-review/session.v4.jsonl b/snapshots/web/plan-review/session.v4.jsonl index ce244393f1..005952c2da 100644 --- a/snapshots/web/plan-review/session.v4.jsonl +++ b/snapshots/web/plan-review/session.v4.jsonl @@ -13,17 +13,18 @@ {"type":"user/message","data":{"content":[{"type":"text","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."}],"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","present","read","read_image","schedule_create","schedule_delete","schedule_list","schedule_update","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Plan a small change: add","messageSeqs":[11],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."},{"type":"text","text":"Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with `exit_plan_mode`."},{"type":"tool-call","id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":4529,"outputTokens":303,"cacheReadTokens":640,"reasoningTokens":52},"stream":[{"type":"chunk","time":1790389349382,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790389349399,"index":0,"dt":[17,15,17,17,17,16,17,16,16,16,16,16,16,15,17,18,14,17,17,15,16,17,16,16,17,16,16,17,14,16,16,16,17,16,16,16,16,16,17,98,16,17,17,16,16,17,17,16,15,16,18],"texts":["The"," user"," wants"," me"," to"," plan"," a"," small"," change"," to"," add"," a"," `","--","gre","eting","`"," flag"," to"," a"," CLI","."," They"," explicitly"," told"," me"," not"," to"," read"," or"," write"," any"," files",","," and"," to"," call"," exit","_","plan","_mode"," with"," a"," short"," plan","."," Let"," me"," do"," that"," directly","."]},{"type":"chunk","time":1790389350326,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1790389350341,"index":1,"dt":[16,16,16,15,17,16,16,16,17,16,17,16,16,16,17,15,17,17,15,17,15,15,16,16,16,17,16,16,15,16],"texts":["Since"," the"," user"," has"," explicitly"," asked"," me"," not"," to"," read"," or"," write"," any"," files"," and"," to"," go"," straight"," to"," planning",","," I","'ll"," proceed"," with"," `","exit","_","plan","_mode","`."]},{"type":"chunk","time":1790389350839,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790389350855,"index":2,"dt":[17,17,15,16,15,17,16,16,17,17,15,16,16,17,17,16,16,17,16,15,16,17,17,16,16,17,16,16,16,15,16,16,17,16,17,16,16,15,16,16,17,16,15,16,16,16,17,16,16,16,17,15,16,16,16,17,16,16,17,17,17,15,17,17,17,16,17,16,17,15,16,16,14,16,16,17,16,16,17,15,16,16,16,16,16,16,15,17,15,16,16,16,16,16,17,17,15,17,16,17,16,16,14,15,16,16,15,17,16,16,16,16,16,16,15,16,16,16,15,16,16,16,16,15,15,17,16,16,16,17,15,17,16,15,16,16,17,15,17,16,17,17,15,17,15,17,14,17,16,16,17,17,15,16,16,17,16,16,16,17,15,16,17,15,17,16,16,16,16,16,17,16,16,16,16,15,17,15,16,16,17,17,16,16,17],"id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","args":["","{","\"","plan","\"",": ","\"","#"," Add"," `","--","gre","eting","`"," flag"," to"," CLI","\\n\\n","-"," **","Loc","ate"," the"," CLI"," entry"," point","**"," (","e",".g",".,"," `","cli",".py","`,"," `","main",".go","`,"," `","index",".js","`"," etc",".)"," and"," find"," the"," argument"," parser"," definition"," (","arg","parse",","," click",","," cob","ra",","," y","args",","," or"," similar",").\\n","-"," **","Register"," a"," new"," optional"," string"," argument","**"," named"," `","--","gre","eting","`"," with"," a"," short"," alias"," (`","-","g","`"," if"," available",")"," and"," a"," sensible"," default"," value"," (","e",".g",".,"," `","\\\"","Hello","\\\"","`",").\\n","-"," **","Thread"," the"," parsed"," value","**"," through"," the"," main"," handler"," function"," so"," it"," is"," passed"," where"," the"," greeting"," string"," is"," used"," (","e",".g",".,"," the"," welcome","/","response"," message",").\\n","-"," **","Update"," the"," help"," text","**"," so"," `","--","help","`"," or"," `","-","h","`"," shows"," the"," new"," flag"," with"," its"," description",".\\n","-"," **","No"," tests"," or"," config"," changes","**"," unless"," they"," already"," exist"," and"," directly"," validate"," the"," flag","'s"," presence",".","\"","}"]},{"type":"chunk","time":1790389353849,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."}}},{"type":"chunk","time":1790389353865,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with `exit_plan_mode`."}}},{"type":"chunk","time":1790389353881,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}}},{"type":"chunk","time":1790389353898,"chunk":{"type":"usage","usage":{"inputTokens":4529,"outputTokens":303,"cacheReadTokens":640,"reasoningTokens":52}}},{"type":"chunk","time":1790389353915,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."},{"type":"text","text":"Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with `exit_plan_mode`."},{"type":"tool-call","id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":4529,"outputTokens":303,"cacheReadTokens":640,"reasoningTokens":52},"stream":[{"type":"chunk","time":1791774409447,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791774409462,"index":0,"dt":[15,16,15,17,15,16,16,17,16,15,17,17,15,17,15,16,17,17,15,16,16,16,16,17,16,15,17,15,15,17,15,16,16,16,17,15,17,15,14,17,16,16,16,15,17,17,15,16,16,15,15],"texts":["The"," user"," wants"," me"," to"," plan"," a"," small"," change"," to"," add"," a"," `","--","gre","eting","`"," flag"," to"," a"," CLI","."," They"," explicitly"," told"," me"," not"," to"," read"," or"," write"," any"," files",","," and"," to"," call"," exit","_","plan","_mode"," with"," a"," short"," plan","."," Let"," me"," do"," that"," directly","."]},{"type":"chunk","time":1791774410291,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1791774410307,"index":1,"dt":[15,17,16,38,17,16,16,16,17,16,16,16,16,17,15,17,15,16,17,16,16,17,17,14,17,15,16,16,17,16],"texts":["Since"," the"," user"," has"," explicitly"," asked"," me"," not"," to"," read"," or"," write"," any"," files"," and"," to"," go"," straight"," to"," planning",","," I","'ll"," proceed"," with"," `","exit","_","plan","_mode","`."]},{"type":"chunk","time":1791774410829,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791774410846,"index":2,"dt":[14,17,16,15,15,17,16,17,15,17,16,16,16,17,15,16,15,17,15,14,17,15,17,15,16,17,15,17,17,15,16,15,16,14,16,17,16,15,16,17,15,16,17,16,16,16,16,15,17,16,16,15,15,17,16,17,17,16,15,16,17,16,18,15,15,18,15,19,15,18,16,15,16,17,17,15,16,17,14,17,15,17,16,16,19,16,16,17,14,17,15,17,15,17,17,16,17,16,17,20,15,21,14,18,16,17,15,16,17,15,17,15,16,17,15,16,15,20,16,18,15,17,15,16,16,16,16,17,16,17,16,16,14,16,15,17,17,15,16,19,16,16,16,17,16,16,16,16,16,16,17,15,17,15,17,15,16,17,15,17,17,15,16,17,17,16,16,17,15,17,15,16,15,14,17,16,16,15,16,17,14,16,16,17,16],"id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","args":["","{","\"","plan","\"",": ","\"","#"," Add"," `","--","gre","eting","`"," flag"," to"," CLI","\\n\\n","-"," **","Loc","ate"," the"," CLI"," entry"," point","**"," (","e",".g",".,"," `","cli",".py","`,"," `","main",".go","`,"," `","index",".js","`"," etc",".)"," and"," find"," the"," argument"," parser"," definition"," (","arg","parse",","," click",","," cob","ra",","," y","args",","," or"," similar",").\\n","-"," **","Register"," a"," new"," optional"," string"," argument","**"," named"," `","--","gre","eting","`"," with"," a"," short"," alias"," (`","-","g","`"," if"," available",")"," and"," a"," sensible"," default"," value"," (","e",".g",".,"," `","\\\"","Hello","\\\"","`",").\\n","-"," **","Thread"," the"," parsed"," value","**"," through"," the"," main"," handler"," function"," so"," it"," is"," passed"," where"," the"," greeting"," string"," is"," used"," (","e",".g",".,"," the"," welcome","/","response"," message",").\\n","-"," **","Update"," the"," help"," text","**"," so"," `","--","help","`"," or"," `","-","h","`"," shows"," the"," new"," flag"," with"," its"," description",".\\n","-"," **","No"," tests"," or"," config"," changes","**"," unless"," they"," already"," exist"," and"," directly"," validate"," the"," flag","'s"," presence",".","\"","}"]},{"type":"chunk","time":1791774413845,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."}}},{"type":"chunk","time":1791774413861,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with `exit_plan_mode`."}}},{"type":"chunk","time":1791774413877,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}}},{"type":"chunk","time":1791774413893,"chunk":{"type":"usage","usage":{"inputTokens":4529,"outputTokens":303,"cacheReadTokens":640,"reasoningTokens":52}}},{"type":"chunk","time":1791774413908,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_TPh5fH8x5kRezK115kgx8155"},"toolCallId":"call_00_TPh5fH8x5kRezK115kgx8155","content":[{"type":"text","text":"Plan approved — plan mode exited; carry out the plan starting with your next step."}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[18],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"plan/mode","data":{"active":false}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:7}}"}},"sourceEventSeqs":[10],"surfaceOp":{"op":"replace","startSeq":10,"endSeq":10}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"series"}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"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."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":441,"outputTokens":43,"cacheReadTokens":4608,"reasoningTokens":40},"stream":[{"type":"chunk","time":1790389355144,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790389355159,"index":0,"dt":[16,16,17,16,17,16,16,16,16,17,15,17,15,16,17,17,16,14,16,16,17,16,16,16,17,15,16,16,19,16,16,17,15,16,16,16,16,16,15],"texts":["The"," plan"," was"," approved","."," The"," user","'s"," last"," instruction"," says",":"," \"","Once"," the"," plan"," is"," approved",","," reply"," with"," the"," single"," word"," D","ONE"," and"," stop",".\""," So"," I"," should"," just"," reply"," with"," D","ONE"," and"," stop","."]},{"type":"chunk","time":1790389355805,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1790389355821,"index":1,"dt":[16],"texts":["D","ONE"]},{"type":"chunk","time":1790389355854,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"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."}}},{"type":"chunk","time":1790389355870,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790389355887,"chunk":{"type":"usage","usage":{"inputTokens":441,"outputTokens":43,"cacheReadTokens":4608,"reasoningTokens":40}}},{"type":"chunk","time":1790389355904,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["ask_user_question","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","present","read","read_image","schedule_create","schedule_delete","schedule_list","schedule_update","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} +{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"exit_plan_mode"}],"role":"developer","id":"{{message:8}}"}},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"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."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"usage":{"inputTokens":441,"outputTokens":43,"cacheReadTokens":4608,"reasoningTokens":40},"stream":[{"type":"chunk","time":1791774415234,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791774415249,"index":0,"dt":[16,17,15,17,16,17,17,17,15,15,16,17,16,15,17,14,15,16,16,15,17,15,16,17,16,16,15,16,16,16,15,17,16,17,18,16,15,17,15],"texts":["The"," plan"," was"," approved","."," The"," user","'s"," last"," instruction"," says",":"," \"","Once"," the"," plan"," is"," approved",","," reply"," with"," the"," single"," word"," D","ONE"," and"," stop",".\""," So"," I"," should"," just"," reply"," with"," D","ONE"," and"," stop","."]},{"type":"chunk","time":1791774415891,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1791774415907,"index":1,"dt":[15],"texts":["D","ONE"]},{"type":"chunk","time":1791774415938,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"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."}}},{"type":"chunk","time":1791774415956,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1791774415971,"chunk":{"type":"usage","usage":{"inputTokens":441,"outputTokens":43,"cacheReadTokens":4608,"reasoningTokens":40}}},{"type":"chunk","time":1791774415987,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/web/ptc-round/system-prompt.expected.md b/snapshots/web/ptc-round/system-prompt.expected.md index 9ba3d79b46..8dd36e8d82 100644 --- a/snapshots/web/ptc-round/system-prompt.expected.md +++ b/snapshots/web/ptc-round/system-prompt.expected.md @@ -107,11 +107,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -419,9 +414,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: boolean; - }; get_goal: { goal: null; } | { From b7ec97ed7da5050695736d7d027dd8dea18382e1 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 12 Oct 2026 11:35:19 +0800 Subject: [PATCH 03/36] test(tools): refresh resumed-session tool inventories --- .../tests/expected/subagent-inheritance/parent.expected.jsonl | 4 ++-- snapshots/web/collapse-timing/next-message.expected.md | 2 +- snapshots/web/collapse-timing/verbose.expected.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl index 1cee326a29..3b3a9e5c7b 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl @@ -17,8 +17,8 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}} -{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"exit_plan_mode"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}} +{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Tighten this session to read-only.","messageSeqs":[3],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"delegate-write","name":"subagent","args":["{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/web/collapse-timing/next-message.expected.md b/snapshots/web/collapse-timing/next-message.expected.md index 5a7c69c657..a8621c148f 100644 --- a/snapshots/web/collapse-timing/next-message.expected.md +++ b/snapshots/web/collapse-timing/next-message.expected.md @@ -11,7 +11,7 @@ - button "Copy" - status: Completed - button "Completed in {{duration}}" [expanded] -- button "Tools updated 31 added" +- button "Tools updated 30 added" - button "Think Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". I'll now reply with DONE as instructed." - paragraph: DONE - button "Copy" diff --git a/snapshots/web/collapse-timing/verbose.expected.md b/snapshots/web/collapse-timing/verbose.expected.md index b747e28130..af243257d3 100644 --- a/snapshots/web/collapse-timing/verbose.expected.md +++ b/snapshots/web/collapse-timing/verbose.expected.md @@ -19,7 +19,7 @@ - button "Copy" - status: Completed - button "Completed in {{duration}}" [disabled] [expanded] -- button "Tools updated 31 added" +- button "Tools updated 30 added" - button "Think Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". I'll now reply with DONE as instructed." - paragraph: DONE - button "Copy" From 06d1caf82fc1f051cfd44b3478d98dd4ab44a37f Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 12 Oct 2026 23:54:41 +0800 Subject: [PATCH 04/36] feat(agent): choose the step route through agent/route - Add the agent/route waterfall, dispatched once per proposed step before system-prompt/prepare and agent/pre-step; model selection captures its choice there, and a later selection applies from the next step. - Pass the chosen StepRoute to prompt preparation and assembly, the agent/pre-step payload, and tool conditions; remove Agent.currentRoute(). - Run agent/request and prepareCall() for each attempt after step/start and prompt assembly; agent/request may change only call controls, and another provider or model fails the step. - Resolve conditional tools and assemble the prompt once per step; retries reuse the route, tool set, and rendered assembly. - Update documentation, Agent Notes, generated catalogs, tests, and the cordis-inspect-jsdoc snapshot. --- ...bles-and-tool-guidance-ownership.i18n.yaml | 8 +- ...t-variables-and-tool-guidance-ownership.md | 4 +- ...ariables-and-tool-guidance-ownership.zh.md | 4 +- ...6-07-05-reconstructable-requests.i18n.yaml | 4 +- .../2026-07-05-reconstructable-requests.md | 2 +- .../2026-07-05-reconstructable-requests.zh.md | 2 +- ...-14-provider-routed-llm-adapters.i18n.yaml | 4 +- ...2026-07-14-provider-routed-llm-adapters.md | 2 +- ...6-07-14-provider-routed-llm-adapters.zh.md | 2 +- ...02-system-prompt-as-surface-node.i18n.yaml | 4 +- ...026-09-02-system-prompt-as-surface-node.md | 2 +- ...-09-02-system-prompt-as-surface-node.zh.md | 2 +- ...-route-chosen-before-preparation.i18n.yaml | 22 +++ ...12-step-route-chosen-before-preparation.md | 36 +++++ ...step-route-chosen-before-preparation.zh.md | 36 +++++ .../feature/2026-06-15-ptc.i18n.yaml | 4 +- .../implemented/feature/2026-06-15-ptc.md | 2 +- .../implemented/feature/2026-06-15-ptc.zh.md | 2 +- .../2026-10-03-pi-extensions-bridge.i18n.yaml | 4 +- .../2026-10-03-pi-extensions-bridge.md | 2 +- .../2026-10-03-pi-extensions-bridge.zh.md | 2 +- apps/cli/tests/fixtures/dsh-badge/snapshot.ts | 3 +- docs/agent-lifecycle.i18n.yaml | 4 +- docs/agent-lifecycle.md | 25 ++-- docs/agent-lifecycle.zh.md | 25 ++-- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 9 +- docs/architecture.zh.md | 9 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.md | 25 ++-- docs/event-producer-consumer.zh.md | 25 ++-- docs/persistence-catalog.i18n.yaml | 4 +- docs/persistence-catalog.md | 2 +- docs/persistence-catalog.zh.md | 2 +- docs/persistence-schema.json | 2 +- docs/subsystems/core.i18n.yaml | 8 +- docs/subsystems/core.md | 78 ++++++++--- docs/subsystems/core.zh.md | 78 ++++++++--- docs/subsystems/llm-streaming.i18n.yaml | 4 +- docs/subsystems/llm-streaming.md | 2 +- docs/subsystems/llm-streaming.zh.md | 2 +- docs/subsystems/session-reference.md | 7 +- docs/subsystems/session-reference.zh.md | 7 +- docs/subsystems/tools.md | 12 +- docs/subsystems/tools.zh.md | 12 +- .../conditional-tools/guide.i18n.yaml | 22 +-- .../v0.2.1-alpha.2/conditional-tools/guide.md | 17 ++- .../conditional-tools/guide.zh.md | 17 ++- packages/acp/acp/README.i18n.yaml | 4 +- packages/acp/acp/README.md | 2 +- packages/acp/acp/README.zh.md | 2 +- packages/acp/acp/src/model-control.ts | 4 +- packages/acp/acp/tests/bridge.spec.ts | 4 +- .../api/job-controller/tests/host-harness.ts | 1 - .../job-controller/tests/observe.host.spec.ts | 1 - packages/api/session-controller/src/agent.ts | 4 +- .../tests/archived-session-gate.host.spec.ts | 3 +- .../tests/session-fork.host.spec.ts | 14 +- .../tests/session-models.host.spec.ts | 33 +++-- .../bundle/headless/tests/headless.spec.ts | 1 - .../tests/compaction-basic.spec.ts | 2 +- .../tests/compaction-loop-repro.spec.ts | 6 +- .../tests/agent-instructions.spec.ts | 30 ++--- .../session-reference/README.i18n.yaml | 8 +- packages/context/session-reference/README.md | 4 +- .../context/session-reference/README.zh.md | 4 +- .../context/session-reference/src/index.ts | 23 ++-- .../tests/loader-composition.spec.ts | 2 +- .../tests/session-reference.spec.ts | 29 ++-- .../time-context/tests/time-context.spec.ts | 3 +- .../tmux-context/tests/tmux-context.spec.ts | 3 +- packages/core/agent-loop/README.i18n.yaml | 8 +- packages/core/agent-loop/README.md | 4 +- packages/core/agent-loop/README.zh.md | 4 +- packages/core/agent-loop/src/agent.ts | 126 +++++++++--------- packages/core/agent-loop/src/index.ts | 4 +- packages/core/agent-loop/src/tool-calls.ts | 2 +- .../tests/contract-regressions.spec.ts | 28 +++- packages/core/agent-loop/tests/inbox.spec.ts | 1 - packages/core/agent-loop/tests/loop.spec.ts | 51 +++---- .../tests/request-reconstruction.spec.ts | 20 ++- .../tests/system-prompt-admission.spec.ts | 28 +++- .../agent-loop/tests/tool-updates.spec.ts | 46 +++---- packages/core/agent/README.i18n.yaml | 8 +- packages/core/agent/README.md | 6 +- packages/core/agent/README.zh.md | 6 +- packages/core/agent/src/model-selection.ts | 55 ++++---- packages/core/agent/src/runtime-types.ts | 57 +++++--- packages/core/agent/tests/agent.spec.ts | 1 - .../agent/tests/archive-admission.spec.ts | 1 - .../core/agent/tests/model-selection.spec.ts | 112 +++++++++------- packages/core/system-prompt/README.i18n.yaml | 8 +- packages/core/system-prompt/README.md | 4 +- packages/core/system-prompt/README.zh.md | 4 +- packages/core/tools/README.i18n.yaml | 4 +- packages/core/tools/README.md | 4 +- packages/core/tools/README.zh.md | 4 +- packages/core/tools/src/index.ts | 40 +++--- packages/core/tools/tests/activation.spec.ts | 13 +- packages/core/tools/tests/ptc.spec.ts | 2 +- .../tool-present/tests/present.spec.ts | 1 - .../tests/resources.spec.ts | 1 - .../tests/loader-composition.spec.ts | 1 - .../tool-terminal/tests/tools.spec.ts | 1 - .../experimental/worktree/tests/harness.ts | 1 - .../extensions/tool-cordis/src/api-catalog.ts | 36 +++-- .../tests/command-feedback.spec.ts | 1 - .../tests/loader-composition.spec.ts | 1 - .../tests/tools.spec.ts | 1 - .../command-goal/tests/command-goal.spec.ts | 1 - packages/goal/goal/tests/goal.spec.ts | 1 - packages/goal/goal/tests/projection.spec.ts | 1 - .../goal/tool-goal/tests/tool-goal.spec.ts | 1 - .../tool-ask-user/tests/tool-ask-user.spec.ts | 1 - packages/jobs/jobs-local/tests/events.spec.ts | 1 - packages/jobs/jobs-local/tests/jobs.spec.ts | 1 - .../tests/account-routing.spec.ts | 23 ++-- packages/llm/llm-retry/tests/retry.spec.ts | 49 +------ packages/plan/plan-mode/README.i18n.yaml | 4 +- packages/plan/plan-mode/README.md | 2 +- packages/plan/plan-mode/README.zh.md | 2 +- packages/plan/plan-mode/src/index.ts | 2 +- .../plan/plan-mode/tests/plan-mode.spec.ts | 15 ++- packages/schedule/schedule/tests/harness.ts | 1 - .../tests/session-checkpoint-policy.spec.ts | 2 +- .../working-directory/README.i18n.yaml | 4 +- packages/session/working-directory/README.md | 2 +- .../session/working-directory/README.zh.md | 2 +- .../tests/loader-composition.spec.ts | 1 - .../tool-bash-persistent/tests/tools.spec.ts | 1 - .../shell/tool-bash/tests/background.spec.ts | 2 - .../tests/loader-composition.spec.ts | 1 - .../tool-pwsh-persistent/tests/tools.spec.ts | 1 - .../shell/tool-pwsh/tests/background.spec.ts | 2 - .../skill/tool-skill/tests/tool-skill.spec.ts | 10 +- .../subagent/tests/archive-admission.spec.ts | 1 - .../tests/external-activation-helpers.ts | 1 - .../tests/model-selection-settings.spec.ts | 1 + .../terminal-bash/tests/index.spec.ts | 3 - .../terminal-bash/tests/local.spec.ts | 1 - .../terminal/terminal/tests/service.spec.ts | 1 - .../tests/loader-composition.spec.ts | 1 - .../tool-workflow/tests/tool-workflow.spec.ts | 2 - scripts/fixtures/python-sdk-dynamic-tools.mjs | 2 +- scripts/gen-cordis-catalog.ts | 3 +- scripts/gen-doc-graphs.ts | 25 ++-- .../python-snapshot-workflow-order.spec.ts | 2 +- scripts/type-equiv.manifest.json | 5 + .../cordis-inspect-jsdoc/session.v4.jsonl | 2 +- .../model-switch-driver.mjs | 10 +- 151 files changed, 923 insertions(+), 711 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md create mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.zh.md diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml index a02253e5ac..349c7778b0 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml @@ -15,8 +15,8 @@ en: 46e67248692e333a zh: 51c5f2c6152c94d7 /agent-note-prompt-variables-and-tool-guidance-ownership/decision/prompt-variables: - en: dc41d226f111d574 - zh: c6242bf30b2ed61c + en: 5f33b9ce0f4b0f9b + zh: 811297eddda54d51 /agent-note-prompt-variables-and-tool-guidance-ownership/decision/persona-as-the-order-0-section: en: c2d32c0ac5d28759 zh: 59cd252ba6da6e59 @@ -36,5 +36,5 @@ en: 31ba63101fca5790 zh: af4ceefab2033142 /agent-note-prompt-variables-and-tool-guidance-ownership/consequences: - en: 94c38eb61a2dcd4a - zh: 8a047857b6d3a4a3 + en: 64e55b14b2511e9d + zh: ea7216af8111b2b2 diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md index 9bfcb0d86e..5eaf8417c5 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md @@ -28,7 +28,7 @@ The assembled system prompt had four defects, all of one family: facts the harne Plugins register `{{name}}` values through `ctx.systemPrompt.variable(name, provider)`. Assembly resolves them into the waterfall-visible variable map. Rendering rejects unknown own-property references, registered providers that return `undefined`, malformed complete references, and unbalanced references that still contain a closing `}}`; a lone unmatched `{{` remains prose, and substituted values are not rescanned. Registration rejects invalid or duplicate variable names, and section names are unique. Sections may set `interpolate: false` to preserve generated documents literally; `tools:sdk` does so because tool descriptions and schemas may document their own `{{…}}` syntax. -`dsh-agent-loop` registers `provider` (= `options.provider`) and `model` (= `options.model`) as pure projections of the context agent. Example personas reference `{{model}}` so the route owns the model name. These variables remain on the loop plugin because they describe the agents it drives; a replacement loop supplies its own. The [Session working-directory decision](2026-09-13-session-working-directory.md) owns directory state and its literal user-context placement; the loop does not register `cwd`. +`dsh-agent-loop` registers `provider` and `model` as pure projections of the assembly context: the step route that `agent/route` chose, or the agent's `options` pair outside a step. Example personas reference `{{model}}` so the route owns the model name. These variables remain on the loop plugin because they describe the agents it drives; a replacement loop supplies its own. The [Session working-directory decision](2026-09-13-session-working-directory.md) owns directory state and its literal user-context placement; the loop does not register `cwd`. ### Persona as the order-0 section @@ -65,7 +65,7 @@ Per-tool semantics and selection guidance live in tool descriptions. Prompt sect ## Consequences - Every fact in the assembled prompt now has exactly one owner, and the hand-maintained tool prose in leaf YAML is gone: loading or dropping a tool plugin no longer means editing any deployment's persona. -- `{{model}}` reflects `AgentOptions.model` at assembly time. A plugin that switches models in the `agent/request` waterfall makes the prompt's claim stale for that step, and one that SUPPLIES the model there (options.model unset — the loop's documented fallback) leaves the variable valueless at render, failing a `{{model}}` persona before the waterfall runs. Both have the same remedy, and it is the ownership rule itself: the plugin that owns the late-bound model fact states it early on the `system-prompt/assemble` waterfall (`assembly.variables['model'] = …`) — one owner, both statements; a loop test pins the supply path end-to-end. Accepted. +- `{{model}}` reflects the step route that `agent/route` chose, and `agent/request` cannot replace that route, so the rendered prompt and the routed header name the same model. A plugin that supplies or switches the model owns that fact on `agent/route`; a loop test pins the supply path end-to-end. Accepted. - While a bound provider is absent (not yet activated, unloaded, mid-HMR-reload), the subagent tool does not exist and a model request in that window simply lacks it. That is the honest state — the alternative was a registered tool whose description or execution could not be trusted. - Strict interpolation rejects missing or valueless variables before a model request. The turn ends with `error` while the loop remains available for later turns; a persona referencing `{{model}}` requires its composing runtime to supply that value. - Inline escapes remain unsupported in interpolated text; literal sections need no escaping. PTC unit tests cover both modes and runtime languages, and the recorded `ptc-turn` scenario preserves tool-template examples in the model-visible prompt. diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md index cf0f3f1c88..adeaf7c0d5 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md @@ -28,7 +28,7 @@ Status: implemented 插件通过 `ctx.systemPrompt.variable(name, provider)` 注册 `{{name}}` 值。组装过程将它们解析到 waterfall 可见的变量映射中。渲染阶段拒绝以下情况:引用未知的自有属性、已注册的提供方返回 `undefined`、格式错误的完整引用、以及仍包含闭合 `}}` 的不平衡引用;孤立的未匹配 `{{` 保留为行文,替换后的值不会被重新扫描。注册阶段拒绝无效或重复的变量名,section 名称也必须唯一。段可设置 `interpolate: false` 来原样保留生成的文档;`tools:sdk` 使用此设置,因为工具描述和 schema 可能会介绍自身的 `{{…}}` 语法。 -`dsh-agent-loop` 注册 `provider`(= `options.provider`)和 `model`(= `options.model`),它们都是上下文 agent 的纯投影。示例 persona 引用 `{{model}}`,由路由拥有模型名称。这些变量保留在 loop 插件上,因为它们描述该循环驱动的 agent;替换循环自行提供自己的变量。[Session 工作目录决策](2026-09-13-session-working-directory.zh.md) 拥有目录状态及其字面用户上下文位置;循环不注册 `cwd`。 +`dsh-agent-loop` 注册 `provider` 和 `model`,它们都是组装上下文的纯投影:步骤内取 `agent/route` 选定的步骤路由,步骤外取 agent 的 `options` 这一对值。示例 persona 引用 `{{model}}`,由路由拥有模型名称。这些变量保留在 loop 插件上,因为它们描述该循环驱动的 agent;替换循环自行提供自己的变量。[Session 工作目录决策](2026-09-13-session-working-directory.zh.md) 拥有目录状态及其字面用户上下文位置;循环不注册 `cwd`。 ### Persona 作为 order-0 section @@ -65,7 +65,7 @@ Status: implemented ## 后果 - 组装后的提示词中每个事实现在恰好有一个归属方,leaf YAML 中手工维护的工具行文已消除:加载或卸载一个工具插件不再需要编辑任何部署的 persona。 -- `{{model}}` 在组装时反映 `AgentOptions.model`。如果一个插件在 `agent/request` waterfall 中切换模型,提示词对该步骤的声明就会过时;如果一个插件在那里提供模型(options.model 未设置——循环文档中记载的回退路径),变量在渲染时无值,包含 `{{model}}` 的 persona 会在 waterfall 运行前失败。两者的补救方式相同,就是归属规则本身:拥有延迟绑定模型事实的插件在 `system-prompt/assemble` waterfall 上提前声明它(`assembly.variables['model'] = …`)——一个归属方,两处声明;一个循环测试端到端固定了 supply 路径。已接受。 +- `{{model}}` 反映 `agent/route` 选定的步骤路由,且 `agent/request` 不能替换该路由,因此渲染后的提示词与路由后的请求头指向同一模型。提供或切换模型的插件在 `agent/route` 上拥有这一事实;一个循环测试端到端固定了 supply 路径。已接受。 - 当一个已绑定的提供方不存在时(尚未激活、已卸载、HMR(热模块替换)重载中),subagent 工具不存在,该窗口内的模型请求中不会包含它。这是诚实的状态——替代方案是注册一个 description 或执行都不可信的工具。 - 严格插值在模型请求之前拒绝缺失或无值的变量。该轮次以 `error` 结束,循环仍可服务后续轮次;引用 `{{model}}` 的 persona 要求组合它的运行时提供该值。 - 插值文本仍不支持行内转义;字面文本段无需转义。PTC 单元测试覆盖两种模式和运行时语言,录制的 `ptc-turn` 场景在模型可见的提示词中保留工具模板示例。 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 4236d3263a..76b76ed269 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 @@ -15,8 +15,8 @@ en: 6da15cf986d59a91 zh: 40282908b54295f9 /agent-note-every-llm-request-is-reconstructable-from-the-session-log/decision/the-mechanism: - en: 1c0ca7de364e4f8b - zh: 906be723ab39e3ae + en: 8a1ec49eb4f0ecf0 + zh: e9d22685d64826d4 /agent-note-every-llm-request-is-reconstructable-from-the-session-log/decision/the-minicode-shape-adopted-with-the-event-log-as-the-source: en: e5f2ffaa3d7de0cc zh: 5ba6b36787a0e189 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 9c7444d050..2744d4828f 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md @@ -24,7 +24,7 @@ Prefix-cache stability is corollary #1, not the headline: an append-only log pro `EpochHeader` records the request's non-history state: call config and tool schemas. Writers omit `tools: []` and `adapterDefaults: {}`; current acceptance rejects those fields and any `header.system`, rather than repairing them. Whitespace-only system-message content, `config.stop: []`, and nested extensions remain intact. The [V3 canonical-envelope decision](2026-09-06-v3-canonical-session-envelopes.md) owns historical conversion. The rendered system prompt is derived history — the `system/message` event at surface node 0, per the [surface-node Agent Note](2026-09-02-system-prompt-as-surface-node.md) — so a prompt change is a surface replacement rather than a header change. Adapter-supplied effort and token defaults retain their `adapterDefaults` ownership; 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, assembles the system prompt and tools, projects the rendered prompt against the surviving `system/message` node, and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, commits a changed prompt as the `system/message` append or node-0 replacement, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. `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 (system message first) and that header with no `system` field, and freezes it while leaving `AbortSignal` live. The [request-freeze evidence reference](../../../../packages/core/agent-loop/README.md) owns reuse of completed message freezes and per-request local header freezing. 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, lets `agent/route` choose the step's provider and model, prepares runtime context, and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, resolves the step's tools, assembles the system prompt, commits a changed prompt as the `system/message` append or node-0 replacement, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. `agent/request` may replace only the frozen call-config controls; the provider and model stay the step route. The loop records the owed initial, resume, change, or series full snapshot, builds `GenerateOptions` from derived messages (system message first) and that header with no `system` field, and freezes it while leaving `AbortSignal` live. The [request-freeze evidence reference](../../../../packages/core/agent-loop/README.md) owns reuse of completed message freezes and per-request local header freezing. 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. 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 21e8e28fd2..6965fa627b 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 @@ -24,7 +24,7 @@ Status: implemented `EpochHeader` 记录请求的非历史状态:调用配置和工具 schema。写入方省略 `tools: []` 与 `adapterDefaults: {}`;当前接纳拒绝这些字段以及任何 `header.system`,而不修复它们。仅含空白的系统消息内容、`config.stop: []` 与嵌套扩展保持原样。[V3 规范信封决策](2026-09-06-v3-canonical-session-envelopes.zh.md)负责历史转换。渲染后的系统提示词是派生历史——surface 第 0 号节点上的 `system/message` 事件,见[surface 节点 Agent Note](2026-09-02-system-prompt-as-surface-node.zh.md)——因此提示词变更是 surface 替换而不是 header 变更。适配器提供的推理强度与 token 默认值会保留其 `adapterDefaults` 来源信息;Web 从日志恢复模型选择时会省略适配器持有的推理强度,因此下一次解析不会把相同的有效配置重新归类为显式选择并产生虚假变更。`request/header` 始终写入完整快照:首个循环实例使用 reason `initial`,后续实例使用 `resume`,实例内变更使用 `change`,内容未变的封装显式开启消息序列或跟随表层替换时使用 `series`。如果发生变化的请求同时开启序列,`change` 快照会携带 `startsSeries: true`,无需重复 header 即可保留这两个独立事实。普通的仅追加后续 Turn、同一序列内后续的 Step 与重试沿用最新快照。`foldRequestHeader` 选择最新快照。旧的 `request/header-delta` 事件和已移除的 `fallback` reason 在追加或加载时都会被拒绝。 -每个拟议步骤先领取其 inbox 批次,组装系统提示词与工具,把渲染后的提示词与存活的 `system/message` 节点比对投影,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,把变化的提示词作为 `system/message` 追加或第 0 号节点替换提交,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。`agent/request` 只能替换冻结的调用配置种子。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息(系统消息在先)与该不含 `system` 字段的 header 构建 `GenerateOptions`,冻结请求但保持 `AbortSignal` 活跃。[请求冻结证据说明](../../../../packages/core/agent-loop/README.zh.md)拥有消息完整冻结的复用规则和每次请求的本地 header 冻结规则。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 +每个拟议步骤先领取其 inbox 批次,由 `agent/route` 选定该步骤的提供方与模型,准备运行时上下文,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,解析该步骤的工具并组装系统提示词,把变化的提示词作为 `system/message` 追加或第 0 号节点替换提交,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。`agent/request` 只能替换冻结调用配置中的控制参数;提供方与模型保持为步骤路由。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息(系统消息在先)与该不含 `system` 字段的 header 构建 `GenerateOptions`,冻结请求但保持 `AbortSignal` 活跃。[请求冻结证据说明](../../../../packages/core/agent-loop/README.zh.md)拥有消息完整冻结的复用规则和每次请求的本地 header 冻结规则。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 **已打开步骤是重建边界。** 进入步骤的 `user/message` 批次与任何新写入的 `request/header` 都位于请求分派之前。原子领取后发生的注入加入后续请求;必须影响本次请求的监听器则通过 `agent/pre-step` 返回消息。header 重建选择该步骤的 `request/header`,或在无新 header 写入时沿用前一个快照。 diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml index d3c4c85807..3ef3879354 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml @@ -12,8 +12,8 @@ en: a15c7c13f167e5ac zh: 63bcc2ef60c2f344 /agent-note-provider-routed-llm-adapters-and-a-generic-pi-ai-backend/decision/provider-is-the-adapter-registration-key: - en: 4921a060c657b790 - zh: 2f9632469c6f0b60 + en: ab32d2c01a78ac3f + zh: fbb1d8d2cade9d2e /agent-note-provider-routed-llm-adapters-and-a-generic-pi-ai-backend/decision/explicit-pi-ai-provider-profiles: en: 1346315312eb35e2 zh: 3555f91c3afb49f8 diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md index d06af266ec..23023a952c 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md @@ -18,7 +18,7 @@ The adapter configuration also assumes one DeepSeek API key and endpoint. A gene ### Provider is the adapter registration key -`GenerateOptions` and `LlmCallConfig` carry `provider: string` beside `model: string`; `AgentOptions` carries the corresponding optional creation field. A loop request is valid only after both values are non-empty, and both values are part of the logged request header. `agent/request` may return a replacement pair on any step, so a session can switch providers and models without changing the Cordis plugin lifecycle. +`GenerateOptions` and `LlmCallConfig` carry `provider: string` beside `model: string`; `AgentOptions` carries the corresponding optional creation field. A loop request is valid only after both values are non-empty, and both values are part of the logged request header. `agent/route` may return a replacement pair for any step, so a session can switch providers and models without changing the Cordis plugin lifecycle; every request attempt in the step keeps that pair. `LlmRuntime` registers and resolves adapters by provider. `registerAdapter(providers, adapter)` checks the entire provider list before mutating the registry, rejects a duplicate with `DUPLICATE_ADAPTER`, and disposes the whole registration as one effect. Model ids are not registration keys; the selected adapter still validates or forwards them. The later [LLM catalog and ACP selection Agent Note](../../archived/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md) added advisory `listProviders()` / `listModels()` discovery without turning model membership into request validation. diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md index d07312ce99..ef049f3c42 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md @@ -18,7 +18,7 @@ Status: implemented ### 提供方作为适配器注册键 -`GenerateOptions` 与 `LlmCallConfig` 在 `model: string` 之外携带 `provider: string`,`AgentOptions` 则携带对应的可选创建字段。只有两个值都非空时,agent loop(智能体循环)请求才有效;两个值也都会写入请求头日志。`agent/request` 可以在任意步骤返回替换后的字段组合,因此会话可以切换提供方与模型,无需改变 Cordis 插件生命周期。 +`GenerateOptions` 与 `LlmCallConfig` 在 `model: string` 之外携带 `provider: string`,`AgentOptions` 则携带对应的可选创建字段。只有两个值都非空时,agent loop(智能体循环)请求才有效;两个值也都会写入请求头日志。`agent/route` 可以为任意步骤返回替换后的字段组合,因此会话可以切换提供方与模型,无需改变 Cordis 插件生命周期;该步骤的每次请求尝试都沿用这一组合。 `LlmRuntime` 按提供方注册和解析适配器。`registerAdapter(providers, adapter)` 在修改注册表前检查整个提供方列表,遇到重复项时返回 `DUPLICATE_ADAPTER`,并以一个 effect 为单位整体 dispose(资源释放)。模型 ID 不作为注册键;仍由选中的适配器负责验证或转发。后续的 [LLM 目录与 ACP 模型选择 Agent Note](../../archived/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md) 增加了建议性的 `listProviders()` / `listModels()` 发现接口,但不会把目录成员关系变成请求校验规则。 diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml index 6077e29553..4d4ce8a93b 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml @@ -18,8 +18,8 @@ en: a217a08932938062 zh: 4924d99d55d9c973 /agent-note-the-system-prompt-is-surface-node-0/decision/ownership-in-the-loop: - en: a7d0d3a61d2fef04 - zh: 29a3d5dbed2f987a + en: 1c56551cd45b1ed4 + zh: 39c26c6c9799de59 /agent-note-the-system-prompt-is-surface-node-0/decision/consumers: en: 39f9f4acffcccdc6 zh: 36b23a57e7d28950 diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md index 2796b9dd52..405f9c2b96 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md @@ -36,7 +36,7 @@ When the initial rendered prompt is empty, the loop reserves an empty system hea `dsh-agent-loop` owns `SystemPromptProjection` beside `RuntimeContextProjection` in `packages/core/agent-loop/src/runtime-context.ts`. It reads the surviving `system/message` nodes from the current surface on every projection, so a compaction or replacement that ran earlier in the same step is already reflected. `project(rendered, { inHistory, startsSeries })` returns `{ message, intent }` — `intent` is `{ surfaceOp: 'append' }` when no system node survives or when the [in-history rule](../feature/2026-09-02-in-history-system-prompt-replacement.md) applies, otherwise a replacement of exactly the latest surviving system node — or `undefined` when the latest node already holds the rendered text. -In `packages/core/agent-loop/src/agent.ts`, `preStep` renders the prompt with `renderPrompt(assembly)` and projects it after the `agent/pre-step` waterfall, so a compaction provider's replacement inside that waterfall is visible to the decision; `turn()` commits the `system/message` immediately after `step/start` and before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `systemPrompt.assemble()` → project runtime context → `agent/pre-step` waterfall → project system prompt → `step/start` → commit `system/message` (when changed) → commit `user/message`s → `agent/request` waterfall → `request/header` → `request/context` → stream. +In `packages/core/agent-loop/src/agent.ts`, `step()` renders the prompt with `renderPrompt(assembly)` after `step/start` and projects it on each attempt after `agent/request` and `prepareCall()`, so a compaction provider's replacement inside `agent/pre-step` or retry recovery is visible to reconciliation; the `system/message` is committed before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `agent/route` waterfall → `systemPrompt.prepare()` → `agent/pre-step` waterfall → `step/start` → resolve tools → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → commit `system/message` (when changed) → commit `user/message`s → `request/header` → `request/context` → stream. `dsh-token-meter` anchors usage to the priced surface immediately before the successful `assistant/message`, not to `step/start`. The loop admits the system prompt and user messages after step start, and retry recovery can replace nodes before rebuilding the request. Capturing that current surface includes every admitted input once; the embedded provider output remains separately priced so durable assistant rewrites retain their signed delta. The open step stores only turn and step for lifecycle validation, not a second node snapshot. diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md index 417bf5fb3e..7384b5f96c 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md @@ -36,7 +36,7 @@ Status: implemented `dsh-agent-loop` 在 `packages/core/agent-loop/src/runtime-context.ts` 中与 `RuntimeContextProjection` 并列拥有 `SystemPromptProjection`。它在每次投影时从当前 surface 读取存活的 `system/message` 节点,因此同一步骤中更早运行的压缩或替换已经反映在内。`project(rendered, { inHistory, startsSeries })` 返回 `{ message, intent }`——没有系统节点存活或[历史内规则](../feature/2026-09-02-in-history-system-prompt-replacement.zh.md)适用时 `intent` 为 `{ surfaceOp: 'append' }`,否则是对最新存活系统节点的精确替换——最新节点已持有渲染文本时返回 `undefined`。 -在 `packages/core/agent-loop/src/agent.ts` 中,`preStep` 用 `renderPrompt(assembly)` 渲染提示词,并在 `agent/pre-step` waterfall 之后投影它,因此压缩提供者在该 waterfall 内做出的替换对决定可见;`turn()` 紧接在 `step/start` 之后、该步骤的 `user/message` 事件之前提交 `system/message`,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `systemPrompt.assemble()` → 投影运行时上下文 → `agent/pre-step` waterfall → 投影系统提示词 → `step/start` → 提交 `system/message`(有变化时) → 提交各条 `user/message` → `agent/request` waterfall → `request/header` → `request/context` → 流式请求。 +在 `packages/core/agent-loop/src/agent.ts` 中,`step()` 在 `step/start` 之后用 `renderPrompt(assembly)` 渲染提示词,并在每次尝试的 `agent/request` 与 `prepareCall()` 之后投影它,因此压缩提供者在 `agent/pre-step` 内或重试恢复中做出的替换对协调可见;`system/message` 在该步骤的 `user/message` 事件之前提交,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `agent/route` waterfall → `systemPrompt.prepare()` → `agent/pre-step` waterfall → `step/start` → 解析工具 → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → 提交 `system/message`(有变化时) → 提交各条 `user/message` → `request/header` → `request/context` → 流式请求。 `dsh-token-meter` 把用量锚定到成功的 `assistant/message` 之前的已计价 surface,而不是 `step/start`。循环在步骤开始之后接纳系统提示词与用户消息,重试恢复还可能在重建请求之前替换节点。捕获当前 surface 会让每个已接纳输入恰好计入一次;内嵌的提供方输出仍单独计价,因此持久 assistant 改写保留其带符号增量。开放步骤只保存 turn 与 step 以验证生命周期,不保存第二份节点快照。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.i18n.yaml new file mode 100644 index 0000000000..c0331d7d6c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-12-step-route-chosen-before-preparation.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md +/agent-note-choose-the-step-route-before-step-preparation: + en: cce89c1039110cb5 + zh: fb29015e2a37b74f +/agent-note-choose-the-step-route-before-step-preparation/problem: + en: 2d6bc81525bc277d + zh: b65ec115cb4a00e4 +/agent-note-choose-the-step-route-before-step-preparation/decision: + en: 38e163581b2f798d + zh: 62c89bb0167ded9e +/agent-note-choose-the-step-route-before-step-preparation/alternatives-considered: + en: a704646ef1631668 + zh: f99b24164105d0bb +/agent-note-choose-the-step-route-before-step-preparation/consequences: + en: ebaeafdadf1ab3cd + zh: 12cb3c213c84fe82 +/agent-note-choose-the-step-route-before-step-preparation/related: + en: 00ef1147a7852c0a + zh: 4bd89960e08b6eda diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md new file mode 100644 index 0000000000..3c347f72b0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md @@ -0,0 +1,36 @@ +# Agent Note: Choose the step route before step preparation + +Status: implemented + +English | [中文](2026-10-12-step-route-chosen-before-preparation.zh.md) + +## Problem + +Tool availability can depend on the route of the request that declares the tools: `web_search` must stay off routes without search credentials, and plan or team state can withhold other tools. Message preparation needs the same route: session references size snapshots by the model's context window, and model selection announces a switch. The loop assembled tools and prompt sections before `agent/pre-step` and decided the route only in `agent/request` after `step/start`, so earlier consumers predicted the route from model-selection state. A listener that replaced the route in `agent/request`, including on a retry, made the assembled prompt and tool catalog describe another model. + +## Decision + +The provider and model are a step fact. After claiming input, the loop dispatches `agent/route` once per proposed step. Its default is the agent options route before this loop logs a request and the logged header route afterwards; `installModelSelection` captures its selection there. The loop passes the resulting `StepRoute` to `system-prompt/prepare` as `AssembleContext.route`, to `agent/pre-step` as `payload.route`, and to tool conditions as `ToolActivationContext.route`. The `{{provider}}` and `{{model}}` prompt variables read it. + +After `agent/pre-step` accepts the step and `step/start` opens it, the loop resolves conditional tools and assembles the prompt once. Each request attempt then runs `agent/request` and `prepareCall()` immediately before admission. `agent/request` may change call controls; a result with another provider or model fails the step. Retries reuse the step's route, tool set, and rendered assembly, and the step-owned tool set closes after the step's tool batch settles. A selection made during a step applies from the next step. + +## Alternatives considered + +- **Bind the route in `agent/request` before `agent/pre-step` and expose `Agent.currentRoute()`.** The prepared call captures the adapter registration and connection settings, so holding it across compaction, hooks, and session reads ignores settings changed meanwhile, and adapters were prepared for steps that `agent/pre-step` rejects. The getter was valid only inside a step and threw elsewhere, and every Agent implementation and test double had to carry it. +- **Record the route inside `agent/pre-step`.** `system-prompt/prepare` runs before that waterfall, and route consumers inside it would depend on listener order. +- **Register the model selection on the Agent without an event.** It adds a single-consumer method to the generic `Agent` interface, moves model-selection effort rules into the loop, and removes the listener path that supplies a route for agents created without one. +- **Keep the route decision in `agent/request` and predict it for earlier consumers.** A prediction diverges whenever a listener other than model selection changes the route. + +## Consequences + +- Tool conditions, prompt variables, reference budgets, and switch notices read the route that the request header records. +- `prepareCall()` stays adjacent to dispatch, so its adapter registration and connection snapshot cover only header logging and streaming. +- A step cannot fail over to another provider on retry; a policy that needs this must run routing, tool resolution, and assembly again for the retried attempt. +- The route cannot depend on `agent/pre-step` outcomes. Plan state commits inside that waterfall, so a plan-specific model would require committing plan selections before routing. +- `agent/pre-step` listeners and direct dispatchers must handle the required `route` field. + +## Related + +- [Provider-routed LLM adapters](2026-07-14-provider-routed-llm-adapters.md) owns provider and model fields in call configuration. +- [Reconstructable requests](2026-07-05-reconstructable-requests.md) owns request reconstruction from the logged header. +- [Prompt variables and tool guidance ownership](2026-07-05-prompt-variables-and-tool-guidance-ownership.md) owns the `{{model}}` variable. diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.zh.md b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.zh.md new file mode 100644 index 0000000000..204039e9e7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 在步骤准备之前选定步骤路由 + +Status: implemented + +[English](2026-10-12-step-route-chosen-before-preparation.md) | 中文 + +## 问题 + +工具是否可用可能取决于声明这些工具的请求所用的路由:`web_search` 不得出现在没有搜索凭据的路由上,计划或团队状态也可能撤下其他工具。消息准备同样需要这一路由:会话引用按模型的上下文窗口确定快照大小,模型选择会通告模型切换。循环原先在 `agent/pre-step` 之前组装工具与提示词段落,直到 `step/start` 之后才在 `agent/request` 中决定路由,因此更早的消费方只能依据模型选择状态预测路由。若监听器在 `agent/request` 中(包括在重试时)替换路由,已组装的提示词与工具目录就会描述另一个模型。 + +## 决策 + +提供方与模型是步骤级事实。领取输入之后,循环为每个拟议步骤派发一次 `agent/route`。其默认值在本循环记录请求之前取 agent 选项中的路由,之后取已记录请求头中的路由;`installModelSelection` 在这里捕获其选择。循环把得到的 `StepRoute` 作为 `AssembleContext.route` 传给 `system-prompt/prepare`,作为 `payload.route` 传给 `agent/pre-step`,作为 `ToolActivationContext.route` 传给工具条件。提示词变量 `{{provider}}` 与 `{{model}}` 读取该路由。 + +`agent/pre-step` 接纳步骤且 `step/start` 打开步骤之后,循环解析条件工具并组装提示词,各执行一次。之后每次请求尝试都在准入之前紧接着运行 `agent/request` 与 `prepareCall()`。`agent/request` 可以修改调用控制参数;返回其他提供方或模型会使步骤失败。重试复用该步骤的路由、工具集合与已渲染组装结果,步骤拥有的工具集合在该步骤的工具批次结束后关闭。步骤进行中做出的选择从下一个步骤开始生效。 + +## 考虑过的替代方案 + +- **在 `agent/pre-step` 之前通过 `agent/request` 绑定路由,并提供 `Agent.currentRoute()`。** 已准备调用会捕获适配器注册与连接设置,因此在压缩、钩子与会话读取期间一直持有它,会忽略期间修改的设置;被 `agent/pre-step` 拒绝的步骤也会准备适配器。该 getter 只在步骤内有效、在其他时刻抛错,且每个 Agent 实现与测试替身都必须提供它。 +- **在 `agent/pre-step` 内记录路由。** `system-prompt/prepare` 在该 waterfall 之前运行,而 waterfall 内的路由消费方将依赖监听器顺序。 +- **不使用事件,直接在 Agent 上登记模型选择。** 这会给通用 `Agent` 接口增加只有单一消费方的方法,把模型选择的推理强度规则移入循环,并移除为创建时没有路由的 agent 提供路由的监听器途径。 +- **路由决定留在 `agent/request`,为更早的消费方预测路由。** 只要模型选择之外的监听器修改路由,预测就会偏离。 + +## 后果 + +- 工具条件、提示词变量、引用预算与切换通告读取的路由,与请求头记录的路由一致。 +- `prepareCall()` 紧邻分发,因此其适配器注册与连接快照只覆盖请求头记录与流式请求。 +- 步骤无法在重试时切换到其他提供方;需要这种能力的策略必须为重试的尝试重新执行路由选择、工具解析与组装。 +- 路由不能依赖 `agent/pre-step` 的结果。计划状态在该 waterfall 内提交,因此按计划模式选择模型需要先在路由选择之前提交计划选择。 +- `agent/pre-step` 监听器与直接派发方必须处理必填的 `route` 字段。 + +## 相关 + +- [基于提供方路由的 LLM 适配器](2026-07-14-provider-routed-llm-adapters.zh.md)负责调用配置中的提供方与模型字段。 +- [可重建请求](2026-07-05-reconstructable-requests.zh.md)负责依据已记录请求头重建请求。 +- [提示词变量与工具指导归属](2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md)负责 `{{model}}` 变量。 diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml index e3bd9b93f5..9c1ddab7b7 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml @@ -15,8 +15,8 @@ en: da694641e1d009de zh: 9d7492d39039af66 /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-registry-owns-the-mode: - en: 091b7bc49b027353 - zh: 42dc77a810202694 + en: 4cd76a34f4712e1a + zh: 303ef72a18644d7c /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-run-code-tool-and-the-dispatch-bridge: en: 6a0e2698b082978e zh: fbb03503520b30e9 diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.md b/.agents/notes/implemented/feature/2026-06-15-ptc.md index 97fc5b04db..e99eccd65b 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.md @@ -40,7 +40,7 @@ The [Node execution decision](../architecture/2026-09-11-sandboxed-node-ptc-runt **SDK prompt section.** In `'ptc'`, the lazy `tools:sdk` section in the tool-guidance order band renders the loaded runtime's language declarations plus fixed usage instructions for the scope's visible capabilities (TypeScript by default; the [language-dispatch note](../../archived/feature/2026-07-31-ptc-language-dispatch.md) added Python and the `ctx.ptcRuntime.language` renderer table). It shares lookup and execution visibility, excludes `run_code`, and sorts tools lexicographically for byte-stable output. -**Assembly ownership.** `run_code` and `tools:sdk` enter the trusted `system-prompt/assemble` waterfall as normal assembly inputs. A scoped `tools:sdk` section may shadow the global default before dispatch, and a listener may remove or replace either contribution. The waterfall's returned assembly is final, so whoever changes these inputs owns preserving a viable PTC mode protocol when the deployment expects PTC mode to remain usable; no restoration pass overrides deliberate composition. +**Assembly ownership.** `tools:sdk` enters the trusted `system-prompt/assemble` presentation waterfall as a normal section, while `run_code` stays a provider-owned declaration that the waterfall cannot remove or replace. A scoped `tools:sdk` section may shadow the global default before dispatch, and a listener may remove or replace the section. Whoever changes it owns preserving a viable PTC mode protocol when the deployment expects PTC mode to remain usable; no restoration pass overrides deliberate composition. **Codegen.** `jsonSchemaToTs()` maps the `defineTool` JSON-Schema subset to TypeScript, carries schema descriptions into JSDoc, and degrades unsupported constructs to `unknown`. The SDK exposes tools as quoted object keys, supporting arbitrary names without aliases or collisions. Typing is advisory because the runtime strips types before execution. diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md index 381448d354..71efafa7f2 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md @@ -40,7 +40,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 **SDK 提示词段。** 在 `'ptc'` 下,tool-guidance order band 中的惰性 `tools:sdk` 段为当前 scope 的可见能力渲染所加载运行时语言的声明加固定的使用说明(默认 TypeScript;[语言分发 note](../../archived/feature/2026-07-31-ptc-language-dispatch.md) 加入了 Python 与按 `ctx.ptcRuntime.language` 选择的渲染器表)。它共享查找和执行可见性,排除 `run_code`,并按字典序排列工具以获得字节稳定的输出。 -**组装所有权。** `run_code` 和 `tools:sdk` 作为正常的组装输入进入受信任的 `system-prompt/assemble` waterfall。一个 scoped 的 `tools:sdk` 段可以在分发前遮蔽全局默认值,监听器也可以移除或替换任一贡献。waterfall 返回的组装结果是最终的,因此修改这些输入的人有责任在部署期望 PTC mode 可用时保持协议面的完整性;没有恢复 pass 会覆盖有意的组合。 +**组装所有权。** `tools:sdk` 作为正常段进入受信任的 `system-prompt/assemble` 展示 waterfall,而 `run_code` 仍是提供方持有的声明,waterfall 不能移除或替换它。一个 scoped 的 `tools:sdk` 段可以在分发前遮蔽全局默认值,监听器也可以移除或替换该段。修改它的人有责任在部署期望 PTC mode 可用时保持协议面的完整性;没有恢复 pass 会覆盖有意的组合。 **代码生成。** `jsonSchemaToTs()` 将 `defineTool` 的 JSON Schema 子集映射为 TypeScript,将 schema 描述带入 JSDoc,不支持的构造降级为 `unknown`。SDK 将工具暴露为带引号的对象键,支持任意名称而无需别名或冲突处理。类型是建议性的,因为运行时在执行前会剥离类型。 diff --git a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.i18n.yaml b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.i18n.yaml index 6a09cae1de..9ab1268936 100644 --- a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.i18n.yaml @@ -18,8 +18,8 @@ en: d95ece799bc6bab7 zh: 1e19d3b49473a57e /agent-note-pi-extensions-bridge/proposal/serving-the-api: - en: b1365f16d76fe27a - zh: 105b88f80eb8964d + en: 2cb8b4ce6c74d8b5 + zh: d66d52f966310dc4 /agent-note-pi-extensions-bridge/proposal/built-in-tool-calls-as-pi-sees-them: en: c74e4662ad0a8ee7 zh: 653729b41e983b13 diff --git a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.md b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.md index 28faf5911a..4ba7f9685d 100644 --- a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.md +++ b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.md @@ -42,7 +42,7 @@ Add an experimental bridge that loads unmodified Pi extension sources and serves | `sendUserMessage`, `sendMessage` | `agent.followup()`, `agent.steer()`, `agent.inject()` | | `appendEntry`, `setLabel`, tool `details`, `ctx.sessionManager` | Ignorable Session records and `tool/result` metadata, read back as Pi entries | | `getActiveTools`, `setActiveTools`, `getAllTools` | `ctx.tools.schemas()`; `setActiveTools` applies a scoped `ctx.tools.restrict()` to global tools and adds or removes the bridge's own Agent-scoped registrations, because a restriction does not hide scoped tools | -| `setModel`, `getThinkingLevel`, `setThinkingLevel` | An `agent/request` override | +| `setModel`, `getThinkingLevel`, `setThinkingLevel` | An `agent/route` override for the model and an `agent/request` override for the thinking level | | `exec` | `ctx.subprocess`, argv without a shell | | `ctx.ui.select`, `confirm`, `input`, `editor` | `ctx.userQuestions` | | `ctx.ui.notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText` | A Remote stream the Web package renders | diff --git a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.zh.md b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.zh.md index 855f7b160c..cccc9eec25 100644 --- a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.zh.md +++ b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.zh.md @@ -42,7 +42,7 @@ DSH 已为另外两个生态提供桥接:为 Claude Code 与 Codex 编写的 s | `sendUserMessage`、`sendMessage` | `agent.followup()`、`agent.steer()`、`agent.inject()` | | `appendEntry`、`setLabel`、工具 `details`、`ctx.sessionManager` | ignorable Session 记录与 `tool/result` 元数据,读回时还原为 Pi 条目 | | `getActiveTools`、`setActiveTools`、`getAllTools` | `ctx.tools.schemas()`;`setActiveTools` 对全局工具使用作用域内的 `ctx.tools.restrict()`,并增删桥接自己在 Agent 作用域的注册,因为限制不会隐藏作用域内的工具 | -| `setModel`、`getThinkingLevel`、`setThinkingLevel` | `agent/request` 覆盖 | +| `setModel`、`getThinkingLevel`、`setThinkingLevel` | `agent/route` 覆盖模型,`agent/request` 覆盖思考等级 | | `exec` | `ctx.subprocess`,不经 shell 的 argv | | `ctx.ui.select`、`confirm`、`input`、`editor` | `ctx.userQuestions` | | `ctx.ui.notify`、`setStatus`、`setWidget`、`setTitle`、`setEditorText` | 由 Web 包渲染的 Remote 流 | diff --git a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts index 87eb1a73b5..f9e58f262f 100644 --- a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts +++ b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts @@ -27,7 +27,6 @@ try { const agentId = SessionId('dsh-badge-snapshot') const session = ctx.sessions.create(agentId, { meta: { cwd: process.cwd() } }) const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, ctx, id: agentId, options: {}, @@ -44,7 +43,7 @@ try { } const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, signal: new AbortController().signal }, + { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const catalog = decision.kind === 'enter' diff --git a/docs/agent-lifecycle.i18n.yaml b/docs/agent-lifecycle.i18n.yaml index 3871250205..1d465b17fa 100644 --- a/docs/agent-lifecycle.i18n.yaml +++ b/docs/agent-lifecycle.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 305a6826a598b96d /agent-turn-and-step-lifecycle: - en: 8b6b2eff5a5c93b9 - zh: f63a8b82e1888d12 + en: ee62762f177bb320 + zh: 271f74cbacc86d98 diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index eceb9229fc..28815a0372 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -25,17 +25,18 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/request waterfall - Driver->>LLM: prepareCall(config, signal), bind Agent.currentRoute() - Driver->>Prompt: system-prompt/prepare waterfall - Driver->>Hooks: agent/pre-step waterfall + Driver->>Hooks: agent/route waterfall chooses the step route + Driver->>Prompt: system-prompt/prepare waterfall on the step route + Driver->>Hooks: agent/pre-step waterfall with the step route Hooks-->>Driver: authoritative reject or enter(messages) alt proposed step rejected, first batch empty, or pre-step failed Driver-->>Driver: claimed batch stays removed, the open turn spends no step else enter proposed step Driver->>Session: step/start - Driver->>Tools: resolve({ agent, signal }) - Driver->>Prompt: system-prompt/assemble with resolved tool set + Driver->>Tools: resolve({ agent, route, signal }) once per step + Driver->>Prompt: system-prompt/assemble with the step tool set + Driver->>Hooks: agent/request waterfall on the step route + Driver->>LLM: prepareCall(config, signal) Note over Driver,LLM: cancellation during preparation commits neither system nor users Note over Driver,Session: synchronous admission using the prepared call capability Driver->>Session: system/message ordered per-node reconciliation @@ -50,7 +51,7 @@ sequenceDiagram Driver-->>SDK: agent/assistant-stream committed end Driver->>Hooks: agent/request-error waterfall Hooks-->>Driver: return retry action or preserve the original error - Note over Driver,LLM: retry resolves route and tools. Unchanged inputs reuse the prompt without repeating pre-step or users + Note over Driver,LLM: retry in the open step: request and prepare again on the same route, tool set, and prompt without repeating pre-step or users else model request succeeded Driver->>Session: assistant/message Driver-->>SDK: agent/assistant-stream committed end @@ -58,7 +59,7 @@ sequenceDiagram loop barriers and bounded rolling pool, reclassify before start opt call starts Driver->>Session: tool/call - Driver->>Tools: ordered pre, concurrent execute with request tool set + Driver->>Tools: ordered pre, concurrent execute with the step tool set Tools-->>Session: tool-owned events when applicable end opt next model-order result ready @@ -66,16 +67,16 @@ sequenceDiagram Driver->>Session: tool/result end end - Driver->>Tools: dispose request tool set + Driver->>Tools: dispose the step tool set Driver->>Session: step/end - Driver->>Driver: clear bound route opt natural stop and next-step inbox empty Driver->>Hooks: agent/turn-stopping serial terminal checkpoint end opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Driver: prepare route and runtime context for the next step + Driver->>Hooks: agent/route waterfall + Driver->>Prompt: system-prompt/prepare waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) end @@ -87,7 +88,7 @@ sequenceDiagram The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes, and embeds the exact compact timed stream. Empty content stays out of derived history. A failed, retried, cancelled, or stream-error attempt that reaches settlement without a surface message records its stream as `assistant/attempt`. Live `agent/assistant-stream` chunk frames are transient; replay reads either durable settlement, and a hard process loss before settlement leaves no durable attempt stream. -`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call and resolves tool conditions before request derivation, without repeating pre-step or user admission. Prompt assembly repeats only when the bound route or tool schemas change. +`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call on the step route and reconciles the retained rendered assembly before request derivation, without repeating routing, tool resolution, assembly, pre-step, or user admission. 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. diff --git a/docs/agent-lifecycle.zh.md b/docs/agent-lifecycle.zh.md index 74b8fb05f6..c1e2b942ab 100644 --- a/docs/agent-lifecycle.zh.md +++ b/docs/agent-lifecycle.zh.md @@ -27,17 +27,18 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/request waterfall - Driver->>LLM: prepareCall(config, signal), bind Agent.currentRoute() - Driver->>Prompt: system-prompt/prepare waterfall - Driver->>Hooks: agent/pre-step waterfall + Driver->>Hooks: agent/route waterfall chooses the step route + Driver->>Prompt: system-prompt/prepare waterfall on the step route + Driver->>Hooks: agent/pre-step waterfall with the step route Hooks-->>Driver: authoritative reject or enter(messages) alt proposed step rejected, first batch empty, or pre-step failed Driver-->>Driver: claimed batch stays removed, the open turn spends no step else enter proposed step Driver->>Session: step/start - Driver->>Tools: resolve({ agent, signal }) - Driver->>Prompt: system-prompt/assemble with resolved tool set + Driver->>Tools: resolve({ agent, route, signal }) once per step + Driver->>Prompt: system-prompt/assemble with the step tool set + Driver->>Hooks: agent/request waterfall on the step route + Driver->>LLM: prepareCall(config, signal) Note over Driver,LLM: cancellation during preparation commits neither system nor users Note over Driver,Session: synchronous admission using the prepared call capability Driver->>Session: system/message ordered per-node reconciliation @@ -52,7 +53,7 @@ sequenceDiagram Driver-->>SDK: agent/assistant-stream committed end Driver->>Hooks: agent/request-error waterfall Hooks-->>Driver: return retry action or preserve the original error - Note over Driver,LLM: retry resolves route and tools. Unchanged inputs reuse the prompt without repeating pre-step or users + Note over Driver,LLM: retry in the open step: request and prepare again on the same route, tool set, and prompt without repeating pre-step or users else model request succeeded Driver->>Session: assistant/message Driver-->>SDK: agent/assistant-stream committed end @@ -60,7 +61,7 @@ sequenceDiagram loop barriers and bounded rolling pool, reclassify before start opt call starts Driver->>Session: tool/call - Driver->>Tools: ordered pre, concurrent execute with request tool set + Driver->>Tools: ordered pre, concurrent execute with the step tool set Tools-->>Session: tool-owned events when applicable end opt next model-order result ready @@ -68,16 +69,16 @@ sequenceDiagram Driver->>Session: tool/result end end - Driver->>Tools: dispose request tool set + Driver->>Tools: dispose the step tool set Driver->>Session: step/end - Driver->>Driver: clear bound route opt natural stop and next-step inbox empty Driver->>Hooks: agent/turn-stopping serial terminal checkpoint end opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Driver: prepare route and runtime context for the next step + Driver->>Hooks: agent/route waterfall + Driver->>Prompt: system-prompt/prepare waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) end @@ -89,7 +90,7 @@ sequenceDiagram `assistant/message` 事件会记录每次成功的提供方调用,包括返回空内容或以 `max-tokens` 结束的调用,并嵌入精确的紧凑带时间 stream。空内容不会进入派生历史。失败、重试、取消或 stream error attempt 到达 settlement 时,如果没有 surface message,就会把 stream 记录为 `assistant/attempt`。实时 `agent/assistant-stream` chunk frame 是瞬态数据;回放读取任一种持久 settlement,如果进程在 settlement 前硬中断,则不会留下持久 attempt stream。 -`dsh-compaction-basic` 在派生请求之前通过 `agent/pre-step` 处理压力,而 `agent/request-error` 仅用于规范的上下文溢出。任一触发条件满足后,系统都会先执行可选的工具结果剪枝,再选择摘要。恢复发生在仍打开的步骤内,只有剪枝或摘要生成推进 surface replacement generation 时才重试,否则仍以原始请求错误为准。每次重试都会在派生请求之前准备调用并解析工具条件,不重复 pre-step 或用户消息准入。只有已绑定路由或工具 schema 变化时才重新组装提示词。 +`dsh-compaction-basic` 在派生请求之前通过 `agent/pre-step` 处理压力,而 `agent/request-error` 仅用于规范的上下文溢出。任一触发条件满足后,系统都会先执行可选的工具结果剪枝,再选择摘要。恢复发生在仍打开的步骤内,只有剪枝或摘要生成推进 surface replacement generation 时才重试,否则仍以原始请求错误为准。每次重试都会在该步骤的路由上准备调用,并在派生请求之前协调保留的已渲染组装结果,不重复路由选择、工具解析、组装、pre-step 或用户消息准入。 以返回的 `agent/pre-step` 决策为准;通过包装 `next()` 的监听器会保留下游消息与 `startsRequestSeries`,除非有意替换。steering(中途引导)和注入的上下文在后续的认领操作取得其下一步骤批次后,会经过同一 waterfall(瀑布式事件)。 diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index a1eca06e56..e865273013 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -24,8 +24,8 @@ en: e89802f066e4955d zh: ea2fb4bef94e086d /deepseek-harness-architecture/turn-flow: - en: e7f529503233d805 - zh: f1d1e4a58e44a2ec + en: 14dc97ef8cc7458c + zh: c6fbb5885080f8c6 /deepseek-harness-architecture/session-log: en: a2e35c43438fec6d zh: e27bdac8e9feff32 diff --git a/docs/architecture.md b/docs/architecture.md index 9157ba13a9..5feeb8c3ba 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -83,13 +83,14 @@ A **step** is one model request plus the tools it calls. A **turn** is zero or m ```text turn/start claim next-step input plus one queued message - agent/request -> prepareCall -> bind Agent.currentRoute() + agent/route -> step provider/model prepare variables + runtime context -> agent/pre-step; project runtime context at fallback reject | enter(messages, startsRequestSeries?) reject, or a first enter rewritten empty -> close the turn with no step step/start - resolve conditional tools + assemble prompt using that tool set + resolve conditional tools + assemble prompt + agent/request -> prepareCall reconcile system/message using the prepared call capability append entered messages as user/message; reconcile retained runtime context log request/header and request/context as needed @@ -104,11 +105,11 @@ turn/start turn/end ``` -`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable session events; the rest are live extension points across three domains. `agent/assistant-stream` publishes process-local start, transient chunk, and end frames. The loop commits the complete compact stream as one message or log-only attempt before a committed end frame, and the Web Session-follow adapter is the live event's only remote consumer. `agent/pre-step`, `agent/request`, `llm/stream`, and the three `tools/*` events are waterfalls, whose listeners must call `next()` to delegate; `agent/turn-stopping` is serial and has no `next()`. +`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable session events; the rest are live extension points across three domains. `agent/assistant-stream` publishes process-local start, transient chunk, and end frames. The loop commits the complete compact stream as one message or log-only attempt before a committed end frame, and the Web Session-follow adapter is the live event's only remote consumer. `agent/route`, `agent/pre-step`, `agent/request`, `llm/stream`, and the three `tools/*` events are waterfalls, whose listeners must call `next()` to delegate; `agent/turn-stopping` is serial and has no `next()`. One inbox feeds the driver; injected context waits for a waking message. AgentLoop’s durable `inbox` projection exposes pending input without live Agents. -`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/request` and `prepareCall()` bind the route before context preparation and `agent/pre-step`; cancellation commits no step or messages. Accepted steps resolve tool conditions before final assembly. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming. Retries do not repeat `agent/pre-step`; prompt assembly repeats only when the resolved route or tool schemas change. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). +`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/route` fixes the step's provider and model before `agent/pre-step`; accepted steps resolve tools and assemble once. Each attempt's `agent/request` may change only call controls, and `prepareCall()` binds the adapter before prompt and user admission; cancellation in either commits neither. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming; retries reuse the route, tools, and assembly. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). The loop sends immutable requests with live cancellation and reuses freeze evidence for frozen identities; [agent-loop](../packages/core/agent-loop/README.md) owns construction and cancellation causes. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 58f110c928..ace6edf25b 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -87,13 +87,14 @@ AgentLoop 在启动已排队工作前等待串行 `agent/created`,初始化失 ```text turn/start claim next-step input plus one queued message - agent/request -> prepareCall -> bind Agent.currentRoute() + agent/route -> step provider/model prepare variables + runtime context -> agent/pre-step; project runtime context at fallback reject | enter(messages, startsRequestSeries?) reject, or a first enter rewritten empty -> close the turn with no step step/start - resolve conditional tools + assemble prompt using that tool set + resolve conditional tools + assemble prompt + agent/request -> prepareCall reconcile system/message using the prepared call capability append entered messages as user/message; reconcile retained runtime context log request/header and request/context as needed @@ -108,11 +109,11 @@ turn/start turn/end ``` -`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久会话事件;其余是分属三个事件域的实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态 chunk 与 end frame。loop 会在 committed end frame 前把完整紧凑 stream 提交为一个 message 或仅日志 attempt;Web Session-follow adapter 是该 live event 唯一的远程消费方。`agent/pre-step`、`agent/request`、`llm/stream` 和三个 `tools/*` 事件是 waterfall(瀑布式事件),其监听器必须调用 `next()` 才能委托下去;`agent/turn-stopping` 是 serial 事件,没有 `next()`。 +`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久会话事件;其余是分属三个事件域的实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态 chunk 与 end frame。loop 会在 committed end frame 前把完整紧凑 stream 提交为一个 message 或仅日志 attempt;Web Session-follow adapter 是该 live event 唯一的远程消费方。`agent/route`、`agent/pre-step`、`agent/request`、`llm/stream` 和三个 `tools/*` 事件是 waterfall(瀑布式事件),其监听器必须调用 `next()` 才能委托下去;`agent/turn-stopping` 是 serial 事件,没有 `next()`。 输入通过同一个 inbox 到达驱动器;注入的上下文等待一条唤醒消息。AgentLoop 的持久 `inbox` 投影使待处理输入在没有活跃 Agent 时仍可读取。 -`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。组装与 `step/start` 之后,`agent/request` 和 `prepareCall()` 先解析实际路由,再提交系统提示词与已接纳用户消息;在任一异步阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求。重试不重复 `agent/pre-step`;仅在已解析路由或工具 schema 改变时重新组装提示词。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 +`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。`agent/route` 在 `agent/pre-step` 之前固定该步骤的提供方与模型;被接纳的步骤随后解析工具并组装一次。每次尝试的 `agent/request` 只能修改调用控制参数,`prepareCall()` 在提示词与用户消息准入前绑定适配器;在任一阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求;重试复用路由、工具与组装结果。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 循环发送不可变请求,同时保持取消有效,仅对完全冻结的对象复用冻结证据;[agent-loop](../packages/core/agent-loop/README.zh.md) 负责请求构建与取消原因。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 4a9002931c..0ded8ddc8d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4156,7 +4156,7 @@ export interface Config { ## `@deepseek-ai/dsh-tools` - `inject`: `systemPrompt` -- `source`: [`packages/core/tools/src/index.ts:733`](../packages/core/tools/src/index.ts) +- `source`: [`packages/core/tools/src/index.ts:735`](../packages/core/tools/src/index.ts) ```ts config-catalog /** Plugin config: how the registered tools are presented to the model. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index e789beb09a..fadc850142 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4158,7 +4158,7 @@ export interface Config { ## `@deepseek-ai/dsh-tools` - `inject`: `systemPrompt` -- `source`: [`packages/core/tools/src/index.ts:733`](../packages/core/tools/src/index.ts) +- `source`: [`packages/core/tools/src/index.ts:735`](../packages/core/tools/src/index.ts) ```ts config-catalog /** Plugin config: how the registered tools are presented to the model. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index fd864d5b9b..a7736702b5 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -10,18 +10,19 @@ 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:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:369`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:267`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:276`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:305`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:313`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:294`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:326`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:343`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:286`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:387`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:271`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:424`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:298`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:331`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:368`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:384`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/route` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:347`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | +| `agent/status` | `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), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:412`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../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 7af06b1e0d..e5dc43c2b2 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -12,18 +12,19 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:369`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:267`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:276`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:305`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:313`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:294`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:326`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:343`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:286`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:387`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:271`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:424`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:298`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:331`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:368`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:384`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/route` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:347`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | +| `agent/status` | `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), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:412`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../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 28e7572580..3083265631 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1239,8 +1239,8 @@ en: f43a635a14568780 zh: 8d22226b045122eb /session-persistence-event-catalog/resolved-persistence-types/toolrestriction: - en: 739d19df365ed5df - zh: b1e41e56995fe238 + en: 0a56a07b1de985b4 + zh: 886c512054d12ad6 /session-persistence-event-catalog/resolved-persistence-types/toolresultmessage: en: 2258683c3cfa4ce3 zh: 5663aa76c911761b diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 4f32309d94..400ddd5a60 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -4996,7 +4996,7 @@ Sources: [`packages/llm/llm/src/types.ts:127`](../packages/llm/llm/src/types.ts) SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -Sources: [`packages/core/tools/src/index.ts:759`](../packages/core/tools/src/index.ts) +Sources: [`packages/core/tools/src/index.ts:761`](../packages/core/tools/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index ac0e952854..089ffbe0de 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -4998,7 +4998,7 @@ SHA-256: `43e311235aa537df1bacdd92d144df8a952337a76e9ac892cdf670f1a797bad8` SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -来源:[`packages/core/tools/src/index.ts:759`](../packages/core/tools/src/index.ts) +来源:[`packages/core/tools/src/index.ts:761`](../packages/core/tools/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index d574506b4f..69a4707e93 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -22908,7 +22908,7 @@ "packages/core/tools/src/index.ts#ToolRestriction" ], "sources": [ - "packages/core/tools/src/index.ts:759" + "packages/core/tools/src/index.ts:761" ] }, { diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 94bed76054..3111071a28 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -12,14 +12,14 @@ en: ab09a38b4e1f0883 zh: 81e2d14c4036ab6c /core/the-agent-handle: - en: c21787347d8e2b14 - zh: 25bc9cb60ee1520a + en: 100e13484382eb7a + zh: 6481f8d4f84fc93a /core/initiating-agent: en: 6c8c47ac78de2dde zh: c9d527a25a85d1d9 /core/interception-decisions: - en: 6fccceb0a5f1cad9 - zh: f43c30c2386d8cc8 + en: f4fdc520107dd17b + zh: a9b2f55e50b6279f /core/sessions: en: 9a38f693a00fa80d zh: d0f66664ac85ae64 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 63a1829890..c045e95349 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -61,14 +61,8 @@ Source: [`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types interface Agent { /** Session-backed Agent identity. */ readonly id: SessionId - /** Initial request options; currentRoute() reports the bound request route. */ + /** Creation-time request options; `agent/route` may choose another provider and model for each step. */ readonly options: AgentOptions - /** - * Read the immutable route bound to this request and its tool batch. - * @returns the actual provider and model selected by prepareCall(). - * @throws when no main request is prepared; never falls back to prior requests. - */ - currentRoute(): Readonly> /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -212,7 +206,19 @@ interface AgentOptions { } ``` -Dispatch requires `provider` and `model` after `agent/request`. An explicit `reasoningEffort` seeds the first request on that route; exact-model resolution validates it, while omission allows the adapter default to materialize. When present, `maxTokens` must be a positive safe integer and caps every conversation-model request; omission allows the exact-model adapter default to materialize before the request header, or otherwise leaves provider behavior unchanged. An agent-scoped `deployment:persona-prefix` prompt section may shadow the global default persona. +Each step requires `provider` and `model` after `agent/route`, which may supply or replace the options pair. An explicit `reasoningEffort` seeds the first request on that route; exact-model resolution validates it, while omission allows the adapter default to materialize. When present, `maxTokens` must be a positive safe integer and caps every conversation-model request; omission allows the exact-model adapter default to materialize before the request header, or otherwise leaves provider behavior unchanged. An agent-scoped `deployment:persona-prefix` prompt section may shadow the global default persona. + +The step keeps the chosen route for prompt preparation, `agent/pre-step`, tool conditions, and every request attempt; `agent/request` may change only call controls: + +```ts type-equiv +/** Provider and model that `agent/route` chose for one step and every request attempt in it. */ +interface StepRoute { + /** Registered provider route. */ + readonly provider: string + /** Model id interpreted by the provider adapter. */ + readonly model: string +} +``` The inbox is the delivery vocabulary — two ordered pending-message lists the agent owns as a durable projection: @@ -317,7 +323,7 @@ Pre-step decisions use the same identified `UserMessage` type as durable user-ro Source: [`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts) -`agent/pre-step` receives one payload carrying the exclusive claimed batch (`messages`), the proposed step's coordinates (`turn`, `step`), and the current turn's cancellation `signal`. The initial proposal runs inside an open turn before any step; a tool continuation may submit an empty claimed batch between steps: +`agent/pre-step` receives one payload carrying the exclusive claimed batch (`messages`), the proposed step's coordinates (`turn`, `step`), its `route`, and the current turn's cancellation `signal`. The initial proposal runs inside an open turn before any step; a tool continuation may submit an empty claimed batch between steps: It returns a `PreStepDecision`. Reject opens no step. Enter supplies the complete message batch appended after `step/start`; claimed messages omitted by the final decision remain removed, while input inserted after the claim stays pending: @@ -945,11 +951,12 @@ Reject a proposed step or replace the messages that enter it. Calling `next()` p * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. + * @param payload.route - the provider and model `agent/route` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise +'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; route: StepRoute; signal: AbortSignal }, next: () => Promise): Promise ``` Types: [Scoped](scope.md) · [UserMessage](session.md) @@ -960,18 +967,22 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/request` — waterfall -Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs before context preparation and `agent/pre-step`. Cancellation here or during subsequent `prepareCall()` resolution opens no step and commits no system prompt or user batch. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. +Replace the frozen call configuration of one request attempt. `await next()` yields the config the machine would use on the step's `agent/route` result: agent options on the first request, the logged header afterwards, and no effort recorded for another model. Return a replacement to change call controls such as reasoning effort; returning another provider or model fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. ```ts cordis-catalog /** - * Replace the frozen call configuration. `await next()` yields the config - * the machine would use (agent options on the first request, the logged - * header afterwards); return a replacement to switch. On step admission, - * this runs before context preparation and `agent/pre-step`. Cancellation - * here or during subsequent `prepareCall()` resolution opens no step and - * commits no system prompt or user batch. The prepared call capability - * governs prompt admission. Model-visible content must use logged channels; - * this waterfall cannot mutate messages. + * Replace the frozen call configuration of one request attempt. `await + * next()` yields the config the machine would use on the step's + * `agent/route` result: agent options on the first request, the logged + * header afterwards, and no effort recorded for another model. Return a + * replacement to change call controls such as reasoning effort; returning + * another provider or model fails the step. On step admission, this runs + * after prompt assembly and `step/start`, before the system prompt and + * accepted user batch are committed, and again for each retry. + * Cancellation here or during subsequent `prepareCall()` resolution + * commits neither. The prepared call capability governs prompt admission. + * Model-visible content must use logged channels; this waterfall cannot + * mutate messages. * @param payload.agent - the agent making the model call. * @param payload.turn - the open turn number. * @param payload.step - the step whose request this is. @@ -1015,6 +1026,35 @@ Types: [LlmFailure](llm-streaming.md) · [ResolvedRetryPolicy](llm-streaming.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + + +#### `agent/route` — waterfall + +Choose the provider and model for one proposed step. `await next()` yields the route the machine would use (agent options before this loop logs a request, the logged header afterwards); return a replacement to switch. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step. + +```ts cordis-catalog +/** + * Choose the provider and model for one proposed step. `await next()` + * yields the route the machine would use (agent options before this loop + * logs a request, the logged header afterwards); return a replacement to + * switch. The loop runs this once per proposed step, before context + * preparation and `agent/pre-step`. Prompt preparation, tool conditions, + * and every request attempt in the step use the result, so a later choice + * applies from the next step. Cancellation here opens no step. + * @param payload.agent - the agent proposing the step. + * @param payload.turn - the turn that will own the step. + * @param payload.step - the step proposed by the loop. + * @param payload.signal - the current turn's explicit abort signal. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode waterfall + */ +'agent/route'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise +``` + +Types: [Scoped](scope.md) + +Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + #### `agent/status` — emit diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index d1eb48008a..96d65b5140 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -65,14 +65,8 @@ interface AgentHandle { interface Agent { /** Session-backed Agent identity. */ readonly id: SessionId - /** Initial request options; currentRoute() reports the bound request route. */ + /** Creation-time request options; `agent/route` may choose another provider and model for each step. */ readonly options: AgentOptions - /** - * Read the immutable route bound to this request and its tool batch. - * @returns the actual provider and model selected by prepareCall(). - * @throws when no main request is prepared; never falls back to prior requests. - */ - currentRoute(): Readonly> /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -216,7 +210,19 @@ interface AgentOptions { } ``` -在 `agent/request` 之后,分发要求 `provider` 与 `model` 都存在。显式 `reasoningEffort` 会为该路由的首次请求提供初始值;确切模型解析会校验该值,省略时则允许填入适配器默认值。提供 `maxTokens` 时,它必须是正安全整数,并限制每次对话模型请求的输出;省略时,系统会在写入请求 header 前填入确切模型的适配器默认值,否则提供方行为保持不变。agent 作用域的 `deployment:persona-prefix` 提示词段落可以遮蔽全局默认 persona。 +每个步骤在 `agent/route` 之后都要求 `provider` 与 `model` 都存在;该 waterfall 可以补上或替换 options 中的这一对值。显式 `reasoningEffort` 会为该路由的首次请求提供初始值;确切模型解析会校验该值,省略时则允许填入适配器默认值。提供 `maxTokens` 时,它必须是正安全整数,并限制每次对话模型请求的输出;省略时,系统会在写入请求 header 前填入确切模型的适配器默认值,否则提供方行为保持不变。agent 作用域的 `deployment:persona-prefix` 提示词段落可以遮蔽全局默认 persona。 + +步骤在提示词准备、`agent/pre-step`、工具条件以及每次请求尝试中都沿用所选路由;`agent/request` 只能修改调用控制参数: + +```ts type-equiv +/** Provider and model that `agent/route` chose for one step and every request attempt in it. */ +interface StepRoute { + /** Registered provider route. */ + readonly provider: string + /** Model id interpreted by the provider adapter. */ + readonly model: string +} +``` inbox 即投递词汇——agent 以持久投影形式拥有的两条有序待处理消息列表: @@ -325,7 +331,7 @@ pre-step 决策使用与持久 user-role 输入相同、带标识的 `UserMessag 源码:[`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts) -`agent/pre-step` 接收一个 payload,携带独占的已领取批次(`messages`)、拟进入步骤的坐标(`turn`、`step`)与当前轮次的取消 `signal`。首次提案在已打开的轮次内、任何步骤开始前运行;工具 continuation 可以在步骤之间提交空的已领取批次: +`agent/pre-step` 接收一个 payload,携带独占的已领取批次(`messages`)、拟进入步骤的坐标(`turn`、`step`)、其路由 `route` 与当前轮次的取消 `signal`。首次提案在已打开的轮次内、任何步骤开始前运行;工具 continuation 可以在步骤之间提交空的已领取批次: 它返回 `PreStepDecision`。reject 不会打开步骤。enter 提供在 `step/start` 后追加的完整消息批次;最终决策省略的已领取消息保持已删除,而领取后插入的输入仍留待后续处理: @@ -957,11 +963,12 @@ Reject a proposed step or replace the messages that enter it. Calling `next()` p * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. + * @param payload.route - the provider and model `agent/route` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise +'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; route: StepRoute; signal: AbortSignal }, next: () => Promise): Promise ``` Types: [Scoped](scope.zh.md) · [UserMessage](session.zh.md) @@ -972,18 +979,22 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/request` — waterfall -Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs before context preparation and `agent/pre-step`. Cancellation here or during subsequent `prepareCall()` resolution opens no step and commits no system prompt or user batch. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. +Replace the frozen call configuration of one request attempt. `await next()` yields the config the machine would use on the step's `agent/route` result: agent options on the first request, the logged header afterwards, and no effort recorded for another model. Return a replacement to change call controls such as reasoning effort; returning another provider or model fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. ```ts cordis-catalog /** - * Replace the frozen call configuration. `await next()` yields the config - * the machine would use (agent options on the first request, the logged - * header afterwards); return a replacement to switch. On step admission, - * this runs before context preparation and `agent/pre-step`. Cancellation - * here or during subsequent `prepareCall()` resolution opens no step and - * commits no system prompt or user batch. The prepared call capability - * governs prompt admission. Model-visible content must use logged channels; - * this waterfall cannot mutate messages. + * Replace the frozen call configuration of one request attempt. `await + * next()` yields the config the machine would use on the step's + * `agent/route` result: agent options on the first request, the logged + * header afterwards, and no effort recorded for another model. Return a + * replacement to change call controls such as reasoning effort; returning + * another provider or model fails the step. On step admission, this runs + * after prompt assembly and `step/start`, before the system prompt and + * accepted user batch are committed, and again for each retry. + * Cancellation here or during subsequent `prepareCall()` resolution + * commits neither. The prepared call capability governs prompt admission. + * Model-visible content must use logged channels; this waterfall cannot + * mutate messages. * @param payload.agent - the agent making the model call. * @param payload.turn - the open turn number. * @param payload.step - the step whose request this is. @@ -1027,6 +1038,35 @@ Types: [LlmFailure](llm-streaming.zh.md) · [ResolvedRetryPolicy](llm-streaming. Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + + +#### `agent/route` — waterfall + +Choose the provider and model for one proposed step. `await next()` yields the route the machine would use (agent options before this loop logs a request, the logged header afterwards); return a replacement to switch. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step. + +```ts cordis-catalog +/** + * Choose the provider and model for one proposed step. `await next()` + * yields the route the machine would use (agent options before this loop + * logs a request, the logged header afterwards); return a replacement to + * switch. The loop runs this once per proposed step, before context + * preparation and `agent/pre-step`. Prompt preparation, tool conditions, + * and every request attempt in the step use the result, so a later choice + * applies from the next step. Cancellation here opens no step. + * @param payload.agent - the agent proposing the step. + * @param payload.turn - the turn that will own the step. + * @param payload.step - the step proposed by the loop. + * @param payload.signal - the current turn's explicit abort signal. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode waterfall + */ +'agent/route'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise +``` + +Types: [Scoped](scope.zh.md) + +Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + #### `agent/status` — emit diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index c5426ddc70..433c358122 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -39,8 +39,8 @@ en: 824d18f76f990711 zh: 8a2895513652e528 /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: - en: f2e6932e211f179b - zh: 75112586a6f3f4aa + en: 2c0198b61bf68192 + zh: d1380ba0acea3ee2 /llm-streaming/official-deepseek-request-extensions: en: 42bc50394b070e96 zh: 007caa743ec3c790 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 4936ba4ae8..8844d5ba3b 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -738,7 +738,7 @@ interface LlmDiscoveredModel { The loop builds each request from logged state. `EpochHeader` records call config, marks the fields supplied by adapter defaults, and records the authoritative returned tool order (configured by `toolOrder`, or lexicographic when unset) through full `request/header` snapshots. The rendered prompt is derived history — the `system/message` at surface node 0, plus any later system node an `in-history` route appended — so the header and the derived history together make the request reconstructable from the session log. See [session.md](session.md#the-request-header-event-requestheader) and the [reconstructability Agent Note](../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md). -`agent/request` receives a frozen call-config seed and may return a replacement to switch provider, model, reasoning effort, or sampling. Before the waterfall, the loop removes values marked as adapter defaults so exact-model preparation materializes the selected route's current values; unmarked explicit settings remain in the proposal. After the waterfall, preparation rejects unsupported explicit effort ids without clamping and logs the effective config plus the fields supplied by adapter defaults under the turn signal. On step admission, this waterfall and preparation run after assembly and `step/start` but before the system prompt and accepted user batch are committed; cancellation during either commits neither. The prepared capability governs prompt reconciliation, and the call keeps one adapter registration through dispatch. Requests reaching `llm/stream` are deep-frozen, so mutation throws, and carry a process-local loop identity so observers do not confuse separately logged frozen auxiliary calls with conversation requests. +`agent/request` receives a frozen call-config seed and may return a replacement to change reasoning effort or sampling; provider and model come from `agent/route` and stay fixed for the step. Before the waterfall, the loop removes values marked as adapter defaults so exact-model preparation materializes the selected route's current values; unmarked explicit settings remain in the proposal. After the waterfall, preparation rejects unsupported explicit effort ids without clamping and logs the effective config plus the fields supplied by adapter defaults under the turn signal. On step admission, this waterfall and preparation run after assembly and `step/start` but before the system prompt and accepted user batch are committed; cancellation during either commits neither. The prepared capability governs prompt reconciliation, and the call keeps one adapter registration through dispatch. Requests reaching `llm/stream` are deep-frozen, so mutation throws, and carry a process-local loop identity so observers do not confuse separately logged frozen auxiliary calls with conversation requests. On the wire, a loop-built request is the derived history alone: the rendered prompt travels as the leading `system`-role message (surface node 0, a `system/message` event) and, when the prepared call declares `systemPromptUpdate: 'in-history'`, a non-empty changed prompt may follow the cached history as a later `system`-role message that the model reads as the effective prompt; the request's `system` field is unset — `GenerateOptions.system` serves direct one-shot callers such as title providers. An empty rendering leaves no system messages in derived history, even when earlier requests retained several prompt versions. The logged request ends with the newest `user/message` on a turn's first step and the previous step's tool results on later steps. diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 47d7c0df31..500ca3f70e 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -744,7 +744,7 @@ interface LlmDiscoveredModel { 循环从已记录状态构建每个请求。`EpochHeader` 记录调用配置,标记由适配器默认值提供的字段,并通过完整的 `request/header` 快照记录权威返回工具顺序(由 `toolOrder` 配置;未配置时按字典序)。渲染后的提示词是派生历史——surface 第 0 号节点上的 `system/message`,加上 `in-history` 路由追加的任何后续系统节点——因此请求头与派生历史共同使请求可由会话日志重建。见 [session.md](session.zh.md#the-request-header-event-requestheader) 与[可重建性 Agent Note](../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md)。 -`agent/request` 接收冻结的调用配置种子,并可返回替代值以切换提供方、模型、推理强度或采样参数。waterfall(瀑布式事件)开始前,循环会移除标记为适配器默认值的值,使确切模型准备过程填入所选路由的当前值;未带标记的显式设置仍保留在提议中。waterfall 结束后,准备过程会在轮次信号控制下拒绝显式指定但不受支持的推理强度 ID(不自动调整),并记录生效配置以及由适配器默认值提供的字段。步骤准入时,该 waterfall 与准备过程在组装和 `step/start` 之后、系统提示词与已接纳用户批次提交之前运行;在任一阶段取消都不会提交这两者。已准备调用的能力决定提示词协调,调用直至分派完成始终持有同一项适配器注册。到达 `llm/stream` 的请求会被深度冻结,因此变更会抛异常;请求还携带进程本地循环标识,使观察者不会把单独记录的冻结辅助调用误认成对话请求。 +`agent/request` 接收冻结的调用配置种子,并可返回替代值以修改推理强度或采样参数;提供方与模型来自 `agent/route`,在整个步骤内保持不变。waterfall(瀑布式事件)开始前,循环会移除标记为适配器默认值的值,使确切模型准备过程填入所选路由的当前值;未带标记的显式设置仍保留在提议中。waterfall 结束后,准备过程会在轮次信号控制下拒绝显式指定但不受支持的推理强度 ID(不自动调整),并记录生效配置以及由适配器默认值提供的字段。步骤准入时,该 waterfall 与准备过程在组装和 `step/start` 之后、系统提示词与已接纳用户批次提交之前运行;在任一阶段取消都不会提交这两者。已准备调用的能力决定提示词协调,调用直至分派完成始终持有同一项适配器注册。到达 `llm/stream` 的请求会被深度冻结,因此变更会抛异常;请求还携带进程本地循环标识,使观察者不会把单独记录的冻结辅助调用误认成对话请求。 在协议中,循环构建的请求只有派生历史:渲染后的提示词作为开头的 `system` 角色消息(surface 第 0 号节点,即一个 `system/message` 事件)传输,并且当已准备调用声明 `systemPromptUpdate: 'in-history'` 时,变化后的非空提示词可以作为后续的 `system` 角色消息跟在已缓存历史之后,由模型读作有效提示词;请求的 `system` 字段不设置——`GenerateOptions.system` 服务于标题提供方等直接单次调用方。空渲染文本使派生历史不包含任何系统消息,即使先前请求保留了多个提示词版本。已记录的请求会以最新的 `user/message`(轮次首步)或上一步的工具结果(后续步骤)结尾。 diff --git a/docs/subsystems/session-reference.md b/docs/subsystems/session-reference.md index a2567a6cc3..6a41f8dd3b 100644 --- a/docs/subsystems/session-reference.md +++ b/docs/subsystems/session-reference.md @@ -205,7 +205,7 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the last assembled route, or agent options before any assembly. + * Automatic budgets use the step route, or agent options for direct preparation. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -213,12 +213,13 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. + * @param route - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ -async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, ): Promise +async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, route?: StepRoute, ): Promise ``` -Types: [Agent](core.md) · [ContentBlock](llm-streaming.md) +Types: [Agent](core.md) · [ContentBlock](llm-streaming.md) · [StepRoute](core.md) Source: [`packages/context/session-reference/src/index.ts`](../../packages/context/session-reference/src/index.ts) diff --git a/docs/subsystems/session-reference.zh.md b/docs/subsystems/session-reference.zh.md index 43cd567aaa..79fbef73ee 100644 --- a/docs/subsystems/session-reference.zh.md +++ b/docs/subsystems/session-reference.zh.md @@ -205,7 +205,7 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the last assembled route, or agent options before any assembly. + * Automatic budgets use the step route, or agent options for direct preparation. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -213,12 +213,13 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. + * @param route - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ -async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, ): Promise +async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, route?: StepRoute, ): Promise ``` -Types: [Agent](core.zh.md) · [ContentBlock](llm-streaming.zh.md) +Types: [Agent](core.zh.md) · [ContentBlock](llm-streaming.zh.md) · [StepRoute](core.zh.md) Source: [`packages/context/session-reference/src/index.ts`](../../packages/context/session-reference/src/index.ts) diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index c9e0a46a73..25eba3d259 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -206,7 +206,7 @@ interface ToolExecutionInput { readonly arguments: unknown /** The agent on whose behalf the call runs (set by the agent loop). */ readonly agent?: Agent - /** Request admission shared by Native and PTC dispatch. Conditional tools require it. */ + /** Step admission shared by Native and PTC dispatch. Conditional tools require it. */ readonly toolSet?: ResolvedToolSet /** * Opaque token of the enclosing transport execution, when one exists. PTC @@ -527,7 +527,7 @@ presentAs(mode: ToolPresentationMode): () => void * Register globally or in the calling agent scope. Scoped tools shadow * globals; duplicates within one layer and the reserved `run_code` name fail. * @param definition - tool schema, execution, and optional finalization/presentation callbacks. - * @param options - optional request-time activation condition. + * @param options - optional step-time activation condition. * @returns the exact disposer that unregisters the tool. */ register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void @@ -560,16 +560,16 @@ guard(guard: ToolGuard): () => void * actually executed. * @param name - the tool name as registered. * @param scope - the viewing scope (the agent); omitted = the global view. - * @param toolSet - request admission; omit only to inspect registered definitions. + * @param toolSet - step admission; omit only to inspect registered definitions. * @returns the definition the scope resolves, or undefined when none is visible. */ get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined /** - * Resolve conditions once for this request without changing shared registrations. + * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - agent with a bound route and request cancellation. + * @param context - preparing agent, step route, and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise @@ -578,7 +578,7 @@ async resolve(context: ToolActivationContext): Promise * Project visible definitions onto the allowlisted model-facing schema fields, * excluding execution and presentation callbacks. * @param scope - the viewing scope (the agent); omitted = the global view. - * @param toolSet - request admission, or omitted for registered-definition inspection. + * @param toolSet - step admission, or omitted for registered-definition inspection. * @returns one deep-cloned schema per visible tool. */ schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[] diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 81a1408320..999f3f4875 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -206,7 +206,7 @@ interface ToolExecutionInput { readonly arguments: unknown /** The agent on whose behalf the call runs (set by the agent loop). */ readonly agent?: Agent - /** Request admission shared by Native and PTC dispatch. Conditional tools require it. */ + /** Step admission shared by Native and PTC dispatch. Conditional tools require it. */ readonly toolSet?: ResolvedToolSet /** * Opaque token of the enclosing transport execution, when one exists. PTC @@ -527,7 +527,7 @@ presentAs(mode: ToolPresentationMode): () => void * Register globally or in the calling agent scope. Scoped tools shadow * globals; duplicates within one layer and the reserved `run_code` name fail. * @param definition - tool schema, execution, and optional finalization/presentation callbacks. - * @param options - optional request-time activation condition. + * @param options - optional step-time activation condition. * @returns the exact disposer that unregisters the tool. */ register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void @@ -560,16 +560,16 @@ guard(guard: ToolGuard): () => void * actually executed. * @param name - the tool name as registered. * @param scope - the viewing scope (the agent); omitted = the global view. - * @param toolSet - request admission; omit only to inspect registered definitions. + * @param toolSet - step admission; omit only to inspect registered definitions. * @returns the definition the scope resolves, or undefined when none is visible. */ get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined /** - * Resolve conditions once for this request without changing shared registrations. + * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - agent with a bound route and request cancellation. + * @param context - preparing agent, step route, and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise @@ -578,7 +578,7 @@ async resolve(context: ToolActivationContext): Promise * Project visible definitions onto the allowlisted model-facing schema fields, * excluding execution and presentation callbacks. * @param scope - the viewing scope (the agent); omitted = the global view. - * @param toolSet - request admission, or omitted for registered-definition inspection. + * @param toolSet - step admission, or omitted for registered-definition inspection. * @returns one deep-cloned schema per visible tool. */ schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[] diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml index 9082916a9b..de2bf1983b 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md /: - en: 0a9569f33806d6bf - zh: 3bd885a0d518aad8 -/update-conditional-tools-and-prompt-hooks: - en: 10c4bc2bc9693697 - zh: e21505b305265c99 -/update-conditional-tools-and-prompt-hooks/change: - en: 018c4ade3568fbc5 - zh: e2f0f9c1467250be -/update-conditional-tools-and-prompt-hooks/migration: - en: abe994f27c41f65e - zh: 106d04a591a0faa2 + en: a6fa0b92ad5adce4 + zh: 743795b5e3985faf +/update-step-routing-conditional-tools-and-prompt-hooks: + en: 7f578f5ad4a1406b + zh: 9b5984f46d7ae7b4 +/update-step-routing-conditional-tools-and-prompt-hooks/change: + en: a914aff13f6391ff + zh: b8a9dfaeaaa7d76f +/update-step-routing-conditional-tools-and-prompt-hooks/migration: + en: bdb131c08b81d7ec + zh: e76b53840dc3bd8a diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md index b9cc48a160..3cce69c4aa 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md @@ -1,21 +1,24 @@ --- kind: upgrade-guide -description: "Custom tool and prompt plugins must use request-owned tool admission and the earlier route preparation stage." +description: "Step routing moves from `agent/request` to `agent/route`, and custom tool and prompt plugins must use step-owned tool admission." --- -# Update conditional tools and prompt hooks +# Update step routing, conditional tools, and prompt hooks English | [中文](guide.zh.md) ## Change -`agent/request` and `prepareCall()` bind the route before `agent/pre-step`. Runtime context preparation uses `system-prompt/prepare`; `system-prompt/assemble` receives presentation fields without a tool array. Tool declarations remain owned by registered providers. Conditional tools require a resolved request set for execution, including nested PTC calls. Replacing a registration does not authorize an outstanding call to run the replacement. +`agent/route` chooses each step's provider and model before `system-prompt/prepare` and `agent/pre-step`. Prompt preparation, `agent/pre-step` through its new `route` payload field, tool conditions, and every request attempt in the step use that route. `agent/request` still runs for each attempt after prompt assembly and `step/start`, but it may change only call controls such as `reasoningEffort`; returning another provider or model fails the step. An agent without an options route must receive one from `agent/route`. Plugins that replaced the provider or model in `agent/request`, including on a retry, are affected. + +Runtime context preparation uses `system-prompt/prepare`; `system-prompt/assemble` receives presentation fields without a tool array. Tool declarations remain owned by registered providers. Conditional tools require a resolved step set for execution, including nested PTC calls. Replacing a registration does not authorize an outstanding call to run the replacement. `exit_plan_mode` is offered only while committed plan mode is active. A failed plan-state write stops step admission and keeps the pending selection. Existing Sessions require no format migration. ## Migration -1. Declare tool conditions with `ctx.tools.register(definition, { when })`. Read the bound route through `agent.currentRoute()`; never infer it from initial options or the preceding Session header. -2. Move runtime-context preparation listeners to `system-prompt/prepare`. Keep presentation changes in `system-prompt/assemble` and stop replacing its tool list. -3. For programmatic conditional calls, resolve `{ agent, signal }` through `ctx.tools.resolve()`, pass the resulting `toolSet` to assembly and execution, and dispose it after the batch settles. AgentLoop does this for model calls. Pass `context.toolSet` when tool guidance queries `ctx.tools.get()` or `schemas()`. -4. Update custom Agent implementations with `currentRoute()`, valid only while a main request is bound. Verify that inactive tools are absent from declarations and that a historical name returns `UNKNOWN_TOOL` without reaching the implementation. +1. Move provider and model replacement from `agent/request` listeners to `agent/route` listeners that return `{ provider, model }`; keep only control changes in `agent/request`. Read the route from `payload.route` in `agent/pre-step` and from `AssembleContext.route` in prompt providers. +2. Declare tool conditions with `ctx.tools.register(definition, { when })`; the condition receives `{ agent, route, signal }`. +3. Move runtime-context preparation listeners to `system-prompt/prepare`. Keep presentation changes in `system-prompt/assemble` and stop replacing its tool list. +4. For programmatic conditional calls, resolve `{ agent, route, signal }` through `ctx.tools.resolve()`, pass the resulting `toolSet` to assembly and execution, and dispose it after the batch settles. AgentLoop does this once per step for model calls. Pass `context.toolSet` when tool guidance queries `ctx.tools.get()` or `schemas()`. +5. Add `route` to `agent/pre-step` payloads that tests dispatch directly. Verify that inactive tools are absent from declarations, that a historical name returns `UNKNOWN_TOOL` without reaching the implementation, and that an `agent/request` listener changing the model ends the turn with an error naming `agent/route`. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md index 1d4b35bca4..20db035c69 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md @@ -1,21 +1,24 @@ --- kind: upgrade-guide -description: "自定义工具和提示词插件必须使用请求拥有的工具准入集合以及提前的路由准备阶段。" +description: "步骤路由选择从 `agent/request` 移到 `agent/route`,自定义工具和提示词插件必须使用步骤拥有的工具准入集合。" --- -# 更新条件工具与提示词钩子 +# 更新步骤路由、条件工具与提示词钩子 [English](guide.md) | 中文 ## 变更 -`agent/request` 与 `prepareCall()` 在 `agent/pre-step` 之前绑定路由。运行时上下文准备使用 `system-prompt/prepare`;`system-prompt/assemble` 接收不含工具数组的展示字段。工具声明仍由已注册提供方持有。条件工具执行需要已解析的请求集合,包括嵌套 PTC 调用。替换注册不会授权尚未执行的旧调用使用新实现。 +`agent/route` 在 `system-prompt/prepare` 与 `agent/pre-step` 之前选定每个步骤的提供方与模型。提示词准备、`agent/pre-step`(通过新增的 payload 字段 `route`)、工具条件以及该步骤的每次请求尝试都使用这一路由。`agent/request` 仍在提示词组装与 `step/start` 之后为每次尝试运行,但只能修改 `reasoningEffort` 等调用控制参数;返回其他提供方或模型会使步骤失败。options 中没有路由的 agent 必须由 `agent/route` 提供路由。在 `agent/request` 中替换提供方或模型的插件(包括在重试时替换的插件)会受到影响。 + +运行时上下文准备使用 `system-prompt/prepare`;`system-prompt/assemble` 接收不含工具数组的展示字段。工具声明仍由已注册提供方持有。条件工具执行需要已解析的步骤集合,包括嵌套 PTC 调用。替换注册不会授权尚未执行的旧调用使用新实现。 `exit_plan_mode` 只在已提交的计划模式启用时提供。计划状态写入失败会停止步骤接纳并保留待提交选择。现有 Session 无需格式迁移。 ## 迁移 -1. 使用 `ctx.tools.register(definition, { when })` 声明工具条件。通过 `agent.currentRoute()` 读取已绑定路由,不从初始选项或先前 Session 请求头推断。 -2. 将运行时上下文准备监听器迁移到 `system-prompt/prepare`。展示变更留在 `system-prompt/assemble`,停止替换它的工具列表。 -3. 程序化调用条件工具时,通过 `ctx.tools.resolve()` 解析 `{ agent, signal }`,将返回的 `toolSet` 传给组装与执行,并在批次结束后释放。AgentLoop 会为模型调用完成这些操作。工具指导查询 `ctx.tools.get()` 或 `schemas()` 时传入 `context.toolSet`。 -4. 为自定义 Agent 实现补充 `currentRoute()`,仅在主请求已绑定期间可用。验证未启用工具不出现在声明中,且使用历史名称调用会返回 `UNKNOWN_TOOL`,不会进入实现。 +1. 把 `agent/request` 监听器中的提供方与模型替换移到返回 `{ provider, model }` 的 `agent/route` 监听器;`agent/request` 只保留调用控制参数的修改。在 `agent/pre-step` 中从 `payload.route` 读取路由,在提示词提供方中从 `AssembleContext.route` 读取路由。 +2. 使用 `ctx.tools.register(definition, { when })` 声明工具条件;条件接收 `{ agent, route, signal }`。 +3. 将运行时上下文准备监听器迁移到 `system-prompt/prepare`。展示变更留在 `system-prompt/assemble`,停止替换它的工具列表。 +4. 程序化调用条件工具时,通过 `ctx.tools.resolve()` 解析 `{ agent, route, signal }`,将返回的 `toolSet` 传给组装与执行,并在批次结束后释放。AgentLoop 会为模型调用在每个步骤完成一次这些操作。工具指导查询 `ctx.tools.get()` 或 `schemas()` 时传入 `context.toolSet`。 +5. 为测试直接派发的 `agent/pre-step` payload 补上 `route`。验证未启用工具不出现在声明中,使用历史名称调用会返回 `UNKNOWN_TOOL` 且不会进入实现,并验证修改模型的 `agent/request` 监听器会让轮次以指向 `agent/route` 的错误结束。 diff --git a/packages/acp/acp/README.i18n.yaml b/packages/acp/acp/README.i18n.yaml index 68c18de182..8be465f41a 100644 --- a/packages/acp/acp/README.i18n.yaml +++ b/packages/acp/acp/README.i18n.yaml @@ -21,8 +21,8 @@ en: c3f5f144daf83157 zh: a65a64842fd35bef /deepseek-ai-dsh-acp/use-this-package/minimal-configuration: - en: 320139cc5ebcf34a - zh: 89beb58d9a0511ba + en: 21dac29aadc0fc57 + zh: 6d2110787c034f8e /deepseek-ai-dsh-acp/use-this-package/start-a-server: en: 4ed8e37834267edb zh: a32d5dedb4e8e919 diff --git a/packages/acp/acp/README.md b/packages/acp/acp/README.md index fa713b872f..fdde64b680 100644 --- a/packages/acp/acp/README.md +++ b/packages/acp/acp/README.md @@ -33,7 +33,7 @@ Choose it when automation should own the interaction: an out-of-process subagent ### Minimal configuration -Every session the server creates uses the provider and model configured here. Both fields are optional so another agent or request listener can supply them; the runnable demo composition sets both. Stdout carries only protocol traffic, so keep logging off it. +Every session the server creates uses the provider and model configured here. Both fields are optional so an `agent/route` listener can supply them; the runnable demo composition sets both. Stdout carries only protocol traffic, so keep logging off it. ```yaml - name: '@deepseek-ai/dsh-acp' diff --git a/packages/acp/acp/README.zh.md b/packages/acp/acp/README.zh.md index e62e154191..33d5ee9b03 100644 --- a/packages/acp/acp/README.zh.md +++ b/packages/acp/acp/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" ### 最小配置 -服务器创建的每个会话都使用此处配置的提供方与模型。两个字段都是可选的,以便由另一个 agent/request 监听器提供;可运行的演示组合会同时设置两者。Stdout 只承载协议流量,因此请让日志远离它。 +服务器创建的每个会话都使用此处配置的提供方与模型。两个字段都是可选的,以便由 `agent/route` 监听器提供;可运行的演示组合会同时设置两者。Stdout 只承载协议流量,因此请让日志远离它。 ```yaml - name: '@deepseek-ai/dsh-acp' diff --git a/packages/acp/acp/src/model-control.ts b/packages/acp/acp/src/model-control.ts index 9138bcdcd7..00860475a0 100644 --- a/packages/acp/acp/src/model-control.ts +++ b/packages/acp/acp/src/model-control.ts @@ -30,7 +30,7 @@ export class AcpModelConfigError extends Error { /** Project and mutate one Agent's provider/model/reasoning selection through ACP config options. */ export class AcpModelControl { - /** Scoped selection reference consumed by Agent request assembly. */ + /** Scoped selection reference consumed by Agent step routing. */ readonly selection: ModelSelectionRef private tail = Promise.resolve() private selected: ModelSelection | undefined @@ -52,7 +52,7 @@ export class AcpModelControl { } /** - * Install request/prompt consistency listeners in the unpublished Agent scope. + * Install step routing listeners in the unpublished Agent scope. * @param agentCtx - Agent scope that consumes this selection. */ install(agentCtx: Context): void { diff --git a/packages/acp/acp/tests/bridge.spec.ts b/packages/acp/acp/tests/bridge.spec.ts index c0f5d73f89..1356e32efb 100644 --- a/packages/acp/acp/tests/bridge.spec.ts +++ b/packages/acp/acp/tests/bridge.spec.ts @@ -834,12 +834,12 @@ describe('automation-only ACP bridge', () => { expect(harness.ctx.agents.get(SessionId(sessionId))?.options).toEqual({}) }) - it('allows request listeners to supply a route when ACP has no initial selection', async () => { + it('allows route listeners to supply a route when ACP has no initial selection', async () => { harness = await makeBridgeHarness({ config: { provider: undefined, model: undefined }, script: [textResponse('listener-routed')], }) - harness.ctx.on('agent/request', async (_payload, next) => ({ + harness.ctx.on('agent/route', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock', diff --git a/packages/api/job-controller/tests/host-harness.ts b/packages/api/job-controller/tests/host-harness.ts index 79776efbd9..85609166b0 100644 --- a/packages/api/job-controller/tests/host-harness.ts +++ b/packages/api/job-controller/tests/host-harness.ts @@ -21,7 +21,6 @@ export async function registerAgent(ctx: Context, rawId: string): Promise Promise } = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/api/job-controller/tests/observe.host.spec.ts b/packages/api/job-controller/tests/observe.host.spec.ts index 51b24ff063..583862eeac 100644 --- a/packages/api/job-controller/tests/observe.host.spec.ts +++ b/packages/api/job-controller/tests/observe.host.spec.ts @@ -226,7 +226,6 @@ describe('JobController', () => { async function liveOwner(ctx: Context, rawId: string): Promise { const session = ctx.sessions.create(SessionId(rawId)) const owner: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/api/session-controller/src/agent.ts b/packages/api/session-controller/src/agent.ts index 60dc95cbd9..4735b47e47 100644 --- a/packages/api/session-controller/src/agent.ts +++ b/packages/api/session-controller/src/agent.ts @@ -282,7 +282,7 @@ export class ApiSessionAgentController { } /** - * Install or return the Session-local model selection used by request preparation. + * Install or return the Session-local model selection that chooses each step's route. * @param agent - live Agent that owns the selection. * @returns the installed mutable selection reference. */ @@ -332,7 +332,7 @@ export class ApiSessionAgentController { } /** - * Commit and cache one validated selection for the next step's request preparation. + * Commit and cache one validated selection for the next step's route. * @param agent - live Agent that owns the selection. * @param selection - validated selection to record and apply. */ diff --git a/packages/api/session-controller/tests/archived-session-gate.host.spec.ts b/packages/api/session-controller/tests/archived-session-gate.host.spec.ts index 8209040d68..3a94d5d5c9 100644 --- a/packages/api/session-controller/tests/archived-session-gate.host.spec.ts +++ b/packages/api/session-controller/tests/archived-session-gate.host.spec.ts @@ -26,7 +26,6 @@ async function harness(): Promise { /** A registered idle Agent double: the gate reads only its Session header. */ async function liveAgent(ctx: Context, session: Session): Promise { const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, @@ -48,7 +47,7 @@ async function liveAgent(ctx: Context, session: Session): Promise { /** Propose one model step for the Agent; the innermost decision enters. */ const proposed = (ctx: Context, agent: Agent) => ctx.waterfall( 'agent/pre-step', - { agent, messages: [], turn: 1, step: 1, signal: new AbortController().signal }, + { agent, messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) diff --git a/packages/api/session-controller/tests/session-fork.host.spec.ts b/packages/api/session-controller/tests/session-fork.host.spec.ts index d94b156d1d..e7ace3a85c 100644 --- a/packages/api/session-controller/tests/session-fork.host.spec.ts +++ b/packages/api/session-controller/tests/session-fork.host.spec.ts @@ -662,14 +662,14 @@ describe('sessions.fork', () => { const child = ctx.agents.get(response.value.sessionId) if (child === undefined) throw new Error('fork did not publish the child agent') expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount)).toEqual(inherited) - const fallback: LlmCallConfig = { provider: 'default-provider', model: 'default-model' } + const signal = new AbortController().signal + const route = await agentEvents(child.ctx, child).waterfall( + 'agent/route', { turn: 1, step: 1, signal }, () => Promise.resolve({ provider: 'default-provider', model: 'default-model' }), + ) + expect(route).toEqual({ provider: 'inherited-provider', model: 'inherited-model' }) await expect(agentEvents(child.ctx, child).waterfall( - 'agent/request', { turn: 1, step: 1, signal: new AbortController().signal }, () => Promise.resolve(fallback), - )).resolves.toMatchObject({ - provider: 'inherited-provider', - model: 'inherited-model', - reasoningEffort: 'high', - }) + 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve({ ...route }), + )).resolves.toEqual({ ...route, reasoningEffort: 'high' }) await ctx.fiber.dispose() }) }) 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 3ebc903a03..099e5637be 100644 --- a/packages/api/session-controller/tests/session-models.host.spec.ts +++ b/packages/api/session-controller/tests/session-models.host.spec.ts @@ -1,14 +1,14 @@ /** * Session Controller model-directory and selection behavior: dynamic provider grouping, * provider-local catalog failures, logged-selection restoration without stale - * catalog injection, unavailable-model refusals, and the request-preparation + * catalog injection, unavailable-model refusals, and the step-route * boundary for a running selection change. */ import { describe, expect, it, vi, onTestFinished } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' -import type { Agent } from '@deepseek-ai/dsh-agent' +import type { Agent, StepRoute } from '@deepseek-ai/dsh-agent' import AttachmentStore from '@deepseek-ai/dsh-attachment' import LlmRuntime, { LlmAdapter, ReasoningEffortId } from '@deepseek-ai/dsh-llm' import type { @@ -486,11 +486,16 @@ describe('Web session model selection', () => { await ctx.fiber.dispose() }) - it('rejects unlisted models and applies a selection when the next step prepares its request', async () => { + it('rejects unlisted models and applies a selection from the next step route', async () => { const { ctx, agent, sessionId } = await harness() const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' }) - const seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 } const signal = new AbortController().signal + const route = (step: number) => agentEvents(ctx, agent).waterfall( + 'agent/route', { turn: 1, step, signal }, () => Promise.resolve({ provider: 'seed', model: 'seed' }), + ) + const requestOn = (step: number, stepRoute: StepRoute) => agentEvents(ctx, agent).waterfall( + 'agent/request', { turn: 1, step, signal }, () => Promise.resolve({ ...stepRoute, temperature: 0.2 }), + ) expect(currentSelection(ctx, sessionId)) .toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' }) @@ -499,9 +504,9 @@ describe('Web session model selection', () => { provider: 'deepseek-official', model: 'deepseek-chat', }))) - await expect(agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve(seed), - )).resolves.toEqual({ ...seed, provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' }) + const chat = await route(1) + expect(chat).toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' }) + await expect(requestOn(1, chat)).resolves.toEqual({ ...chat, temperature: 0.2, reasoningEffort: 'high' }) const selected = expectValue(await remote.selectModel(request({ sessionId, @@ -514,16 +519,10 @@ describe('Web session model selection', () => { model: 'deepseek-reasoner', reasoningEffort: 'max', }) - await expect(agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve(seed), - )).resolves.toEqual({ ...seed, provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' }) - await expect(agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 1, step: 2, signal }, () => Promise.resolve(seed), - )).resolves.toMatchObject({ - provider: 'deepseek-official', - model: 'deepseek-reasoner', - reasoningEffort: 'max', - }) + await expect(requestOn(1, chat)).resolves.toEqual({ ...chat, temperature: 0.2, reasoningEffort: 'high' }) + const reasoner = await route(2) + expect(reasoner).toEqual({ provider: 'deepseek-official', model: 'deepseek-reasoner' }) + await expect(requestOn(2, reasoner)).resolves.toEqual({ ...reasoner, temperature: 0.2, reasoningEffort: 'max' }) const unsupported = await remote.selectModel(request({ sessionId, diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index e290f7a342..cc73507d5f 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -149,7 +149,6 @@ async function bench(script: Script, options: BenchOptions = {}): Promise<{ let idle = Promise.resolve() let running = false const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: createOptions.agentOptions ?? {}, session, diff --git a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts index 3736aa5c5e..d43a6828d6 100644 --- a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts +++ b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts @@ -1675,7 +1675,7 @@ describe('default one-shot summarizer', () => { describe('automatic listener and loader composition', () => { function preStep(ctx: Context, owner: Agent, signal = SIGNAL) { return agentEvents(ctx, owner).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) } diff --git a/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts b/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts index 8d762591eb..84117631aa 100644 --- a/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts +++ b/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts @@ -205,9 +205,9 @@ function overflowHistorySeed(): readonly SessionEvent[] { } describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => { - it('uses the model actually routed by agent/request for post-step pressure', async () => { + it('uses the model actually routed by agent/route for post-step pressure', async () => { const { ctx } = await harness(8) - ctx.on('agent/request', async (_payload, next) => ({ + ctx.on('agent/route', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock', })) try { @@ -380,7 +380,7 @@ describe('context-overflow recovery across the real loop and compaction-basic', await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(TokenMeter) ctx.llm.registerAdapter(['mock'], adapter) - ctx.on('agent/request', async (_payload, next) => ({ + ctx.on('agent/route', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock', })) await ctx.plugin(BasicCompactionEngine, { diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index 721866df73..d6b22860b9 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -310,7 +310,7 @@ async function agentInstructionsOf(agent: Agent): Promise { async function syncAgentInstructions(ctx: Context, agent: Agent): Promise { await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, signal: testToolSignal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: testToolSignal }, async () => ({ kind: 'enter' as const, messages: [] }), ) } @@ -345,13 +345,13 @@ async function composeBaselinePrefix(ctx: Context, agent: TestAgent): Promise Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const claimed = claimInbox(agent, 'next-step') const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 2, signal }, + { messages: claimed, turn: 1, step: 2, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) const entered = decision.kind === 'enter' ? decision.messages : [] @@ -1724,7 +1724,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(ctx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const inserted = original.inbox.nextStep[0] @@ -1738,7 +1738,7 @@ describe('workspace context request injection', () => { const claimed = claimInbox(resumed, 'next-step') const decision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: claimed, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) if (decision.kind !== 'enter') throw new Error('recovered baseline was rejected') @@ -1773,7 +1773,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(ctx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const stale = original.inbox.nextStep[0] @@ -1788,7 +1788,7 @@ describe('workspace context request injection', () => { const staleClaim = claimInbox(resumed, 'next-step') const staleDecision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', - { messages: staleClaim, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: staleClaim, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: staleClaim }), ) @@ -1831,7 +1831,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(originalCtx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const stale = original.inbox.nextStep[0] @@ -1846,7 +1846,7 @@ describe('workspace context request injection', () => { const claimed = claimInbox(resumed, 'next-step') const decision = await agentEvents(resumedCtx, resumed).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: claimed, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) @@ -1959,7 +1959,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [prompt], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [prompt], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve(downstream), ) @@ -2551,7 +2551,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve(downstream), ) @@ -2673,7 +2673,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [prompt], turn: 2, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [prompt], turn: 2, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [prompt] }), ) @@ -3137,7 +3137,7 @@ describe('workspace context request injection', () => { const reason = new Error('cancel prefix') const pending = agentEvents(ctx, await stubAgent(root)).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, signal: controller.signal }, + { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: controller.signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) @@ -5770,7 +5770,7 @@ describe('workspace context inbox synchronization', () => { controller.abort(new Error('abort pre-step reconciliation')) await expect(agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, signal: controller.signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: controller.signal }, async () => ({ kind: 'enter' as const, messages: [] }), )).rejects.toThrow('abort pre-step reconciliation') @@ -5889,7 +5889,7 @@ describe('workspace context inbox synchronization', () => { const downstream = { kind: 'enter' as const, messages: claimed } const decision = await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: claimed, turn: 1, step: 1, signal: testToolSignal }, + 'agent/pre-step', { messages: claimed, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: testToolSignal }, async () => downstream, ) diff --git a/packages/context/session-reference/README.i18n.yaml b/packages/context/session-reference/README.i18n.yaml index 3b7443317e..3022c2b8f5 100644 --- a/packages/context/session-reference/README.i18n.yaml +++ b/packages/context/session-reference/README.i18n.yaml @@ -27,14 +27,14 @@ en: 169f100ba62f2120 zh: 3fd4fc0bd73b2370 /deepseek-ai-dsh-session-reference/use-this-package/configuration: - en: 5dfb1f0c52d300bf - zh: ae731dd6fcd93027 + en: d9abc1b28c3feb40 + zh: ac85539027b37130 /deepseek-ai-dsh-session-reference/understand-the-implementation: en: db349483e453caf7 zh: 70035c291e1efe84 /deepseek-ai-dsh-session-reference/understand-the-implementation/design-concept: - en: d7ff10eae41712ad - zh: 2b91a16dee11808e + en: 364238fb1f73a8eb + zh: ecb21f01b1a15f77 /deepseek-ai-dsh-session-reference/understand-the-implementation/source-map: en: 7c7b413082507150 zh: 0229eb73d441b305 diff --git a/packages/context/session-reference/README.md b/packages/context/session-reference/README.md index 79221efeec..64f86e7e3c 100644 --- a/packages/context/session-reference/README.md +++ b/packages/context/session-reference/README.md @@ -50,7 +50,7 @@ For a truncated reference, an optional spill backend saves the full captured tex | `maxReferenceBytes` | automatic | Explicit maximum serialized JSON bytes per source; overrides the automatic budget exactly | | `referenceContextFraction` | `0.2` | Context-window fraction per source, from `0` to `1` | -The automatic budget is `max(65536, floor(contextWindow × 4 × referenceContextFraction))` bytes per source. Model context capacity is measured in tokens; four bytes per token is a sizing heuristic, not an exact token conversion. A missing LLM service, adapter, or capacity uses 64 KiB; other model metadata lookup errors and cancellation fail preparation. +The automatic budget is `max(65536, floor(contextWindow × 4 × referenceContextFraction))` bytes per source. Model context capacity is measured in tokens; four bytes per token is a sizing heuristic, not an exact token conversion. A missing route, LLM service, adapter, or capacity uses 64 KiB; other model metadata lookup errors and cancellation fail preparation. The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-session-reference) is the exhaustive source for every accepted field and its JSDoc. @@ -70,7 +70,7 @@ Preparation reads each referenced session's current surface exactly once, when t The resolver discovers optional storage through `ctx.get("spillStore")` and saves only truncated references. Storage ownership is the target session; the source descriptor identifies the referenced session and label, without a fabricated tool call. Cancellation is checked after the asynchronous save and prevents publication even if an artifact was written. Artifact expiry remains the backend's existing policy. -The budget uses `agent.currentRoute()`, bound before step input preparation. The agent must have a prepared main request when a model-relative budget is needed; initial options and stored headers do not select the budget model. +The budget uses the step route that `agent/route` chose, which `agent/pre-step` carries. Direct `prepare` calls without a route use agent options; session headers do not select the budget model. ### Source map diff --git a/packages/context/session-reference/README.zh.md b/packages/context/session-reference/README.zh.md index edd4e673b4..546735ad59 100644 --- a/packages/context/session-reference/README.zh.md +++ b/packages/context/session-reference/README.zh.md @@ -50,7 +50,7 @@ kind: "package-reference" | `maxReferenceBytes` | 自动 | 每个来源的最大序列化 JSON 字节数;显式设置时精确覆盖自动预算 | | `referenceContextFraction` | `0.2` | 每个来源的上下文窗口比例,范围为 `0` 到 `1` | -自动预算为每个来源 `max(65536, floor(contextWindow × 4 × referenceContextFraction))` 字节。模型上下文容量以 token 计量;每个 token 四字节是容量估算,不是精确的 token 换算。缺少 LLM(大语言模型)服务、适配器或容量时使用 64 KiB;其他模型元数据查询错误与取消会使准备失败。 +自动预算为每个来源 `max(65536, floor(contextWindow × 4 × referenceContextFraction))` 字节。模型上下文容量以 token 计量;每个 token 四字节是容量估算,不是精确的 token 换算。缺少路由、LLM(大语言模型)服务、适配器或容量时使用 64 KiB;其他模型元数据查询错误与取消会使准备失败。 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-session-reference)是每个受支持字段及其 JSDoc 的穷尽式真源。 @@ -70,7 +70,7 @@ kind: "package-reference" 解析器通过 `ctx.get("spillStore")` 获取可选存储,只保存被截断的引用。存储归目标会话所有;来源信息标识被引用的源会话与标签,不伪造工具调用。异步保存后会检查取消,即使产物已写入,也会阻止发布。产物过期仍遵循后端既有策略。 -预算使用步骤输入准备前绑定的 `agent.currentRoute()`。需要模型相对预算时,agent 必须已有准备完成的主请求;初始选项与已存储请求头不决定预算模型。 +预算使用 `agent/route` 选定、由 `agent/pre-step` 携带的步骤路由。未传入路由的直接 `prepare` 调用使用 agent 选项;Session 请求头不决定预算模型。 ### 源码地图 diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index df9a66e850..007d5d6cb2 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -7,7 +7,7 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import type { Agent, PreStepDecision, StepRoute } from '@deepseek-ai/dsh-agent' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { createUserMessage, freezeMessage, LlmError } from '@deepseek-ai/dsh-llm' import type { ContentBlock, LlmResolvedModelInfo, UserMessage } from '@deepseek-ai/dsh-llm' @@ -122,12 +122,12 @@ export class SessionReferenceResolver extends TypertRemoteService { 'SESSION_REFERENCE_INVALID_CONFIG', ) } - ctx.on('agent/pre-step', async ({ agent, signal }, next): Promise => { + ctx.on('agent/pre-step', async ({ agent, route, signal }, next): Promise => { const decision = await next() if (decision.kind === 'reject') return decision return { ...decision, - messages: await this.prepareDirectMessages(agent, decision.messages, signal), + messages: await this.prepareDirectMessages(agent, route, decision.messages, signal), } }, { prepend: true }) } @@ -136,12 +136,14 @@ export class SessionReferenceResolver extends TypertRemoteService { * Replace canonical mentions in direct user messages and place each prepared * snapshot immediately after the message that cited it. * @param agent - agent entering the model step. + * @param route - provider and model of the step. * @param messages - messages accepted by downstream pre-step listeners. * @param signal - active turn cancellation. * @returns direct messages followed by their session-reference context in citation order. */ private async prepareDirectMessages( agent: Agent, + route: StepRoute, messages: readonly UserMessage[], signal: AbortSignal, ): Promise { @@ -155,7 +157,7 @@ export class SessionReferenceResolver extends TypertRemoteService { return { type: 'text', text: parsed.text } }) if (references.length === 0) return [message] - const resolved = await this.prepare(agent, content, references, signal) + const resolved = await this.prepare(agent, content, references, signal, route) const direct = freezeMessage({ ...message, content: resolved.content }) /* v8 ignore if -- a parsed canonical mention always leaves one normalized reference */ if (resolved.additionalContext === undefined) { @@ -276,7 +278,7 @@ export class SessionReferenceResolver extends TypertRemoteService { /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the last assembled route, or agent options before any assembly. + * Automatic budgets use the step route, or agent options for direct preparation. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -284,6 +286,7 @@ export class SessionReferenceResolver extends TypertRemoteService { * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. + * @param route - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ async prepare( @@ -291,12 +294,13 @@ export class SessionReferenceResolver extends TypertRemoteService { content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, + route?: StepRoute, ): Promise { const acceptedContent = structuredClone(content) const inputs = normalizeReferences(agent.id, references, this.config.maxReferences) if (inputs.length === 0) return { content: acceptedContent } assertNotCancelled(signal) - const maxReferenceBytes = await this.referenceBudget(agent, signal) + const maxReferenceBytes = await this.referenceBudget(agent, route, signal) assertNotCancelled(signal) let prepared: PreparedSource[] try { @@ -347,11 +351,12 @@ export class SessionReferenceResolver extends TypertRemoteService { return { content: acceptedContent, additionalContext } } - private async referenceBudget(agent: Agent, signal: AbortSignal | undefined): Promise { + private async referenceBudget(agent: Agent, route: StepRoute | undefined, signal: AbortSignal | undefined): Promise { if (this.config.maxReferenceBytes !== undefined) return this.config.maxReferenceBytes - const { provider, model } = agent.currentRoute() + // Options seed direct preparation; the step route owns model-step preparation. + const { provider, model } = route ?? agent.options const llm = this.ctx.get('llm') - if (llm === undefined) return DEFAULT_MAX_REFERENCE_BYTES + if (provider === undefined || model === undefined || llm === undefined) return DEFAULT_MAX_REFERENCE_BYTES let info: LlmResolvedModelInfo try { info = await settleWithCancellation(llm.resolveModelInfo(provider, model, signal), signal) diff --git a/packages/context/session-reference/tests/loader-composition.spec.ts b/packages/context/session-reference/tests/loader-composition.spec.ts index 3c8cfa6e15..eaca6a673e 100644 --- a/packages/context/session-reference/tests/loader-composition.spec.ts +++ b/packages/context/session-reference/tests/loader-composition.spec.ts @@ -77,7 +77,7 @@ describe('session-reference real Loader composition', () => { source: { kind: 'user' }, }) const decision = await agentEvents(ctx, agent).waterfall('agent/pre-step', { - messages: [direct], turn: 1, step: 1, signal: new AbortController().signal, + messages: [direct], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: new AbortController().signal, }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct] })) expect(decision.kind).toBe('enter') if (decision.kind !== 'enter') throw new Error('Expected admitted reference') diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index b7af57466d..e1c4f6d9ec 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -86,8 +86,7 @@ function withProjectionCache( } function fakeAgent(session: Session): Agent { - const options: Agent['options'] = {} - return { id: session.id, session, options, currentRoute: () => ({ provider: options.provider ?? 'seed', model: options.model ?? 'seed' }) } as Agent + return { id: session.id, session, options: {} } as Agent } function expectCode(code: SessionReferenceErrorCode): Error { @@ -467,7 +466,7 @@ describe('session reference spill outcomes', () => { }) const direct = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const pending = agentEvents(ctx, fakeAgent(target)).waterfall('agent/pre-step', - { messages: [direct], turn: 1, step: 1, signal: controller.signal }, + { messages: [direct], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: controller.signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct] })) const rejected = expect(pending).rejects.toThrow(expectCode('SESSION_REFERENCE_CANCELLED')) await started.promise @@ -534,13 +533,12 @@ describe('model-relative reference budgets', () => { else expect(resolve).toHaveBeenCalledWith('seed', 'seed', undefined) }) - it('uses the bound request route independently of stored and initial routes', async () => { + it('uses the step route rather than agent options', async () => { const { ctx, agent, source, resolve } = await setup() let route = { provider: 'selected', model: 'large' } - vi.spyOn(agent, 'currentRoute').mockImplementation(() => route) const message = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const signal = new AbortController().signal - const enter = () => agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, signal }, + const enter = () => agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, route, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [message] })) const first = await enter() expect(first.kind).toBe('enter') @@ -549,7 +547,6 @@ describe('model-relative reference budgets', () => { if (firstContext === undefined) throw new Error('expected reference context') expect(bytes({ content: [], additionalContext: firstContext })).toBe(160_000) expect(resolve).toHaveBeenLastCalledWith('selected', 'large', signal) - await ctx.systemPrompt.assemble({ agent, scope: agent }) route = { provider: 'selected', model: 'small' } resolve.mockResolvedValue({ provider: 'selected', id: 'small', name: 'small', context: { contextWindow: 8_000 } }) const second = await enter() @@ -558,13 +555,17 @@ describe('model-relative reference budgets', () => { expect(resolve).toHaveBeenLastCalledWith('selected', 'small', signal) }) - it('uses the floor for absent metadata or service', async () => { - const { ctx, agent, resolve, prepare, llmFiber } = await setup() + it('uses the floor for absent metadata, service, or direct-preparation route', async () => { + const { agent, resolve, prepare, llmFiber } = await setup() resolve.mockResolvedValue({ provider: 'seed', id: 'seed', name: 'seed' }) expect(bytes(await prepare())).toBe(65_536) expect(resolve).toHaveBeenCalledOnce() + delete agent.options.model + expect(bytes(await prepare())).toBe(65_536) + expect(resolve).toHaveBeenCalledOnce() + agent.options.model = 'seed' await llmFiber.dispose() - expect(bytes(await ctx.sessionReferenceResolver.prepare(agent, [], [{ sessionId: SessionId('source') }]))).toBe(65_536) + expect(bytes(await prepare())).toBe(65_536) }) it('uses the floor when the real LLM runtime has no adapter for the route', async () => { @@ -620,7 +621,7 @@ describe('model-relative reference budgets', () => { expect(resolve).toHaveBeenLastCalledWith('seed', 'seed', undefined) const message = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const seed = { kind: 'enter' as const, messages: [message] } - await expect(agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, signal: new AbortController().signal }, + await expect(agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, () => Promise.resolve(seed))).resolves.toBe(seed) }) @@ -876,7 +877,7 @@ describe('session reference discovery and preparation', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [direct, ordinary, plugin], turn: 1, step: 1, signal }, + { messages: [direct, ordinary, plugin], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct, ordinary, plugin] }), ) @@ -912,14 +913,14 @@ describe('session reference discovery and preparation', () => { await expect(agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [malformed], turn: 1, step: 1, signal }, + { messages: [malformed], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'reject' as const }), )).resolves.toEqual({ kind: 'reject' }) expect(readSurface).not.toHaveBeenCalled() await expect(agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [malformed], turn: 1, step: 1, signal }, + { messages: [malformed], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [malformed] }), )).rejects.toThrow(/invalid session reference URI/) }) diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index f5b28c96ef..2fe2f9dc6a 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -47,7 +47,6 @@ async function mount(config: Config = {}) { function sessionAgent(session: Session, id = 'agent'): Agent { const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: SessionId(id), options: {}, session, @@ -99,7 +98,7 @@ async function fire( }) const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [proposed], turn, step, signal }, + { messages: [proposed], turn, step, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [proposed] }), ) if (decision.kind === 'enter') { diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index b895f139db..636d592077 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -106,7 +106,6 @@ async function mount( function sessionAgent(session: Session, id = 'agent'): Agent { const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: SessionId(id), options: {}, session, @@ -152,7 +151,7 @@ async function fire( ): Promise { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn, step, signal }, + { messages: [], turn, step, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 5c19f9b0b8..03b0a75c41 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -18,8 +18,8 @@ en: 35a960c0100a6aa4 zh: 438e133fb4c24a9e /deepseek-ai-dsh-agent-loop/use-this-package/configure-declarative-agents: - en: 96295035babf4f90 - zh: 8848f9497019ee63 + en: 1da69e82fc23ccd0 + zh: f722cf3827b821bc /deepseek-ai-dsh-agent-loop/use-this-package/create-or-resume-agents-programmatically: en: 82ec792637e8e57f zh: e32f8ec5ee17afcf @@ -45,8 +45,8 @@ en: 3c5721bc00a0bbf4 zh: 711f832343ffbb75 /deepseek-ai-dsh-agent-loop/understand-the-implementation/turn-and-step-flow: - en: 29c33bc92b4a8db6 - zh: d1152a6656bb772d + en: 787a9f96297a6024 + zh: e9b34c0c7ff26e25 /deepseek-ai-dsh-agent-loop/understand-the-implementation/failure-and-cancellation: en: eea56903c4ff82f5 zh: c0d5abb5767780ed diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 7ff895ef11..4e27d6c0a8 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -29,7 +29,7 @@ Mount `dsh-agent-loop` in any composition that should run agents. It supplies th ### Configure declarative agents -Agents declared in the config start automatically when the plugin loads. Each entry needs an `id` label; a model call additionally requires both `provider` and `model` (`agent/request` may supply a missing pair before dispatch). +Agents declared in the config start automatically when the plugin loads. Each entry needs an `id` label; a model call additionally requires both `provider` and `model` (`agent/route` may supply a missing pair for each step). ```yaml - name: '@deepseek-ai/dsh-agent-loop' @@ -117,7 +117,7 @@ The loop is the production acquisition point for session write handles. When `ct ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver binds the route through `agent/request` and `prepareCall()`, prepares variables and runtime context, then runs `agent/pre-step`; its fallback projects that context. A rejected decision or empty first batch opens no step. Cancellation during route preparation commits neither a system prompt nor users. After acceptance, `step/start` precedes asynchronous tool activation and final prompt assembly. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt with its owned context candidate replaced in place, and restores removed runtime context, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries resolve tool conditions against their bound route without repeating `agent/pre-step` or user admission. An unchanged route and tool schema set reuse the accepted prompt; a changed route or tool set assembles the corresponding prompt again. The request-owned tool set is closed after dispatch settles, and the bound Agent route is cleared when the step ends. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver chooses the step route through `agent/route`, prepares variables and runtime context on that route, then runs `agent/pre-step`; its fallback projects that context. A rejected decision or empty first batch opens no step. Cancellation during routing opens no step. After acceptance, `step/start` precedes asynchronous tool activation and final prompt assembly, both once per step. Each attempt then runs the `agent/request` waterfall and `prepareCall()` on the step route; a listener that returns another provider or model fails the step, and cancellation during either async phase commits neither the pending system prompt nor accepted users. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt with its owned context candidate replaced in place, and restores removed runtime context, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the step's route, tool set, and rendered assembly without repeating routing, tool activation, assembly, `agent/pre-step`, or user admission. The step-owned tool set is closed after the step's tool batch settles. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) Prompt admission uses the actual `prepareCall()` result, not the preceding `request/context`. With no system node, even an empty prompt is appended (reserving node 0 without a wire message). On an incapable route or at a new request series, a non-empty rendering is consolidated at the first system node: each non-empty later system node receives a logged per-node empty replacement, then the head is rewritten if needed. Dormant empty tails need no replacement and do not determine the effective text. Consolidation applies even when the latest effective text is unchanged. On a continuing `in-history` series, an unchanged effective prompt produces no event and a non-empty change appends. An empty rendering clears every non-empty later system node through a logged per-node empty replacement, then empties the head if needed, regardless of route or series state. No older instructions remain model-visible. An empty head with no active later system node means no prompt; repeated clears and resume leave it empty. A restored non-empty prompt follows the same route/series rule: a continuing capable route may append it, while an incapable route or new series refills the head. A step starts a series when the pre-step decision declares `startsRequestSeries` or `session.surface.contentGeneration` changed since attachment or the last request (a replacement or image-offload decision). Visible tool-schema changes force prompt consolidation only when the prepared route lacks `toolUpdate`. Routes supporting both tool and system-prompt updates can append a changed prompt and activate added tools without rewriting earlier messages. If another admission condition replaces a system node, the request starts a new series with current tool declarations. Resume and a provider or model swap alone continue the series; the prepared route still governs admission. Per-node empty replacements preserve intervening history without a surface delete operation. diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index daf4663ac9..ae052e9af1 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 配置声明式 agent -配置中声明的 agent 会在插件加载时自动启动。每个条目需要一个 `id` 标签;模型调用还同时需要 `provider` 与 `model`(`agent/request` 可以在分发前补齐缺失的这一对值)。 +配置中声明的 agent 会在插件加载时自动启动。每个条目需要一个 `id` 标签;模型调用还同时需要 `provider` 与 `model`(`agent/route` 可以为每个步骤补齐缺失的这一对值)。 ```yaml - name: '@deepseek-ai/dsh-agent-loop' @@ -117,7 +117,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器通过 `agent/request` 与 `prepareCall()` 绑定路由,准备变量和运行时上下文,然后运行 `agent/pre-step`;fallback 投影该上下文。被拒绝的决定或空的首批输入不打开步骤。路由准备期间取消不会提交系统提示词或用户消息。接纳后,`step/start` 先于异步工具激活与最终提示词组装。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次并原位替换循环自有上下文候选、恢复被移除的运行时上下文、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试按其绑定路由重新解析工具条件,不重复 `agent/pre-step` 或用户消息接纳。路由与工具 schema 集合未变时复用已接纳提示词;任一变化时重新组装对应提示词。请求拥有的工具集合在分派结束后关闭,Agent 的绑定路由在步骤结束时清除。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器通过 `agent/route` 选定步骤路由,在该路由上准备变量和运行时上下文,然后运行 `agent/pre-step`;fallback 投影该上下文。被拒绝的决定或空的首批输入不打开步骤。路由选择期间取消不会打开步骤。接纳后,`step/start` 先于异步工具激活与最终提示词组装,两者每个步骤各执行一次。每次尝试随后在步骤路由上运行 `agent/request` waterfall 与 `prepareCall()`;监听器若返回其他提供方或模型,步骤会失败,而在任一异步阶段取消都不会提交待定的系统提示词或已接纳用户消息。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次并原位替换循环自有上下文候选、恢复被移除的运行时上下文、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试复用该步骤的路由、工具集合与已渲染组装结果,不重复路由选择、工具激活、组装、`agent/pre-step` 或用户消息接纳。步骤拥有的工具集合在该步骤的工具批次结束后关闭。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 提示词准入依据实际的 `prepareCall()` 结果,而非先前的 `request/context`。没有系统节点时,即使提示词为空也追加(预留第 0 号节点,但不产生协议消息)。在不具备能力的路由上或新请求序列开始时,非空渲染文本归并到首个系统节点:每个非空的后续系统节点分别收到有日志记录的空内容替换,随后按需重写头节点。未生效的空尾节点无需替换,也不决定有效文本。即使最新有效文本未变,也执行归并。延续中的 `in-history` 序列在有效提示词不变时不产生事件,非空变更则追加。无论路由或序列状态如何,空渲染文本都会通过有日志记录的逐节点空内容替换清除每个非空的后续系统节点,再按需清空头节点。模型不会继续看到旧指令。空头节点且没有生效的后续系统节点表示没有提示词;重复清除与恢复会话都保持为空。重新提供的非空提示词遵循同一路由/序列规则:延续中的具备能力路由可以追加它,不具备能力的路由或新序列则重新填充头节点。以下情况开启序列:pre-step 决定声明 `startsRequestSeries`,或 `session.surface.contentGeneration` 自附接或上次请求以来发生变化(替换或图片省略决定)。仅当已准备路由未声明 `toolUpdate` 时,可见工具 schema 变化才强制归并提示词。同时支持工具和系统提示词更新的路由可以追加变更后的提示词并激活新增工具,无需改写此前消息。如果其他准入条件替换系统节点,请求会以当前工具声明开启新序列。恢复与单纯的提供方或模型切换都延续序列;准入仍由已准备的路由决定。逐节点的空内容替换保留其间历史,无需 surface 删除操作。 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index d473dc5d23..25858436fc 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -14,6 +14,7 @@ import type { InboxTarget, PreStepDecision, RequestErrorAction, + StepRoute, } from '@deepseek-ai/dsh-agent' import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm' @@ -63,8 +64,8 @@ type PreparedStep = kind: 'enter' messages: UserMessage[] startsRequestSeries?: true + route: StepRoute preparation: PromptPreparation - request: PreparedRequest } /** Remove adapter-derived values before plugins propose the next request config. */ @@ -104,7 +105,6 @@ function abortedCancelCause(signal: AbortSignal): AgentCancelCause | undefined { /** Drives one session through turn and step boundaries. */ export class ReactLoopAgent implements Agent { readonly inbox: ReactLoopInbox - private requestRoute: Readonly> | undefined private phase: Phase private activityDone: Promise = Promise.resolve() @@ -145,11 +145,6 @@ export class ReactLoopAgent implements Agent { this.systemPrompt = new SystemPromptProjection(session) } - currentRoute(): Readonly> { - if (this.requestRoute === undefined) throw new Error('agent has no prepared model request') - return this.requestRoute - } - get status(): AgentStatus { return this.phase.kind === 'idle' || this.phase.kind === 'maintenance' ? 'idle' : 'running' } @@ -282,12 +277,11 @@ export class ReactLoopAgent implements Agent { if (this.phase.kind !== 'running') throw new Error(`agent "${this.id}": pre-step outside running phase`) const signal = this.phase.abort.signal const claimed = this.inbox.claim(target, position.turn) - const request = await this.prepareRequest(position.turn, position.step, signal) - const preparation = await this.loopCtx.systemPrompt.prepare(assembleContextFor(this, signal)) - preparation.variables = { ...preparation.variables, ...this.currentRoute() } + const route = await this.chooseRoute(position.turn, position.step, signal) + const preparation = await this.loopCtx.systemPrompt.prepare({ ...assembleContextFor(this, signal), route }) signal.throwIfAborted() const decision = await this.dispatch.waterfall( - 'agent/pre-step', { messages: claimed, ...position, signal }, + 'agent/pre-step', { messages: claimed, ...position, route, signal }, (): Promise => { const sections = renderContextSections(preparation) const context = this.runtimeContext.project(joinContextSections(sections), sections) @@ -299,7 +293,21 @@ export class ReactLoopAgent implements Agent { ) signal.throwIfAborted() if (decision.kind === 'reject') return decision - return { ...decision, preparation, request } + return { ...decision, route, preparation } + } + + /** Choose the provider and model that the proposed step keeps for every request attempt. */ + private async chooseRoute(turn: number, step: number, signal: AbortSignal): Promise { + const { provider, model } = this.requestBase() + const route = await this.dispatch.waterfall( + 'agent/route', { turn, step, signal }, + () => Promise.resolve({ provider, model }), + ) + signal.throwIfAborted() + if (!route.provider || !route.model) { + throw new Error(`agent "${this.id}" has no provider/model: set AgentOptions.provider and AgentOptions.model or supply both via the agent/route waterfall`) + } + return Object.freeze({ provider: route.provider, model: route.model }) } /** Whether the assembled tool schemas differ from the logged request header's. */ @@ -328,7 +336,6 @@ export class ReactLoopAgent implements Agent { let target: InboxTarget = 'next-turn' try { while (true) { - this.requestRoute = undefined signal.throwIfAborted() const step = phase.step + 1 const decision = await this.preStep(target, { turn, step }) @@ -372,7 +379,6 @@ export class ReactLoopAgent implements Agent { } finally { stopRecovery() this.session.append('step/end', { turn, step }) - this.requestRoute = undefined } signal.throwIfAborted() if (turnEnds && this.inbox.nextStep.length === 0) { @@ -397,7 +403,6 @@ export class ReactLoopAgent implements Agent { } this.throwError(error) } finally { - this.requestRoute = undefined try { // oxlint-disable-next-line typescript/no-non-null-assertion -- every exit assigns a turn ending this.session.append('turn/end', { turn, reason: turnEnds! }) @@ -419,24 +424,18 @@ export class ReactLoopAgent implements Agent { const { turn, step, abort: { signal } } = this.phase signal.throwIfAborted() - let firstAttempt = true - let acceptedAssembly: { provider: string; model: string; schemas: string; assembly: PromptAssembly } | undefined - while (true) { - const { config, preparedCall } = firstAttempt ? decision.request : await this.prepareRequest(turn, step, signal) - const toolSet = await this.loopCtx.tools.resolve({ agent: this, signal }) - try { - const schemas = JSON.stringify(this.loopCtx.tools.schemas(this, toolSet)) - if (acceptedAssembly === undefined || acceptedAssembly.provider !== config.provider - || acceptedAssembly.model !== config.model || acceptedAssembly.schemas !== schemas) { - const assembly = await this.loopCtx.systemPrompt.assemble( - { ...assembleContextFor(this, signal), toolSet }, - { ...decision.preparation, variables: { ...decision.preparation.variables, ...this.currentRoute() } }, - ) - acceptedAssembly = { provider: config.provider, model: config.model, schemas, assembly } - } - const { assembly } = acceptedAssembly - const renderedPrompt = renderPrompt(assembly) - const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, assembleContextFor(this, signal)) + const { route } = decision + const toolSet = await this.loopCtx.tools.resolve({ agent: this, route, signal }) + try { + const assembly = await this.loopCtx.systemPrompt.assemble( + { ...assembleContextFor(this, signal), route, toolSet }, + decision.preparation, + ) + const renderedPrompt = renderPrompt(assembly) + let firstAttempt = true + while (true) { + const { config, preparedCall } = await this.prepareRequest(turn, step, route, signal) + const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, { ...assembleContextFor(this, signal), route }) const sections = renderContextSections(currentContext) const context = this.runtimeContext.project(joinContextSections(sections), sections) signal.throwIfAborted() @@ -586,24 +585,21 @@ export class ReactLoopAgent implements Agent { if (!live.ended) live.abandon() throw error } - } finally { - toolSet.dispose() } + } finally { + toolSet.dispose() } } - /** Resolve request config and bind its adapter before admitting model-visible input. */ - private async prepareRequest( - turn: number, - step: number, - signal: AbortSignal, - ): Promise { - this.requestRoute = undefined - const { session } = this - - // A loop instance starts from its declared route, restoring only an explicit - // effort owned by that exact model. Later steps re-resolve marked defaults. - const persistedHeader = session.requestHeader() + /** + * The config this loop instance proposes before plugins act: its declared + * route on the first request, restoring only an explicit effort owned by + * that exact model, then the logged header without adapter defaults. + */ + private requestBase(): LlmCallConfig { + const persistedHeader = this.session.requestHeader() + // oxlint-disable-next-line typescript/no-non-null-assertion -- the instance logged the header it now folds + if (this.requestHeaderLogged) return requestProposal(persistedHeader!) const persistedConfig = persistedHeader?.config const route = { provider: this.options.provider ?? '', model: this.options.model ?? '' } const persistedReasoningEffort = persistedConfig?.provider === route.provider @@ -613,23 +609,34 @@ export class ReactLoopAgent implements Agent { : undefined const reasoningEffort = this.options.reasoningEffort ?? persistedReasoningEffort const maxTokens = this.options.maxTokens - const seedConfig = deepFreeze(structuredClone( - this.requestHeaderLogged - // oxlint-disable-next-line typescript/no-non-null-assertion -- the instance logged the header it now folds - ? requestProposal(persistedHeader!) - : { - ...route, - ...reasoningEffort === undefined ? {} : { reasoningEffort }, - ...maxTokens === undefined ? {} : { maxTokens }, - }, - )) + return { + ...route, + ...reasoningEffort === undefined ? {} : { reasoningEffort }, + ...maxTokens === undefined ? {} : { maxTokens }, + } + } + + /** Resolve one attempt's config on the step route and bind its adapter before admitting model-visible input. */ + private async prepareRequest( + turn: number, + step: number, + route: StepRoute, + signal: AbortSignal, + ): Promise { + let seed = this.requestBase() + if (seed.provider !== route.provider || seed.model !== route.model) { + // An effort belongs to one model; another route starts from its own default. + const { reasoningEffort: _effort, ...controls } = seed + seed = { ...controls, provider: route.provider, model: route.model } + } + const seedConfig = deepFreeze(structuredClone(seed)) const proposedConfig = await this.dispatch.waterfall( 'agent/request', { turn, step, signal }, () => Promise.resolve(seedConfig), ) signal.throwIfAborted() - if (!proposedConfig.provider || !proposedConfig.model) { - throw new Error(`agent "${this.id}" has no provider/model: set AgentOptions.provider and AgentOptions.model or supply both via the agent/request waterfall`) + if (proposedConfig.provider !== route.provider || proposedConfig.model !== route.model) { + throw new Error(`agent "${this.id}": agent/request cannot replace the step route ${route.provider}/${route.model} with ${proposedConfig.provider}/${proposedConfig.model}; choose routes with the agent/route waterfall`) } let config: LlmCallConfig let preparedCall: PreparedLlmCall | undefined @@ -642,7 +649,6 @@ export class ReactLoopAgent implements Agent { config = proposedConfig } signal.throwIfAborted() - this.requestRoute = Object.freeze({ provider: config.provider, model: config.model }) return { config, ...preparedCall === undefined ? {} : { preparedCall } } } diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index ca4532af8c..9fd38c9742 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -386,8 +386,8 @@ export class AgentLoop extends Service implements AgentFactory { }) }, 'agentLoop.transactions()') ctx.effect(() => ctx.agents.setFactory(this), 'agentLoop.setFactory()') - ctx.systemPrompt.variable('provider', context => context.agent?.options.provider) - ctx.systemPrompt.variable('model', context => context.agent?.options.model) + ctx.systemPrompt.variable('provider', context => context.route?.provider ?? context.agent?.options.provider) + ctx.systemPrompt.variable('model', context => context.route?.model ?? context.agent?.options.model) for (const { id, sessionId, cwd, resumeSessionId, ...options } of this.config.agents) { const meta = cwd === undefined ? {} : { cwd } diff --git a/packages/core/agent-loop/src/tool-calls.ts b/packages/core/agent-loop/src/tool-calls.ts index 72bbc08f8e..8185bf70ec 100644 --- a/packages/core/agent-loop/src/tool-calls.ts +++ b/packages/core/agent-loop/src/tool-calls.ts @@ -57,7 +57,7 @@ interface GroupOutcome { * @param toolCalls - assistant calls in model order. * @param signal - abort signal shared by the step. * @param acceptContext - accepts committed result context for the next step boundary. - * @param toolSet - request-owned admission propagated into every Native dispatch. + * @param toolSet - step-owned admission propagated into every Native dispatch. */ export async function executeToolCalls( ctx: Context, diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index f6a887eea3..84d702d79c 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -437,7 +437,7 @@ describe('adapter registration, routing, and accepted-input ownership', () => { expect(ctx.llm.listProviders()).toEqual([{ id: 'm1', name: 'm1' }]) }) - it('an agent without a model fails the step with a clear error (not NO_ADAPTER for "default")', async () => { + it('an agent without a model fails the turn with a clear error (not NO_ADAPTER for "default")', async () => { const adapter = new MockAdapter([textResponse('never')]) const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('a1'), {}) // no model @@ -450,15 +450,17 @@ describe('adapter registration, routing, and accepted-input ownership', () => { : undefined).toContain('has no provider/model') expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' ? turnEnd.data.reason.error.message - : undefined).toContain('agent/request') + : undefined).toContain('agent/route') + expect(agent.session.snapshotEvents().some(event => event.type === 'step/start')).toBe(false) + expect(adapter.requests).toHaveLength(0) }) - it('the agent/request waterfall can supply the model for a model-less agent', async () => { + it('the agent/route waterfall can supply the model for a model-less agent', async () => { const adapter = new MockAdapter([textResponse('routed')]) const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('a1'), {}) // no model — router plugin decides - ctx.on('agent/request', async (_payload, next) => { + ctx.on('agent/route', async (_payload, next) => { return { ...await next(), provider: 'mock', model: 'mock' } }) @@ -468,6 +470,24 @@ describe('adapter registration, routing, and accepted-input ownership', () => { expect(agent.session.deriveMessages().at(-1)?.content).toEqual([{ type: 'text', text: 'routed' }]) }) + it('agent/request cannot replace the step route', async () => { + const adapter = new MockAdapter([textResponse('never')]) + const ctx = await harness(adapter) + ctx.llm.registerAdapter(['other'], new MockAdapter([textResponse('never')])) + const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) + ctx.on('agent/request', async (_payload, next) => ({ ...await next(), provider: 'other' })) + + send(agent, 'go') + await waitForIdle(ctx, agent) + const turnEnd = agent.session.snapshotEvents().findLast(event => event.type === 'turn/end') + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' + ? turnEnd.data.reason.error.message + : undefined).toContain('agent/request cannot replace the step route mock/mock with other/mock') + expect(agent.session.snapshotEvents().filter(event => ['request/header', 'system/message', 'user/message'].includes(event.type))) + .toEqual([]) + expect(adapter.requests).toHaveLength(0) + }) + it('durable inbox splices carry exact messages and the claimed steer preserves its source', async () => { const adapter = new MockAdapter([toolCallResponse('c1', 'noop', {}), textResponse('done')]) const ctx = await harness(adapter) diff --git a/packages/core/agent-loop/tests/inbox.spec.ts b/packages/core/agent-loop/tests/inbox.spec.ts index 8f1ac7eeef..739d18b990 100644 --- a/packages/core/agent-loop/tests/inbox.spec.ts +++ b/packages/core/agent-loop/tests/inbox.spec.ts @@ -22,7 +22,6 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { const session = overrides.session ?? Session.create(id) const ctx = overrides.ctx ?? new Context() return { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index 9ae652df61..6f992a1c68 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -602,23 +602,12 @@ describe('agent loop', () => { expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed') }) - it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => { - // AgentOptions.model unset: the model arrives in the agent/request - // waterfall (the loop's documented fallback — see runStep's no-model - // error). {{model}} renders BEFORE that waterfall, so the SAME plugin - // states the fact early on system-prompt/assemble — the owner of a - // late-bound fact owns stating it wherever it is claimed. + it('renders a {{model}} persona from the route an agent/route listener supplies', async () => { + // AgentOptions.model unset: the step route arrives through agent/route, + // before prompt preparation, so the prompt variables already name it. const adapter = new MockAdapter([textResponse('ok')]) const ctx = await harness(adapter, 'You run on {{model}}.') - ctx.on('system-prompt/assemble', async (assembly, _context, next) => { - assembly.variables['provider'] = 'mock' - assembly.variables['model'] = 'mock' - return next() - }) - ctx.on('agent/request', async (_payload, next) => { - const config = await next() - return { ...config, provider: 'mock', model: 'mock' } - }) + ctx.on('agent/route', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock' })) const agent = await ctx.agentLoop.create(SessionId('a-late-model'), {}) send(agent, 'hi') @@ -1309,19 +1298,12 @@ describe('agent loop', () => { expect(texts).toContain('late steering') }) - it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => { + it('agent/route waterfall switches models for the step; the switch is logged', async () => { const adapter = new MockAdapter([textResponse('ok')]) const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) - ctx.on('agent/request', async (_payload, next) => { - const config = await next() - // The seed is frozen — config is not a mutable per-call knob; a switch - // is proposed by returning a replacement, and the loop logs it. - expect(Object.isFrozen(config)).toBe(true) - expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError) - return { ...config, model: 'other-model' } - }) + ctx.on('agent/route', async (_payload, next) => ({ ...await next(), model: 'other-model' })) send(agent, 'hi') await waitForIdle(ctx, agent) @@ -1332,6 +1314,27 @@ describe('agent loop', () => { expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model') }) + it('agent/request waterfall replaces call controls with a replacement config; the change is logged', async () => { + const adapter = new MockAdapter([textResponse('ok')]) + const ctx = await harness(adapter) + const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) + + ctx.on('agent/request', async (_payload, next) => { + const config = await next() + // The seed is frozen — config is not a mutable per-call knob; a change + // is proposed by returning a replacement, and the loop logs it. + expect(Object.isFrozen(config)).toBe(true) + expect(() => { (config as { temperature?: number }).temperature = 0.5 }).toThrow(TypeError) + return { ...config, temperature: 0.5 } + }) + + send(agent, 'hi') + await waitForIdle(ctx, agent) + expect(adapter.requests[0]!.temperature).toBe(0.5) + const headerEvent = agent.session.snapshotEvents().find(e => e.type === 'request/header') + expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.temperature).toBe(0.5) + }) + it('agent/pre-step fires once per proposed step before the step is opened', async () => { const adapter = new MockAdapter([ toolCallResponse('c1', 'echo', {}, 'calling echo'), diff --git a/packages/core/agent-loop/tests/request-reconstruction.spec.ts b/packages/core/agent-loop/tests/request-reconstruction.spec.ts index 69014d400d..7c0fe9b60e 100644 --- a/packages/core/agent-loop/tests/request-reconstruction.spec.ts +++ b/packages/core/agent-loop/tests/request-reconstruction.spec.ts @@ -294,11 +294,9 @@ describe('request stability across the loop', () => { provider: 'deepseek', model: 'deepseek-model', }) - ctx.on('agent/request', async ({ turn }, next) => { - const config = await next() - return turn === 2 - ? { ...config, provider: 'other', model: 'other-model' } - : config + ctx.on('agent/route', async ({ turn }, next) => { + const route = await next() + return turn === 2 ? { provider: 'other', model: 'other-model' } : route }) send(agent, 'first') @@ -328,11 +326,9 @@ describe('request stability across the loop', () => { model: 'deepseek-model', maxTokens: 4_096, }) - ctx.on('agent/request', async ({ turn }, next) => { - const config = await next() - return turn === 2 - ? { ...config, provider: 'other', model: 'other-model' } - : config + ctx.on('agent/route', async ({ turn }, next) => { + const route = await next() + return turn === 2 ? { provider: 'other', model: 'other-model' } : route }) send(agent, 'first') @@ -948,7 +944,7 @@ describe('request/context capacity records', () => { send(agent, 'first') await waitForIdle(ctx, agent) - ctx.on('agent/request', ({ agent: subject }, next) => subject === agent + ctx.on('agent/route', ({ agent: subject }, next) => subject === agent ? Promise.resolve({ provider: 'mock', model: 'large' }) : next()) send(agent, 'second') @@ -976,7 +972,7 @@ describe('request/context capacity records', () => { const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('capacity-clear'), { provider: 'mock', model: 'known' }) let model = 'known' - ctx.on('agent/request', ({ agent: subject }, next) => subject === agent + ctx.on('agent/route', ({ agent: subject }, next) => subject === agent ? Promise.resolve({ provider: 'mock', model }) : next()) diff --git a/packages/core/agent-loop/tests/system-prompt-admission.spec.ts b/packages/core/agent-loop/tests/system-prompt-admission.spec.ts index 47390d938b..b904088576 100644 --- a/packages/core/agent-loop/tests/system-prompt-admission.spec.ts +++ b/packages/core/agent-loop/tests/system-prompt-admission.spec.ts @@ -369,13 +369,13 @@ describe('prepared-route prompt admission', () => { expect(resumed.session.snapshotEvents().filter(event => event.type === 'request/header').at(-1)?.data.reason).toBe('resume') }) - it.each(['request', 'prepare'] as const)('cancels during %s before step and input admission', async (stage) => { + it.each(['request', 'prepare'] as const)('cancels during %s with a balanced empty step before input admission', async (stage) => { const h = await harness() const entered = Promise.withResolvers() const release = Promise.withResolvers() const observe = async () => { const types = h.agent.session.snapshotEvents().map(event => event.type) - expect(types).not.toContain('step/start') + expect(types).toContain('step/start') expect(types).not.toContain('system/message') expect(types).not.toContain('user/message') expect(types).not.toContain('request/header') @@ -394,10 +394,32 @@ describe('prepared-route prompt admission', () => { await h.agent.whenIdle() expect(h.capable.requests).toHaveLength(0) const types = h.agent.session.snapshotEvents().map(event => event.type) - expect(types.filter(type => type === 'step/start' || type === 'step/end')).toEqual([]) + expect(types.filter(type => type === 'step/start' || type === 'step/end')).toEqual(['step/start', 'step/end']) expect(types.filter(type => ['system/message', 'user/message', 'request/header'].includes(type))).toEqual([]) }) + it('cancels during route before a step opens', async () => { + const h = await harness() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + h.ctx.on('agent/route', async (_payload, next) => { + expect(h.agent.session.snapshotEvents().map(event => event.type)).not.toContain('step/start') + entered.resolve(undefined) + await release.promise + return next() + }) + h.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'cancelled' }], source: { kind: 'user' } })) + await entered.promise + h.agent.cancel({ kind: 'user' }) + release.resolve(undefined) + await h.agent.whenIdle() + expect(h.capable.requests).toHaveLength(0) + const types = h.agent.session.snapshotEvents().map(event => event.type) + expect(types.filter(type => ['step/start', 'step/end', 'system/message', 'user/message', 'request/header'].includes(type))) + .toEqual([]) + expect(types.filter(type => type === 'turn/start' || type === 'turn/end')).toEqual(['turn/start', 'turn/end']) + }) + it('keeps generic config changes and concurrent selection on the same prepared route', async () => { const h = await harness() await send(h.agent, 'first') diff --git a/packages/core/agent-loop/tests/tool-updates.spec.ts b/packages/core/agent-loop/tests/tool-updates.spec.ts index bd0542cc74..5b7e4157d2 100644 --- a/packages/core/agent-loop/tests/tool-updates.spec.ts +++ b/packages/core/agent-loop/tests/tool-updates.spec.ts @@ -113,9 +113,8 @@ describe('tool update emission', () => { }) }) - -describe('request-time tool activation', () => { - it('uses the bound route for asynchronous conditions and rejects a historical name after removal', async () => { +describe('step-time tool activation', () => { + it('uses the step route for asynchronous conditions and rejects a historical name after removal', async () => { const adapter = new MockAdapter([ toolCallResponse('allowed', 'conditional', {}), textResponse('done'), toolCallResponse('removed', 'conditional', {}), textResponse('done'), @@ -124,35 +123,33 @@ describe('request-time tool activation', () => { const routed: string[] = [] let calls = 0 let model = 'enabled' - ctx.on('agent/request', async (_payload, next) => ({ ...await next(), model })) + ctx.on('agent/route', async (_payload, next) => ({ ...await next(), model })) ctx.tools.register(defineContentToolFixture({ name: 'conditional', description: 'Available on one route.', parameters: {}, async execute(_args, exec) { - expect(exec.agent?.currentRoute()).toEqual({ provider: 'mock', model: 'enabled' }) + expect(exec.agent?.session.requestHeader()?.config.model).toBe('enabled') calls++ return [{ type: 'text', text: 'done' }] }, - }), { when: async ({ agent: subject }) => { - const route = subject.currentRoute() + }), { when: async ({ route }) => { expect(Object.isFrozen(route)).toBe(true) routed.push(route.model) await Promise.resolve() return route.model === 'enabled' } }) - expect(() => agent.currentRoute()).toThrow('no prepared model request') await send(agent, 'enabled') model = 'disabled' await send(agent, 'try the historical name') expect(calls).toBe(1) expect(routed).toEqual(['enabled', 'enabled', 'disabled', 'disabled']) + expect(adapter.requests.map(request => request.model)).toEqual(routed) expect(developerEvents(agent).at(-1)?.data.message.content) .toEqual([{ type: 'tool-removal', toolName: 'conditional' }]) expect(agent.session.snapshotEvents().find(event => event.type === 'tool/result' && event.data.message.toolCallId === 'removed')?.data) .toMatchObject({ error: { code: 'UNKNOWN_TOOL' } }) - expect(() => agent.currentRoute()).toThrow('no prepared model request') }) - it('cancels an asynchronous condition without committing the proposed request', async () => { + it('cancels an asynchronous condition without committing the step request', async () => { const adapter = new MockAdapter([textResponse('unused')]) const { ctx, agent } = await harness(adapter) const entered = Promise.withResolvers() @@ -168,21 +165,21 @@ describe('request-time tool activation', () => { await running expect(adapter.requests).toEqual([]) expect(agent.session.snapshotEvents().filter(event => ['request/header', 'system/message', 'user/message'].includes(event.type))).toEqual([]) - expect(() => agent.currentRoute()).toThrow('no prepared model request') }) - it.each(['condition', 'route'])('reassembles on a retry after the %s changes without admitting users again', async (change) => { + it('keeps one route, tool set, and prompt across retries without admitting users again', async () => { const adapter = new MockAdapter([ [{ type: 'finish', reason: { kind: 'error', failure: { code: 'SERVER', message: 'retry', status: 503 } } }], textResponse('done'), ]) const { ctx, agent } = await harness(adapter) let retried = false - let admissions = 0 - ctx.on('agent/pre-step', (_input, next) => { admissions++; return next() }) - ctx.on('agent/request', async (_input, next) => ({ - ...await next(), model: change === 'route' && retried ? 'second' : 'first', - })) + const counts = { routes: 0, conditions: 0, admissions: 0 } + ctx.on('agent/pre-step', (_input, next) => { counts.admissions++; return next() }) + ctx.on('agent/route', async (_input, next) => { + counts.routes++ + return { ...await next(), model: retried ? 'second' : 'first' } + }) ctx.on('agent/request-error', async (_input, next) => { await next() retried = true @@ -191,18 +188,18 @@ describe('request-time tool activation', () => { ctx.tools.register(defineContentToolFixture({ name: 'conditional', description: 'Retry-dependent availability.', parameters: {}, execute: async () => [{ type: 'text', text: 'unused' }], - }), { when: () => change === 'route' || retried }) + }), { when: () => { counts.conditions++; return retried } }) ctx.systemPrompt.section({ name: 'retry:guidance', order: 0, complete: true, - text: context => `${agent.currentRoute().model}:${ctx.tools.schemas(agent, context.toolSet).map(tool => tool.name).join(',')}`, + text: context => `${context.route?.model}:${ctx.tools.schemas(agent, context.toolSet).map(tool => tool.name).join(',')}`, }) await send(agent, 'retry once') - const prompts = adapter.requests.map(request => request.messages.find(message => message.role === 'system')?.content) - expect(prompts[0]).toEqual([{ type: 'text', text: change === 'route' ? 'first:conditional' : 'first:' }]) - expect(prompts[1]).toEqual([{ type: 'text', text: change === 'route' ? 'second:conditional' : 'first:conditional' }]) - expect(admissions).toBe(1) + expect(adapter.requests.map(request => request.model)).toEqual(['first', 'first']) + expect(adapter.requests.map(request => request.tools ?? [])).toEqual([[], []]) + expect(adapter.requests.map(request => request.messages.find(message => message.role === 'system')?.content)) + .toEqual([[{ type: 'text', text: 'first:' }], [{ type: 'text', text: 'first:' }]]) + expect(counts).toEqual({ routes: 1, conditions: 1, admissions: 1 }) expect(agent.session.snapshotEvents().filter(event => event.type === 'user/message' && event.data.source.kind === 'user')).toHaveLength(1) - expect(() => agent.currentRoute()).toThrow('no prepared model request') }) it('reports condition failures without admitting a partial request', async () => { @@ -217,7 +214,6 @@ describe('request-time tool activation', () => { expect(agent.session.snapshotEvents().filter(event => ['request/header', 'system/message', 'user/message'].includes(event.type))).toEqual([]) expect(agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data) .toMatchObject({ reason: { kind: 'error', error: { code: 'TOOL_ACTIVATION_FAILED' } } }) - expect(() => agent.currentRoute()).toThrow('no prepared model request') }) it('shares the selected set with prompt guidance', async () => { diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 1502bd30aa..e7e1759e5f 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2594a1e02adea801 zh: cae8860369728efb /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: - en: fb42e501ef88a040 - zh: 8822f29727d14bef + en: 5d700c9eed84bcf5 + zh: a0498f1814bfee05 /deepseek-ai-dsh-agent/understand-the-implementation: en: ce7e776e9d516bdb zh: 59d2751743db7795 @@ -36,8 +36,8 @@ en: 7c850051d2857bfa zh: 4cab817553114e15 /deepseek-ai-dsh-agent/understand-the-implementation/step-admission: - en: 5bba803d6c23370a - zh: 0e5e3c037a111141 + en: edd4ed5033c294e7 + zh: 7c627497fe450702 /deepseek-ai-dsh-agent/understand-the-implementation/durable-inbox: en: f6802c7f94f623b3 zh: cc3885db80765970 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index d2255afddb..0ca04dd4e4 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -64,7 +64,7 @@ await handle.agent.whenIdle() ### Intercept or observe work in flight -The `agent/*` events let plugins act on live work without depending on the loop package. `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). +The `agent/*` events let plugins act on live work without depending on the loop package. `agent/route` chooses each step's provider and model; `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). ----- @@ -82,9 +82,9 @@ The package is built on one separation: the public `Agent` surface and registry ### Step admission -`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. Route preparation runs before `agent/pre-step`. Acceptance does not commit the batch: tool conditions and prompt assembly must also succeed before system and user messages are logged. Cancellation during route preparation opens no step and commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. +`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. `agent/route` chooses the step's provider and model before `agent/pre-step`, whose payload carries that `route`. Acceptance does not commit the batch: after `step/start`, tool conditions, prompt assembly, `agent/request`, and `prepareCall()` must succeed before system and user messages are logged. Cancellation during routing opens no step, and cancellation during a later async phase commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. -`agent.currentRoute()` returns the immutable provider/model bound by request preparation, through the corresponding tool batch. It throws before preparation and after the batch ends; initial options and previous Session headers are not fallbacks. Auxiliary model calls do not replace the main request route. +The step route supplies or replaces the creation-time options pair. Prompt preparation, `agent/pre-step`, tool conditions, and every request attempt in the step use it; an `agent/request` listener that returns another provider or model fails the step. `installModelSelection` captures its selection when `agent/route` runs, so a selection made during a step applies from the next step. ### Durable inbox diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index 722b9edd45..c8f9a23c29 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -64,7 +64,7 @@ await handle.agent.whenIdle() ### 拦截或观察进行中的工作 -`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 +`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/route` 选定每个步骤的提供方与模型;`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 ----- @@ -82,9 +82,9 @@ await handle.agent.whenIdle() ### 步骤准入 -`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。路由准备在 `agent/pre-step` 之前执行。接纳不等于提交:工具条件与提示词组装也必须成功,随后才记录系统提示词与用户批次。在路由准备期间取消不会打开步骤,也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 +`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。`agent/route` 在 `agent/pre-step` 之前选定该步骤的提供方与模型,`agent/pre-step` 的 payload 携带该 `route`。接纳不等于提交:`step/start` 之后,工具条件、提示词组装、`agent/request` 与 `prepareCall()` 都成功后,才记录系统提示词与用户批次。在路由选择期间取消不会打开步骤,在之后任一异步阶段取消也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 -`agent.currentRoute()` 返回请求准备绑定的不可变提供方与模型,持续到对应工具批次结束。准备前和批次结束后调用会抛错,不回退到初始选项或先前 Session 请求头。辅助模型调用不会替换主请求路由。 +步骤路由会补上或替换创建时 options 中的这对值。提示词准备、`agent/pre-step`、工具条件以及该步骤的每次请求尝试都使用它;`agent/request` 监听器若返回其他提供方或模型,步骤会失败。`installModelSelection` 在 `agent/route` 运行时捕获其选择,因此步骤进行中做出的选择从下一个步骤开始生效。 ### 持久 inbox diff --git a/packages/core/agent/src/model-selection.ts b/packages/core/agent/src/model-selection.ts index d5801e30b7..eaf693beb0 100644 --- a/packages/core/agent/src/model-selection.ts +++ b/packages/core/agent/src/model-selection.ts @@ -10,7 +10,7 @@ import { type LlmCallConfig, type ReasoningEffortId, } from '@deepseek-ai/dsh-llm' -import type { PreStepDecision } from './runtime-types.ts' +import type { PreStepDecision, StepRoute } from './runtime-types.ts' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { @@ -30,21 +30,21 @@ export interface ModelSelection { /** Mutable model selection plus the value captured for the current step. */ export interface ModelSelectionRef { - /** Model selected for the next step entering route preparation. */ + /** Model selected for the next step to start. */ current: ModelSelection | undefined - /** Selection captured by the first route preparation of the current step. */ + /** Selection captured when the current step chose its route. */ assembled: ModelSelection | undefined } -function sameRoute(left: ModelSelection, right: ModelSelection): boolean { +function sameRoute(left: StepRoute, right: StepRoute): boolean { return left.provider === right.provider && left.model === right.model } -function routeLabel(route: ModelSelection, other: ModelSelection): string { +function routeLabel(route: StepRoute, other: StepRoute): string { return route.provider === other.provider ? route.model : `${route.provider}/${route.model}` } -function modelSwitchNotice(previous: ModelSelection, selected: ModelSelection) { +function modelSwitchNotice(previous: StepRoute, selected: StepRoute) { const from = routeLabel(previous, selected) const to = routeLabel(selected, previous) return createUserMessage({ @@ -61,38 +61,39 @@ function modelSwitchNotice(previous: ModelSelection, selected: ModelSelection) { } /** - * Couple one mutable selection to Agent-scoped request routing. The first - * request preparation in a step captures the selection before delegating; - * retries retain it, and concurrent selections apply to later steps. An absent - * selected effort clears inherited effort, restoring the model's provider default. + * Couple one mutable selection to Agent-scoped step routing. Each step + * captures the selection when `agent/route` chooses its provider and model, + * and every request attempt in that step applies the captured effort; a + * selection made during the step applies from the next step. An absent + * selected effort clears inherited effort, restoring the model's provider + * default. * * A provider/model change appends a durable user-role notice to the next - * admitted request. It compares the bound request route with the latest - * request header; effort-only changes and empty no-request decisions add no - * notice. Failure before header persistence repeats the notice on the next - * request. + * admitted request. It compares the step route with the latest request + * header; effort-only changes and empty no-request decisions add no notice. + * Failure before header persistence repeats the notice on the next request. * * @param agentCtx - The selected Agent's scoped context. * @param selection - Mutable selection owned by the calling entry point. * @returns Disposer for all scoped waterfall listeners. */ export function installModelSelection(agentCtx: Context, selection: ModelSelectionRef): () => void { - let capturedStep: { turn: number; step: number } | undefined + const disposeRoute = agentCtx.on('agent/route', async (_payload, next): Promise => { + const selected = selection.current === undefined ? undefined : { ...selection.current } + selection.assembled = selected + const route = await next() + return selected === undefined ? route : { provider: selected.provider, model: selected.model } + }) const disposeRequest = agentCtx.on( 'agent/request', - async ({ turn, step }, next): Promise => { - if (capturedStep?.turn !== turn || capturedStep.step !== step) { - capturedStep = { turn, step } - selection.assembled = selection.current === undefined ? undefined : { ...selection.current } - } + async (_payload, next): Promise => { const resolved = await next() const selected = selection.assembled - if (selected === undefined) return resolved + // Another route listener may have replaced the captured route; its model keeps its own effort. + if (selected === undefined || !sameRoute(selected, resolved)) return resolved const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved return { ...withoutInheritedEffort, - provider: selected.provider, - model: selected.model, ...selected.reasoningEffort === undefined ? {} : { reasoningEffort: selected.reasoningEffort }, @@ -101,19 +102,19 @@ export function installModelSelection(agentCtx: Context, selection: ModelSelecti ) const disposeNotice = agentCtx.on( 'agent/pre-step', - async ({ agent, messages, signal, step }, next): Promise => { + async ({ agent, messages, route, signal, step }, next): Promise => { const decision = await next() if (decision.kind === 'reject' || signal.aborted) return decision // The loop skips an empty first step and an emptied offered continuation. if (decision.messages.length === 0 && (step === 1 || messages.length > 0)) return decision - const selected = agent.currentRoute() const previous = agent.session.requestHeader()?.config - if (previous === undefined || sameRoute(selected, previous)) return decision - return { ...decision, messages: [...decision.messages, modelSwitchNotice(previous, selected)] } + if (previous === undefined || sameRoute(route, previous)) return decision + return { ...decision, messages: [...decision.messages, modelSwitchNotice(previous, route)] } }, { prepend: true }, ) return () => { + disposeRoute() disposeRequest() disposeNotice() } diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 9501b45841..ec1c03a7c4 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -19,9 +19,19 @@ declare module '@deepseek-ai/dsh-system-prompt' { interface AssembleContext { /** Agent for this assembly; absent on diagnostics. When present, `scope` must identify the same agent. */ agent?: Agent + /** Provider and model of the step being assembled; absent outside a step. */ + route?: StepRoute } } +/** Provider and model that `agent/route` chose for one step and every request attempt in it. */ +export interface StepRoute { + /** Registered provider route. */ + readonly provider: string + /** Model id interpreted by the provider adapter. */ + readonly model: string +} + /** Merge-extensible agent creation options. Persona belongs to system-prompt sections. */ export interface AgentOptions { /** Provider route (must have a registered adapter at call time). */ @@ -162,14 +172,8 @@ export type AssistantStreamFrame = declare module './types.ts' { interface Agent { - /** Initial request options; currentRoute() reports the bound request route. */ + /** Creation-time request options; `agent/route` may choose another provider and model for each step. */ readonly options: AgentOptions - /** - * Read the immutable route bound to this request and its tool batch. - * @returns the actual provider and model selected by prepareCall(). - * @throws when no main request is prepared; never falls back to prior requests. - */ - currentRoute(): Readonly> /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -319,20 +323,41 @@ declare module '@deepseek-ai/cordis' { * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. + * @param payload.route - the provider and model `agent/route` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ - 'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise + 'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; route: StepRoute; signal: AbortSignal }, next: () => Promise): Promise /** - * Replace the frozen call configuration. `await next()` yields the config - * the machine would use (agent options on the first request, the logged - * header afterwards); return a replacement to switch. On step admission, - * this runs before context preparation and `agent/pre-step`. Cancellation - * here or during subsequent `prepareCall()` resolution opens no step and - * commits no system prompt or user batch. The prepared call capability - * governs prompt admission. Model-visible content must use logged channels; - * this waterfall cannot mutate messages. + * Choose the provider and model for one proposed step. `await next()` + * yields the route the machine would use (agent options before this loop + * logs a request, the logged header afterwards); return a replacement to + * switch. The loop runs this once per proposed step, before context + * preparation and `agent/pre-step`. Prompt preparation, tool conditions, + * and every request attempt in the step use the result, so a later choice + * applies from the next step. Cancellation here opens no step. + * @param payload.agent - the agent proposing the step. + * @param payload.turn - the turn that will own the step. + * @param payload.step - the step proposed by the loop. + * @param payload.signal - the current turn's explicit abort signal. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode waterfall + */ + 'agent/route'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise + /** + * Replace the frozen call configuration of one request attempt. `await + * next()` yields the config the machine would use on the step's + * `agent/route` result: agent options on the first request, the logged + * header afterwards, and no effort recorded for another model. Return a + * replacement to change call controls such as reasoning effort; returning + * another provider or model fails the step. On step admission, this runs + * after prompt assembly and `step/start`, before the system prompt and + * accepted user batch are committed, and again for each retry. + * Cancellation here or during subsequent `prepareCall()` resolution + * commits neither. The prepared call capability governs prompt admission. + * Model-visible content must use logged channels; this waterfall cannot + * mutate messages. * @param payload.agent - the agent making the model call. * @param payload.turn - the open turn number. * @param payload.step - the step whose request this is. diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index 282c942dd6..c31acf5c66 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -18,7 +18,6 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { const session = overrides.session ?? Session.create(id) const ctx = overrides.ctx ?? new Context() const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/core/agent/tests/archive-admission.spec.ts b/packages/core/agent/tests/archive-admission.spec.ts index 40556764c7..0f84de4fe0 100644 --- a/packages/core/agent/tests/archive-admission.spec.ts +++ b/packages/core/agent/tests/archive-admission.spec.ts @@ -15,7 +15,6 @@ async function liveAgent(ctx: Context, rawId: string, initial: AgentStatus): Pro const cancels: CancelCall[] = [] let status = initial const agent: LiveAgent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session: Session.create(id), diff --git a/packages/core/agent/tests/model-selection.spec.ts b/packages/core/agent/tests/model-selection.spec.ts index 7dddee1b9a..c0d028cefe 100644 --- a/packages/core/agent/tests/model-selection.spec.ts +++ b/packages/core/agent/tests/model-selection.spec.ts @@ -1,7 +1,14 @@ -/** Model selection is captured before route preparation and remains stable within a step. */ +/** Model selection chooses each step's route once; requests in that step keep it. */ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { agentEvents, installModelSelection, type Agent, type ModelSelection, type ModelSelectionRef } from '../src/index.ts' +import { + agentEvents, + installModelSelection, + type Agent, + type ModelSelection, + type ModelSelectionRef, + type StepRoute, +} from '../src/index.ts' import { createUserMessage, ReasoningEffortId, type LlmCallConfig } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' @@ -11,23 +18,23 @@ afterEach(async () => { }) const signal = new AbortController().signal const input = createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'user' } }) +const seedRoute: StepRoute = { provider: 'seed', model: 'seed' } function harness(current?: ModelSelection, previous?: ModelSelection) { const ctx = new Context() contexts.push(ctx) const selection: ModelSelectionRef = { current, assembled: undefined } const dispose = installModelSelection(ctx, selection) - let route: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 } - const agent = { session: Session.create(SessionId('model-selection')), currentRoute: () => route } as Agent + const agent = { session: Session.create(SessionId('model-selection')) } as Agent if (previous) agent.session.append('request/header', { header: { config: previous }, reason: 'initial' }) - const request = async (step: number, seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 }) => { - route = await agentEvents(ctx, agent).waterfall('agent/request', { turn: 1, step, signal }, () => Promise.resolve(seed)) - return route - } - const preStep = (messages = [input], offered = [input], step = 1, requestSignal = signal) => - agentEvents(ctx, agent).waterfall('agent/pre-step', { turn: 1, step, messages: offered, signal: requestSignal }, + const route = (step: number, seed: StepRoute = seedRoute) => + agentEvents(ctx, agent).waterfall('agent/route', { turn: 1, step, signal }, () => Promise.resolve(seed)) + const request = (step: number, seed: LlmCallConfig) => + agentEvents(ctx, agent).waterfall('agent/request', { turn: 1, step, signal }, () => Promise.resolve(seed)) + const preStep = (stepRoute: StepRoute, messages = [input], offered = [input], step = 1, stepSignal = signal) => + agentEvents(ctx, agent).waterfall('agent/pre-step', { turn: 1, step, messages: offered, route: stepRoute, signal: stepSignal }, () => Promise.resolve({ kind: 'enter' as const, messages })) - return { ctx, agent, selection, dispose, request, preStep } + return { ctx, agent, selection, dispose, route, request, preStep } } function notice(from: string, to: string) { @@ -35,54 +42,67 @@ function notice(from: string, to: string) { } describe('installModelSelection()', () => { - it('captures selection per step, preserves retries, and disposes routing', async () => { + it('captures one selection per step for its route and every request effort, then disposes routing', async () => { const h = harness() - const seed: LlmCallConfig = { provider: 'seed', model: 'seed', temperature: 0.2 } - expect(await h.request(0, seed)).toBe(seed) + expect(await h.route(1)).toBe(seedRoute) + const inherited: LlmCallConfig = { provider: 'alpha', model: 'a1', reasoningEffort: ReasoningEffortId('max'), temperature: 0.2 } + expect(await h.request(1, inherited)).toBe(inherited) + h.selection.current = { provider: 'alpha', model: 'a1', reasoningEffort: ReasoningEffortId('high') } - expect(await h.request(1)).toEqual({ ...seed, ...h.selection.current }) + expect(await h.route(2)).toEqual({ provider: 'alpha', model: 'a1' }) h.selection.current = { provider: 'beta', model: 'b1' } - expect(await h.request(1)).toMatchObject({ provider: 'alpha', model: 'a1' }) - expect(await h.request(2, { ...seed, reasoningEffort: ReasoningEffortId('max') })).toEqual({ ...seed, ...h.selection.current }) + const selected = { ...inherited, reasoningEffort: ReasoningEffortId('high') } + expect(await h.request(2, inherited)).toEqual(selected) + expect(await h.request(2, inherited)).toEqual(selected) + + expect(await h.route(3)).toEqual({ provider: 'beta', model: 'b1' }) + expect(await h.request(3, { ...inherited, provider: 'beta', model: 'b1' })) + .toEqual({ provider: 'beta', model: 'b1', temperature: 0.2 }) + h.dispose() - expect(await h.request(3, seed)).toBe(seed) + expect(await h.route(4)).toBe(seedRoute) + expect(await h.request(4, inherited)).toBe(inherited) }) - it('announces the bound same-provider and cross-provider routes', async () => { - const h = harness({ provider: 'alpha', model: 'a1' }, { provider: 'alpha', model: 'a0' }) - await h.request(1) - await expect(h.preStep()).resolves.toMatchObject({ messages: [input, notice('a0', 'a1')] }) - h.selection.current = { provider: 'beta', model: 'b1' } - await h.request(2) - h.selection.current = { provider: 'alpha', model: 'a2' } - await expect(h.preStep()).resolves.toMatchObject({ messages: [input, notice('alpha/a0', 'beta/b1')] }) - await h.request(3) - await expect(h.preStep()).resolves.toMatchObject({ messages: [input, notice('a0', 'a2')] }) + it('keeps the effort of a route that an outer listener replaced', async () => { + const h = harness({ provider: 'alpha', model: 'a1', reasoningEffort: ReasoningEffortId('high') }) + h.ctx.on('agent/route', async (_payload, next) => { + await next() + return { provider: 'gamma', model: 'g1' } + }, { prepend: true }) + expect(await h.route(1)).toEqual({ provider: 'gamma', model: 'g1' }) + const config: LlmCallConfig = { provider: 'gamma', model: 'g1', reasoningEffort: ReasoningEffortId('max') } + expect(await h.request(1, config)).toBe(config) + }) + + it('announces same-provider and cross-provider step routes', async () => { + const h = harness(undefined, { provider: 'alpha', model: 'a0' }) + await expect(h.preStep({ provider: 'alpha', model: 'a1' })).resolves.toMatchObject({ messages: [input, notice('a0', 'a1')] }) + await expect(h.preStep({ provider: 'beta', model: 'b1' })).resolves.toMatchObject({ messages: [input, notice('alpha/a0', 'beta/b1')] }) }) it('preserves initial, unchanged, rejected, cancelled, and disposed decisions', async () => { - const h = harness({ provider: 'alpha', model: 'a0' }) - await h.request(1) - await expect(h.preStep()).resolves.toEqual({ kind: 'enter', messages: [input] }) - h.agent.session.append('request/header', { header: { config: h.agent.currentRoute() }, reason: 'initial' }) - h.selection.current = { provider: 'alpha', model: 'a0', reasoningEffort: ReasoningEffortId('high') } - await h.request(2) - await expect(h.preStep()).resolves.toEqual({ kind: 'enter', messages: [input] }) - h.selection.current = { provider: 'alpha', model: 'a1' } - await h.request(3) - await expect(agentEvents(h.ctx, h.agent).waterfall('agent/pre-step', { turn: 1, step: 3, messages: [], signal }, + const h = harness() + const route = { provider: 'alpha', model: 'a0' } + await expect(h.preStep(route)).resolves.toEqual({ kind: 'enter', messages: [input] }) + h.agent.session.append('request/header', { + header: { config: { ...route, reasoningEffort: ReasoningEffortId('high') } }, + reason: 'initial', + }) + await expect(h.preStep(route)).resolves.toEqual({ kind: 'enter', messages: [input] }) + const switched = { provider: 'alpha', model: 'a1' } + await expect(agentEvents(h.ctx, h.agent).waterfall('agent/pre-step', { turn: 1, step: 3, messages: [], route: switched, signal }, () => Promise.resolve({ kind: 'reject' as const }))).resolves.toEqual({ kind: 'reject' }) - const aborted = AbortSignal.abort() - await expect(h.preStep([input], [input], 3, aborted)).resolves.toEqual({ kind: 'enter', messages: [input] }) + await expect(h.preStep(switched, [input], [input], 3, AbortSignal.abort())).resolves.toEqual({ kind: 'enter', messages: [input] }) h.dispose() - await expect(h.preStep()).resolves.toEqual({ kind: 'enter', messages: [input] }) + await expect(h.preStep(switched)).resolves.toEqual({ kind: 'enter', messages: [input] }) }) it('preserves empty claims and announces an empty tool continuation', async () => { - const h = harness({ provider: 'alpha', model: 'a1' }, { provider: 'alpha', model: 'a0' }) - await h.request(1) - await expect(h.preStep([])).resolves.toEqual({ kind: 'enter', messages: [] }) - await expect(h.preStep([], [input], 2)).resolves.toEqual({ kind: 'enter', messages: [] }) - await expect(h.preStep([], [], 2)).resolves.toMatchObject({ messages: [notice('a0', 'a1')] }) + const h = harness(undefined, { provider: 'alpha', model: 'a0' }) + const route = { provider: 'alpha', model: 'a1' } + await expect(h.preStep(route, [])).resolves.toEqual({ kind: 'enter', messages: [] }) + await expect(h.preStep(route, [], [input], 2)).resolves.toEqual({ kind: 'enter', messages: [] }) + await expect(h.preStep(route, [], [], 2)).resolves.toMatchObject({ messages: [notice('a0', 'a1')] }) }) }) diff --git a/packages/core/system-prompt/README.i18n.yaml b/packages/core/system-prompt/README.i18n.yaml index 18bb14f61c..8abb19e207 100644 --- a/packages/core/system-prompt/README.i18n.yaml +++ b/packages/core/system-prompt/README.i18n.yaml @@ -21,8 +21,8 @@ en: 87e28893e6cf58d7 zh: 06f476b38c4d2038 /deepseek-ai-dsh-system-prompt/use-this-package/contribute-a-prompt-section: - en: db364cc533949015 - zh: a6e8a12d9a661b60 + en: 1d970a1e99cd71bb + zh: 62f30c25e82bdbea /deepseek-ai-dsh-system-prompt/use-this-package/contribute-a-prompt-variable: en: b3e4c9b4ced59488 zh: d80c791e72bd5821 @@ -72,8 +72,8 @@ en: 3039bc5e7a796b21 zh: 6b7a9eaf69c9ea53 /deepseek-ai-dsh-system-prompt/model-experience/tool-schemas/what-the-model-sees: - en: b3873ff844d91e34 - zh: 5cccd2afda37af9a + en: a976fa380a4c733c + zh: 57894caf0640898a /deepseek-ai-dsh-system-prompt/model-experience/tool-schemas/token-effect: en: f3a7d374c55e1720 zh: 0ee48af678cb875f diff --git a/packages/core/system-prompt/README.md b/packages/core/system-prompt/README.md index d6a37baa85..70c465cdaf 100644 --- a/packages/core/system-prompt/README.md +++ b/packages/core/system-prompt/README.md @@ -67,7 +67,7 @@ Set `interpolate: false` on a section or dynamic context to preserve its text li `refreshContext(assembly, context)` refreshes registered runtime facts after pre-step and route preparation. It preserves accepted sections, tools, variables, and contexts contributed only by the assembly waterfall, applies current optional-context suppression, and restores missing required entries. Put changing facts in context providers; registered context text is read again before admission. -`prepare(context)` resolves variables and runtime facts through `system-prompt/prepare` before step admission. After the loop binds the route and commits step selections, `assemble(context, preparation)` resolves sections and tool declarations. Presentation listeners receive sections, contexts, and variables; tools remain provider-owned. Tool-aware section callbacks use `context.toolSet` to inspect the same request selection as execution. +`prepare(context)` resolves variables and runtime facts through `system-prompt/prepare` before step admission. After `agent/pre-step` accepts the step and commits its selections, `assemble(context, preparation)` resolves sections and tool declarations. Presentation listeners receive sections, contexts, and variables; tools remain provider-owned. Tool-aware section callbacks use `context.toolSet` to inspect the same step selection as execution. ### Contribute a prompt variable @@ -159,7 +159,7 @@ Prefix-stable while identity, persona, variables, section text, and order render #### What the model sees -For shipped tools, the model receives the per-agent-visible subset of the [generated tool schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tools), ordered by configuration or lexicographically after restrictions and request-time activation. Extensions can contribute additional definitions through the same registry. Sections and schema providers are separate assembly inputs. A restriction does not remove a section registration: tool-guidance plugins use `text({ scope, toolSet })` and `ctx.tools.get(name, scope, toolSet)` to return empty text or select applicable fragments. Arbitrary static sections are not automatically rewritten. +For shipped tools, the model receives the per-agent-visible subset of the [generated tool schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tools), ordered by configuration or lexicographically after restrictions and step-time activation. Extensions can contribute additional definitions through the same registry. Sections and schema providers are separate assembly inputs. A restriction does not remove a section registration: tool-guidance plugins use `text({ scope, toolSet })` and `ctx.tools.get(name, scope, toolSet)` to return empty text or select applicable fragments. Arbitrary static sections are not automatically rewritten. #### Token effect diff --git a/packages/core/system-prompt/README.zh.md b/packages/core/system-prompt/README.zh.md index 117ba86ffc..1ec9b81050 100644 --- a/packages/core/system-prompt/README.zh.md +++ b/packages/core/system-prompt/README.zh.md @@ -67,7 +67,7 @@ ctx.systemPrompt.section({ `refreshContext(assembly, context)` 在 pre-step 与路由准备之后刷新已注册的运行时事实。它保留已接纳的段、工具、变量及仅由组装 waterfall 添加的上下文,应用当前的可选上下文抑制,并恢复缺失的必需条目。将变化的事实放在上下文 provider 中;已注册上下文的文本会在准入前再次读取。 -`prepare(context)` 在步骤接纳前通过 `system-prompt/prepare` 解析变量与运行时事实。循环绑定路由并提交步骤选择后,`assemble(context, preparation)` 解析段落与工具声明。展示监听器接收段落、上下文与变量;工具声明仍由提供方持有。依赖工具的段落回调通过 `context.toolSet` 读取与执行相同的请求集合。 +`prepare(context)` 在步骤接纳前通过 `system-prompt/prepare` 解析变量与运行时事实。`agent/pre-step` 接纳步骤并提交其选择后,`assemble(context, preparation)` 解析段落与工具声明。展示监听器接收段落、上下文与变量;工具声明仍由提供方持有。依赖工具的段落回调通过 `context.toolSet` 读取与执行相同的步骤集合。 ### 贡献提示词变量 @@ -159,7 +159,7 @@ You are an AI agent powered by DeepSeek Harness. #### 模型看到什么 -对于已交付工具,模型会收到[生成工具 schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tools)中对每个 agent 可见的子集;限制与请求时激活完成后,按配置或字典序排列。扩展可以通过同一注册表贡献其他定义。段与 schema 提供方是独立的组装输入。限制不会移除段落注册:工具指导插件通过 `text({ scope, toolSet })` 与 `ctx.tools.get(name, scope, toolSet)` 返回空文本或选择适用片段。任意静态段落不会被自动改写。 +对于已交付工具,模型会收到[生成工具 schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tools)中对每个 agent 可见的子集;限制与步骤时激活完成后,按配置或字典序排列。扩展可以通过同一注册表贡献其他定义。段与 schema 提供方是独立的组装输入。限制不会移除段落注册:工具指导插件通过 `text({ scope, toolSet })` 与 `ctx.tools.get(name, scope, toolSet)` 返回空文本或选择适用片段。任意静态段落不会被自动改写。 #### Token 影响 diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index 8d693e9081..a3bf51caa5 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -21,8 +21,8 @@ en: 9d2e6caa39c53d62 zh: 096a777f828c7565 /deepseek-ai-dsh-tools/use-this-package/conditional-tools: - en: 93008deced28d5fe - zh: 09fe2f8693c5f147 + en: ddd6bd2f0cf93524 + zh: 17339d994d48bfa2 /deepseek-ai-dsh-tools/use-this-package/configure-the-presentation-mode: en: 4e27c45ae889369e zh: 7a0cd7a9dc7fe139 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index 3cc61888cb..f54f423bb4 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -65,9 +65,9 @@ The unified schema DSL supports `string`, `number`, `integer`, `boolean`, `null` ### Conditional tools -`register(definition, { when })` evaluates a synchronous or asynchronous condition for each model request. The condition receives `{ agent, signal }`; `agent.currentRoute()` reports the resolved provider/model. False omits the tool from Native declarations, PTC bindings, and execution. A thrown condition fails request preparation as `TOOL_ACTIVATION_FAILED`; it is not treated as ordinary unavailability. Conditions must observe cancellation and must not change registrations or perform tool work. +`register(definition, { when })` evaluates a synchronous or asynchronous condition once for each model step. The condition receives `{ agent, route, signal }`, where `route` is the provider and model that `agent/route` chose for every request attempt in the step. False omits the tool from Native declarations, PTC bindings, and execution. A thrown condition fails step preparation as `TOOL_ACTIVATION_FAILED`; it is not treated as ordinary unavailability. Conditions must observe cancellation and must not change registrations or perform tool work. -`resolve({ agent, signal })` returns a request-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and every Native or PTC execution, then dispose it after the batch settles. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, cancellation, or same-name replacement prevent unstarted calls from using it. Started operations retain their cooperative cancellation obligations. Conditional calls without a resolved set return `UNKNOWN_TOOL`. +`resolve({ agent, route, signal })` returns a step-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and every Native or PTC execution, then dispose it after the step's batch settles; retries in the step reuse it. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, cancellation, or same-name replacement prevent unstarted calls from using it. Started operations retain their cooperative cancellation obligations. Conditional calls without a resolved set return `UNKNOWN_TOOL`. `get(name, scope, toolSet)` and `schemas(scope, toolSet)` inspect an admitted set; omitting `toolSet` inspects registered definitions without evaluating conditions. Tool guidance receives the same selection as `AssembleContext.toolSet`. A presentation transform cannot add or remove callable tools. diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index ce5c49d331..d0ea16d5da 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -65,9 +65,9 @@ ctx.tools.register(defineTool({ ### 条件工具 -`register(definition, { when })` 为每次模型请求计算同步或异步条件。条件接收 `{ agent, signal }`;`agent.currentRoute()` 返回已解析的提供方与模型。返回 false 会从原生声明、PTC 绑定和执行集合中排除工具。条件抛错会以 `TOOL_ACTIVATION_FAILED` 中止请求准备,不会被当成正常不可用。条件必须响应取消,不得改变注册或执行工具操作。 +`register(definition, { when })` 为每个模型步骤计算一次同步或异步条件。条件接收 `{ agent, route, signal }`,其中 `route` 是 `agent/route` 为该步骤所有请求尝试选定的提供方与模型。返回 false 会从原生声明、PTC 绑定和执行集合中排除工具。条件抛错会以 `TOOL_ACTIVATION_FAILED` 中止步骤准备,不会被当成正常不可用。条件必须响应取消,不得改变注册或执行工具操作。 -`resolve({ agent, signal })` 返回请求拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及每次原生或 PTC 执行,批次结束后释放。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制、取消或同名替换会阻止尚未开始的调用继续使用它。已经开始的操作保留协作取消义务。没有已解析集合的条件工具调用返回 `UNKNOWN_TOOL`。 +`resolve({ agent, route, signal })` 返回步骤拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及每次原生或 PTC 执行,步骤的批次结束后释放;同一步骤内的重试复用它。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制、取消或同名替换会阻止尚未开始的调用继续使用它。已经开始的操作保留协作取消义务。没有已解析集合的条件工具调用返回 `UNKNOWN_TOOL`。 `get(name, scope, toolSet)` 和 `schemas(scope, toolSet)` 读取已准入集合;省略 `toolSet` 时只查看已注册定义,不计算条件。工具指导文本通过 `AssembleContext.toolSet` 接收同一集合。展示变换不能增删可调用工具。 diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index 0b8cd9a638..e51018b860 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -11,7 +11,7 @@ import { AnonymousEntries, NamedEntries, ScopedLayers, scopeOf, scopeTarget } fr import type { ScopeKey, ScopeLayer, Scoped } from '@deepseek-ai/dsh-scope' import type { ToolCallId, ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm' import { HarnessError } from '@deepseek-ai/dsh-llm' -import type { Agent } from '@deepseek-ai/dsh-agent' +import type { Agent, StepRoute } from '@deepseek-ai/dsh-agent' import type { UserMessage } from '@deepseek-ai/dsh-session' import { assertNever, deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' import type { PromptSection, ToolProviderResult } from '@deepseek-ai/dsh-system-prompt' @@ -31,7 +31,7 @@ import { renderToolsSdkPy } from './py-types.ts' declare module '@deepseek-ai/dsh-system-prompt' { interface AssembleContext { - /** Request-owned tool selection; absent when inspecting registered definitions. */ + /** Step-owned tool selection; absent when inspecting registered definitions. */ toolSet?: ResolvedToolSet } } @@ -227,29 +227,31 @@ export interface ToolOutputDefinition { presentationMeta?(args: unknown, value: JsonValue): JsonValue } -/** Inputs for a tool's request-time activation condition. */ +/** Inputs for a tool's step-time activation condition. */ export interface ToolActivationContext { - /** Agent whose currentRoute() is bound to the request being prepared. */ + /** Agent preparing the step. */ readonly agent: Agent - /** Cancellation of request preparation; asynchronous conditions must observe it. */ + /** Provider and model that every request attempt in the step uses. */ + readonly route: StepRoute + /** Cancellation of step preparation; asynchronous conditions must observe it. */ readonly signal: AbortSignal } /** Lifecycle-owned conditions for a registered tool. */ export interface ToolRegistrationOptions { /** - * Decide whether this request may call the tool. Omission enables it. False - * excludes it from both declarations and dispatch; rejection fails request - * preparation. Conditions must not mutate registrations or start tool work. - * @param context - requesting agent and cancellation signal. - * @returns whether the tool participates in this request. + * Decide whether the step's requests may call the tool. Omission enables + * it. False excludes it from both declarations and dispatch; rejection fails + * step preparation. Conditions must not mutate registrations or start tool work. + * @param context - preparing agent, step route, and cancellation signal. + * @returns whether the tool participates in this step. */ readonly when?: (context: ToolActivationContext) => boolean | Promise } -/** One request's admitted registrations, also used by nested PTC calls. */ +/** One step's admitted registrations, also used by nested PTC calls. */ export interface ResolvedToolSet { - /** Close request admission after its tool batch settles. */ + /** Close admission after the step's tool batch settles. */ dispose(): void /** * Read admitted registrations that remain visible in their original scope. @@ -259,7 +261,7 @@ export interface ResolvedToolSet { view(scope: ScopeKey | undefined): ReadonlyMap } -/** Failure to determine a tool's request-time availability. */ +/** Failure to determine a tool's step-time availability. */ export class ToolActivationError extends HarnessError { /** * Preserve a condition failure without treating it as normal unavailability. @@ -394,7 +396,7 @@ export interface ToolExecutionInput { readonly arguments: unknown /** The agent on whose behalf the call runs (set by the agent loop). */ readonly agent?: Agent - /** Request admission shared by Native and PTC dispatch. Conditional tools require it. */ + /** Step admission shared by Native and PTC dispatch. Conditional tools require it. */ readonly toolSet?: ResolvedToolSet /** * Opaque token of the enclosing transport execution, when one exists. PTC @@ -1125,7 +1127,7 @@ export class ToolRuntime extends Service { * Register globally or in the calling agent scope. Scoped tools shadow * globals; duplicates within one layer and the reserved `run_code` name fail. * @param definition - tool schema, execution, and optional finalization/presentation callbacks. - * @param options - optional request-time activation condition. + * @param options - optional step-time activation condition. * @returns the exact disposer that unregisters the tool. */ register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void { @@ -1298,7 +1300,7 @@ export class ToolRuntime extends Service { * actually executed. * @param name - the tool name as registered. * @param scope - the viewing scope (the agent); omitted = the global view. - * @param toolSet - request admission; omit only to inspect registered definitions. + * @param toolSet - step admission; omit only to inspect registered definitions. * @returns the definition the scope resolves, or undefined when none is visible. */ get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined { @@ -1306,10 +1308,10 @@ export class ToolRuntime extends Service { } /** - * Resolve conditions once for this request without changing shared registrations. + * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - agent with a bound route and request cancellation. + * @param context - preparing agent, step route, and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise { @@ -1379,7 +1381,7 @@ export class ToolRuntime extends Service { * Project visible definitions onto the allowlisted model-facing schema fields, * excluding execution and presentation callbacks. * @param scope - the viewing scope (the agent); omitted = the global view. - * @param toolSet - request admission, or omitted for registered-definition inspection. + * @param toolSet - step admission, or omitted for registered-definition inspection. * @returns one deep-cloned schema per visible tool. */ schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[] { diff --git a/packages/core/tools/tests/activation.spec.ts b/packages/core/tools/tests/activation.spec.ts index 5b052468d0..168e0e12a3 100644 --- a/packages/core/tools/tests/activation.spec.ts +++ b/packages/core/tools/tests/activation.spec.ts @@ -18,7 +18,8 @@ async function setup() { contexts.push(ctx) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) - const agent = { id: SessionId('activation'), currentRoute: () => ({ provider: 'test', model: 'test' }) } as Agent + const agent = { id: SessionId('activation') } as Agent + const route = { provider: 'test', model: 'test' } let scope!: Scope await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, { inject: ['tools'] })) const controller = new AbortController() @@ -29,8 +30,8 @@ async function setup() { async execute() { calls++; return 'done' }, }) const input = { agent, name: tool.name, arguments: {}, callId: ToolCallId('call'), signal: controller.signal } - const resolve = () => ctx.tools.resolve({ agent, signal: controller.signal }) - return { ctx, agent, scope, controller, tool, input, resolve, calls: () => calls } + const resolve = () => ctx.tools.resolve({ agent, route, signal: controller.signal }) + return { ctx, agent, route, scope, controller, tool, input, resolve, calls: () => calls } } it('activates and deactivates a registered tool without allowing historical calls', async () => { @@ -103,7 +104,11 @@ it('does not restore a registration removed during its asynchronous condition', it('propagates cancellation after an asynchronous condition settles', async () => { const h = await setup() const condition = Promise.withResolvers() - h.ctx.tools.register(h.tool, { when: ({ signal }) => { expect(signal).toBe(h.controller.signal); return condition.promise } }) + h.ctx.tools.register(h.tool, { when: ({ route, signal }) => { + expect(route).toBe(h.route) + expect(signal).toBe(h.controller.signal) + return condition.promise + } }) const pending = h.resolve() const rejection = expect(pending).rejects.toMatchObject({ name: 'AbortError' }) h.controller.abort() diff --git a/packages/core/tools/tests/ptc.spec.ts b/packages/core/tools/tests/ptc.spec.ts index dbd633de86..496b007a81 100644 --- a/packages/core/tools/tests/ptc.spec.ts +++ b/packages/core/tools/tests/ptc.spec.ts @@ -187,7 +187,7 @@ describe('mode-aware wire contribution', () => { const unregister = ctx.tools.register(definition, { when: () => active }) for (const enabled of [false, true]) { active = enabled - const toolSet = await ctx.tools.resolve({ agent, signal: testToolSignal }) + const toolSet = await ctx.tools.resolve({ agent, route: { provider: 'test', model: 'test' }, signal: testToolSignal }) try { const assembly = await systemPrompt.assemble({ scope: agent, agent, toolSet }) const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? '' diff --git a/packages/deliverables/tool-present/tests/present.spec.ts b/packages/deliverables/tool-present/tests/present.spec.ts index 0583f21f1d..afbbf5958a 100644 --- a/packages/deliverables/tool-present/tests/present.spec.ts +++ b/packages/deliverables/tool-present/tests/present.spec.ts @@ -31,7 +31,6 @@ async function agent(ctx: Context, cwd: string | undefined): Promise { version: SESSION_FORMAT_VERSION, id, createdAt: 0, ...cwd === undefined ? {} : { cwd }, isSeeded: false, }) const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/experimental/browser-use-runtime/tests/resources.spec.ts b/packages/experimental/browser-use-runtime/tests/resources.spec.ts index 285394c448..f838191d44 100644 --- a/packages/experimental/browser-use-runtime/tests/resources.spec.ts +++ b/packages/experimental/browser-use-runtime/tests/resources.spec.ts @@ -16,7 +16,6 @@ async function fixture() { const fiber = ctx.plugin(() => {}) const session = Session.create(SessionId(id)) const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, session, ctx: fiber.ctx, options: {}, status: 'idle', inbox: unsupportedInbox(), send() {}, followup() {}, inject() {}, cancel() {}, steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }), diff --git a/packages/experimental/tool-terminal/tests/loader-composition.spec.ts b/packages/experimental/tool-terminal/tests/loader-composition.spec.ts index 1a624d6d04..9d2db58481 100644 --- a/packages/experimental/tool-terminal/tests/loader-composition.spec.ts +++ b/packages/experimental/tool-terminal/tests/loader-composition.spec.ts @@ -43,7 +43,6 @@ async function agent(ctx: Context): Promise { const id = SessionId('pty-loader-agent') const session = Session.create(id) const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, diff --git a/packages/experimental/tool-terminal/tests/tools.spec.ts b/packages/experimental/tool-terminal/tests/tools.spec.ts index e00ba3542e..8f6f3a5897 100644 --- a/packages/experimental/tool-terminal/tests/tools.spec.ts +++ b/packages/experimental/tool-terminal/tests/tools.spec.ts @@ -20,7 +20,6 @@ async function fakeAgent(ctx: Context, rawId: string): Promise { const id = SessionId(rawId) const session = Session.create(id) const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, diff --git a/packages/experimental/worktree/tests/harness.ts b/packages/experimental/worktree/tests/harness.ts index f425987975..c38be4d57c 100644 --- a/packages/experimental/worktree/tests/harness.ts +++ b/packages/experimental/worktree/tests/harness.ts @@ -42,7 +42,6 @@ export function testAgent(ctx: Context, cwd: string, name = 'worktree-test'): Ag const id = SessionId(name) const session = Session.create(id, [], { version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false, cwd }) const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, session, options: {}, status: 'idle', ctx: scope.ctx, inbox: unsupportedInbox(), send() {}, followup() {}, steer() {}, inject() {}, cancel() {}, whenIdle: async () => {}, runMaintenance: task => task(new AbortController().signal), diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 2e4a243b00..43771aec8e 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2393,9 +2393,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'mention-carrying candidates in rank order.', }, { - signature: 'async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, ): Promise', - description: 'Snapshot all references for one accepted direct message and return one aggregated durable context. Automatic budgets use the last assembled route, or agent options before any assembly. Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. Cancellation prevents context publication, including when storage completes after cancellation.', - parameters: [{ name: 'agent', description: 'target agent; references to it are rejected.' }, { name: 'content', description: 'already host-normalized readable message content.' }, { name: 'references', description: 'structured source sessions in mention order.' }, { name: 'signal', description: 'optional cancellation boundary for the active turn.' }], + signature: 'async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, route?: StepRoute, ): Promise', + description: 'Snapshot all references for one accepted direct message and return one aggregated durable context. Automatic budgets use the step route, or agent options for direct preparation. Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. Cancellation prevents context publication, including when storage completes after cancellation.', + parameters: [{ name: 'agent', description: 'target agent; references to it are rejected.' }, { name: 'content', description: 'already host-normalized readable message content.' }, { name: 'references', description: 'structured source sessions in mention order.' }, { name: 'signal', description: 'optional cancellation boundary for the active turn.' }, { name: 'route', description: 'provider and model of the step admitting the message; omitted for direct preparation.' }], returns: 'detached content and optional referenced-session context.', }, ], @@ -3342,7 +3342,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { signature: 'register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void', description: 'Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.', - parameters: [{ name: 'definition', description: 'tool schema, execution, and optional finalization/presentation callbacks.' }, { name: 'options', description: 'optional request-time activation condition.' }], + parameters: [{ name: 'definition', description: 'tool schema, execution, and optional finalization/presentation callbacks.' }, { name: 'options', description: 'optional step-time activation condition.' }], returns: 'the exact disposer that unregisters the tool.', }, { @@ -3360,19 +3360,19 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { signature: 'get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined', description: 'Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.', - parameters: [{ name: 'name', description: 'the tool name as registered.' }, { name: 'scope', description: 'the viewing scope (the agent); omitted = the global view.' }, { name: 'toolSet', description: 'request admission; omit only to inspect registered definitions.' }], + parameters: [{ name: 'name', description: 'the tool name as registered.' }, { name: 'scope', description: 'the viewing scope (the agent); omitted = the global view.' }, { name: 'toolSet', description: 'step admission; omit only to inspect registered definitions.' }], returns: 'the definition the scope resolves, or undefined when none is visible.', }, { signature: 'async resolve(context: ToolActivationContext): Promise', - description: 'Resolve conditions once for this request without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.', - parameters: [{ name: 'context', description: 'agent with a bound route and request cancellation.' }], + description: 'Resolve conditions once for this step without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.', + parameters: [{ name: 'context', description: 'preparing agent, step route, and cancellation.' }], returns: 'the complete selection; the caller disposes it after its tool batch settles.', }, { signature: 'schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]', description: 'Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.', - parameters: [{ name: 'scope', description: 'the viewing scope (the agent); omitted = the global view.' }, { name: 'toolSet', description: 'request admission, or omitted for registered-definition inspection.' }], + parameters: [{ name: 'scope', description: 'the viewing scope (the agent); omitted = the global view.' }, { name: 'toolSet', description: 'step admission, or omitted for registered-definition inspection.' }], returns: 'one deep-cloned schema per visible tool.', }, { @@ -3995,7 +3995,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ { name: 'agent/pre-step', mode: 'waterfall', - signature: '\'agent/pre-step\'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', + signature: '\'agent/pre-step\'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; route: StepRoute; signal: AbortSignal }, next: () => Promise): Promise', summary: 'Reject a proposed step or replace the messages that enter it.', description: 'Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages.', parameters: [{ name: 'payload', description: '.signal - the current turn\'s cancellation signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], @@ -4004,8 +4004,8 @@ export const EVENT_API: readonly EventApiEntry[] = [ name: 'agent/request', mode: 'waterfall', signature: '\'agent/request\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', - summary: 'Replace the frozen call configuration.', - description: 'Replace the frozen call configuration. `await next()` yields the config the machine would use (agent options on the first request, the logged header afterwards); return a replacement to switch. On step admission, this runs before context preparation and `agent/pre-step`. Cancellation here or during subsequent `prepareCall()` resolution opens no step and commits no system prompt or user batch. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages.', + summary: 'Replace the frozen call configuration of one request attempt.', + description: 'Replace the frozen call configuration of one request attempt. `await next()` yields the config the machine would use on the step\'s `agent/route` result: agent options on the first request, the logged header afterwards, and no effort recorded for another model. Return a replacement to change call controls such as reasoning effort; returning another provider or model fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages.', parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, { @@ -4016,6 +4016,14 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Handle one failed model-request attempt before the loop retries or closes its step. A listener returns `{ kind: \'retry\' }` without calling `next()` when it owns recovery, or calls `next()` to delegate. The default `undefined` leaves the failure terminal.', parameters: [{ name: 'payload', description: '.signal - the turn abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, + { + name: 'agent/route', + mode: 'waterfall', + signature: '\'agent/route\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', + summary: 'Choose the provider and model for one proposed step.', + description: 'Choose the provider and model for one proposed step. `await next()` yields the route the machine would use (agent options before this loop logs a request, the logged header afterwards); return a replacement to switch. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step.', + parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], + }, { name: 'agent/status', mode: 'emit', @@ -7564,6 +7572,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SshStreamEndpoint', declaration: 'export type SshStreamEndpoint = z.infer;', }, + { + name: 'StepRoute', + declaration: 'export interface StepRoute {\n readonly provider: string;\n readonly model: string;\n}', + }, { name: 'StorageBackend', declaration: 'export interface StorageBackend {\n readonly kv?: KvFacet;\n close(): Promise;\n}', @@ -7954,7 +7966,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolActivationContext', - declaration: 'export interface ToolActivationContext {\n readonly agent: Agent;\n readonly signal: AbortSignal;\n}', + declaration: 'export interface ToolActivationContext {\n readonly agent: Agent;\n readonly route: StepRoute;\n readonly signal: AbortSignal;\n}', }, { name: 'ToolAdditionBlock', diff --git a/packages/feedback/command-feedback/tests/command-feedback.spec.ts b/packages/feedback/command-feedback/tests/command-feedback.spec.ts index 680a1e87f0..4e5401c09e 100644 --- a/packages/feedback/command-feedback/tests/command-feedback.spec.ts +++ b/packages/feedback/command-feedback/tests/command-feedback.spec.ts @@ -33,7 +33,6 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } const session = ctx.sessions.create(SessionId(id)) let status: AgentStatus = 'idle' const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/feedback/command-feedback/tests/loader-composition.spec.ts b/packages/feedback/command-feedback/tests/loader-composition.spec.ts index bf2090a66c..273657e579 100644 --- a/packages/feedback/command-feedback/tests/loader-composition.spec.ts +++ b/packages/feedback/command-feedback/tests/loader-composition.spec.ts @@ -32,7 +32,6 @@ async function agent(ctx: Context): Promise { const session = ctx.sessions.create(id) let status: AgentStatus = 'idle' const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts index 8e2855bd45..74b8ce5dd6 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -34,7 +34,6 @@ async function agent(ctx: Context, cwd: string): Promise { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false, }) const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 0329d2eea1..1e4e65c7a1 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -25,7 +25,6 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } const inbox = createInboxStub() let status: AgentStatus = 'idle' const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/goal/goal/tests/goal.spec.ts b/packages/goal/goal/tests/goal.spec.ts index 9f98194d2a..fe9c2d0030 100644 --- a/packages/goal/goal/tests/goal.spec.ts +++ b/packages/goal/goal/tests/goal.spec.ts @@ -54,7 +54,6 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent } const inbox = createInboxStub() const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index b2f6491192..227da38ad8 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -39,7 +39,6 @@ interface Bench { async function liveAgent(ctx: Context, session: Session): Promise { const status: AgentStatus = 'idle' const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index 65fcdc64fc..ecc7822bce 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -54,7 +54,6 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St const inbox = createInboxStub() let status: AgentStatus = 'running' const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts index c6af01c97b..5ba9c7f544 100644 --- a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts +++ b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts @@ -80,7 +80,6 @@ async function setup(config: toolAskUser.Config = { mode: 'timed', timeout: -1 } function stubAgent(id: string, delegationDepth = 0): Agent { const agentId = SessionId(id) const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: agentId, options: {}, session: Session.create(agentId, [], { diff --git a/packages/jobs/jobs-local/tests/events.spec.ts b/packages/jobs/jobs-local/tests/events.spec.ts index 89e629dd65..5a653569b9 100644 --- a/packages/jobs/jobs-local/tests/events.spec.ts +++ b/packages/jobs/jobs-local/tests/events.spec.ts @@ -19,7 +19,6 @@ function agentIn(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { } const session = Session.create(id) return { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/jobs/jobs-local/tests/jobs.spec.ts b/packages/jobs/jobs-local/tests/jobs.spec.ts index 3d24152a0f..0c409049b9 100644 --- a/packages/jobs/jobs-local/tests/jobs.spec.ts +++ b/packages/jobs/jobs-local/tests/jobs.spec.ts @@ -35,7 +35,6 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { } const session = Session.create(id) const agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/llm/llm-deepseek/tests/account-routing.spec.ts b/packages/llm/llm-deepseek/tests/account-routing.spec.ts index 2ff15b69c9..1db78b540d 100644 --- a/packages/llm/llm-deepseek/tests/account-routing.spec.ts +++ b/packages/llm/llm-deepseek/tests/account-routing.spec.ts @@ -88,26 +88,21 @@ it.each(['deepseek-account', 'deepseek-official'])('cancels only the active acco ? { kind: 'hook', reason: 'deepseek-account/signed-out' } : { kind: 'user' } } }) }) -it.each(['tool', 'retry'])('replaces the active provider only after the next request binds: %s', async (transition) => { +it('replaces the active provider only after the next step request binds', async () => { const ctx = await harness() const preparing = Promise.withResolvers() const proceed = Promise.withResolvers() const streaming = Promise.withResolvers() - let requests = 0 - ctx.on('agent/request', async (_event, next) => { - const config = await next() - if (++requests === 1) return config + let steps = 0 + ctx.on('agent/route', async (_event, next) => { + const route = await next() + if (++steps === 1) return route preparing.resolve(undefined) await proceed.promise - return { ...config, provider: 'deepseek-official' } + return { ...route, provider: 'deepseek-official' } }) - ctx.on('agent/request-error', async (_event, next) => { await next(); return { kind: 'retry' } }) ctx.on('llm/stream', async function* (request) { if (request.provider === 'deepseek-account') { - if (transition === 'retry') { - yield { type: 'finish', reason: { kind: 'error', failure: { code: 'TRANSPORT', message: 'retry fixture' } } } - return - } yield { type: 'block-start', index: 0, blockType: 'tool-call' } yield { type: 'block-end', index: 0, block: { type: 'tool-call', id: ToolCallId('switch-call'), name: 'continue', arguments: '{}' } } yield { type: 'finish', reason: { kind: 'tool-calls' } } @@ -256,11 +251,11 @@ it('ignores idle account history but uses the last bound route during a new turn expect(cancel).not.toHaveBeenCalled() const preparing = Promise.withResolvers() const proceed = Promise.withResolvers() - ctx.on('agent/request', async (_event, next) => { - const config = await next() + ctx.on('agent/route', async (_event, next) => { + const route = await next() preparing.resolve(undefined) await proceed.promise - return { ...config, provider: 'deepseek-official' } + return { ...route, provider: 'deepseek-official' } }) try { send(agent) diff --git a/packages/llm/llm-retry/tests/retry.spec.ts b/packages/llm/llm-retry/tests/retry.spec.ts index 3adb88de05..3ab84ba450 100644 --- a/packages/llm/llm-retry/tests/retry.spec.ts +++ b/packages/llm/llm-retry/tests/retry.spec.ts @@ -524,7 +524,7 @@ describe('provider-routed retry policy', () => { expect(adapter.requests.map(request => request.provider)).toEqual(['mock', 'other', 'other']) }) - it('selects an always policy from the provider chosen by agent/request', async () => { + it('selects an always policy from the provider chosen by agent/route', async () => { vi.useFakeTimers() const adapter = new ScriptedAdapter([ new LlmError('rerouted auth failed', 'AUTH'), @@ -533,7 +533,7 @@ describe('provider-routed retry policy', () => { ;({ ctx: context } = await harness(adapter, { other: alwaysConfig({ initialDelayMs: 1, maxDelayMs: 1, jitterRatio: 0 }), }, (ctx) => { - ctx.on('agent/request', async (_payload, next) => ({ + ctx.on('agent/route', async (_payload, next) => ({ ...await next(), provider: 'other', })) @@ -553,51 +553,6 @@ describe('provider-routed retry policy', () => { expect(adapter.requests.map(request => request.provider)).toEqual(['other', 'other']) }) - it('keeps finite retry budgets scoped to the failed provider', async () => { - vi.useFakeTimers() - const adapter = new ScriptedAdapter([ - new LlmError('mock failed', 'SERVER'), - new LlmError('other failed', 'SERVER'), - textResponse('other recovered'), - ]) - ;({ ctx: context } = await harness(adapter, { - mock: normalConfig({ - maxRetries: 1, - backoff: { initialDelayMs: 1, maxDelayMs: 1 }, - }), - other: normalConfig({ - maxRetries: 1, - backoff: { initialDelayMs: 1, maxDelayMs: 1 }, - }), - }, (ctx) => { - ctx.on('agent/request', async (_payload, next) => ({ - ...await next(), - provider: adapter.requests.length === 0 ? 'mock' : 'other', - })) - })) - const agent = await context.agentLoop.create(SessionId('retry-provider-budgets'), { - provider: 'mock', - model: 'mock', - }) - const idle = waitForIdle(context, agent) - - agent.followup(createUserMessage({ - content: [{ type: 'text', text: 'switch provider after failure' }], - source: { kind: 'user' }, - })) - await vi.runAllTimersAsync() - await idle - - expect(adapter.requests.map(request => request.provider)).toEqual(['mock', 'other', 'other']) - expect(agent.session.snapshotEvents().filter(event => event.type === 'llm/retry').map(event => ({ - provider: event.data.provider, - retry: event.data.retry, - }))).toEqual([ - { provider: 'mock', retry: 1 }, - { provider: 'other', retry: 1 }, - ]) - }) - it.each(['thrown', 'in-band'] as const)( 'uses the serving registration policy and resets changed-policy history after a %s failure', async (failureKind) => { diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index f1556c826d..9fadebb38e 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -96,8 +96,8 @@ en: a1a020eb7ba26e7c zh: a99208693d331a31 /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/kv-cache-effect: - en: f640fc33aa30602f - zh: e0925a15d01141e9 + en: 9d9626fbf4cdc8de + zh: 8237cbc3ca048024 /deepseek-ai-dsh-plan-mode/known-limitations-and-deferred-work: en: a87aabfede0087fd zh: 201e9b3766980005 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 5e88c052fc..26b24ed4c3 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -172,7 +172,7 @@ The schema is paid only while active, according to ToolRuntime mode, and each pl #### KV Cache effect -Mode transitions add or remove the exit tool through the route’s tool-update protocol; plan arguments and review results extend the conversation normally. +Entering plan mode adds the exit tool through the route’s tool-update protocol, and leaving removes it. An `in-history` route records both changes after cached history. An `addition-only` route, such as the default catalog’s `deepseek-flash`, cannot record the removal and drops the tool from later requests, so the first request after leaving can miss part of the cached prefix; a route without tool updates resends its changed declaration list after either transition. Plan arguments and review results extend the conversation normally. ## Known Limitations and Deferred Work diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index e1d4b3abb6..3239d57803 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -172,7 +172,7 @@ schema 仅在启用时按 ToolRuntime 模式计入开销;每份计划参数与 #### KV Cache 影响 -模式转换通过路由的工具更新协议新增或移除退出工具;计划参数与评审结果正常扩展对话。 +进入计划模式时,退出工具通过路由的工具更新协议新增,离开时则移除。`in-history` 路由会在已缓存历史之后记录这两种变化。`addition-only` 路由(例如默认目录中的 `deepseek-flash`)无法记录移除,只能在之后的请求中去掉该工具,因此离开后的首个请求可能无法命中部分已缓存前缀;不支持工具更新的路由在任一方向转换后都会重新发送变化后的声明列表。计划参数与评审结果正常扩展对话。 ## 已知限制与延期工作 diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 05df478183..e99f53f95a 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -9,7 +9,7 @@ * The `plan` projection folds the session log, so resume and fork restore the * state. User selections remain pending until the next accepted in-turn * pre-step. The service appends `plan/mode` from `agent/pre-step` before - * request-time tool conditions and plan guidance read that committed state. + * step-time tool conditions and plan guidance read that committed state. * Same-step retries do not commit pending selections. * * The exit tool is admitted only for requests whose committed plan state is diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index cbf82de36b..cbbbf44fa6 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -1,6 +1,4 @@ import { describe, expect, it, vi } from 'vitest' - -const testToolSignal = new AbortController().signal import { Context } from '@deepseek-ai/cordis' import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' @@ -20,6 +18,9 @@ import PlanModeController, { EXIT_PLAN_MODE, planProjectionDefinition, resolveCo import type { PlanModeConfig } from '../src/index.ts' import type { PlanUnitState } from '../src/types.ts' +const testToolSignal = new AbortController().signal +const TEST_ROUTE = { provider: 'test', model: 'test' } + const TEST_PLAN_SECTION = 'Test plan mode instructions.' const PLAN_CONFIG = { section: TEST_PLAN_SECTION } satisfies PlanModeConfig @@ -75,7 +76,7 @@ async function agentWithSession( } async function assembleFor(ctx: Context, agent: Agent) { - const toolSet = await ctx.tools.resolve({ agent, signal: testToolSignal }) + const toolSet = await ctx.tools.resolve({ agent, route: TEST_ROUTE, signal: testToolSignal }) return ctx.systemPrompt.assemble({ agent, scope: agent, toolSet }) } @@ -116,7 +117,7 @@ async function boundary(ctx: Context, agent: Agent & { session: Session }, type: const signal = new AbortController().signal const decision = await events.waterfall( 'agent/pre-step', - { messages: [message], turn: 1, step: 1, signal }, + { messages: [message], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [message] }), ) if (decision.kind === 'enter') { @@ -797,7 +798,7 @@ describe('exit_plan_mode', () => { async function callExit(ctx: Context, agent: Agent | undefined, plan = '# The plan\n\ndo things') { const signal = new AbortController().signal - const toolSet = agent === undefined ? undefined : await ctx.tools.resolve({ agent, signal }) + const toolSet = agent === undefined ? undefined : await ctx.tools.resolve({ agent, route: TEST_ROUTE, signal }) return ctx.tools.execute({ ...toolSet === undefined ? {} : { toolSet }, callId: ToolCallId(`call-exit-${++callCounter}`), @@ -932,7 +933,7 @@ describe('exit_plan_mode', () => { const agent = await agentWithSession(ctx, 'ptc-exit', { active: true }) const result = await ctx.tools.execute({ - toolSet: await ctx.tools.resolve({ agent, signal: testToolSignal }), + toolSet: await ctx.tools.resolve({ agent, route: TEST_ROUTE, signal: testToolSignal }), callId: ToolCallId(`call-exit-${++callCounter}`), name: RUN_CODE_NAME, arguments: { code: `return await tools.${EXIT_PLAN_MODE}({ plan: ${JSON.stringify(plan)} })`, description: 'Submit the plan for review' }, @@ -1082,7 +1083,7 @@ describe('exit_plan_mode', () => { const { ctx, agent, asked } = await setupWithReview({ selected: ['Approve'] }) const controller = new AbortController() const result = await ctx.tools.execute({ - toolSet: await ctx.tools.resolve({ agent, signal: testToolSignal }), + toolSet: await ctx.tools.resolve({ agent, route: TEST_ROUTE, signal: testToolSignal }), callId: ToolCallId(`call-exit-${++callCounter}`), name: EXIT_PLAN_MODE, arguments: { plan: '# P' }, diff --git a/packages/schedule/schedule/tests/harness.ts b/packages/schedule/schedule/tests/harness.ts index f6c9794a32..bf152ad187 100644 --- a/packages/schedule/schedule/tests/harness.ts +++ b/packages/schedule/schedule/tests/harness.ts @@ -125,7 +125,6 @@ export interface HarnessAgent extends Agent { export function agentFor(ctx: Context, id = 'original', meta?: CreateSessionOptions['meta']): HarnessAgent { const session = ctx.sessions.create(SessionId(id), meta === undefined ? undefined : { meta }) return { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, session, ctx: ctx.extend(), options: {}, status: 'idle', inbox: unsupportedInbox(), send() {}, followup: vi.fn<(message: UserMessage) => void>(), steer() {}, inject() {}, cancel() {}, whenIdle: async () => {}, runMaintenance: operation => operation(new AbortController().signal), diff --git a/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts b/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts index 654b1ab18f..84814ab160 100644 --- a/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts +++ b/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts @@ -220,7 +220,7 @@ describe('session-checkpoint-policy tool and step boundaries', () => { ctx.on('session/flush', (current) => { flushed.push(current.id) }) const signal = new AbortController().signal await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter', messages: [] }), ) expect(flushed).toEqual([session.id]) diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index cee7dbc5ed..2a03b75013 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -39,8 +39,8 @@ en: f5a095acef81df3b zh: 758796edbc4337fc /deepseek-ai-dsh-working-directory/known-limitations-and-deferred-work: - en: 7f93a8dd08c52ac5 - zh: 38f35141d2e7eb6d + en: 17ecae217e34f3cd + zh: 92d52f4ced97d044 /deepseek-ai-dsh-working-directory/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: a4b126f9a4eaca6f diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 19f00941aa..8866317c01 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -77,7 +77,7 @@ Directory transitions append context without replacing the stable system-prompt -- **Missing original project** — when the current directory and the original project are both unavailable, request preparation rejects every model turn, including chat-only turns. The service does not choose or recreate a repository. Restore the original directory, or use SDK `setWorkingDirectory` (`set_working_directory` in Python) or `ctx.workingDirectory.set` to select an existing absolute directory before retrying. Existing shells retain their process-local directories. +- **Missing original project** — when the current directory and the original project are both unavailable, step preparation rejects every model turn, including chat-only turns. The service does not choose or recreate a repository. Restore the original directory, or use SDK `setWorkingDirectory` (`set_working_directory` in Python) or `ctx.workingDirectory.set` to select an existing absolute directory before retrying. Existing shells retain their process-local directories. ### Dev Note diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index b656f1e835..f3e65358b5 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -77,7 +77,7 @@ Session 投影拥有当前目录,并通过 Session observation 暴露它,因 -- **原始项目缺失** — 当前目录与原始项目均不可用时,请求准备会拒绝每个模型轮次,包括纯聊天轮次。服务不会另选或重建仓库。请先恢复原始目录,或通过 SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`)或 `ctx.workingDirectory.set` 选择现有的绝对目录,再重试。已有 shell 保留各自进程的目录。 +- **原始项目缺失** — 当前目录与原始项目均不可用时,步骤准备会拒绝每个模型轮次,包括纯聊天轮次。服务不会另选或重建仓库。请先恢复原始目录,或通过 SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`)或 `ctx.workingDirectory.set` 选择现有的绝对目录,再重试。已有 shell 保留各自进程的目录。 ### 开发备注 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 d8644dbc62..f30e87b978 100644 --- a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts @@ -45,7 +45,6 @@ async function agent(ctx: Context, cwd: string): Promise { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false, }) const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/shell/tool-bash-persistent/tests/tools.spec.ts b/packages/shell/tool-bash-persistent/tests/tools.spec.ts index ab9967bfd9..d3507373c7 100644 --- a/packages/shell/tool-bash-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/tools.spec.ts @@ -39,7 +39,6 @@ async function agent(ctx: Context, cwd: string | undefined): Promise { ...cwd === undefined ? {} : { cwd }, }) const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/shell/tool-bash/tests/background.spec.ts b/packages/shell/tool-bash/tests/background.spec.ts index 35e6b566ba..3a1fbff9bb 100644 --- a/packages/shell/tool-bash/tests/background.spec.ts +++ b/packages/shell/tool-bash/tests/background.spec.ts @@ -352,7 +352,6 @@ describe('foreground commands as jobs', () => { const ctx = await setup() const ownerId = SessionId('promote-owner') const owner: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: ownerId, options: {}, session: Session.create(ownerId, undefined, { @@ -469,7 +468,6 @@ describe('owned background output', () => { const ctx = await setup() const ownerId = SessionId('background-owner') const owner: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: ownerId, options: {}, session: Session.create(ownerId, undefined, { diff --git a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts index f48241d964..90c29923a0 100644 --- a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts @@ -80,7 +80,6 @@ async function agent(ctx: Context, cwd: string): Promise { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false, }) const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts index 6c0f41fe57..b2b6d96137 100644 --- a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts @@ -39,7 +39,6 @@ async function agent(ctx: Context, cwd: string | undefined): Promise { ...cwd === undefined ? {} : { cwd }, }) const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/shell/tool-pwsh/tests/background.spec.ts b/packages/shell/tool-pwsh/tests/background.spec.ts index 3382c91132..8a1d46addc 100644 --- a/packages/shell/tool-pwsh/tests/background.spec.ts +++ b/packages/shell/tool-pwsh/tests/background.spec.ts @@ -204,7 +204,6 @@ describe('owned background output (pwsh)', () => { const { ctx, pwsh } = await setup() const ownerId = SessionId('pwsh-background-owner') const owner: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: ownerId, options: {}, session: Session.create(ownerId, undefined, { @@ -405,7 +404,6 @@ describe('foreground commands as jobs (pwsh)', () => { const { ctx, pwsh } = await setup() const ownerId = SessionId('pwsh-promote-owner') const owner: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: ownerId, options: {}, session: Session.create(ownerId, undefined, { diff --git a/packages/skill/tool-skill/tests/tool-skill.spec.ts b/packages/skill/tool-skill/tests/tool-skill.spec.ts index 21253e2cac..d2d8ef53ed 100644 --- a/packages/skill/tool-skill/tests/tool-skill.spec.ts +++ b/packages/skill/tool-skill/tests/tool-skill.spec.ts @@ -69,7 +69,6 @@ function agentForCwd(cwd: string): Agent { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false, }) return { - currentRoute() { throw new Error('no prepared model request in this fixture') }, ctx: new Context(), id, options: {}, @@ -88,7 +87,6 @@ function agentForCwd(cwd: string): Agent { function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent { const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: SessionId(id), options: {}, session, @@ -118,7 +116,7 @@ async function fireStep(ctx: Context, agent: Agent, turn: number, step: number): const signal = new AbortController().signal const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn, step, signal }, + { messages: [], turn, step, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { @@ -136,7 +134,7 @@ async function proposeStep( const signal = new AbortController().signal return await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages, turn: 1, step: 1, signal }, + { messages, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages }), ) } @@ -168,7 +166,7 @@ async function composePrefix(ctx: Context, cwd: string, signal = new AbortContro async function composePrefixForAgent(ctx: Context, agent: Agent, signal = new AbortController().signal): Promise { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, signal }, + { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { @@ -1106,7 +1104,7 @@ describe('user-explicit invocation injection', () => { const signal = new AbortController().signal const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [gesture('/hidden-demo blocked step')], turn: 1, step: 1, signal }, + { messages: [gesture('/hidden-demo blocked step')], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'reject' as const }), ) expect(decision).toEqual({ kind: 'reject' }) diff --git a/packages/subagent/subagent/tests/archive-admission.spec.ts b/packages/subagent/subagent/tests/archive-admission.spec.ts index 9aba8f2235..9e8c1b2b12 100644 --- a/packages/subagent/subagent/tests/archive-admission.spec.ts +++ b/packages/subagent/subagent/tests/archive-admission.spec.ts @@ -31,7 +31,6 @@ async function liveAgent(ctx: Context, session: Session, initial: AgentStatus): const cancels: CancelCall[] = [] let status = initial const agent: LiveAgent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, diff --git a/packages/subagent/subagent/tests/external-activation-helpers.ts b/packages/subagent/subagent/tests/external-activation-helpers.ts index 21f53b0e22..389ce804d6 100644 --- a/packages/subagent/subagent/tests/external-activation-helpers.ts +++ b/packages/subagent/subagent/tests/external-activation-helpers.ts @@ -33,7 +33,6 @@ export async function externalTestParent(ctx: Context, cwd?: string): Promise { messages: [], turn: 1, step: 1, + route: { provider: 'test', model: 'test' }, signal: new AbortController().signal, } await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next)) diff --git a/packages/terminal/terminal-bash/tests/index.spec.ts b/packages/terminal/terminal-bash/tests/index.spec.ts index 0d980ca245..a68c798321 100644 --- a/packages/terminal/terminal-bash/tests/index.spec.ts +++ b/packages/terminal/terminal-bash/tests/index.spec.ts @@ -55,7 +55,6 @@ function agent(ctx: Context, cwd?: string): Agent { version: SESSION_FORMAT_VERSION, id, createdAt: 0, isSeeded: false, ...cwd === undefined ? {} : { cwd }, }) return { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx, @@ -676,7 +675,6 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: ownerFiber.ctx, @@ -728,7 +726,6 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('pending-mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: ownerFiber.ctx, diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index 0d11094467..e5a53123d0 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -40,7 +40,6 @@ function stubAgent(ctx: Context, rawId: string): Agent { const scope = ctx.plugin(() => {}) const session = Session.create(id) const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index b14e47b3ab..11da341945 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -24,7 +24,6 @@ function stubAgent(ctx: Context, rawId: string): Agent { const scopeFiber = ctx.plugin(() => {}) const session = Session.create(id) const agent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index 11a8cdbc9e..3642d8485f 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -34,7 +34,6 @@ async function agent(ctx: Context): Promise { const id = SessionId('todo-loader-agent') const session = Session.create(id) const value: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, followup: () => {}, steer: () => {}, inject: () => {}, send: () => {}, cancel() {}, diff --git a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts index bc39c173eb..7c7f819072 100644 --- a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts +++ b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts @@ -457,7 +457,6 @@ describe('dsh-tool-workflow', () => { const engine = ctx.workflowEngine as StubEngine const session = Session.create(SessionId('caller')) const parent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx, send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), @@ -671,7 +670,6 @@ describe('dsh-tool-workflow', () => { await ctx.plugin(toolWorkflow, {}) const session = Session.create(SessionId('caller')) const parent: Agent = { - currentRoute() { throw new Error('no prepared model request in this fixture') }, id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx, send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), diff --git a/scripts/fixtures/python-sdk-dynamic-tools.mjs b/scripts/fixtures/python-sdk-dynamic-tools.mjs index f64930c327..f884b925a5 100644 --- a/scripts/fixtures/python-sdk-dynamic-tools.mjs +++ b/scripts/fixtures/python-sdk-dynamic-tools.mjs @@ -14,7 +14,7 @@ export function apply(ctx) { render(_args, value) { return [{ type: 'text', text: value }] }, }, async execute() { return 'pong' }, - }, { when: async ({ agent }) => active && agent.currentRoute().provider === 'deepseek-official' }) + }, { when: async ({ route }) => active && route.provider === 'deepseek-official' }) ctx.on('tools/post-execute', async (exec, result, next) => { const downstream = await next() if (result.isError) return downstream diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index d13c160f0b..8c850099de 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -334,6 +334,7 @@ export const LINK_MAP: Readonly> = { InspectorJsonValue: 'extensions.md', MessageId: 'llm-streaming.md', ResumeAgentOptions: 'core.md', + StepRoute: 'core.md', SettleReason: 'core.md', AdapterRegistrationHandle: 'llm-streaming.md', DirectoryRegistrationHandle: 'llm-streaming.md', @@ -936,7 +937,7 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { KnobState: 'projection unit state fields are owned by packages/interaction/permission-presets/README.md', ToolActivationContext: 'conditional activation inputs are owned by packages/core/tools/README.md', ToolRegistrationOptions: 'conditional registration options are owned by packages/core/tools/README.md', - ResolvedToolSet: 'request-owned admission is owned by packages/core/tools/README.md', + ResolvedToolSet: 'step-owned admission is owned by packages/core/tools/README.md', PromptAssembly: 'assembly result is owned by packages/core/system-prompt/README.md', PromptPreparation: 'preparation inputs are owned by packages/core/system-prompt/README.md', PromptPresentation: 'presentation inputs are owned by packages/core/system-prompt/README.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index fbc0258d35..984bbb8ccd 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1548,17 +1548,18 @@ function renderLifecycle(): string { ' Note over Agent,Driver: claim pending next-step input plus one queued prompt', ` Driver-->>SDK: ${mermaidCode('agent/inbox/spliced')} pure deletion`, ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, - ` Driver->>Hooks: ${mermaidCode('agent/request')} waterfall`, - ' Driver->>LLM: prepareCall(config, signal), bind Agent.currentRoute()', - ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall`, - ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`, + ` Driver->>Hooks: ${mermaidCode('agent/route')} waterfall chooses the step route`, + ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall on the step route`, + ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall with the step route`, ' Hooks-->>Driver: authoritative reject or enter(messages)', ' alt proposed step rejected, first batch empty, or pre-step failed', ' Driver-->>Driver: claimed batch stays removed, the open turn spends no step', ' else enter proposed step', ` Driver->>Session: ${mermaidCode('step/start')}`, - ' Driver->>Tools: resolve({ agent, signal })', - ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} with resolved tool set`, + ' Driver->>Tools: resolve({ agent, route, signal }) once per step', + ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} with the step tool set`, + ` Driver->>Hooks: ${mermaidCode('agent/request')} waterfall on the step route`, + ' Driver->>LLM: prepareCall(config, signal)', ' Note over Driver,LLM: cancellation during preparation commits neither system nor users', ' Note over Driver,Session: synchronous admission using the prepared call capability', ` Driver->>Session: ${mermaidCode('system/message')} ordered per-node reconciliation`, @@ -1573,7 +1574,7 @@ function renderLifecycle(): string { ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`, ` Driver->>Hooks: ${mermaidCode('agent/request-error')} waterfall`, ' Hooks-->>Driver: return retry action or preserve the original error', - ' Note over Driver,LLM: retry resolves route and tools. Unchanged inputs reuse the prompt without repeating pre-step or users', + ' Note over Driver,LLM: retry in the open step: request and prepare again on the same route, tool set, and prompt without repeating pre-step or users', ' else model request succeeded', ` Driver->>Session: ${mermaidCode('assistant/message')}`, ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`, @@ -1581,7 +1582,7 @@ function renderLifecycle(): string { ' loop barriers and bounded rolling pool, reclassify before start', ' opt call starts', ` Driver->>Session: ${mermaidCode('tool/call')}`, - ' Driver->>Tools: ordered pre, concurrent execute with request tool set', + ' Driver->>Tools: ordered pre, concurrent execute with the step tool set', ' Tools-->>Session: tool-owned events when applicable', ' end', ' opt next model-order result ready', @@ -1589,16 +1590,16 @@ function renderLifecycle(): string { ` Driver->>Session: ${mermaidCode('tool/result')}`, ' end', ' end', - ' Driver->>Tools: dispose request tool set', + ' Driver->>Tools: dispose the step tool set', ` Driver->>Session: ${mermaidCode('step/end')}`, - ' Driver->>Driver: clear bound route', ' opt natural stop and next-step inbox empty', ` Driver->>Hooks: ${mermaidCode('agent/turn-stopping')} serial terminal checkpoint`, ' end', ' opt next-step input is pending', ' Driver-->>Driver: claim pending next-step input', ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, - ' Driver->>Driver: prepare route and runtime context for the next step', + ` Driver->>Hooks: ${mermaidCode('agent/route')} waterfall`, + ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall`, ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`, ' Hooks-->>Driver: authoritative reject or enter(messages)', ' end', @@ -1610,7 +1611,7 @@ function renderLifecycle(): string { '', 'The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes, and embeds the exact compact timed stream. Empty content stays out of derived history. A failed, retried, cancelled, or stream-error attempt that reaches settlement without a surface message records its stream as `assistant/attempt`. Live `agent/assistant-stream` chunk frames are transient; replay reads either durable settlement, and a hard process loss before settlement leaves no durable attempt stream.', '', - '`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call and resolves tool conditions before request derivation, without repeating pre-step or user admission. Prompt assembly repeats only when the bound route or tool schemas change.', + '`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call on the step route and reconciles the retained rendered assembly before request derivation, without repeating routing, tool resolution, assembly, pre-step, or user admission.', '', '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.', '', diff --git a/scripts/python-snapshot-workflow-order.spec.ts b/scripts/python-snapshot-workflow-order.spec.ts index b82796cb52..6a6881797b 100644 --- a/scripts/python-snapshot-workflow-order.spec.ts +++ b/scripts/python-snapshot-workflow-order.spec.ts @@ -44,7 +44,7 @@ async function harness(direct = false) { runId: WorkflowRunId('run'), seq: 1, label: 'workflow-child', childId, }) const step = (overrides = {}) => agentEvents(ctx, agent).waterfall('agent/pre-step', { - turn: 1, step: 1, messages, signal: controller.signal, ...overrides, + turn: 1, step: 1, messages, route: { provider: 'test', model: 'test' }, signal: controller.signal, ...overrides, }, next) return { ctx, fiber, parent, other, session, agent, controller, decision, next, start, step } } diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 37f21e08c1..9c8493b0c3 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2151,6 +2151,11 @@ "symbol": "AgentOptions", "source": "packages/core/agent/src/runtime-types.ts" }, + { + "doc": "docs/subsystems/core.md", + "symbol": "StepRoute", + "source": "packages/core/agent/src/runtime-types.ts" + }, { "doc": "docs/subsystems/feedback.md", "symbol": "MessageFeedbackVersion", diff --git a/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl b/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl index ac1bcf8418..f53dd034a2 100644 --- a/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl +++ b/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Inspect the exact tools service","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788778145981,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788778145981,"index":0,"dt":[],"id":"inspect-tools-api","name":"cordis_inspect_query","args":["{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"]},{"type":"chunk","time":1788778145981,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}}},{"type":"chunk","time":1788778145981,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788778145981,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"inspect-tools-api"},"toolCallId":"inspect-tools-api","content":[{"type":"text","text":"{\n \"platform\": \"host\",\n \"provider\": \"Service\",\n \"method\": \"listService\",\n \"data\": {\n \"mode\": \"service\",\n \"service\": {\n \"key\": \"tools\",\n \"description\": \"Tool registry and execution pipeline. Scoped registrations shadow globals; one visibility resolver feeds presentation, lookup, and dispatch.\",\n \"access\": {\n \"optional\": {\n \"expression\": \"ctx.get(\\\"tools\\\")\",\n \"requiresUndefinedCheck\": true\n },\n \"hardDependency\": {\n \"inject\": [\n \"tools\"\n ],\n \"expression\": \"ctx.tools\"\n }\n },\n \"methods\": [\n {\n \"signature\": \"presentAs(mode: ToolPresentationMode): () => void\",\n \"description\": \"Present the calling scope's tools in `mode` instead of the deployment default. Nearest scope on the chain wins, so a preset's standing declaration covers every agent joined under it.\\n\\nScoped only, and one declaration per scope: this is how an agent preset composes PTC mode agents beside native ones in the same process, and a process-global override would be the `mode` config field instead.\",\n \"parameters\": [\n {\n \"name\": \"mode\",\n \"description\": \"the presentation the covered agents' models see.\"\n }\n ],\n \"returns\": \"the exact disposer that restores the deployment default.\"\n },\n {\n \"signature\": \"register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void\",\n \"description\": \"Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.\",\n \"parameters\": [\n {\n \"name\": \"definition\",\n \"description\": \"tool schema, execution, and optional finalization/presentation callbacks.\"\n },\n {\n \"name\": \"options\",\n \"description\": \"optional request-time activation condition.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the tool.\"\n },\n {\n \"signature\": \"restrict(filter: ToolRestriction): () => void\",\n \"description\": \"Restrict global tools for the calling agent scope. Empty filters, unknown names, scope-local names, and reserved transport names fail. Restrictions intersect; scoped registrations remain visible.\",\n \"parameters\": [\n {\n \"name\": \"filter\",\n \"description\": \"global-tool mask: `allow` (keep only) and/or `deny` (remove).\"\n }\n ],\n \"returns\": \"the exact disposer that lifts this restriction.\"\n },\n {\n \"signature\": \"guard(guard: ToolGuard): () => void\",\n \"description\": \"Register a monotonic guard after the extensible `tools/pre-execute` waterfall. A plain-context guard applies globally; one registered through `agent.ctx` applies only to that agent. Any matching guard may deny by returning a reason, while no guard can force-allow a call another guard denied. The exact effect disposer is returned for ordered ownership and HMR cleanup.\",\n \"parameters\": [\n {\n \"name\": \"guard\",\n \"description\": \"synchronous check; a returned string denies the execution.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the guard.\"\n },\n {\n \"signature\": \"get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined\",\n \"description\": \"Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.\",\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the tool name as registered.\"\n },\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"request admission; omit only to inspect registered definitions.\"\n }\n ],\n \"returns\": \"the definition the scope resolves, or undefined when none is visible.\"\n },\n {\n \"signature\": \"async resolve(context: ToolActivationContext): Promise\",\n \"description\": \"Resolve conditions once for this request without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.\",\n \"parameters\": [\n {\n \"name\": \"context\",\n \"description\": \"agent with a bound route and request cancellation.\"\n }\n ],\n \"returns\": \"the complete selection; the caller disposes it after its tool batch settles.\"\n },\n {\n \"signature\": \"schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]\",\n \"description\": \"Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.\",\n \"parameters\": [\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"request admission, or omitted for registered-definition inspection.\"\n }\n ],\n \"returns\": \"one deep-cloned schema per visible tool.\"\n },\n {\n \"signature\": \"executionMode(exec: ToolExecutionInput): ToolExecutionMode\",\n \"description\": \"Classify a pending call through the caller's visible tool definition. Only an exact `true` is parallel; unknown, hidden, undeclared, invalid, or throwing classifiers are exclusive.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"call name, parsed arguments, and optional agent scope.\"\n }\n ],\n \"returns\": \"the fail-closed scheduling mode.\"\n },\n {\n \"signature\": \"async execute(exec: ToolExecutionInput): Promise\",\n \"description\": \"Execute through pre-policy, guards, around-dispatch, post-policy, definition-owned content finalization, and final notification. Tool and listener failures resolve as materialized error results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen snapshot final observers receive. Cancellation arriving after entry and before final result materialization skips a not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a successful started outcome with `ABORTED`; already-started work is still drained and may retain a tool-owned structured error.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"the typed same-process call input. The registry assigns its correlation token before policy begins.\"\n }\n ],\n \"returns\": \"the materialized final result.\"\n }\n ]\n },\n \"referencedTypes\": [\n {\n \"name\": \"Agent\",\n \"declaration\": \"export interface Agent {\\n readonly id: SessionId;\\n}\"\n },\n {\n \"name\": \"Branded\",\n \"declaration\": \"export type Branded = string & {\\n readonly [BRAND]: B;\\n};\"\n },\n {\n \"name\": \"DiffCallView\",\n \"declaration\": \"export interface DiffCallView {\\n card: 'diff';\\n title: string;\\n diffs: FileDiff[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"DiffResultView\",\n \"declaration\": \"export interface DiffResultView {\\n card: 'diff';\\n title?: string;\\n diffs: FileDiff[];\\n}\"\n },\n {\n \"name\": \"FileDiff\",\n \"declaration\": \"export interface FileDiff {\\n path: string;\\n oldText: string | null;\\n newText: string;\\n}\"\n },\n {\n \"name\": \"FileLocation\",\n \"declaration\": \"export interface FileLocation {\\n path: string;\\n line?: number;\\n}\"\n },\n {\n \"name\": \"GenericCallView\",\n \"declaration\": \"export interface GenericCallView {\\n card: 'generic';\\n title: string;\\n kind?: ToolCallKind;\\n rawInput?: unknown;\\n content?: ContentBlock[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"GenericResultView\",\n \"declaration\": \"export interface GenericResultView {\\n card: 'generic';\\n title?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"JsonSchemaNode\",\n \"declaration\": \"export interface JsonSchemaNode {\\n type?: JsonSchemaType;\\n oneOf?: JsonSchemaNode[];\\n properties?: Record;\\n required?: string[];\\n additionalProperties?: boolean;\\n items?: JsonSchemaNode;\\n enum?: JsonSchemaScalar[];\\n const?: JsonSchemaScalar;\\n description?: string;\\n title?: string;\\n default?: JsonValue;\\n examples?: JsonValue;\\n}\"\n },\n {\n \"name\": \"JsonSchemaScalar\",\n \"declaration\": \"export type JsonSchemaScalar = string | number | boolean | null;\"\n },\n {\n \"name\": \"JsonSchemaType\",\n \"declaration\": \"export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\"\n },\n {\n \"name\": \"JsonValue\",\n \"declaration\": \"export type JsonValue = null | boolean | number | string | JsonValue[] | {\\n [key: string]: JsonValue;\\n};\"\n },\n {\n \"name\": \"ReadFileLine\",\n \"declaration\": \"export interface ReadFileLine {\\n number: number;\\n text: string;\\n}\"\n },\n {\n \"name\": \"ReadResultView\",\n \"declaration\": \"export interface ReadResultView {\\n card: 'read';\\n title?: string;\\n path: string;\\n offset: number;\\n lines: ReadFileLine[];\\n totalLines: number;\\n lang?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"ResolvedToolSet\",\n \"declaration\": \"export interface ResolvedToolSet {\\n dispose(): void;\\n view(scope: ScopeKey | undefined): ReadonlyMap;\\n}\"\n },\n {\n \"name\": \"ScopeKey\",\n \"declaration\": \"export type ScopeKey = object;\"\n },\n {\n \"name\": \"SearchFileMatches\",\n \"declaration\": \"export interface SearchFileMatches {\\n path: string;\\n matches: SearchLineMatch[];\\n}\"\n },\n {\n \"name\": \"SearchLineMatch\",\n \"declaration\": \"export interface SearchLineMatch {\\n lineNumber: number;\\n line: string;\\n}\"\n },\n {\n \"name\": \"SearchMatchesResultView\",\n \"declaration\": \"export interface SearchMatchesResultView {\\n card: 'search';\\n shape: 'matches';\\n title?: string;\\n files: SearchFileMatches[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchPathsResultView\",\n \"declaration\": \"export interface SearchPathsResultView {\\n card: 'search';\\n shape: 'paths';\\n title?: string;\\n paths: string[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchResultView\",\n \"declaration\": \"export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;\"\n },\n {\n \"name\": \"SessionId\",\n \"declaration\": \"export type SessionId = Branded<'SessionId'>;\"\n },\n {\n \"name\": \"TerminalCallView\",\n \"declaration\": \"export interface TerminalCallView {\\n card: 'terminal';\\n title: string;\\n description?: string;\\n cwd?: string;\\n}\"\n },\n {\n \"name\": \"TerminalResultView\",\n \"declaration\": \"export interface TerminalResultView {\\n card: 'terminal';\\n title?: string;\\n output?: string;\\n exitCode?: number;\\n signal?: string;\\n}\"\n },\n {\n \"name\": \"ToolActivationContext\",\n \"declaration\": \"export interface ToolActivationContext {\\n readonly agent: Agent;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolCallId\",\n \"declaration\": \"export type ToolCallId = Branded<'ToolCallId'>;\"\n },\n {\n \"name\": \"ToolCallKind\",\n \"declaration\": \"export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\"\n },\n {\n \"name\": \"ToolCallView\",\n \"declaration\": \"export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\"\n },\n {\n \"name\": \"ToolDefinition\",\n \"declaration\": \"export interface ToolDefinition extends ToolSchema {\\n readonly output: ToolOutputDefinition;\\n execute(args: unknown, exec: ToolRunContext): Promise;\\n projectContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n timeoutMs?: number;\\n isConcurrencySafe?(args: unknown): boolean;\\n presentCall?(args: unknown): ToolCallView | undefined;\\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\\n}\"\n },\n {\n \"name\": \"ToolErrorInfo\",\n \"declaration\": \"export interface ToolErrorInfo {\\n name: string;\\n code: string;\\n reason?: string;\\n}\"\n },\n {\n \"name\": \"ToolExecution\",\n \"declaration\": \"export interface ToolExecution extends ToolExecutionInput {\\n readonly rootCallId: ToolCallId;\\n readonly token: ToolExecutionToken;\\n}\"\n },\n {\n \"name\": \"ToolExecutionFailure\",\n \"declaration\": \"export interface ToolExecutionFailure {\\n readonly isError: true;\\n readonly error: ToolFailure;\\n readonly value?: never;\\n readonly content: ContentBlock[];\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: never;\\n}\"\n },\n {\n \"name\": \"ToolExecutionInput\",\n \"declaration\": \"export interface ToolExecutionInput {\\n readonly callId: ToolCallId;\\n readonly rootCallId?: ToolCallId;\\n readonly name: string;\\n readonly schema?: ToolSchema;\\n readonly arguments: unknown;\\n readonly agent?: Agent;\\n readonly toolSet?: ResolvedToolSet;\\n readonly parent?: ToolExecutionToken;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolExecutionMode\",\n \"declaration\": \"export type ToolExecutionMode = {\\n kind: 'parallel';\\n} | {\\n kind: 'exclusive';\\n};\"\n },\n {\n \"name\": \"ToolExecutionResult\",\n \"declaration\": \"export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\"\n },\n {\n \"name\": \"ToolExecutionSuccess\",\n \"declaration\": \"export interface ToolExecutionSuccess {\\n readonly isError: false;\\n readonly value: JsonValue;\\n readonly content: ContentBlock[];\\n readonly error?: never;\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: true;\\n}\"\n },\n {\n \"name\": \"ToolExecutionToken\",\n \"declaration\": \"export type ToolExecutionToken = symbol & {\\n readonly [toolExecutionTokenBrand]: true;\\n};\"\n },\n {\n \"name\": \"ToolFailure\",\n \"declaration\": \"export interface ToolFailure {\\n message: string;\\n info?: ToolErrorInfo;\\n}\"\n },\n {\n \"name\": \"ToolGuard\",\n \"declaration\": \"export type ToolGuard = (execution: Readonly) => string | undefined;\"\n },\n {\n \"name\": \"ToolOutputDefinition\",\n \"declaration\": \"export interface ToolOutputDefinition {\\n readonly schema: JsonSchemaNode;\\n render(args: unknown, value: JsonValue): ContentBlock[];\\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolPresentationMode\",\n \"declaration\": \"export type ToolPresentationMode = 'native' | 'ptc';\"\n },\n {\n \"name\": \"ToolRegistrationOptions\",\n \"declaration\": \"export interface ToolRegistrationOptions {\\n readonly when?: (context: ToolActivationContext) => boolean | Promise;\\n}\"\n },\n {\n \"name\": \"ToolRestriction\",\n \"declaration\": \"export interface ToolRestriction {\\n readonly allow?: readonly string[];\\n readonly deny?: readonly string[];\\n}\"\n },\n {\n \"name\": \"ToolResult\",\n \"declaration\": \"export interface ToolResult {\\n content: ContentBlock[];\\n isError: boolean;\\n meta?: JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolResultView\",\n \"declaration\": \"export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | SearchResultView | ReadResultView | WebResultView;\"\n },\n {\n \"name\": \"ToolRunContext\",\n \"declaration\": \"export interface ToolRunContext extends ToolExecution {\\n deferContext(context: UserMessage): void;\\n concludeTurn(): void;\\n}\"\n },\n {\n \"name\": \"ToolSchema\",\n \"declaration\": \"export interface ToolSchema {\\n deferLoading?: true;\\n name: string;\\n description: string;\\n parameters: Record;\\n}\"\n },\n {\n \"name\": \"UserMessage\",\n \"declaration\": \"export interface UserMessage extends MessageBase {\\n readonly role: 'user';\\n}\"\n },\n {\n \"name\": \"WebFetchResultView\",\n \"declaration\": \"export interface WebFetchResultView {\\n card: 'web';\\n kind: 'fetch';\\n title?: string;\\n url: string;\\n statusCode: number;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebResultView\",\n \"declaration\": \"export type WebResultView = WebSearchResultView | WebFetchResultView;\"\n },\n {\n \"name\": \"WebSearchResultView\",\n \"declaration\": \"export interface WebSearchResultView {\\n card: 'web';\\n kind: 'search';\\n title?: string;\\n sources: WebSource[];\\n answer?: string;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebSource\",\n \"declaration\": \"export interface WebSource {\\n url: string;\\n title?: string;\\n snippet?: string;\\n publishedAt?: string;\\n}\"\n }\n ]\n }\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"inspect-tools-api"},"toolCallId":"inspect-tools-api","content":[{"type":"text","text":"{\n \"platform\": \"host\",\n \"provider\": \"Service\",\n \"method\": \"listService\",\n \"data\": {\n \"mode\": \"service\",\n \"service\": {\n \"key\": \"tools\",\n \"description\": \"Tool registry and execution pipeline. Scoped registrations shadow globals; one visibility resolver feeds presentation, lookup, and dispatch.\",\n \"access\": {\n \"optional\": {\n \"expression\": \"ctx.get(\\\"tools\\\")\",\n \"requiresUndefinedCheck\": true\n },\n \"hardDependency\": {\n \"inject\": [\n \"tools\"\n ],\n \"expression\": \"ctx.tools\"\n }\n },\n \"methods\": [\n {\n \"signature\": \"presentAs(mode: ToolPresentationMode): () => void\",\n \"description\": \"Present the calling scope's tools in `mode` instead of the deployment default. Nearest scope on the chain wins, so a preset's standing declaration covers every agent joined under it.\\n\\nScoped only, and one declaration per scope: this is how an agent preset composes PTC mode agents beside native ones in the same process, and a process-global override would be the `mode` config field instead.\",\n \"parameters\": [\n {\n \"name\": \"mode\",\n \"description\": \"the presentation the covered agents' models see.\"\n }\n ],\n \"returns\": \"the exact disposer that restores the deployment default.\"\n },\n {\n \"signature\": \"register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void\",\n \"description\": \"Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.\",\n \"parameters\": [\n {\n \"name\": \"definition\",\n \"description\": \"tool schema, execution, and optional finalization/presentation callbacks.\"\n },\n {\n \"name\": \"options\",\n \"description\": \"optional step-time activation condition.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the tool.\"\n },\n {\n \"signature\": \"restrict(filter: ToolRestriction): () => void\",\n \"description\": \"Restrict global tools for the calling agent scope. Empty filters, unknown names, scope-local names, and reserved transport names fail. Restrictions intersect; scoped registrations remain visible.\",\n \"parameters\": [\n {\n \"name\": \"filter\",\n \"description\": \"global-tool mask: `allow` (keep only) and/or `deny` (remove).\"\n }\n ],\n \"returns\": \"the exact disposer that lifts this restriction.\"\n },\n {\n \"signature\": \"guard(guard: ToolGuard): () => void\",\n \"description\": \"Register a monotonic guard after the extensible `tools/pre-execute` waterfall. A plain-context guard applies globally; one registered through `agent.ctx` applies only to that agent. Any matching guard may deny by returning a reason, while no guard can force-allow a call another guard denied. The exact effect disposer is returned for ordered ownership and HMR cleanup.\",\n \"parameters\": [\n {\n \"name\": \"guard\",\n \"description\": \"synchronous check; a returned string denies the execution.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the guard.\"\n },\n {\n \"signature\": \"get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined\",\n \"description\": \"Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.\",\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the tool name as registered.\"\n },\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission; omit only to inspect registered definitions.\"\n }\n ],\n \"returns\": \"the definition the scope resolves, or undefined when none is visible.\"\n },\n {\n \"signature\": \"async resolve(context: ToolActivationContext): Promise\",\n \"description\": \"Resolve conditions once for this step without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.\",\n \"parameters\": [\n {\n \"name\": \"context\",\n \"description\": \"preparing agent, step route, and cancellation.\"\n }\n ],\n \"returns\": \"the complete selection; the caller disposes it after its tool batch settles.\"\n },\n {\n \"signature\": \"schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]\",\n \"description\": \"Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.\",\n \"parameters\": [\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission, or omitted for registered-definition inspection.\"\n }\n ],\n \"returns\": \"one deep-cloned schema per visible tool.\"\n },\n {\n \"signature\": \"executionMode(exec: ToolExecutionInput): ToolExecutionMode\",\n \"description\": \"Classify a pending call through the caller's visible tool definition. Only an exact `true` is parallel; unknown, hidden, undeclared, invalid, or throwing classifiers are exclusive.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"call name, parsed arguments, and optional agent scope.\"\n }\n ],\n \"returns\": \"the fail-closed scheduling mode.\"\n },\n {\n \"signature\": \"async execute(exec: ToolExecutionInput): Promise\",\n \"description\": \"Execute through pre-policy, guards, around-dispatch, post-policy, definition-owned content finalization, and final notification. Tool and listener failures resolve as materialized error results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen snapshot final observers receive. Cancellation arriving after entry and before final result materialization skips a not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a successful started outcome with `ABORTED`; already-started work is still drained and may retain a tool-owned structured error.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"the typed same-process call input. The registry assigns its correlation token before policy begins.\"\n }\n ],\n \"returns\": \"the materialized final result.\"\n }\n ]\n },\n \"referencedTypes\": [\n {\n \"name\": \"Agent\",\n \"declaration\": \"export interface Agent {\\n readonly id: SessionId;\\n}\"\n },\n {\n \"name\": \"Branded\",\n \"declaration\": \"export type Branded = string & {\\n readonly [BRAND]: B;\\n};\"\n },\n {\n \"name\": \"DiffCallView\",\n \"declaration\": \"export interface DiffCallView {\\n card: 'diff';\\n title: string;\\n diffs: FileDiff[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"DiffResultView\",\n \"declaration\": \"export interface DiffResultView {\\n card: 'diff';\\n title?: string;\\n diffs: FileDiff[];\\n}\"\n },\n {\n \"name\": \"FileDiff\",\n \"declaration\": \"export interface FileDiff {\\n path: string;\\n oldText: string | null;\\n newText: string;\\n}\"\n },\n {\n \"name\": \"FileLocation\",\n \"declaration\": \"export interface FileLocation {\\n path: string;\\n line?: number;\\n}\"\n },\n {\n \"name\": \"GenericCallView\",\n \"declaration\": \"export interface GenericCallView {\\n card: 'generic';\\n title: string;\\n kind?: ToolCallKind;\\n rawInput?: unknown;\\n content?: ContentBlock[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"GenericResultView\",\n \"declaration\": \"export interface GenericResultView {\\n card: 'generic';\\n title?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"JsonSchemaNode\",\n \"declaration\": \"export interface JsonSchemaNode {\\n type?: JsonSchemaType;\\n oneOf?: JsonSchemaNode[];\\n properties?: Record;\\n required?: string[];\\n additionalProperties?: boolean;\\n items?: JsonSchemaNode;\\n enum?: JsonSchemaScalar[];\\n const?: JsonSchemaScalar;\\n description?: string;\\n title?: string;\\n default?: JsonValue;\\n examples?: JsonValue;\\n}\"\n },\n {\n \"name\": \"JsonSchemaScalar\",\n \"declaration\": \"export type JsonSchemaScalar = string | number | boolean | null;\"\n },\n {\n \"name\": \"JsonSchemaType\",\n \"declaration\": \"export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\"\n },\n {\n \"name\": \"JsonValue\",\n \"declaration\": \"export type JsonValue = null | boolean | number | string | JsonValue[] | {\\n [key: string]: JsonValue;\\n};\"\n },\n {\n \"name\": \"ReadFileLine\",\n \"declaration\": \"export interface ReadFileLine {\\n number: number;\\n text: string;\\n}\"\n },\n {\n \"name\": \"ReadResultView\",\n \"declaration\": \"export interface ReadResultView {\\n card: 'read';\\n title?: string;\\n path: string;\\n offset: number;\\n lines: ReadFileLine[];\\n totalLines: number;\\n lang?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"ResolvedToolSet\",\n \"declaration\": \"export interface ResolvedToolSet {\\n dispose(): void;\\n view(scope: ScopeKey | undefined): ReadonlyMap;\\n}\"\n },\n {\n \"name\": \"ScopeKey\",\n \"declaration\": \"export type ScopeKey = object;\"\n },\n {\n \"name\": \"SearchFileMatches\",\n \"declaration\": \"export interface SearchFileMatches {\\n path: string;\\n matches: SearchLineMatch[];\\n}\"\n },\n {\n \"name\": \"SearchLineMatch\",\n \"declaration\": \"export interface SearchLineMatch {\\n lineNumber: number;\\n line: string;\\n}\"\n },\n {\n \"name\": \"SearchMatchesResultView\",\n \"declaration\": \"export interface SearchMatchesResultView {\\n card: 'search';\\n shape: 'matches';\\n title?: string;\\n files: SearchFileMatches[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchPathsResultView\",\n \"declaration\": \"export interface SearchPathsResultView {\\n card: 'search';\\n shape: 'paths';\\n title?: string;\\n paths: string[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchResultView\",\n \"declaration\": \"export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;\"\n },\n {\n \"name\": \"SessionId\",\n \"declaration\": \"export type SessionId = Branded<'SessionId'>;\"\n },\n {\n \"name\": \"StepRoute\",\n \"declaration\": \"export interface StepRoute {\\n readonly provider: string;\\n readonly model: string;\\n}\"\n },\n {\n \"name\": \"TerminalCallView\",\n \"declaration\": \"export interface TerminalCallView {\\n card: 'terminal';\\n title: string;\\n description?: string;\\n cwd?: string;\\n}\"\n },\n {\n \"name\": \"TerminalResultView\",\n \"declaration\": \"export interface TerminalResultView {\\n card: 'terminal';\\n title?: string;\\n output?: string;\\n exitCode?: number;\\n signal?: string;\\n}\"\n },\n {\n \"name\": \"ToolActivationContext\",\n \"declaration\": \"export interface ToolActivationContext {\\n readonly agent: Agent;\\n readonly route: StepRoute;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolCallId\",\n \"declaration\": \"export type ToolCallId = Branded<'ToolCallId'>;\"\n },\n {\n \"name\": \"ToolCallKind\",\n \"declaration\": \"export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\"\n },\n {\n \"name\": \"ToolCallView\",\n \"declaration\": \"export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\"\n },\n {\n \"name\": \"ToolDefinition\",\n \"declaration\": \"export interface ToolDefinition extends ToolSchema {\\n readonly output: ToolOutputDefinition;\\n execute(args: unknown, exec: ToolRunContext): Promise;\\n projectContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n timeoutMs?: number;\\n isConcurrencySafe?(args: unknown): boolean;\\n presentCall?(args: unknown): ToolCallView | undefined;\\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\\n}\"\n },\n {\n \"name\": \"ToolErrorInfo\",\n \"declaration\": \"export interface ToolErrorInfo {\\n name: string;\\n code: string;\\n reason?: string;\\n}\"\n },\n {\n \"name\": \"ToolExecution\",\n \"declaration\": \"export interface ToolExecution extends ToolExecutionInput {\\n readonly rootCallId: ToolCallId;\\n readonly token: ToolExecutionToken;\\n}\"\n },\n {\n \"name\": \"ToolExecutionFailure\",\n \"declaration\": \"export interface ToolExecutionFailure {\\n readonly isError: true;\\n readonly error: ToolFailure;\\n readonly value?: never;\\n readonly content: ContentBlock[];\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: never;\\n}\"\n },\n {\n \"name\": \"ToolExecutionInput\",\n \"declaration\": \"export interface ToolExecutionInput {\\n readonly callId: ToolCallId;\\n readonly rootCallId?: ToolCallId;\\n readonly name: string;\\n readonly schema?: ToolSchema;\\n readonly arguments: unknown;\\n readonly agent?: Agent;\\n readonly toolSet?: ResolvedToolSet;\\n readonly parent?: ToolExecutionToken;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolExecutionMode\",\n \"declaration\": \"export type ToolExecutionMode = {\\n kind: 'parallel';\\n} | {\\n kind: 'exclusive';\\n};\"\n },\n {\n \"name\": \"ToolExecutionResult\",\n \"declaration\": \"export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\"\n },\n {\n \"name\": \"ToolExecutionSuccess\",\n \"declaration\": \"export interface ToolExecutionSuccess {\\n readonly isError: false;\\n readonly value: JsonValue;\\n readonly content: ContentBlock[];\\n readonly error?: never;\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: true;\\n}\"\n },\n {\n \"name\": \"ToolExecutionToken\",\n \"declaration\": \"export type ToolExecutionToken = symbol & {\\n readonly [toolExecutionTokenBrand]: true;\\n};\"\n },\n {\n \"name\": \"ToolFailure\",\n \"declaration\": \"export interface ToolFailure {\\n message: string;\\n info?: ToolErrorInfo;\\n}\"\n },\n {\n \"name\": \"ToolGuard\",\n \"declaration\": \"export type ToolGuard = (execution: Readonly) => string | undefined;\"\n },\n {\n \"name\": \"ToolOutputDefinition\",\n \"declaration\": \"export interface ToolOutputDefinition {\\n readonly schema: JsonSchemaNode;\\n render(args: unknown, value: JsonValue): ContentBlock[];\\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolPresentationMode\",\n \"declaration\": \"export type ToolPresentationMode = 'native' | 'ptc';\"\n },\n {\n \"name\": \"ToolRegistrationOptions\",\n \"declaration\": \"export interface ToolRegistrationOptions {\\n readonly when?: (context: ToolActivationContext) => boolean | Promise;\\n}\"\n },\n {\n \"name\": \"ToolRestriction\",\n \"declaration\": \"export interface ToolRestriction {\\n readonly allow?: readonly string[];\\n readonly deny?: readonly string[];\\n}\"\n },\n {\n \"name\": \"ToolResult\",\n \"declaration\": \"export interface ToolResult {\\n content: ContentBlock[];\\n isError: boolean;\\n meta?: JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolResultView\",\n \"declaration\": \"export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | SearchResultView | ReadResultView | WebResultView;\"\n },\n {\n \"name\": \"ToolRunContext\",\n \"declaration\": \"export interface ToolRunContext extends ToolExecution {\\n deferContext(context: UserMessage): void;\\n concludeTurn(): void;\\n}\"\n },\n {\n \"name\": \"ToolSchema\",\n \"declaration\": \"export interface ToolSchema {\\n deferLoading?: true;\\n name: string;\\n description: string;\\n parameters: Record;\\n}\"\n },\n {\n \"name\": \"UserMessage\",\n \"declaration\": \"export interface UserMessage extends MessageBase {\\n readonly role: 'user';\\n}\"\n },\n {\n \"name\": \"WebFetchResultView\",\n \"declaration\": \"export interface WebFetchResultView {\\n card: 'web';\\n kind: 'fetch';\\n title?: string;\\n url: string;\\n statusCode: number;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebResultView\",\n \"declaration\": \"export type WebResultView = WebSearchResultView | WebFetchResultView;\"\n },\n {\n \"name\": \"WebSearchResultView\",\n \"declaration\": \"export interface WebSearchResultView {\\n card: 'web';\\n kind: 'search';\\n title?: string;\\n sources: WebSource[];\\n answer?: string;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebSource\",\n \"declaration\": \"export interface WebSource {\\n url: string;\\n title?: string;\\n snippet?: string;\\n publishedAt?: string;\\n}\"\n }\n ]\n }\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-subprocess-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788778146017,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788778146017,"index":0,"dt":[],"id":"inspect-subprocess-api","name":"cordis_inspect_query","args":["{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"]},{"type":"chunk","time":1788778146017,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"inspect-subprocess-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"}}},{"type":"chunk","time":1788778146017,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788778146017,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/model-switch-notice/model-switch-driver.mjs b/snapshots/session/model-switch-notice/model-switch-driver.mjs index 072dc673af..4ce42062b5 100644 --- a/snapshots/session/model-switch-notice/model-switch-driver.mjs +++ b/snapshots/session/model-switch-notice/model-switch-driver.mjs @@ -7,17 +7,15 @@ export const name = 'model-switch-driver' export const inject = ['agents'] /** - * Change the request route after `todo_write`; headless owns the selection notice. + * Change the step route after `todo_write`; headless owns the selection notice. * @param {import('@deepseek-ai/cordis').Context} ctx - composition context. */ export function apply(ctx) { ctx.on('session/event', (session, event) => { if (event.type === 'todo/write') switched.add(session) }) - ctx.on('agent/request', async ({ agent }, next) => { - const resolved = await next() - if (!switched.has(agent.session)) return resolved - const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved - return { ...withoutInheritedEffort, ...SELECTED } + ctx.on('agent/route', async ({ agent }, next) => { + const route = await next() + return switched.has(agent.session) ? SELECTED : route }) } From 043539da055b01d824c96e4b2cbd375356ff322d Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 13 Oct 2026 10:58:57 +0800 Subject: [PATCH 05/36] feat(agent): choose provider, model, and effort through agent/model Rename agent/route to agent/model and make its result a complete ModelSelection, so each step fixes its provider, model, and reasoning effort before prompt preparation, agent/pre-step, tool conditions, and every request attempt. agent/request may change only sampling controls; returning another provider, model, or reasoning effort fails the step. installModelSelection installs one agent/model listener and ModelSelectionRef drops assembled. The pre-step payload, AssembleContext, and ToolActivationContext carry modelSelection. Webhook initial selection and the CLI mock effort switch move to agent/model. --- ...bles-and-tool-guidance-ownership.i18n.yaml | 8 +- ...t-variables-and-tool-guidance-ownership.md | 4 +- ...ariables-and-tool-guidance-ownership.zh.md | 4 +- ...6-07-05-reconstructable-requests.i18n.yaml | 4 +- .../2026-07-05-reconstructable-requests.md | 2 +- .../2026-07-05-reconstructable-requests.zh.md | 2 +- ...-14-provider-routed-llm-adapters.i18n.yaml | 4 +- ...2026-07-14-provider-routed-llm-adapters.md | 2 +- ...6-07-14-provider-routed-llm-adapters.zh.md | 2 +- ...02-system-prompt-as-surface-node.i18n.yaml | 4 +- ...026-09-02-system-prompt-as-surface-node.md | 2 +- ...-09-02-system-prompt-as-surface-node.zh.md | 2 +- ...-model-chosen-before-preparation.i18n.yaml | 22 +++++ ...12-step-model-chosen-before-preparation.md | 37 +++++++ ...step-model-chosen-before-preparation.zh.md | 37 +++++++ ...-route-chosen-before-preparation.i18n.yaml | 22 ----- ...12-step-route-chosen-before-preparation.md | 36 ------- ...step-route-chosen-before-preparation.zh.md | 36 ------- .../2026-10-03-pi-extensions-bridge.i18n.yaml | 4 +- .../2026-10-03-pi-extensions-bridge.md | 2 +- .../2026-10-03-pi-extensions-bridge.zh.md | 2 +- apps/cli/tests/fixtures/dsh-badge/snapshot.ts | 2 +- docs/agent-lifecycle.i18n.yaml | 4 +- docs/agent-lifecycle.md | 16 +-- docs/agent-lifecycle.zh.md | 16 +-- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 6 +- docs/architecture.zh.md | 6 +- docs/event-producer-consumer.md | 26 ++--- docs/event-producer-consumer.zh.md | 26 ++--- docs/subsystems/core.i18n.yaml | 8 +- docs/subsystems/core.md | 97 ++++++++++--------- docs/subsystems/core.zh.md | 97 ++++++++++--------- docs/subsystems/llm-streaming.i18n.yaml | 4 +- docs/subsystems/llm-streaming.md | 2 +- docs/subsystems/llm-streaming.zh.md | 2 +- docs/subsystems/session-reference.md | 8 +- docs/subsystems/session-reference.zh.md | 8 +- docs/subsystems/tools.md | 2 +- docs/subsystems/tools.zh.md | 2 +- .../conditional-tools/guide.i18n.yaml | 22 ++--- .../v0.2.1-alpha.2/conditional-tools/guide.md | 14 +-- .../conditional-tools/guide.zh.md | 14 +-- packages/acp/acp/README.i18n.yaml | 4 +- packages/acp/acp/README.md | 2 +- packages/acp/acp/README.zh.md | 2 +- packages/acp/acp/src/model-control.ts | 7 +- packages/acp/acp/tests/bridge.spec.ts | 4 +- packages/api/session-controller/src/agent.ts | 5 +- .../tests/archived-session-gate.host.spec.ts | 2 +- .../commands-queue-attachment.host.spec.ts | 5 +- .../tests/commands-upload-file.host.spec.ts | 5 +- .../tests/session-fork.host.spec.ts | 9 +- .../tests/session-models.host.spec.ts | 24 ++--- packages/bundle/headless/src/index.ts | 2 +- .../tests/compaction-basic.spec.ts | 2 +- .../tests/compaction-loop-repro.spec.ts | 6 +- .../tests/agent-instructions.spec.ts | 30 +++--- .../session-reference/README.i18n.yaml | 4 +- packages/context/session-reference/README.md | 2 +- .../context/session-reference/README.zh.md | 2 +- .../context/session-reference/src/index.ts | 30 +++--- .../tests/loader-composition.spec.ts | 2 +- .../tests/session-reference.spec.ts | 18 ++-- .../time-context/tests/time-context.spec.ts | 2 +- .../tmux-context/tests/tmux-context.spec.ts | 2 +- packages/core/agent-loop/README.i18n.yaml | 8 +- packages/core/agent-loop/README.md | 4 +- packages/core/agent-loop/README.zh.md | 4 +- packages/core/agent-loop/src/agent.ts | 74 +++++++------- packages/core/agent-loop/src/index.ts | 4 +- .../tests/contract-regressions.spec.ts | 17 ++-- packages/core/agent-loop/tests/loop.spec.ts | 22 +++-- .../tests/request-reconstruction.spec.ts | 22 ++--- .../tests/system-prompt-admission.spec.ts | 6 +- .../agent-loop/tests/tool-updates.spec.ts | 32 +++--- packages/core/agent/README.i18n.yaml | 12 +-- packages/core/agent/README.md | 8 +- packages/core/agent/README.zh.md | 8 +- packages/core/agent/src/model-selection.ts | 84 +++++----------- packages/core/agent/src/runtime-types.ts | 51 +++++----- .../core/agent/tests/model-selection.spec.ts | 80 ++++++--------- packages/core/tools/README.i18n.yaml | 4 +- packages/core/tools/README.md | 4 +- packages/core/tools/README.zh.md | 4 +- packages/core/tools/src/index.ts | 10 +- packages/core/tools/tests/activation.spec.ts | 10 +- packages/core/tools/tests/ptc.spec.ts | 2 +- packages/experimental/webhook/src/session.ts | 16 ++- .../webhook/tests/session.spec.ts | 33 ++++--- .../extensions/tool-cordis/src/api-catalog.ts | 34 +++---- .../tests/account-routing.spec.ts | 14 +-- .../llm/llm-deepseek/tests/adapter.spec.ts | 2 +- packages/llm/llm-retry/tests/retry.spec.ts | 4 +- .../plan/plan-mode/tests/plan-mode.spec.ts | 12 +-- .../tests/session-checkpoint-policy.spec.ts | 2 +- .../skill/tool-skill/tests/tool-skill.spec.ts | 8 +- .../tests/model-selection-settings.spec.ts | 2 +- .../tests/fixtures/cli-mock-llm.ts | 6 +- scripts/fixtures/python-sdk-dynamic-tools.mjs | 2 +- scripts/gen-cordis-catalog.ts | 1 - scripts/gen-doc-graphs.ts | 16 +-- .../python-snapshot-workflow-order.spec.ts | 2 +- scripts/type-equiv.manifest.json | 2 +- .../cordis-inspect-jsdoc/session.v4.jsonl | 2 +- .../model-switch-driver.mjs | 8 +- 106 files changed, 693 insertions(+), 738 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md create mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md delete mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.i18n.yaml delete mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md delete mode 100644 .agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.zh.md diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml index 349c7778b0..f331bc345e 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml @@ -15,8 +15,8 @@ en: 46e67248692e333a zh: 51c5f2c6152c94d7 /agent-note-prompt-variables-and-tool-guidance-ownership/decision/prompt-variables: - en: 5f33b9ce0f4b0f9b - zh: 811297eddda54d51 + en: f5cbf8a901143c06 + zh: 534836ed5176a8ec /agent-note-prompt-variables-and-tool-guidance-ownership/decision/persona-as-the-order-0-section: en: c2d32c0ac5d28759 zh: 59cd252ba6da6e59 @@ -36,5 +36,5 @@ en: 31ba63101fca5790 zh: af4ceefab2033142 /agent-note-prompt-variables-and-tool-guidance-ownership/consequences: - en: 64e55b14b2511e9d - zh: ea7216af8111b2b2 + en: e57137faf5a35b1e + zh: baf3643398f5e005 diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md index 5eaf8417c5..73931b9c8e 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md @@ -28,7 +28,7 @@ The assembled system prompt had four defects, all of one family: facts the harne Plugins register `{{name}}` values through `ctx.systemPrompt.variable(name, provider)`. Assembly resolves them into the waterfall-visible variable map. Rendering rejects unknown own-property references, registered providers that return `undefined`, malformed complete references, and unbalanced references that still contain a closing `}}`; a lone unmatched `{{` remains prose, and substituted values are not rescanned. Registration rejects invalid or duplicate variable names, and section names are unique. Sections may set `interpolate: false` to preserve generated documents literally; `tools:sdk` does so because tool descriptions and schemas may document their own `{{…}}` syntax. -`dsh-agent-loop` registers `provider` and `model` as pure projections of the assembly context: the step route that `agent/route` chose, or the agent's `options` pair outside a step. Example personas reference `{{model}}` so the route owns the model name. These variables remain on the loop plugin because they describe the agents it drives; a replacement loop supplies its own. The [Session working-directory decision](2026-09-13-session-working-directory.md) owns directory state and its literal user-context placement; the loop does not register `cwd`. +`dsh-agent-loop` registers `provider` and `model` as pure projections of the assembly context: the step model selection that `agent/model` chose, or the agent's `options` pair outside a step. Example personas reference `{{model}}` so the model selection owns the model name. These variables remain on the loop plugin because they describe the agents it drives; a replacement loop supplies its own. The [Session working-directory decision](2026-09-13-session-working-directory.md) owns directory state and its literal user-context placement; the loop does not register `cwd`. ### Persona as the order-0 section @@ -65,7 +65,7 @@ Per-tool semantics and selection guidance live in tool descriptions. Prompt sect ## Consequences - Every fact in the assembled prompt now has exactly one owner, and the hand-maintained tool prose in leaf YAML is gone: loading or dropping a tool plugin no longer means editing any deployment's persona. -- `{{model}}` reflects the step route that `agent/route` chose, and `agent/request` cannot replace that route, so the rendered prompt and the routed header name the same model. A plugin that supplies or switches the model owns that fact on `agent/route`; a loop test pins the supply path end-to-end. Accepted. +- `{{model}}` reflects the step model selection that `agent/model` chose, and `agent/request` cannot replace that model, so the rendered prompt and the routed header name the same model. A plugin that supplies or switches the model owns that fact on `agent/model`; a loop test pins the supply path end-to-end. Accepted. - While a bound provider is absent (not yet activated, unloaded, mid-HMR-reload), the subagent tool does not exist and a model request in that window simply lacks it. That is the honest state — the alternative was a registered tool whose description or execution could not be trusted. - Strict interpolation rejects missing or valueless variables before a model request. The turn ends with `error` while the loop remains available for later turns; a persona referencing `{{model}}` requires its composing runtime to supply that value. - Inline escapes remain unsupported in interpolated text; literal sections need no escaping. PTC unit tests cover both modes and runtime languages, and the recorded `ptc-turn` scenario preserves tool-template examples in the model-visible prompt. diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md index adeaf7c0d5..12944274fa 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md @@ -28,7 +28,7 @@ Status: implemented 插件通过 `ctx.systemPrompt.variable(name, provider)` 注册 `{{name}}` 值。组装过程将它们解析到 waterfall 可见的变量映射中。渲染阶段拒绝以下情况:引用未知的自有属性、已注册的提供方返回 `undefined`、格式错误的完整引用、以及仍包含闭合 `}}` 的不平衡引用;孤立的未匹配 `{{` 保留为行文,替换后的值不会被重新扫描。注册阶段拒绝无效或重复的变量名,section 名称也必须唯一。段可设置 `interpolate: false` 来原样保留生成的文档;`tools:sdk` 使用此设置,因为工具描述和 schema 可能会介绍自身的 `{{…}}` 语法。 -`dsh-agent-loop` 注册 `provider` 和 `model`,它们都是组装上下文的纯投影:步骤内取 `agent/route` 选定的步骤路由,步骤外取 agent 的 `options` 这一对值。示例 persona 引用 `{{model}}`,由路由拥有模型名称。这些变量保留在 loop 插件上,因为它们描述该循环驱动的 agent;替换循环自行提供自己的变量。[Session 工作目录决策](2026-09-13-session-working-directory.zh.md) 拥有目录状态及其字面用户上下文位置;循环不注册 `cwd`。 +`dsh-agent-loop` 注册 `provider` 和 `model`,它们都是组装上下文的纯投影:步骤内取 `agent/model` 选定的步骤模型选择,步骤外取 agent 的 `options` 这一对值。示例 persona 引用 `{{model}}`,由模型选择拥有模型名称。这些变量保留在 loop 插件上,因为它们描述该循环驱动的 agent;替换循环自行提供自己的变量。[Session 工作目录决策](2026-09-13-session-working-directory.zh.md) 拥有目录状态及其字面用户上下文位置;循环不注册 `cwd`。 ### Persona 作为 order-0 section @@ -65,7 +65,7 @@ Status: implemented ## 后果 - 组装后的提示词中每个事实现在恰好有一个归属方,leaf YAML 中手工维护的工具行文已消除:加载或卸载一个工具插件不再需要编辑任何部署的 persona。 -- `{{model}}` 反映 `agent/route` 选定的步骤路由,且 `agent/request` 不能替换该路由,因此渲染后的提示词与路由后的请求头指向同一模型。提供或切换模型的插件在 `agent/route` 上拥有这一事实;一个循环测试端到端固定了 supply 路径。已接受。 +- `{{model}}` 反映 `agent/model` 选定的步骤模型选择,且 `agent/request` 不能替换该模型,因此渲染后的提示词与路由后的请求头指向同一模型。提供或切换模型的插件在 `agent/model` 上拥有这一事实;一个循环测试端到端固定了 supply 路径。已接受。 - 当一个已绑定的提供方不存在时(尚未激活、已卸载、HMR(热模块替换)重载中),subagent 工具不存在,该窗口内的模型请求中不会包含它。这是诚实的状态——替代方案是注册一个 description 或执行都不可信的工具。 - 严格插值在模型请求之前拒绝缺失或无值的变量。该轮次以 `error` 结束,循环仍可服务后续轮次;引用 `{{model}}` 的 persona 要求组合它的运行时提供该值。 - 插值文本仍不支持行内转义;字面文本段无需转义。PTC 单元测试覆盖两种模式和运行时语言,录制的 `ptc-turn` 场景在模型可见的提示词中保留工具模板示例。 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 76b76ed269..5809b9a8d4 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 @@ -15,8 +15,8 @@ en: 6da15cf986d59a91 zh: 40282908b54295f9 /agent-note-every-llm-request-is-reconstructable-from-the-session-log/decision/the-mechanism: - en: 8a1ec49eb4f0ecf0 - zh: e9d22685d64826d4 + en: b053c2b01866a634 + zh: cb15fa3a7fdefe60 /agent-note-every-llm-request-is-reconstructable-from-the-session-log/decision/the-minicode-shape-adopted-with-the-event-log-as-the-source: en: e5f2ffaa3d7de0cc zh: 5ba6b36787a0e189 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 2744d4828f..022f6dcb06 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md @@ -24,7 +24,7 @@ Prefix-cache stability is corollary #1, not the headline: an append-only log pro `EpochHeader` records the request's non-history state: call config and tool schemas. Writers omit `tools: []` and `adapterDefaults: {}`; current acceptance rejects those fields and any `header.system`, rather than repairing them. Whitespace-only system-message content, `config.stop: []`, and nested extensions remain intact. The [V3 canonical-envelope decision](2026-09-06-v3-canonical-session-envelopes.md) owns historical conversion. The rendered system prompt is derived history — the `system/message` event at surface node 0, per the [surface-node Agent Note](2026-09-02-system-prompt-as-surface-node.md) — so a prompt change is a surface replacement rather than a header change. Adapter-supplied effort and token defaults retain their `adapterDefaults` ownership; 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, lets `agent/route` choose the step's provider and model, prepares runtime context, and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, resolves the step's tools, assembles the system prompt, commits a changed prompt as the `system/message` append or node-0 replacement, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. `agent/request` may replace only the frozen call-config controls; the provider and model stay the step route. The loop records the owed initial, resume, change, or series full snapshot, builds `GenerateOptions` from derived messages (system message first) and that header with no `system` field, and freezes it while leaving `AbortSignal` live. The [request-freeze evidence reference](../../../../packages/core/agent-loop/README.md) owns reuse of completed message freezes and per-request local header freezing. 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, lets `agent/model` choose the step's provider, model, and reasoning effort, prepares runtime context, and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, resolves the step's tools, assembles the system prompt, commits a changed prompt as the `system/message` append or node-0 replacement, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. `agent/request` may replace only the frozen call config's sampling controls; the provider, model, and reasoning effort stay the step's model selection. The loop records the owed initial, resume, change, or series full snapshot, builds `GenerateOptions` from derived messages (system message first) and that header with no `system` field, and freezes it while leaving `AbortSignal` live. The [request-freeze evidence reference](../../../../packages/core/agent-loop/README.md) owns reuse of completed message freezes and per-request local header freezing. 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. 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 6965fa627b..9b94859d12 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 @@ -24,7 +24,7 @@ Status: implemented `EpochHeader` 记录请求的非历史状态:调用配置和工具 schema。写入方省略 `tools: []` 与 `adapterDefaults: {}`;当前接纳拒绝这些字段以及任何 `header.system`,而不修复它们。仅含空白的系统消息内容、`config.stop: []` 与嵌套扩展保持原样。[V3 规范信封决策](2026-09-06-v3-canonical-session-envelopes.zh.md)负责历史转换。渲染后的系统提示词是派生历史——surface 第 0 号节点上的 `system/message` 事件,见[surface 节点 Agent Note](2026-09-02-system-prompt-as-surface-node.zh.md)——因此提示词变更是 surface 替换而不是 header 变更。适配器提供的推理强度与 token 默认值会保留其 `adapterDefaults` 来源信息;Web 从日志恢复模型选择时会省略适配器持有的推理强度,因此下一次解析不会把相同的有效配置重新归类为显式选择并产生虚假变更。`request/header` 始终写入完整快照:首个循环实例使用 reason `initial`,后续实例使用 `resume`,实例内变更使用 `change`,内容未变的封装显式开启消息序列或跟随表层替换时使用 `series`。如果发生变化的请求同时开启序列,`change` 快照会携带 `startsSeries: true`,无需重复 header 即可保留这两个独立事实。普通的仅追加后续 Turn、同一序列内后续的 Step 与重试沿用最新快照。`foldRequestHeader` 选择最新快照。旧的 `request/header-delta` 事件和已移除的 `fallback` reason 在追加或加载时都会被拒绝。 -每个拟议步骤先领取其 inbox 批次,由 `agent/route` 选定该步骤的提供方与模型,准备运行时上下文,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,解析该步骤的工具并组装系统提示词,把变化的提示词作为 `system/message` 追加或第 0 号节点替换提交,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。`agent/request` 只能替换冻结调用配置中的控制参数;提供方与模型保持为步骤路由。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息(系统消息在先)与该不含 `system` 字段的 header 构建 `GenerateOptions`,冻结请求但保持 `AbortSignal` 活跃。[请求冻结证据说明](../../../../packages/core/agent-loop/README.zh.md)拥有消息完整冻结的复用规则和每次请求的本地 header 冻结规则。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 +每个拟议步骤先领取其 inbox 批次,由 `agent/model` 选定该步骤的提供方、模型与推理强度,准备运行时上下文,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,解析该步骤的工具并组装系统提示词,把变化的提示词作为 `system/message` 追加或第 0 号节点替换提交,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。`agent/request` 只能替换冻结调用配置中的采样控制参数;提供方、模型与推理强度保持为步骤的模型选择。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息(系统消息在先)与该不含 `system` 字段的 header 构建 `GenerateOptions`,冻结请求但保持 `AbortSignal` 活跃。[请求冻结证据说明](../../../../packages/core/agent-loop/README.zh.md)拥有消息完整冻结的复用规则和每次请求的本地 header 冻结规则。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 **已打开步骤是重建边界。** 进入步骤的 `user/message` 批次与任何新写入的 `request/header` 都位于请求分派之前。原子领取后发生的注入加入后续请求;必须影响本次请求的监听器则通过 `agent/pre-step` 返回消息。header 重建选择该步骤的 `request/header`,或在无新 header 写入时沿用前一个快照。 diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml index 3ef3879354..dc310776ac 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.i18n.yaml @@ -12,8 +12,8 @@ en: a15c7c13f167e5ac zh: 63bcc2ef60c2f344 /agent-note-provider-routed-llm-adapters-and-a-generic-pi-ai-backend/decision/provider-is-the-adapter-registration-key: - en: ab32d2c01a78ac3f - zh: fbb1d8d2cade9d2e + en: b0586701c1989416 + zh: 5b64205431325b03 /agent-note-provider-routed-llm-adapters-and-a-generic-pi-ai-backend/decision/explicit-pi-ai-provider-profiles: en: 1346315312eb35e2 zh: 3555f91c3afb49f8 diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md index 23023a952c..b9fe53ed7e 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.md @@ -18,7 +18,7 @@ The adapter configuration also assumes one DeepSeek API key and endpoint. A gene ### Provider is the adapter registration key -`GenerateOptions` and `LlmCallConfig` carry `provider: string` beside `model: string`; `AgentOptions` carries the corresponding optional creation field. A loop request is valid only after both values are non-empty, and both values are part of the logged request header. `agent/route` may return a replacement pair for any step, so a session can switch providers and models without changing the Cordis plugin lifecycle; every request attempt in the step keeps that pair. +`GenerateOptions` and `LlmCallConfig` carry `provider: string` beside `model: string`; `AgentOptions` carries the corresponding optional creation field. A loop request is valid only after both values are non-empty, and both values are part of the logged request header. `agent/model` may return a replacement pair, with that model's reasoning effort, for any step, so a session can switch providers and models without changing the Cordis plugin lifecycle; every request attempt in the step keeps that selection. `LlmRuntime` registers and resolves adapters by provider. `registerAdapter(providers, adapter)` checks the entire provider list before mutating the registry, rejects a duplicate with `DUPLICATE_ADAPTER`, and disposes the whole registration as one effect. Model ids are not registration keys; the selected adapter still validates or forwards them. The later [LLM catalog and ACP selection Agent Note](../../archived/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md) added advisory `listProviders()` / `listModels()` discovery without turning model membership into request validation. diff --git a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md index ef049f3c42..bdde3cd88f 100644 --- a/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-14-provider-routed-llm-adapters.zh.md @@ -18,7 +18,7 @@ Status: implemented ### 提供方作为适配器注册键 -`GenerateOptions` 与 `LlmCallConfig` 在 `model: string` 之外携带 `provider: string`,`AgentOptions` 则携带对应的可选创建字段。只有两个值都非空时,agent loop(智能体循环)请求才有效;两个值也都会写入请求头日志。`agent/route` 可以为任意步骤返回替换后的字段组合,因此会话可以切换提供方与模型,无需改变 Cordis 插件生命周期;该步骤的每次请求尝试都沿用这一组合。 +`GenerateOptions` 与 `LlmCallConfig` 在 `model: string` 之外携带 `provider: string`,`AgentOptions` 则携带对应的可选创建字段。只有两个值都非空时,agent loop(智能体循环)请求才有效;两个值也都会写入请求头日志。`agent/model` 可以为任意步骤返回替换后的字段组合及该模型的推理强度,因此会话可以切换提供方与模型,无需改变 Cordis 插件生命周期;该步骤的每次请求尝试都沿用这一选择。 `LlmRuntime` 按提供方注册和解析适配器。`registerAdapter(providers, adapter)` 在修改注册表前检查整个提供方列表,遇到重复项时返回 `DUPLICATE_ADAPTER`,并以一个 effect 为单位整体 dispose(资源释放)。模型 ID 不作为注册键;仍由选中的适配器负责验证或转发。后续的 [LLM 目录与 ACP 模型选择 Agent Note](../../archived/architecture/2026-07-15-llm-model-catalog-and-acp-selection.md) 增加了建议性的 `listProviders()` / `listModels()` 发现接口,但不会把目录成员关系变成请求校验规则。 diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml index 4d4ce8a93b..ba1077a0ec 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml @@ -18,8 +18,8 @@ en: a217a08932938062 zh: 4924d99d55d9c973 /agent-note-the-system-prompt-is-surface-node-0/decision/ownership-in-the-loop: - en: 1c56551cd45b1ed4 - zh: 39c26c6c9799de59 + en: 1626e01049f6d312 + zh: bb000a96944c8168 /agent-note-the-system-prompt-is-surface-node-0/decision/consumers: en: 39f9f4acffcccdc6 zh: 36b23a57e7d28950 diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md index 405f9c2b96..dbcdaea1f2 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md @@ -36,7 +36,7 @@ When the initial rendered prompt is empty, the loop reserves an empty system hea `dsh-agent-loop` owns `SystemPromptProjection` beside `RuntimeContextProjection` in `packages/core/agent-loop/src/runtime-context.ts`. It reads the surviving `system/message` nodes from the current surface on every projection, so a compaction or replacement that ran earlier in the same step is already reflected. `project(rendered, { inHistory, startsSeries })` returns `{ message, intent }` — `intent` is `{ surfaceOp: 'append' }` when no system node survives or when the [in-history rule](../feature/2026-09-02-in-history-system-prompt-replacement.md) applies, otherwise a replacement of exactly the latest surviving system node — or `undefined` when the latest node already holds the rendered text. -In `packages/core/agent-loop/src/agent.ts`, `step()` renders the prompt with `renderPrompt(assembly)` after `step/start` and projects it on each attempt after `agent/request` and `prepareCall()`, so a compaction provider's replacement inside `agent/pre-step` or retry recovery is visible to reconciliation; the `system/message` is committed before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `agent/route` waterfall → `systemPrompt.prepare()` → `agent/pre-step` waterfall → `step/start` → resolve tools → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → commit `system/message` (when changed) → commit `user/message`s → `request/header` → `request/context` → stream. +In `packages/core/agent-loop/src/agent.ts`, `step()` renders the prompt with `renderPrompt(assembly)` after `step/start` and projects it on each attempt after `agent/request` and `prepareCall()`, so a compaction provider's replacement inside `agent/pre-step` or retry recovery is visible to reconciliation; the `system/message` is committed before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `agent/model` waterfall → `systemPrompt.prepare()` → `agent/pre-step` waterfall → `step/start` → resolve tools → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → commit `system/message` (when changed) → commit `user/message`s → `request/header` → `request/context` → stream. `dsh-token-meter` anchors usage to the priced surface immediately before the successful `assistant/message`, not to `step/start`. The loop admits the system prompt and user messages after step start, and retry recovery can replace nodes before rebuilding the request. Capturing that current surface includes every admitted input once; the embedded provider output remains separately priced so durable assistant rewrites retain their signed delta. The open step stores only turn and step for lifecycle validation, not a second node snapshot. diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md index 7384b5f96c..fada9e3085 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md @@ -36,7 +36,7 @@ Status: implemented `dsh-agent-loop` 在 `packages/core/agent-loop/src/runtime-context.ts` 中与 `RuntimeContextProjection` 并列拥有 `SystemPromptProjection`。它在每次投影时从当前 surface 读取存活的 `system/message` 节点,因此同一步骤中更早运行的压缩或替换已经反映在内。`project(rendered, { inHistory, startsSeries })` 返回 `{ message, intent }`——没有系统节点存活或[历史内规则](../feature/2026-09-02-in-history-system-prompt-replacement.zh.md)适用时 `intent` 为 `{ surfaceOp: 'append' }`,否则是对最新存活系统节点的精确替换——最新节点已持有渲染文本时返回 `undefined`。 -在 `packages/core/agent-loop/src/agent.ts` 中,`step()` 在 `step/start` 之后用 `renderPrompt(assembly)` 渲染提示词,并在每次尝试的 `agent/request` 与 `prepareCall()` 之后投影它,因此压缩提供者在 `agent/pre-step` 内或重试恢复中做出的替换对协调可见;`system/message` 在该步骤的 `user/message` 事件之前提交,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `agent/route` waterfall → `systemPrompt.prepare()` → `agent/pre-step` waterfall → `step/start` → 解析工具 → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → 提交 `system/message`(有变化时) → 提交各条 `user/message` → `request/header` → `request/context` → 流式请求。 +在 `packages/core/agent-loop/src/agent.ts` 中,`step()` 在 `step/start` 之后用 `renderPrompt(assembly)` 渲染提示词,并在每次尝试的 `agent/request` 与 `prepareCall()` 之后投影它,因此压缩提供者在 `agent/pre-step` 内或重试恢复中做出的替换对协调可见;`system/message` 在该步骤的 `user/message` 事件之前提交,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `agent/model` waterfall → `systemPrompt.prepare()` → `agent/pre-step` waterfall → `step/start` → 解析工具 → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → 提交 `system/message`(有变化时) → 提交各条 `user/message` → `request/header` → `request/context` → 流式请求。 `dsh-token-meter` 把用量锚定到成功的 `assistant/message` 之前的已计价 surface,而不是 `step/start`。循环在步骤开始之后接纳系统提示词与用户消息,重试恢复还可能在重建请求之前替换节点。捕获当前 surface 会让每个已接纳输入恰好计入一次;内嵌的提供方输出仍单独计价,因此持久 assistant 改写保留其带符号增量。开放步骤只保存 turn 与 step 以验证生命周期,不保存第二份节点快照。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml new file mode 100644 index 0000000000..3559e84201 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-12-step-model-chosen-before-preparation.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md +/agent-note-choose-the-step-model-before-step-preparation: + en: f068fddb192978d2 + zh: 601deb72d3d90263 +/agent-note-choose-the-step-model-before-step-preparation/problem: + en: cb8d6f058dd5f47d + zh: bb70e1cfe6880da5 +/agent-note-choose-the-step-model-before-step-preparation/decision: + en: d0ee43966ff59a93 + zh: 4f69bc120de87c44 +/agent-note-choose-the-step-model-before-step-preparation/alternatives-considered: + en: 3114082393f6a55f + zh: a3790bd3b18658e0 +/agent-note-choose-the-step-model-before-step-preparation/consequences: + en: c553f9931c8c467b + zh: 0d77c5c71d266d27 +/agent-note-choose-the-step-model-before-step-preparation/related: + en: 00ef1147a7852c0a + zh: 4bd89960e08b6eda diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md new file mode 100644 index 0000000000..c9a6c8dde9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md @@ -0,0 +1,37 @@ +# Agent Note: Choose the step model before step preparation + +Status: implemented + +English | [中文](2026-10-12-step-model-chosen-before-preparation.zh.md) + +## Problem + +Tool availability can depend on the route of the request that declares the tools: `web_search` must stay off routes without search credentials, and plan or team state can withhold other tools. Message preparation needs the same model: session references size snapshots by the model's context window, and model selection announces a switch. The loop assembled tools and prompt sections before `agent/pre-step` and decided the provider, model, and reasoning effort only in `agent/request` after `step/start`, so earlier consumers predicted them from model-selection state. A listener that replaced them in `agent/request`, including on a retry, made the assembled prompt and tool catalog describe another model. + +## Decision + +The provider, model, and reasoning effort are a step fact, chosen together as the user chooses them before sending a message. After claiming input, the loop dispatches `agent/model` once per proposed step. Its default comes from the agent options before this loop logs a request and from the logged header afterwards, with an effort only when one was chosen for that exact model; `installModelSelection` returns its current selection there. The loop passes the resulting `ModelSelection` to `system-prompt/prepare` as `AssembleContext.modelSelection`, to `agent/pre-step` as `payload.modelSelection`, and to tool conditions as `ToolActivationContext.modelSelection`. The `{{provider}}` and `{{model}}` prompt variables read it. + +After `agent/pre-step` accepts the step and `step/start` opens it, the loop resolves conditional tools and assembles the prompt once. Each request attempt then runs `agent/request` and `prepareCall()` immediately before admission. `agent/request` may change sampling controls; a result with another provider, model, or reasoning effort fails the step. Retries reuse the step's model selection, tool set, and rendered assembly, and the step-owned tool set closes after the step's tool batch settles. A selection made during a step applies from the next step. + +## Alternatives considered + +- **Bind the route in `agent/request` before `agent/pre-step` and expose `Agent.currentRoute()`.** The prepared call captures the adapter registration and connection settings, so holding it across compaction, hooks, and session reads ignores settings changed meanwhile, and adapters were prepared for steps that `agent/pre-step` rejects. The getter was valid only inside a step and threw elsewhere, and every Agent implementation and test double had to carry it. +- **Record the model in `agent/pre-step`.** `system-prompt/prepare` runs before that waterfall, and model consumers inside it would depend on listener order. +- **Register the model selection on the Agent without an event.** It adds a single-consumer method to the generic `Agent` interface and removes the listener path that supplies a model for agents created without one. +- **Keep the decision in `agent/request` and predict it for earlier consumers.** A prediction diverges whenever a listener other than model selection changes the model. +- **Choose only the provider and model per step and leave reasoning effort to `agent/request`.** An effort is valid only for the model it was chosen for. The split required `installModelSelection` to capture the selection in one waterfall and apply its effort in another only when no other listener had replaced the model, and it let a retry change effort within a step. + +## Consequences + +- Tool conditions, prompt variables, reference budgets, and switch notices read the provider and model that the request header records. +- `prepareCall()` stays adjacent to dispatch, so its adapter registration and connection snapshot cover only header logging and streaming. +- A step cannot fail over to another provider or change reasoning effort on retry; a policy that needs this must run model selection, tool resolution, and assembly again for the retried attempt. +- The model selection cannot depend on `agent/pre-step` outcomes. Plan state commits inside that waterfall, so a plan-specific model would require committing plan selections before model selection. +- `agent/pre-step` listeners and direct dispatchers must handle the required `modelSelection` field. + +## Related + +- [Provider-routed LLM adapters](2026-07-14-provider-routed-llm-adapters.md) owns provider and model fields in call configuration. +- [Reconstructable requests](2026-07-05-reconstructable-requests.md) owns request reconstruction from the logged header. +- [Prompt variables and tool guidance ownership](2026-07-05-prompt-variables-and-tool-guidance-ownership.md) owns the `{{model}}` variable. diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md new file mode 100644 index 0000000000..09ef27ac4f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 在步骤准备之前选定步骤模型 + +Status: implemented + +[English](2026-10-12-step-model-chosen-before-preparation.md) | 中文 + +## 问题 + +工具是否可用可能取决于声明这些工具的请求所用的路由:`web_search` 不得出现在没有搜索凭据的路由上,计划或团队状态也可能撤下其他工具。消息准备同样需要这一模型:会话引用按模型的上下文窗口确定快照大小,模型选择会通告模型切换。循环原先在 `agent/pre-step` 之前组装工具与提示词段落,直到 `step/start` 之后才在 `agent/request` 中决定提供方、模型与推理强度,因此更早的消费方只能依据模型选择状态预测它们。若监听器在 `agent/request` 中(包括在重试时)替换它们,已组装的提示词与工具目录就会描述另一个模型。 + +## 决策 + +提供方、模型与推理强度是步骤级事实,像用户在发送消息前那样一起选定。领取输入之后,循环为每个拟议步骤派发一次 `agent/model`。其默认值在本循环记录请求之前取自 agent 选项,之后取自已记录的请求头,且只有为该确切模型选定过的推理强度才会保留;`installModelSelection` 在这里返回其当前选择。循环把得到的 `ModelSelection` 作为 `AssembleContext.modelSelection` 传给 `system-prompt/prepare`,作为 `payload.modelSelection` 传给 `agent/pre-step`,作为 `ToolActivationContext.modelSelection` 传给工具条件。提示词变量 `{{provider}}` 与 `{{model}}` 读取该选择。 + +`agent/pre-step` 接纳步骤且 `step/start` 打开步骤之后,循环解析条件工具并组装提示词,各执行一次。之后每次请求尝试都在准入之前紧接着运行 `agent/request` 与 `prepareCall()`。`agent/request` 可以修改采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。重试复用该步骤的模型选择、工具集合与已渲染组装结果,步骤拥有的工具集合在该步骤的工具批次结束后关闭。步骤进行中做出的选择从下一个步骤开始生效。 + +## 考虑过的替代方案 + +- **在 `agent/pre-step` 之前通过 `agent/request` 绑定路由,并提供 `Agent.currentRoute()`。** 已准备调用会捕获适配器注册与连接设置,因此在压缩、钩子与会话读取期间一直持有它,会忽略期间修改的设置;被 `agent/pre-step` 拒绝的步骤也会准备适配器。该 getter 只在步骤内有效、在其他时刻抛错,且每个 Agent 实现与测试替身都必须提供它。 +- **在 `agent/pre-step` 内记录模型。** `system-prompt/prepare` 在该 waterfall 之前运行,而 waterfall 内的模型消费方将依赖监听器顺序。 +- **不使用事件,直接在 Agent 上登记模型选择。** 这会给通用 `Agent` 接口增加只有单一消费方的方法,并移除为创建时没有模型的 agent 提供模型的监听器途径。 +- **决定留在 `agent/request`,为更早的消费方预测它。** 只要模型选择之外的监听器修改模型,预测就会偏离。 +- **每个步骤只选定提供方与模型,推理强度留给 `agent/request`。** 推理强度只对选定它的模型有效。拆开后,`installModelSelection` 必须在一个 waterfall 中捕获选择,再在另一个 waterfall 中、且仅当其他监听器没有替换模型时应用推理强度;重试也可以在步骤内修改推理强度。 + +## 后果 + +- 工具条件、提示词变量、引用预算与切换通告读取的提供方与模型,与请求头记录的一致。 +- `prepareCall()` 紧邻分发,因此其适配器注册与连接快照只覆盖请求头记录与流式请求。 +- 步骤无法在重试时切换到其他提供方或修改推理强度;需要这种能力的策略必须为重试的尝试重新执行模型选择、工具解析与组装。 +- 模型选择不能依赖 `agent/pre-step` 的结果。计划状态在该 waterfall 内提交,因此按计划模式选择模型需要先在模型选择之前提交计划选择。 +- `agent/pre-step` 监听器与直接派发方必须处理必填的 `modelSelection` 字段。 + +## 相关 + +- [基于提供方路由的 LLM 适配器](2026-07-14-provider-routed-llm-adapters.zh.md)负责调用配置中的提供方与模型字段。 +- [可重建请求](2026-07-05-reconstructable-requests.zh.md)负责依据已记录请求头重建请求。 +- [提示词变量与工具指导归属](2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md)负责 `{{model}}` 变量。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.i18n.yaml deleted file mode 100644 index c0331d7d6c..0000000000 --- a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.i18n.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# Bilingual-pair consistency record for 2026-10-12-step-route-chosen-before-preparation.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md -/agent-note-choose-the-step-route-before-step-preparation: - en: cce89c1039110cb5 - zh: fb29015e2a37b74f -/agent-note-choose-the-step-route-before-step-preparation/problem: - en: 2d6bc81525bc277d - zh: b65ec115cb4a00e4 -/agent-note-choose-the-step-route-before-step-preparation/decision: - en: 38e163581b2f798d - zh: 62c89bb0167ded9e -/agent-note-choose-the-step-route-before-step-preparation/alternatives-considered: - en: a704646ef1631668 - zh: f99b24164105d0bb -/agent-note-choose-the-step-route-before-step-preparation/consequences: - en: ebaeafdadf1ab3cd - zh: 12cb3c213c84fe82 -/agent-note-choose-the-step-route-before-step-preparation/related: - en: 00ef1147a7852c0a - zh: 4bd89960e08b6eda diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md deleted file mode 100644 index 3c347f72b0..0000000000 --- a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.md +++ /dev/null @@ -1,36 +0,0 @@ -# Agent Note: Choose the step route before step preparation - -Status: implemented - -English | [中文](2026-10-12-step-route-chosen-before-preparation.zh.md) - -## Problem - -Tool availability can depend on the route of the request that declares the tools: `web_search` must stay off routes without search credentials, and plan or team state can withhold other tools. Message preparation needs the same route: session references size snapshots by the model's context window, and model selection announces a switch. The loop assembled tools and prompt sections before `agent/pre-step` and decided the route only in `agent/request` after `step/start`, so earlier consumers predicted the route from model-selection state. A listener that replaced the route in `agent/request`, including on a retry, made the assembled prompt and tool catalog describe another model. - -## Decision - -The provider and model are a step fact. After claiming input, the loop dispatches `agent/route` once per proposed step. Its default is the agent options route before this loop logs a request and the logged header route afterwards; `installModelSelection` captures its selection there. The loop passes the resulting `StepRoute` to `system-prompt/prepare` as `AssembleContext.route`, to `agent/pre-step` as `payload.route`, and to tool conditions as `ToolActivationContext.route`. The `{{provider}}` and `{{model}}` prompt variables read it. - -After `agent/pre-step` accepts the step and `step/start` opens it, the loop resolves conditional tools and assembles the prompt once. Each request attempt then runs `agent/request` and `prepareCall()` immediately before admission. `agent/request` may change call controls; a result with another provider or model fails the step. Retries reuse the step's route, tool set, and rendered assembly, and the step-owned tool set closes after the step's tool batch settles. A selection made during a step applies from the next step. - -## Alternatives considered - -- **Bind the route in `agent/request` before `agent/pre-step` and expose `Agent.currentRoute()`.** The prepared call captures the adapter registration and connection settings, so holding it across compaction, hooks, and session reads ignores settings changed meanwhile, and adapters were prepared for steps that `agent/pre-step` rejects. The getter was valid only inside a step and threw elsewhere, and every Agent implementation and test double had to carry it. -- **Record the route inside `agent/pre-step`.** `system-prompt/prepare` runs before that waterfall, and route consumers inside it would depend on listener order. -- **Register the model selection on the Agent without an event.** It adds a single-consumer method to the generic `Agent` interface, moves model-selection effort rules into the loop, and removes the listener path that supplies a route for agents created without one. -- **Keep the route decision in `agent/request` and predict it for earlier consumers.** A prediction diverges whenever a listener other than model selection changes the route. - -## Consequences - -- Tool conditions, prompt variables, reference budgets, and switch notices read the route that the request header records. -- `prepareCall()` stays adjacent to dispatch, so its adapter registration and connection snapshot cover only header logging and streaming. -- A step cannot fail over to another provider on retry; a policy that needs this must run routing, tool resolution, and assembly again for the retried attempt. -- The route cannot depend on `agent/pre-step` outcomes. Plan state commits inside that waterfall, so a plan-specific model would require committing plan selections before routing. -- `agent/pre-step` listeners and direct dispatchers must handle the required `route` field. - -## Related - -- [Provider-routed LLM adapters](2026-07-14-provider-routed-llm-adapters.md) owns provider and model fields in call configuration. -- [Reconstructable requests](2026-07-05-reconstructable-requests.md) owns request reconstruction from the logged header. -- [Prompt variables and tool guidance ownership](2026-07-05-prompt-variables-and-tool-guidance-ownership.md) owns the `{{model}}` variable. diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.zh.md b/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.zh.md deleted file mode 100644 index 204039e9e7..0000000000 --- a/.agents/notes/implemented/architecture/2026-10-12-step-route-chosen-before-preparation.zh.md +++ /dev/null @@ -1,36 +0,0 @@ -# Agent Note: 在步骤准备之前选定步骤路由 - -Status: implemented - -[English](2026-10-12-step-route-chosen-before-preparation.md) | 中文 - -## 问题 - -工具是否可用可能取决于声明这些工具的请求所用的路由:`web_search` 不得出现在没有搜索凭据的路由上,计划或团队状态也可能撤下其他工具。消息准备同样需要这一路由:会话引用按模型的上下文窗口确定快照大小,模型选择会通告模型切换。循环原先在 `agent/pre-step` 之前组装工具与提示词段落,直到 `step/start` 之后才在 `agent/request` 中决定路由,因此更早的消费方只能依据模型选择状态预测路由。若监听器在 `agent/request` 中(包括在重试时)替换路由,已组装的提示词与工具目录就会描述另一个模型。 - -## 决策 - -提供方与模型是步骤级事实。领取输入之后,循环为每个拟议步骤派发一次 `agent/route`。其默认值在本循环记录请求之前取 agent 选项中的路由,之后取已记录请求头中的路由;`installModelSelection` 在这里捕获其选择。循环把得到的 `StepRoute` 作为 `AssembleContext.route` 传给 `system-prompt/prepare`,作为 `payload.route` 传给 `agent/pre-step`,作为 `ToolActivationContext.route` 传给工具条件。提示词变量 `{{provider}}` 与 `{{model}}` 读取该路由。 - -`agent/pre-step` 接纳步骤且 `step/start` 打开步骤之后,循环解析条件工具并组装提示词,各执行一次。之后每次请求尝试都在准入之前紧接着运行 `agent/request` 与 `prepareCall()`。`agent/request` 可以修改调用控制参数;返回其他提供方或模型会使步骤失败。重试复用该步骤的路由、工具集合与已渲染组装结果,步骤拥有的工具集合在该步骤的工具批次结束后关闭。步骤进行中做出的选择从下一个步骤开始生效。 - -## 考虑过的替代方案 - -- **在 `agent/pre-step` 之前通过 `agent/request` 绑定路由,并提供 `Agent.currentRoute()`。** 已准备调用会捕获适配器注册与连接设置,因此在压缩、钩子与会话读取期间一直持有它,会忽略期间修改的设置;被 `agent/pre-step` 拒绝的步骤也会准备适配器。该 getter 只在步骤内有效、在其他时刻抛错,且每个 Agent 实现与测试替身都必须提供它。 -- **在 `agent/pre-step` 内记录路由。** `system-prompt/prepare` 在该 waterfall 之前运行,而 waterfall 内的路由消费方将依赖监听器顺序。 -- **不使用事件,直接在 Agent 上登记模型选择。** 这会给通用 `Agent` 接口增加只有单一消费方的方法,把模型选择的推理强度规则移入循环,并移除为创建时没有路由的 agent 提供路由的监听器途径。 -- **路由决定留在 `agent/request`,为更早的消费方预测路由。** 只要模型选择之外的监听器修改路由,预测就会偏离。 - -## 后果 - -- 工具条件、提示词变量、引用预算与切换通告读取的路由,与请求头记录的路由一致。 -- `prepareCall()` 紧邻分发,因此其适配器注册与连接快照只覆盖请求头记录与流式请求。 -- 步骤无法在重试时切换到其他提供方;需要这种能力的策略必须为重试的尝试重新执行路由选择、工具解析与组装。 -- 路由不能依赖 `agent/pre-step` 的结果。计划状态在该 waterfall 内提交,因此按计划模式选择模型需要先在路由选择之前提交计划选择。 -- `agent/pre-step` 监听器与直接派发方必须处理必填的 `route` 字段。 - -## 相关 - -- [基于提供方路由的 LLM 适配器](2026-07-14-provider-routed-llm-adapters.zh.md)负责调用配置中的提供方与模型字段。 -- [可重建请求](2026-07-05-reconstructable-requests.zh.md)负责依据已记录请求头重建请求。 -- [提示词变量与工具指导归属](2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md)负责 `{{model}}` 变量。 diff --git a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.i18n.yaml b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.i18n.yaml index 9ab1268936..e5b7e4e9d5 100644 --- a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.i18n.yaml @@ -18,8 +18,8 @@ en: d95ece799bc6bab7 zh: 1e19d3b49473a57e /agent-note-pi-extensions-bridge/proposal/serving-the-api: - en: 2cb8b4ce6c74d8b5 - zh: d66d52f966310dc4 + en: bebdef0423773026 + zh: 8ee758d07afee560 /agent-note-pi-extensions-bridge/proposal/built-in-tool-calls-as-pi-sees-them: en: c74e4662ad0a8ee7 zh: 653729b41e983b13 diff --git a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.md b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.md index 4ba7f9685d..03cdf1c2f3 100644 --- a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.md +++ b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.md @@ -42,7 +42,7 @@ Add an experimental bridge that loads unmodified Pi extension sources and serves | `sendUserMessage`, `sendMessage` | `agent.followup()`, `agent.steer()`, `agent.inject()` | | `appendEntry`, `setLabel`, tool `details`, `ctx.sessionManager` | Ignorable Session records and `tool/result` metadata, read back as Pi entries | | `getActiveTools`, `setActiveTools`, `getAllTools` | `ctx.tools.schemas()`; `setActiveTools` applies a scoped `ctx.tools.restrict()` to global tools and adds or removes the bridge's own Agent-scoped registrations, because a restriction does not hide scoped tools | -| `setModel`, `getThinkingLevel`, `setThinkingLevel` | An `agent/route` override for the model and an `agent/request` override for the thinking level | +| `setModel`, `getThinkingLevel`, `setThinkingLevel` | An `agent/model` override for the model and thinking level | | `exec` | `ctx.subprocess`, argv without a shell | | `ctx.ui.select`, `confirm`, `input`, `editor` | `ctx.userQuestions` | | `ctx.ui.notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText` | A Remote stream the Web package renders | diff --git a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.zh.md b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.zh.md index cccc9eec25..49ca8a03f4 100644 --- a/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.zh.md +++ b/.agents/notes/proposed/feature/2026-10-03-pi-extensions-bridge.zh.md @@ -42,7 +42,7 @@ DSH 已为另外两个生态提供桥接:为 Claude Code 与 Codex 编写的 s | `sendUserMessage`、`sendMessage` | `agent.followup()`、`agent.steer()`、`agent.inject()` | | `appendEntry`、`setLabel`、工具 `details`、`ctx.sessionManager` | ignorable Session 记录与 `tool/result` 元数据,读回时还原为 Pi 条目 | | `getActiveTools`、`setActiveTools`、`getAllTools` | `ctx.tools.schemas()`;`setActiveTools` 对全局工具使用作用域内的 `ctx.tools.restrict()`,并增删桥接自己在 Agent 作用域的注册,因为限制不会隐藏作用域内的工具 | -| `setModel`、`getThinkingLevel`、`setThinkingLevel` | `agent/route` 覆盖模型,`agent/request` 覆盖思考等级 | +| `setModel`、`getThinkingLevel`、`setThinkingLevel` | `agent/model` 覆盖模型与思考等级 | | `exec` | `ctx.subprocess`,不经 shell 的 argv | | `ctx.ui.select`、`confirm`、`input`、`editor` | `ctx.userQuestions` | | `ctx.ui.notify`、`setStatus`、`setWidget`、`setTitle`、`setEditorText` | 由 Web 包渲染的 Remote 流 | diff --git a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts index f9e58f262f..f6674047bf 100644 --- a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts +++ b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts @@ -43,7 +43,7 @@ try { } const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, + { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const catalog = decision.kind === 'enter' diff --git a/docs/agent-lifecycle.i18n.yaml b/docs/agent-lifecycle.i18n.yaml index 1d465b17fa..0eaf4b0884 100644 --- a/docs/agent-lifecycle.i18n.yaml +++ b/docs/agent-lifecycle.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 305a6826a598b96d /agent-turn-and-step-lifecycle: - en: ee62762f177bb320 - zh: 271f74cbacc86d98 + en: ebc39fdd0332ae21 + zh: a4fc5664fea5d025 diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 28815a0372..b1d099df0b 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -25,17 +25,17 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/route waterfall chooses the step route - Driver->>Prompt: system-prompt/prepare waterfall on the step route - Driver->>Hooks: agent/pre-step waterfall with the step route + Driver->>Hooks: agent/model waterfall chooses the step provider, model, and effort + Driver->>Prompt: system-prompt/prepare waterfall with the step model selection + Driver->>Hooks: agent/pre-step waterfall with the step model selection Hooks-->>Driver: authoritative reject or enter(messages) alt proposed step rejected, first batch empty, or pre-step failed Driver-->>Driver: claimed batch stays removed, the open turn spends no step else enter proposed step Driver->>Session: step/start - Driver->>Tools: resolve({ agent, route, signal }) once per step + Driver->>Tools: resolve({ agent, modelSelection, signal }) once per step Driver->>Prompt: system-prompt/assemble with the step tool set - Driver->>Hooks: agent/request waterfall on the step route + Driver->>Hooks: agent/request waterfall with the step model selection Driver->>LLM: prepareCall(config, signal) Note over Driver,LLM: cancellation during preparation commits neither system nor users Note over Driver,Session: synchronous admission using the prepared call capability @@ -51,7 +51,7 @@ sequenceDiagram Driver-->>SDK: agent/assistant-stream committed end Driver->>Hooks: agent/request-error waterfall Hooks-->>Driver: return retry action or preserve the original error - Note over Driver,LLM: retry in the open step: request and prepare again on the same route, tool set, and prompt without repeating pre-step or users + Note over Driver,LLM: retry in the open step: request and prepare again with the same model selection, tool set, and prompt without repeating pre-step or users else model request succeeded Driver->>Session: assistant/message Driver-->>SDK: agent/assistant-stream committed end @@ -75,7 +75,7 @@ sequenceDiagram opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/route waterfall + Driver->>Hooks: agent/model waterfall Driver->>Prompt: system-prompt/prepare waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) @@ -88,7 +88,7 @@ sequenceDiagram The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes, and embeds the exact compact timed stream. Empty content stays out of derived history. A failed, retried, cancelled, or stream-error attempt that reaches settlement without a surface message records its stream as `assistant/attempt`. Live `agent/assistant-stream` chunk frames are transient; replay reads either durable settlement, and a hard process loss before settlement leaves no durable attempt stream. -`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call on the step route and reconciles the retained rendered assembly before request derivation, without repeating routing, tool resolution, assembly, pre-step, or user admission. +`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call with the step model selection and reconciles the retained rendered assembly before request derivation, without repeating model selection, tool resolution, assembly, pre-step, or user admission. 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. diff --git a/docs/agent-lifecycle.zh.md b/docs/agent-lifecycle.zh.md index c1e2b942ab..ebb6dbec73 100644 --- a/docs/agent-lifecycle.zh.md +++ b/docs/agent-lifecycle.zh.md @@ -27,17 +27,17 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/route waterfall chooses the step route - Driver->>Prompt: system-prompt/prepare waterfall on the step route - Driver->>Hooks: agent/pre-step waterfall with the step route + Driver->>Hooks: agent/model waterfall chooses the step provider, model, and effort + Driver->>Prompt: system-prompt/prepare waterfall with the step model selection + Driver->>Hooks: agent/pre-step waterfall with the step model selection Hooks-->>Driver: authoritative reject or enter(messages) alt proposed step rejected, first batch empty, or pre-step failed Driver-->>Driver: claimed batch stays removed, the open turn spends no step else enter proposed step Driver->>Session: step/start - Driver->>Tools: resolve({ agent, route, signal }) once per step + Driver->>Tools: resolve({ agent, modelSelection, signal }) once per step Driver->>Prompt: system-prompt/assemble with the step tool set - Driver->>Hooks: agent/request waterfall on the step route + Driver->>Hooks: agent/request waterfall with the step model selection Driver->>LLM: prepareCall(config, signal) Note over Driver,LLM: cancellation during preparation commits neither system nor users Note over Driver,Session: synchronous admission using the prepared call capability @@ -53,7 +53,7 @@ sequenceDiagram Driver-->>SDK: agent/assistant-stream committed end Driver->>Hooks: agent/request-error waterfall Hooks-->>Driver: return retry action or preserve the original error - Note over Driver,LLM: retry in the open step: request and prepare again on the same route, tool set, and prompt without repeating pre-step or users + Note over Driver,LLM: retry in the open step: request and prepare again with the same model selection, tool set, and prompt without repeating pre-step or users else model request succeeded Driver->>Session: assistant/message Driver-->>SDK: agent/assistant-stream committed end @@ -77,7 +77,7 @@ sequenceDiagram opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/route waterfall + Driver->>Hooks: agent/model waterfall Driver->>Prompt: system-prompt/prepare waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) @@ -90,7 +90,7 @@ sequenceDiagram `assistant/message` 事件会记录每次成功的提供方调用,包括返回空内容或以 `max-tokens` 结束的调用,并嵌入精确的紧凑带时间 stream。空内容不会进入派生历史。失败、重试、取消或 stream error attempt 到达 settlement 时,如果没有 surface message,就会把 stream 记录为 `assistant/attempt`。实时 `agent/assistant-stream` chunk frame 是瞬态数据;回放读取任一种持久 settlement,如果进程在 settlement 前硬中断,则不会留下持久 attempt stream。 -`dsh-compaction-basic` 在派生请求之前通过 `agent/pre-step` 处理压力,而 `agent/request-error` 仅用于规范的上下文溢出。任一触发条件满足后,系统都会先执行可选的工具结果剪枝,再选择摘要。恢复发生在仍打开的步骤内,只有剪枝或摘要生成推进 surface replacement generation 时才重试,否则仍以原始请求错误为准。每次重试都会在该步骤的路由上准备调用,并在派生请求之前协调保留的已渲染组装结果,不重复路由选择、工具解析、组装、pre-step 或用户消息准入。 +`dsh-compaction-basic` 在派生请求之前通过 `agent/pre-step` 处理压力,而 `agent/request-error` 仅用于规范的上下文溢出。任一触发条件满足后,系统都会先执行可选的工具结果剪枝,再选择摘要。恢复发生在仍打开的步骤内,只有剪枝或摘要生成推进 surface replacement generation 时才重试,否则仍以原始请求错误为准。每次重试都会按该步骤的模型选择准备调用,并在派生请求之前协调保留的已渲染组装结果,不重复模型选择、工具解析、组装、pre-step 或用户消息准入。 以返回的 `agent/pre-step` 决策为准;通过包装 `next()` 的监听器会保留下游消息与 `startsRequestSeries`,除非有意替换。steering(中途引导)和注入的上下文在后续的认领操作取得其下一步骤批次后,会经过同一 waterfall(瀑布式事件)。 diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index e865273013..e3e6bbdaa4 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -24,8 +24,8 @@ en: e89802f066e4955d zh: ea2fb4bef94e086d /deepseek-harness-architecture/turn-flow: - en: 14dc97ef8cc7458c - zh: c6fbb5885080f8c6 + en: 5001f8affe8d84f0 + zh: de2632709bb4e93a /deepseek-harness-architecture/session-log: en: a2e35c43438fec6d zh: e27bdac8e9feff32 diff --git a/docs/architecture.md b/docs/architecture.md index 5feeb8c3ba..3c120ed3b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -83,7 +83,7 @@ A **step** is one model request plus the tools it calls. A **turn** is zero or m ```text turn/start claim next-step input plus one queued message - agent/route -> step provider/model + agent/model -> step provider/model/effort prepare variables + runtime context -> agent/pre-step; project runtime context at fallback reject | enter(messages, startsRequestSeries?) @@ -105,11 +105,11 @@ turn/start turn/end ``` -`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable session events; the rest are live extension points across three domains. `agent/assistant-stream` publishes process-local start, transient chunk, and end frames. The loop commits the complete compact stream as one message or log-only attempt before a committed end frame, and the Web Session-follow adapter is the live event's only remote consumer. `agent/route`, `agent/pre-step`, `agent/request`, `llm/stream`, and the three `tools/*` events are waterfalls, whose listeners must call `next()` to delegate; `agent/turn-stopping` is serial and has no `next()`. +`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable session events; the rest are live extension points across three domains. `agent/assistant-stream` publishes process-local start, transient chunk, and end frames. The loop commits the complete compact stream as one message or log-only attempt before a committed end frame, and the Web Session-follow adapter is the live event's only remote consumer. `agent/model`, `agent/pre-step`, `agent/request`, `llm/stream`, and the three `tools/*` events are waterfalls, whose listeners must call `next()` to delegate; `agent/turn-stopping` is serial and has no `next()`. One inbox feeds the driver; injected context waits for a waking message. AgentLoop’s durable `inbox` projection exposes pending input without live Agents. -`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/route` fixes the step's provider and model before `agent/pre-step`; accepted steps resolve tools and assemble once. Each attempt's `agent/request` may change only call controls, and `prepareCall()` binds the adapter before prompt and user admission; cancellation in either commits neither. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming; retries reuse the route, tools, and assembly. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). +`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/model` fixes the step's provider, model, and effort before `agent/pre-step`; accepted steps resolve tools and assemble once. Each attempt's `agent/request` may change only sampling, and `prepareCall()` binds the adapter before prompt and user admission; cancellation in either commits neither. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming; retries reuse the selection, tools, and assembly. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). The loop sends immutable requests with live cancellation and reuses freeze evidence for frozen identities; [agent-loop](../packages/core/agent-loop/README.md) owns construction and cancellation causes. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index ace6edf25b..1d8e3718b9 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -87,7 +87,7 @@ AgentLoop 在启动已排队工作前等待串行 `agent/created`,初始化失 ```text turn/start claim next-step input plus one queued message - agent/route -> step provider/model + agent/model -> step provider/model/effort prepare variables + runtime context -> agent/pre-step; project runtime context at fallback reject | enter(messages, startsRequestSeries?) @@ -109,11 +109,11 @@ turn/start turn/end ``` -`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久会话事件;其余是分属三个事件域的实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态 chunk 与 end frame。loop 会在 committed end frame 前把完整紧凑 stream 提交为一个 message 或仅日志 attempt;Web Session-follow adapter 是该 live event 唯一的远程消费方。`agent/route`、`agent/pre-step`、`agent/request`、`llm/stream` 和三个 `tools/*` 事件是 waterfall(瀑布式事件),其监听器必须调用 `next()` 才能委托下去;`agent/turn-stopping` 是 serial 事件,没有 `next()`。 +`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久会话事件;其余是分属三个事件域的实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态 chunk 与 end frame。loop 会在 committed end frame 前把完整紧凑 stream 提交为一个 message 或仅日志 attempt;Web Session-follow adapter 是该 live event 唯一的远程消费方。`agent/model`、`agent/pre-step`、`agent/request`、`llm/stream` 和三个 `tools/*` 事件是 waterfall(瀑布式事件),其监听器必须调用 `next()` 才能委托下去;`agent/turn-stopping` 是 serial 事件,没有 `next()`。 输入通过同一个 inbox 到达驱动器;注入的上下文等待一条唤醒消息。AgentLoop 的持久 `inbox` 投影使待处理输入在没有活跃 Agent 时仍可读取。 -`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。`agent/route` 在 `agent/pre-step` 之前固定该步骤的提供方与模型;被接纳的步骤随后解析工具并组装一次。每次尝试的 `agent/request` 只能修改调用控制参数,`prepareCall()` 在提示词与用户消息准入前绑定适配器;在任一阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求;重试复用路由、工具与组装结果。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 +`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。`agent/model` 在 `agent/pre-step` 之前固定该步骤的提供方、模型与推理强度;被接纳的步骤随后解析工具并组装一次。每次尝试的 `agent/request` 只能修改采样控制参数,`prepareCall()` 在提示词与用户消息准入前绑定适配器;在任一阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求;重试复用模型选择、工具与组装结果。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 循环发送不可变请求,同时保持取消有效,仅对完全冻结的对象复用冻结证据;[agent-loop](../packages/core/agent-loop/README.zh.md) 负责请求构建与取消原因。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index a7736702b5..ac302aefdd 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -10,19 +10,19 @@ 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:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:271`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:424`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:298`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:331`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:368`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:384`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/route` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:347`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | -| `agent/status` | `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), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:412`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:273`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:282`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:319`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../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/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:352`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:373`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `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), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../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 e5dc43c2b2..cb221a48b9 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -12,19 +12,19 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:271`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:424`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:298`](../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/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:331`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:368`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:384`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/route` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:347`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | -| `agent/status` | `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), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:412`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:273`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:282`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:319`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../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/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:352`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:373`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `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), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 3111071a28..35c730cee9 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -12,14 +12,14 @@ en: ab09a38b4e1f0883 zh: 81e2d14c4036ab6c /core/the-agent-handle: - en: 100e13484382eb7a - zh: 6481f8d4f84fc93a + en: fbcbf559b0362d11 + zh: e2cc3f4e28f23687 /core/initiating-agent: en: 6c8c47ac78de2dde zh: c9d527a25a85d1d9 /core/interception-decisions: - en: f4fdc520107dd17b - zh: a9b2f55e50b6279f + en: f50b0e1933657f39 + zh: 961a69f1247951df /core/sessions: en: 9a38f693a00fa80d zh: d0f66664ac85ae64 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index c045e95349..34fc5d394d 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -61,7 +61,7 @@ Source: [`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types interface Agent { /** Session-backed Agent identity. */ readonly id: SessionId - /** Creation-time request options; `agent/route` may choose another provider and model for each step. */ + /** Creation-time request options; `agent/model` may choose another provider, model, and effort for each step. */ readonly options: AgentOptions /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session @@ -206,17 +206,19 @@ interface AgentOptions { } ``` -Each step requires `provider` and `model` after `agent/route`, which may supply or replace the options pair. An explicit `reasoningEffort` seeds the first request on that route; exact-model resolution validates it, while omission allows the adapter default to materialize. When present, `maxTokens` must be a positive safe integer and caps every conversation-model request; omission allows the exact-model adapter default to materialize before the request header, or otherwise leaves provider behavior unchanged. An agent-scoped `deployment:persona-prefix` prompt section may shadow the global default persona. +Each step requires `provider` and `model` after `agent/model`, which may supply or replace the options' provider, model, and effort. An explicit `reasoningEffort` seeds the first step's selection for that model; exact-model resolution validates it, while omission allows the adapter default to materialize. When present, `maxTokens` must be a positive safe integer and caps every conversation-model request; omission allows the exact-model adapter default to materialize before the request header, or otherwise leaves provider behavior unchanged. An agent-scoped `deployment:persona-prefix` prompt section may shadow the global default persona. -The step keeps the chosen route for prompt preparation, `agent/pre-step`, tool conditions, and every request attempt; `agent/request` may change only call controls: +The step keeps its model selection for prompt preparation, `agent/pre-step`, tool conditions, and every request attempt; `agent/request` may change only sampling controls such as `maxTokens`, `temperature`, and `stop`: ```ts type-equiv -/** Provider and model that `agent/route` chose for one step and every request attempt in it. */ -interface StepRoute { +/** Complete provider, model, and optional reasoning effort; `agent/model` fixes one for each step. */ +interface ModelSelection { /** Registered provider route. */ - readonly provider: string - /** Model id interpreted by the provider adapter. */ - readonly model: string + provider: string + /** Provider-owned model id. */ + model: string + /** Adapter-owned reasoning effort, or provider/default behavior when absent. */ + reasoningEffort?: ReasoningEffortId } ``` @@ -323,7 +325,7 @@ Pre-step decisions use the same identified `UserMessage` type as durable user-ro Source: [`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts) -`agent/pre-step` receives one payload carrying the exclusive claimed batch (`messages`), the proposed step's coordinates (`turn`, `step`), its `route`, and the current turn's cancellation `signal`. The initial proposal runs inside an open turn before any step; a tool continuation may submit an empty claimed batch between steps: +`agent/pre-step` receives one payload carrying the exclusive claimed batch (`messages`), the proposed step's coordinates (`turn`, `step`), its `modelSelection`, and the current turn's cancellation `signal`. The initial proposal runs inside an open turn before any step; a tool continuation may submit an empty claimed batch between steps: It returns a `PreStepDecision`. Reject opens no step. Enter supplies the complete message batch appended after `step/start`; claimed messages omitted by the final decision remain removed, while input inserted after the claim stays pending: @@ -937,6 +939,38 @@ Types: [Scoped](scope.md) · [UserMessage](session.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + + +#### `agent/model` — waterfall + +Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step. + +```ts cordis-catalog +/** + * Choose the provider, model, and reasoning effort for one proposed step. + * `await next()` yields the selection the machine would use: agent options + * before this loop logs a request, the logged header afterwards, with an + * effort only when one was chosen for that exact model. Return a + * replacement to switch; an effort belongs to its model, so a replacement + * that changes the model names that model's effort or omits it for the + * provider default. The loop runs this once per proposed step, before + * context preparation and `agent/pre-step`. Prompt preparation, tool + * conditions, and every request attempt in the step use the result, so a + * later choice applies from the next step. Cancellation here opens no step. + * @param payload.agent - the agent proposing the step. + * @param payload.turn - the turn that will own the step. + * @param payload.step - the step proposed by the loop. + * @param payload.signal - the current turn's explicit abort signal. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode waterfall + */ +'agent/model'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise +``` + +Types: [Scoped](scope.md) + +Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + #### `agent/pre-step` — waterfall @@ -951,12 +985,12 @@ Reject a proposed step or replace the messages that enter it. Calling `next()` p * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. - * @param payload.route - the provider and model `agent/route` chose for this step. + * @param payload.modelSelection - the provider, model, and effort `agent/model` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; route: StepRoute; signal: AbortSignal }, next: () => Promise): Promise +'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; modelSelection: ModelSelection; signal: AbortSignal }, next: () => Promise): Promise ``` Types: [Scoped](scope.md) · [UserMessage](session.md) @@ -967,16 +1001,16 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/request` — waterfall -Replace the frozen call configuration of one request attempt. `await next()` yields the config the machine would use on the step's `agent/route` result: agent options on the first request, the logged header afterwards, and no effort recorded for another model. Return a replacement to change call controls such as reasoning effort; returning another provider or model fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. +Replace the frozen call configuration of one request attempt. `await next()` yields the step's `agent/model` selection with the machine's other call controls: agent options on the first request, the logged header afterwards. Return a replacement to change sampling controls such as `maxTokens`, `temperature`, or `stop`; returning another provider, model, or reasoning effort fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. ```ts cordis-catalog /** * Replace the frozen call configuration of one request attempt. `await - * next()` yields the config the machine would use on the step's - * `agent/route` result: agent options on the first request, the logged - * header afterwards, and no effort recorded for another model. Return a - * replacement to change call controls such as reasoning effort; returning - * another provider or model fails the step. On step admission, this runs + * next()` yields the step's `agent/model` selection with the machine's + * other call controls: agent options on the first request, the logged + * header afterwards. Return a replacement to change sampling controls such + * as `maxTokens`, `temperature`, or `stop`; returning another provider, + * model, or reasoning effort fails the step. On step admission, this runs * after prompt assembly and `step/start`, before the system prompt and * accepted user batch are committed, and again for each retry. * Cancellation here or during subsequent `prepareCall()` resolution @@ -1026,35 +1060,6 @@ Types: [LlmFailure](llm-streaming.md) · [ResolvedRetryPolicy](llm-streaming.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - - -#### `agent/route` — waterfall - -Choose the provider and model for one proposed step. `await next()` yields the route the machine would use (agent options before this loop logs a request, the logged header afterwards); return a replacement to switch. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step. - -```ts cordis-catalog -/** - * Choose the provider and model for one proposed step. `await next()` - * yields the route the machine would use (agent options before this loop - * logs a request, the logged header afterwards); return a replacement to - * switch. The loop runs this once per proposed step, before context - * preparation and `agent/pre-step`. Prompt preparation, tool conditions, - * and every request attempt in the step use the result, so a later choice - * applies from the next step. Cancellation here opens no step. - * @param payload.agent - the agent proposing the step. - * @param payload.turn - the turn that will own the step. - * @param payload.step - the step proposed by the loop. - * @param payload.signal - the current turn's explicit abort signal. - * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. - * @mode waterfall - */ -'agent/route'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise -``` - -Types: [Scoped](scope.md) - -Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - #### `agent/status` — emit diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 96d65b5140..59c3b51e19 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -65,7 +65,7 @@ interface AgentHandle { interface Agent { /** Session-backed Agent identity. */ readonly id: SessionId - /** Creation-time request options; `agent/route` may choose another provider and model for each step. */ + /** Creation-time request options; `agent/model` may choose another provider, model, and effort for each step. */ readonly options: AgentOptions /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session @@ -210,17 +210,19 @@ interface AgentOptions { } ``` -每个步骤在 `agent/route` 之后都要求 `provider` 与 `model` 都存在;该 waterfall 可以补上或替换 options 中的这一对值。显式 `reasoningEffort` 会为该路由的首次请求提供初始值;确切模型解析会校验该值,省略时则允许填入适配器默认值。提供 `maxTokens` 时,它必须是正安全整数,并限制每次对话模型请求的输出;省略时,系统会在写入请求 header 前填入确切模型的适配器默认值,否则提供方行为保持不变。agent 作用域的 `deployment:persona-prefix` 提示词段落可以遮蔽全局默认 persona。 +每个步骤在 `agent/model` 之后都要求 `provider` 与 `model` 都存在;该 waterfall 可以补上或替换 options 中的提供方、模型与推理强度。显式 `reasoningEffort` 会为该模型的首个步骤选择提供初始值;确切模型解析会校验该值,省略时则允许填入适配器默认值。提供 `maxTokens` 时,它必须是正安全整数,并限制每次对话模型请求的输出;省略时,系统会在写入请求 header 前填入确切模型的适配器默认值,否则提供方行为保持不变。agent 作用域的 `deployment:persona-prefix` 提示词段落可以遮蔽全局默认 persona。 -步骤在提示词准备、`agent/pre-step`、工具条件以及每次请求尝试中都沿用所选路由;`agent/request` 只能修改调用控制参数: +步骤在提示词准备、`agent/pre-step`、工具条件以及每次请求尝试中都沿用其模型选择;`agent/request` 只能修改 `maxTokens`、`temperature`、`stop` 等采样控制参数: ```ts type-equiv -/** Provider and model that `agent/route` chose for one step and every request attempt in it. */ -interface StepRoute { +/** Complete provider, model, and optional reasoning effort; `agent/model` fixes one for each step. */ +interface ModelSelection { /** Registered provider route. */ - readonly provider: string - /** Model id interpreted by the provider adapter. */ - readonly model: string + provider: string + /** Provider-owned model id. */ + model: string + /** Adapter-owned reasoning effort, or provider/default behavior when absent. */ + reasoningEffort?: ReasoningEffortId } ``` @@ -331,7 +333,7 @@ pre-step 决策使用与持久 user-role 输入相同、带标识的 `UserMessag 源码:[`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts) -`agent/pre-step` 接收一个 payload,携带独占的已领取批次(`messages`)、拟进入步骤的坐标(`turn`、`step`)、其路由 `route` 与当前轮次的取消 `signal`。首次提案在已打开的轮次内、任何步骤开始前运行;工具 continuation 可以在步骤之间提交空的已领取批次: +`agent/pre-step` 接收一个 payload,携带独占的已领取批次(`messages`)、拟进入步骤的坐标(`turn`、`step`)、其模型选择 `modelSelection` 与当前轮次的取消 `signal`。首次提案在已打开的轮次内、任何步骤开始前运行;工具 continuation 可以在步骤之间提交空的已领取批次: 它返回 `PreStepDecision`。reject 不会打开步骤。enter 提供在 `step/start` 后追加的完整消息批次;最终决策省略的已领取消息保持已删除,而领取后插入的输入仍留待后续处理: @@ -949,6 +951,38 @@ Types: [Scoped](scope.zh.md) · [UserMessage](session.zh.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + + +#### `agent/model` — waterfall + +Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step. + +```ts cordis-catalog +/** + * Choose the provider, model, and reasoning effort for one proposed step. + * `await next()` yields the selection the machine would use: agent options + * before this loop logs a request, the logged header afterwards, with an + * effort only when one was chosen for that exact model. Return a + * replacement to switch; an effort belongs to its model, so a replacement + * that changes the model names that model's effort or omits it for the + * provider default. The loop runs this once per proposed step, before + * context preparation and `agent/pre-step`. Prompt preparation, tool + * conditions, and every request attempt in the step use the result, so a + * later choice applies from the next step. Cancellation here opens no step. + * @param payload.agent - the agent proposing the step. + * @param payload.turn - the turn that will own the step. + * @param payload.step - the step proposed by the loop. + * @param payload.signal - the current turn's explicit abort signal. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode waterfall + */ +'agent/model'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise +``` + +Types: [Scoped](scope.zh.md) + +Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + #### `agent/pre-step` — waterfall @@ -963,12 +997,12 @@ Reject a proposed step or replace the messages that enter it. Calling `next()` p * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. - * @param payload.route - the provider and model `agent/route` chose for this step. + * @param payload.modelSelection - the provider, model, and effort `agent/model` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; route: StepRoute; signal: AbortSignal }, next: () => Promise): Promise +'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; modelSelection: ModelSelection; signal: AbortSignal }, next: () => Promise): Promise ``` Types: [Scoped](scope.zh.md) · [UserMessage](session.zh.md) @@ -979,16 +1013,16 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/request` — waterfall -Replace the frozen call configuration of one request attempt. `await next()` yields the config the machine would use on the step's `agent/route` result: agent options on the first request, the logged header afterwards, and no effort recorded for another model. Return a replacement to change call controls such as reasoning effort; returning another provider or model fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. +Replace the frozen call configuration of one request attempt. `await next()` yields the step's `agent/model` selection with the machine's other call controls: agent options on the first request, the logged header afterwards. Return a replacement to change sampling controls such as `maxTokens`, `temperature`, or `stop`; returning another provider, model, or reasoning effort fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages. ```ts cordis-catalog /** * Replace the frozen call configuration of one request attempt. `await - * next()` yields the config the machine would use on the step's - * `agent/route` result: agent options on the first request, the logged - * header afterwards, and no effort recorded for another model. Return a - * replacement to change call controls such as reasoning effort; returning - * another provider or model fails the step. On step admission, this runs + * next()` yields the step's `agent/model` selection with the machine's + * other call controls: agent options on the first request, the logged + * header afterwards. Return a replacement to change sampling controls such + * as `maxTokens`, `temperature`, or `stop`; returning another provider, + * model, or reasoning effort fails the step. On step admission, this runs * after prompt assembly and `step/start`, before the system prompt and * accepted user batch are committed, and again for each retry. * Cancellation here or during subsequent `prepareCall()` resolution @@ -1038,35 +1072,6 @@ Types: [LlmFailure](llm-streaming.zh.md) · [ResolvedRetryPolicy](llm-streaming. Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - - -#### `agent/route` — waterfall - -Choose the provider and model for one proposed step. `await next()` yields the route the machine would use (agent options before this loop logs a request, the logged header afterwards); return a replacement to switch. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step. - -```ts cordis-catalog -/** - * Choose the provider and model for one proposed step. `await next()` - * yields the route the machine would use (agent options before this loop - * logs a request, the logged header afterwards); return a replacement to - * switch. The loop runs this once per proposed step, before context - * preparation and `agent/pre-step`. Prompt preparation, tool conditions, - * and every request attempt in the step use the result, so a later choice - * applies from the next step. Cancellation here opens no step. - * @param payload.agent - the agent proposing the step. - * @param payload.turn - the turn that will own the step. - * @param payload.step - the step proposed by the loop. - * @param payload.signal - the current turn's explicit abort signal. - * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. - * @mode waterfall - */ -'agent/route'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise -``` - -Types: [Scoped](scope.zh.md) - -Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - #### `agent/status` — emit diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index 433c358122..7cf1e6afb7 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -39,8 +39,8 @@ en: 824d18f76f990711 zh: 8a2895513652e528 /llm-streaming/the-model-request/the-request-envelope-llmcallconfig-and-the-logged-header: - en: 2c0198b61bf68192 - zh: d1380ba0acea3ee2 + en: d3b170f622848cd3 + zh: 2c4e998f499efd99 /llm-streaming/official-deepseek-request-extensions: en: 42bc50394b070e96 zh: 007caa743ec3c790 diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 8844d5ba3b..237b8edd1f 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -738,7 +738,7 @@ interface LlmDiscoveredModel { The loop builds each request from logged state. `EpochHeader` records call config, marks the fields supplied by adapter defaults, and records the authoritative returned tool order (configured by `toolOrder`, or lexicographic when unset) through full `request/header` snapshots. The rendered prompt is derived history — the `system/message` at surface node 0, plus any later system node an `in-history` route appended — so the header and the derived history together make the request reconstructable from the session log. See [session.md](session.md#the-request-header-event-requestheader) and the [reconstructability Agent Note](../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md). -`agent/request` receives a frozen call-config seed and may return a replacement to change reasoning effort or sampling; provider and model come from `agent/route` and stay fixed for the step. Before the waterfall, the loop removes values marked as adapter defaults so exact-model preparation materializes the selected route's current values; unmarked explicit settings remain in the proposal. After the waterfall, preparation rejects unsupported explicit effort ids without clamping and logs the effective config plus the fields supplied by adapter defaults under the turn signal. On step admission, this waterfall and preparation run after assembly and `step/start` but before the system prompt and accepted user batch are committed; cancellation during either commits neither. The prepared capability governs prompt reconciliation, and the call keeps one adapter registration through dispatch. Requests reaching `llm/stream` are deep-frozen, so mutation throws, and carry a process-local loop identity so observers do not confuse separately logged frozen auxiliary calls with conversation requests. +`agent/request` receives a frozen call-config seed and may return a replacement to change sampling; provider, model, and reasoning effort come from `agent/model` and stay fixed for the step. Before both waterfalls, the loop removes values marked as adapter defaults so exact-model preparation materializes the selected route's current values; unmarked explicit settings remain in the proposal. After `agent/request`, preparation rejects unsupported explicit effort ids without clamping and logs the effective config plus the fields supplied by adapter defaults under the turn signal. On step admission, this waterfall and preparation run after assembly and `step/start` but before the system prompt and accepted user batch are committed; cancellation during either commits neither. The prepared capability governs prompt reconciliation, and the call keeps one adapter registration through dispatch. Requests reaching `llm/stream` are deep-frozen, so mutation throws, and carry a process-local loop identity so observers do not confuse separately logged frozen auxiliary calls with conversation requests. On the wire, a loop-built request is the derived history alone: the rendered prompt travels as the leading `system`-role message (surface node 0, a `system/message` event) and, when the prepared call declares `systemPromptUpdate: 'in-history'`, a non-empty changed prompt may follow the cached history as a later `system`-role message that the model reads as the effective prompt; the request's `system` field is unset — `GenerateOptions.system` serves direct one-shot callers such as title providers. An empty rendering leaves no system messages in derived history, even when earlier requests retained several prompt versions. The logged request ends with the newest `user/message` on a turn's first step and the previous step's tool results on later steps. diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 500ca3f70e..65b02618b5 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -744,7 +744,7 @@ interface LlmDiscoveredModel { 循环从已记录状态构建每个请求。`EpochHeader` 记录调用配置,标记由适配器默认值提供的字段,并通过完整的 `request/header` 快照记录权威返回工具顺序(由 `toolOrder` 配置;未配置时按字典序)。渲染后的提示词是派生历史——surface 第 0 号节点上的 `system/message`,加上 `in-history` 路由追加的任何后续系统节点——因此请求头与派生历史共同使请求可由会话日志重建。见 [session.md](session.zh.md#the-request-header-event-requestheader) 与[可重建性 Agent Note](../../.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.zh.md)。 -`agent/request` 接收冻结的调用配置种子,并可返回替代值以修改推理强度或采样参数;提供方与模型来自 `agent/route`,在整个步骤内保持不变。waterfall(瀑布式事件)开始前,循环会移除标记为适配器默认值的值,使确切模型准备过程填入所选路由的当前值;未带标记的显式设置仍保留在提议中。waterfall 结束后,准备过程会在轮次信号控制下拒绝显式指定但不受支持的推理强度 ID(不自动调整),并记录生效配置以及由适配器默认值提供的字段。步骤准入时,该 waterfall 与准备过程在组装和 `step/start` 之后、系统提示词与已接纳用户批次提交之前运行;在任一阶段取消都不会提交这两者。已准备调用的能力决定提示词协调,调用直至分派完成始终持有同一项适配器注册。到达 `llm/stream` 的请求会被深度冻结,因此变更会抛异常;请求还携带进程本地循环标识,使观察者不会把单独记录的冻结辅助调用误认成对话请求。 +`agent/request` 接收冻结的调用配置种子,并可返回替代值以修改采样参数;提供方、模型与推理强度来自 `agent/model`,在整个步骤内保持不变。这两个 waterfall(瀑布式事件)开始前,循环会移除标记为适配器默认值的值,使确切模型准备过程填入所选路由的当前值;未带标记的显式设置仍保留在提议中。`agent/request` 结束后,准备过程会在轮次信号控制下拒绝显式指定但不受支持的推理强度 ID(不自动调整),并记录生效配置以及由适配器默认值提供的字段。步骤准入时,该 waterfall 与准备过程在组装和 `step/start` 之后、系统提示词与已接纳用户批次提交之前运行;在任一阶段取消都不会提交这两者。已准备调用的能力决定提示词协调,调用直至分派完成始终持有同一项适配器注册。到达 `llm/stream` 的请求会被深度冻结,因此变更会抛异常;请求还携带进程本地循环标识,使观察者不会把单独记录的冻结辅助调用误认成对话请求。 在协议中,循环构建的请求只有派生历史:渲染后的提示词作为开头的 `system` 角色消息(surface 第 0 号节点,即一个 `system/message` 事件)传输,并且当已准备调用声明 `systemPromptUpdate: 'in-history'` 时,变化后的非空提示词可以作为后续的 `system` 角色消息跟在已缓存历史之后,由模型读作有效提示词;请求的 `system` 字段不设置——`GenerateOptions.system` 服务于标题提供方等直接单次调用方。空渲染文本使派生历史不包含任何系统消息,即使先前请求保留了多个提示词版本。已记录的请求会以最新的 `user/message`(轮次首步)或上一步的工具结果(后续步骤)结尾。 diff --git a/docs/subsystems/session-reference.md b/docs/subsystems/session-reference.md index 6a41f8dd3b..517b395729 100644 --- a/docs/subsystems/session-reference.md +++ b/docs/subsystems/session-reference.md @@ -205,7 +205,7 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the step route, or agent options for direct preparation. + * Automatic budgets use the step's model selection, or agent options for direct preparation. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -213,13 +213,13 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. - * @param route - provider and model of the step admitting the message; omitted for direct preparation. + * @param modelSelection - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ -async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, route?: StepRoute, ): Promise +async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, modelSelection?: ModelSelection, ): Promise ``` -Types: [Agent](core.md) · [ContentBlock](llm-streaming.md) · [StepRoute](core.md) +Types: [Agent](core.md) · [ContentBlock](llm-streaming.md) · [ModelSelection](core.md) Source: [`packages/context/session-reference/src/index.ts`](../../packages/context/session-reference/src/index.ts) diff --git a/docs/subsystems/session-reference.zh.md b/docs/subsystems/session-reference.zh.md index 79fbef73ee..f76a9a7371 100644 --- a/docs/subsystems/session-reference.zh.md +++ b/docs/subsystems/session-reference.zh.md @@ -205,7 +205,7 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the step route, or agent options for direct preparation. + * Automatic budgets use the step's model selection, or agent options for direct preparation. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -213,13 +213,13 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. - * @param route - provider and model of the step admitting the message; omitted for direct preparation. + * @param modelSelection - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ -async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, route?: StepRoute, ): Promise +async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, modelSelection?: ModelSelection, ): Promise ``` -Types: [Agent](core.zh.md) · [ContentBlock](llm-streaming.zh.md) · [StepRoute](core.zh.md) +Types: [Agent](core.zh.md) · [ContentBlock](llm-streaming.zh.md) · [ModelSelection](core.zh.md) Source: [`packages/context/session-reference/src/index.ts`](../../packages/context/session-reference/src/index.ts) diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index 25eba3d259..5350cc8f7d 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -569,7 +569,7 @@ get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - preparing agent, step route, and cancellation. + * @param context - preparing agent, step model selection, and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 999f3f4875..5d33028bde 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -569,7 +569,7 @@ get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - preparing agent, step route, and cancellation. + * @param context - preparing agent, step model selection, and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml index de2bf1983b..d97d05ce94 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md /: - en: a6fa0b92ad5adce4 - zh: 743795b5e3985faf -/update-step-routing-conditional-tools-and-prompt-hooks: - en: 7f578f5ad4a1406b - zh: 9b5984f46d7ae7b4 -/update-step-routing-conditional-tools-and-prompt-hooks/change: - en: a914aff13f6391ff - zh: b8a9dfaeaaa7d76f -/update-step-routing-conditional-tools-and-prompt-hooks/migration: - en: bdb131c08b81d7ec - zh: e76b53840dc3bd8a + en: b56fc42e23dfd970 + zh: cbe86c0b3af8eee7 +/update-step-model-selection-conditional-tools-and-prompt-hooks: + en: 81e0b8c4355e86a3 + zh: 2563f89226c11cfb +/update-step-model-selection-conditional-tools-and-prompt-hooks/change: + en: b2a7c15a9971ce4a + zh: ef217bd430dfb48f +/update-step-model-selection-conditional-tools-and-prompt-hooks/migration: + en: f818cf83d987ae4b + zh: 7d4f431cdb10dd91 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md index 3cce69c4aa..cff2857104 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md @@ -1,15 +1,15 @@ --- kind: upgrade-guide -description: "Step routing moves from `agent/request` to `agent/route`, and custom tool and prompt plugins must use step-owned tool admission." +description: "Step provider, model, and reasoning-effort selection moves from `agent/request` to `agent/model`, and custom tool and prompt plugins must use step-owned tool admission." --- -# Update step routing, conditional tools, and prompt hooks +# Update step model selection, conditional tools, and prompt hooks English | [中文](guide.zh.md) ## Change -`agent/route` chooses each step's provider and model before `system-prompt/prepare` and `agent/pre-step`. Prompt preparation, `agent/pre-step` through its new `route` payload field, tool conditions, and every request attempt in the step use that route. `agent/request` still runs for each attempt after prompt assembly and `step/start`, but it may change only call controls such as `reasoningEffort`; returning another provider or model fails the step. An agent without an options route must receive one from `agent/route`. Plugins that replaced the provider or model in `agent/request`, including on a retry, are affected. +`agent/model` returns each step's `ModelSelection` (provider, model, and optional reasoning effort) before `system-prompt/prepare` and `agent/pre-step`. Prompt preparation, `agent/pre-step` through its new `modelSelection` payload field, tool conditions, and every request attempt in the step use that selection. `agent/request` still runs for each attempt after prompt assembly and `step/start`, but it may change only sampling controls such as `maxTokens`, `temperature`, and `stop`; returning another provider, model, or reasoning effort fails the step. An agent without options provider and model must receive them from `agent/model`. Plugins that replaced the provider, model, or effort in `agent/request`, including on a retry, are affected. `installModelSelection` applies its selection through `agent/model`, and `ModelSelectionRef` no longer has `assembled`. Runtime context preparation uses `system-prompt/prepare`; `system-prompt/assemble` receives presentation fields without a tool array. Tool declarations remain owned by registered providers. Conditional tools require a resolved step set for execution, including nested PTC calls. Replacing a registration does not authorize an outstanding call to run the replacement. @@ -17,8 +17,8 @@ Runtime context preparation uses `system-prompt/prepare`; `system-prompt/assembl ## Migration -1. Move provider and model replacement from `agent/request` listeners to `agent/route` listeners that return `{ provider, model }`; keep only control changes in `agent/request`. Read the route from `payload.route` in `agent/pre-step` and from `AssembleContext.route` in prompt providers. -2. Declare tool conditions with `ctx.tools.register(definition, { when })`; the condition receives `{ agent, route, signal }`. +1. Move provider, model, and reasoning-effort replacement from `agent/request` listeners to `agent/model` listeners that return `{ provider, model, reasoningEffort? }`; an omitted effort uses the model's provider default. Keep only sampling changes in `agent/request`. Read the selection from `payload.modelSelection` in `agent/pre-step` and from `AssembleContext.modelSelection` in prompt providers. +2. Declare tool conditions with `ctx.tools.register(definition, { when })`; the condition receives `{ agent, modelSelection, signal }`. 3. Move runtime-context preparation listeners to `system-prompt/prepare`. Keep presentation changes in `system-prompt/assemble` and stop replacing its tool list. -4. For programmatic conditional calls, resolve `{ agent, route, signal }` through `ctx.tools.resolve()`, pass the resulting `toolSet` to assembly and execution, and dispose it after the batch settles. AgentLoop does this once per step for model calls. Pass `context.toolSet` when tool guidance queries `ctx.tools.get()` or `schemas()`. -5. Add `route` to `agent/pre-step` payloads that tests dispatch directly. Verify that inactive tools are absent from declarations, that a historical name returns `UNKNOWN_TOOL` without reaching the implementation, and that an `agent/request` listener changing the model ends the turn with an error naming `agent/route`. +4. For programmatic conditional calls, resolve `{ agent, modelSelection, signal }` through `ctx.tools.resolve()`, pass the resulting `toolSet` to assembly and execution, and dispose it after the batch settles. AgentLoop does this once per step for model calls. Pass `context.toolSet` when tool guidance queries `ctx.tools.get()` or `schemas()`. +5. Remove `assembled` from `ModelSelectionRef` objects, and add `modelSelection` to `agent/pre-step` payloads that tests dispatch directly. Verify that inactive tools are absent from declarations, that a historical name returns `UNKNOWN_TOOL` without reaching the implementation, and that an `agent/request` listener changing the model or effort ends the turn with an error naming `agent/model`. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md index 20db035c69..01fa5cfec8 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md @@ -1,15 +1,15 @@ --- kind: upgrade-guide -description: "步骤路由选择从 `agent/request` 移到 `agent/route`,自定义工具和提示词插件必须使用步骤拥有的工具准入集合。" +description: "步骤的提供方、模型与推理强度选择从 `agent/request` 移到 `agent/model`,自定义工具和提示词插件必须使用步骤拥有的工具准入集合。" --- -# 更新步骤路由、条件工具与提示词钩子 +# 更新步骤模型选择、条件工具与提示词钩子 [English](guide.md) | 中文 ## 变更 -`agent/route` 在 `system-prompt/prepare` 与 `agent/pre-step` 之前选定每个步骤的提供方与模型。提示词准备、`agent/pre-step`(通过新增的 payload 字段 `route`)、工具条件以及该步骤的每次请求尝试都使用这一路由。`agent/request` 仍在提示词组装与 `step/start` 之后为每次尝试运行,但只能修改 `reasoningEffort` 等调用控制参数;返回其他提供方或模型会使步骤失败。options 中没有路由的 agent 必须由 `agent/route` 提供路由。在 `agent/request` 中替换提供方或模型的插件(包括在重试时替换的插件)会受到影响。 +`agent/model` 在 `system-prompt/prepare` 与 `agent/pre-step` 之前返回每个步骤的 `ModelSelection`(提供方、模型与可选的推理强度)。提示词准备、`agent/pre-step`(通过新增的 payload 字段 `modelSelection`)、工具条件以及该步骤的每次请求尝试都使用这一选择。`agent/request` 仍在提示词组装与 `step/start` 之后为每次尝试运行,但只能修改 `maxTokens`、`temperature`、`stop` 等采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。options 中没有提供方与模型的 agent 必须由 `agent/model` 提供。在 `agent/request` 中替换提供方、模型或推理强度的插件(包括在重试时替换的插件)会受到影响。`installModelSelection` 通过 `agent/model` 应用其选择,`ModelSelectionRef` 不再包含 `assembled`。 运行时上下文准备使用 `system-prompt/prepare`;`system-prompt/assemble` 接收不含工具数组的展示字段。工具声明仍由已注册提供方持有。条件工具执行需要已解析的步骤集合,包括嵌套 PTC 调用。替换注册不会授权尚未执行的旧调用使用新实现。 @@ -17,8 +17,8 @@ description: "步骤路由选择从 `agent/request` 移到 `agent/route`,自 ## 迁移 -1. 把 `agent/request` 监听器中的提供方与模型替换移到返回 `{ provider, model }` 的 `agent/route` 监听器;`agent/request` 只保留调用控制参数的修改。在 `agent/pre-step` 中从 `payload.route` 读取路由,在提示词提供方中从 `AssembleContext.route` 读取路由。 -2. 使用 `ctx.tools.register(definition, { when })` 声明工具条件;条件接收 `{ agent, route, signal }`。 +1. 把 `agent/request` 监听器中的提供方、模型与推理强度替换移到返回 `{ provider, model, reasoningEffort? }` 的 `agent/model` 监听器;省略推理强度时使用该模型的提供方默认值。`agent/request` 只保留采样参数的修改。在 `agent/pre-step` 中从 `payload.modelSelection` 读取选择,在提示词提供方中从 `AssembleContext.modelSelection` 读取选择。 +2. 使用 `ctx.tools.register(definition, { when })` 声明工具条件;条件接收 `{ agent, modelSelection, signal }`。 3. 将运行时上下文准备监听器迁移到 `system-prompt/prepare`。展示变更留在 `system-prompt/assemble`,停止替换它的工具列表。 -4. 程序化调用条件工具时,通过 `ctx.tools.resolve()` 解析 `{ agent, route, signal }`,将返回的 `toolSet` 传给组装与执行,并在批次结束后释放。AgentLoop 会为模型调用在每个步骤完成一次这些操作。工具指导查询 `ctx.tools.get()` 或 `schemas()` 时传入 `context.toolSet`。 -5. 为测试直接派发的 `agent/pre-step` payload 补上 `route`。验证未启用工具不出现在声明中,使用历史名称调用会返回 `UNKNOWN_TOOL` 且不会进入实现,并验证修改模型的 `agent/request` 监听器会让轮次以指向 `agent/route` 的错误结束。 +4. 程序化调用条件工具时,通过 `ctx.tools.resolve()` 解析 `{ agent, modelSelection, signal }`,将返回的 `toolSet` 传给组装与执行,并在批次结束后释放。AgentLoop 会为模型调用在每个步骤完成一次这些操作。工具指导查询 `ctx.tools.get()` 或 `schemas()` 时传入 `context.toolSet`。 +5. 从 `ModelSelectionRef` 对象中删除 `assembled`,并为测试直接派发的 `agent/pre-step` payload 补上 `modelSelection`。验证未启用工具不出现在声明中,使用历史名称调用会返回 `UNKNOWN_TOOL` 且不会进入实现,并验证修改模型或推理强度的 `agent/request` 监听器会让轮次以指向 `agent/model` 的错误结束。 diff --git a/packages/acp/acp/README.i18n.yaml b/packages/acp/acp/README.i18n.yaml index 8be465f41a..6b0b7637c0 100644 --- a/packages/acp/acp/README.i18n.yaml +++ b/packages/acp/acp/README.i18n.yaml @@ -21,8 +21,8 @@ en: c3f5f144daf83157 zh: a65a64842fd35bef /deepseek-ai-dsh-acp/use-this-package/minimal-configuration: - en: 21dac29aadc0fc57 - zh: 6d2110787c034f8e + en: 7b9e6833800ee1a6 + zh: 8bb7ab276aa912ab /deepseek-ai-dsh-acp/use-this-package/start-a-server: en: 4ed8e37834267edb zh: a32d5dedb4e8e919 diff --git a/packages/acp/acp/README.md b/packages/acp/acp/README.md index fdde64b680..11014dbb31 100644 --- a/packages/acp/acp/README.md +++ b/packages/acp/acp/README.md @@ -33,7 +33,7 @@ Choose it when automation should own the interaction: an out-of-process subagent ### Minimal configuration -Every session the server creates uses the provider and model configured here. Both fields are optional so an `agent/route` listener can supply them; the runnable demo composition sets both. Stdout carries only protocol traffic, so keep logging off it. +Every session the server creates uses the provider and model configured here. Both fields are optional so an `agent/model` listener can supply them; the runnable demo composition sets both. Stdout carries only protocol traffic, so keep logging off it. ```yaml - name: '@deepseek-ai/dsh-acp' diff --git a/packages/acp/acp/README.zh.md b/packages/acp/acp/README.zh.md index 33d5ee9b03..0ef7065344 100644 --- a/packages/acp/acp/README.zh.md +++ b/packages/acp/acp/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" ### 最小配置 -服务器创建的每个会话都使用此处配置的提供方与模型。两个字段都是可选的,以便由 `agent/route` 监听器提供;可运行的演示组合会同时设置两者。Stdout 只承载协议流量,因此请让日志远离它。 +服务器创建的每个会话都使用此处配置的提供方与模型。两个字段都是可选的,以便由 `agent/model` 监听器提供;可运行的演示组合会同时设置两者。Stdout 只承载协议流量,因此请让日志远离它。 ```yaml - name: '@deepseek-ai/dsh-acp' diff --git a/packages/acp/acp/src/model-control.ts b/packages/acp/acp/src/model-control.ts index 00860475a0..4adc1ccb1a 100644 --- a/packages/acp/acp/src/model-control.ts +++ b/packages/acp/acp/src/model-control.ts @@ -30,7 +30,7 @@ export class AcpModelConfigError extends Error { /** Project and mutate one Agent's provider/model/reasoning selection through ACP config options. */ export class AcpModelControl { - /** Scoped selection reference consumed by Agent step routing. */ + /** Scoped selection reference taken by each Agent step. */ readonly selection: ModelSelectionRef private tail = Promise.resolve() private selected: ModelSelection | undefined @@ -47,12 +47,11 @@ export class AcpModelControl { this.selection = { get current() { return getCurrent() }, set current(value) { setCurrent(value) }, - assembled: undefined, } } /** - * Install step routing listeners in the unpublished Agent scope. + * Install step model-selection listeners in the unpublished Agent scope. * @param agentCtx - Agent scope that consumes this selection. */ install(agentCtx: Context): void { @@ -61,7 +60,7 @@ export class AcpModelControl { /** * Snapshot the selection attached to the next accepted ACP prompt. - * @returns a detached future selection, or undefined when listeners supply the route. + * @returns a detached future selection, or undefined when listeners supply the model. */ snapshot(): ModelSelection | undefined { return this.selected === undefined ? undefined : { ...this.selected } diff --git a/packages/acp/acp/tests/bridge.spec.ts b/packages/acp/acp/tests/bridge.spec.ts index 1356e32efb..bb6b1f579d 100644 --- a/packages/acp/acp/tests/bridge.spec.ts +++ b/packages/acp/acp/tests/bridge.spec.ts @@ -834,12 +834,12 @@ describe('automation-only ACP bridge', () => { expect(harness.ctx.agents.get(SessionId(sessionId))?.options).toEqual({}) }) - it('allows route listeners to supply a route when ACP has no initial selection', async () => { + it('allows model listeners to supply a model when ACP has no initial selection', async () => { harness = await makeBridgeHarness({ config: { provider: undefined, model: undefined }, script: [textResponse('listener-routed')], }) - harness.ctx.on('agent/route', async (_payload, next) => ({ + harness.ctx.on('agent/model', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock', diff --git a/packages/api/session-controller/src/agent.ts b/packages/api/session-controller/src/agent.ts index 4735b47e47..38e07a293e 100644 --- a/packages/api/session-controller/src/agent.ts +++ b/packages/api/session-controller/src/agent.ts @@ -282,7 +282,7 @@ export class ApiSessionAgentController { } /** - * Install or return the Session-local model selection that chooses each step's route. + * Install or return the Session-local model selection that each step takes. * @param agent - live Agent that owns the selection. * @returns the installed mutable selection reference. */ @@ -324,7 +324,6 @@ export class ApiSessionAgentController { picked = undefined return true }, - assembled: undefined, } installModelSelection(agent.ctx, selection) this.selections.set(agent, selection) @@ -332,7 +331,7 @@ export class ApiSessionAgentController { } /** - * Commit and cache one validated selection for the next step's route. + * Commit and cache one validated selection for the next step. * @param agent - live Agent that owns the selection. * @param selection - validated selection to record and apply. */ diff --git a/packages/api/session-controller/tests/archived-session-gate.host.spec.ts b/packages/api/session-controller/tests/archived-session-gate.host.spec.ts index 3a94d5d5c9..3c9d962f9e 100644 --- a/packages/api/session-controller/tests/archived-session-gate.host.spec.ts +++ b/packages/api/session-controller/tests/archived-session-gate.host.spec.ts @@ -47,7 +47,7 @@ async function liveAgent(ctx: Context, session: Session): Promise { /** Propose one model step for the Agent; the innermost decision enters. */ const proposed = (ctx: Context, agent: Agent) => ctx.waterfall( 'agent/pre-step', - { agent, messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, + { agent, messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) diff --git a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts index 5a4d946bf0..70ce7a0c3e 100644 --- a/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts +++ b/packages/api/session-controller/tests/commands-queue-attachment.host.spec.ts @@ -96,10 +96,7 @@ async function commandHarness( currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }), saveSelection: () => Promise.resolve(), } as never) - const selection: ModelSelectionRef = { - current: { provider: 'fixture', model: 'fixture-model' }, - assembled: undefined, - } + const selection: ModelSelectionRef = { current: { provider: 'fixture', model: 'fixture-model' } } const agents = { resolveAgent: (id: SessionId) => Promise.resolve(id === agent.id ? { agent } diff --git a/packages/api/session-controller/tests/commands-upload-file.host.spec.ts b/packages/api/session-controller/tests/commands-upload-file.host.spec.ts index 53d1137628..a27abe018b 100644 --- a/packages/api/session-controller/tests/commands-upload-file.host.spec.ts +++ b/packages/api/session-controller/tests/commands-upload-file.host.spec.ts @@ -88,10 +88,7 @@ async function uploadHarness(origin?: 'subagent'): Promise<{ listProviders: () => [{ id: 'fixture', name: 'Fixture' }], resolveModelInfo: () => Promise.resolve({ provider: 'fixture', id: 'fixture-model', name: 'Fixture' }), } as never) - const selection: ModelSelectionRef = { - current: { provider: 'fixture', model: 'fixture-model' }, - assembled: undefined, - } + const selection: ModelSelectionRef = { current: { provider: 'fixture', model: 'fixture-model' } } const agents = { resolveAgent: () => Promise.resolve({ agent }), selectionFor: () => selection, diff --git a/packages/api/session-controller/tests/session-fork.host.spec.ts b/packages/api/session-controller/tests/session-fork.host.spec.ts index e7ace3a85c..ed27f6abf5 100644 --- a/packages/api/session-controller/tests/session-fork.host.spec.ts +++ b/packages/api/session-controller/tests/session-fork.host.spec.ts @@ -8,7 +8,6 @@ import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deep import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import { ToolCallId, createMessage, createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm' -import type { LlmCallConfig } from '@deepseek-ai/dsh-llm' import SessionStore, { TOOL_OUTCOME_UNKNOWN, SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import { SessionPersistenceRevision, type SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence' @@ -663,13 +662,9 @@ describe('sessions.fork', () => { if (child === undefined) throw new Error('fork did not publish the child agent') expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount)).toEqual(inherited) const signal = new AbortController().signal - const route = await agentEvents(child.ctx, child).waterfall( - 'agent/route', { turn: 1, step: 1, signal }, () => Promise.resolve({ provider: 'default-provider', model: 'default-model' }), - ) - expect(route).toEqual({ provider: 'inherited-provider', model: 'inherited-model' }) await expect(agentEvents(child.ctx, child).waterfall( - 'agent/request', { turn: 1, step: 1, signal }, () => Promise.resolve({ ...route }), - )).resolves.toEqual({ ...route, reasoningEffort: 'high' }) + 'agent/model', { turn: 1, step: 1, signal }, () => Promise.resolve({ provider: 'default-provider', model: 'default-model' }), + )).resolves.toEqual({ provider: 'inherited-provider', model: 'inherited-model', reasoningEffort: 'high' }) await ctx.fiber.dispose() }) }) 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 099e5637be..21b21f78f2 100644 --- a/packages/api/session-controller/tests/session-models.host.spec.ts +++ b/packages/api/session-controller/tests/session-models.host.spec.ts @@ -1,18 +1,18 @@ /** * Session Controller model-directory and selection behavior: dynamic provider grouping, * provider-local catalog failures, logged-selection restoration without stale - * catalog injection, unavailable-model refusals, and the step-route + * catalog injection, unavailable-model refusals, and the step-model * boundary for a running selection change. */ import { describe, expect, it, vi, onTestFinished } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' -import type { Agent, StepRoute } from '@deepseek-ai/dsh-agent' +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, LlmCallConfigAdapterDefaults, LlmModelInfo, + GenerateOptions, LlmCallConfigAdapterDefaults, LlmModelInfo, LlmModelReasoningInfo, LlmProviderInfo, LlmResolvedModelInfo, StreamChunk, UserMessage, } from '@deepseek-ai/dsh-llm' @@ -486,15 +486,12 @@ describe('Web session model selection', () => { await ctx.fiber.dispose() }) - it('rejects unlisted models and applies a selection from the next step route', async () => { + it('rejects unlisted models and applies a selection from the next step', async () => { const { ctx, agent, sessionId } = await harness() const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), cwd: '/tmp' }) const signal = new AbortController().signal - const route = (step: number) => agentEvents(ctx, agent).waterfall( - 'agent/route', { turn: 1, step, signal }, () => Promise.resolve({ provider: 'seed', model: 'seed' }), - ) - const requestOn = (step: number, stepRoute: StepRoute) => agentEvents(ctx, agent).waterfall( - 'agent/request', { turn: 1, step, signal }, () => Promise.resolve({ ...stepRoute, temperature: 0.2 }), + const choose = (step: number) => agentEvents(ctx, agent).waterfall( + 'agent/model', { turn: 1, step, signal }, () => Promise.resolve({ provider: 'seed', model: 'seed' }), ) expect(currentSelection(ctx, sessionId)) @@ -504,9 +501,7 @@ describe('Web session model selection', () => { provider: 'deepseek-official', model: 'deepseek-chat', }))) - const chat = await route(1) - expect(chat).toEqual({ provider: 'deepseek-official', model: 'deepseek-chat' }) - await expect(requestOn(1, chat)).resolves.toEqual({ ...chat, temperature: 0.2, reasoningEffort: 'high' }) + await expect(choose(1)).resolves.toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' }) const selected = expectValue(await remote.selectModel(request({ sessionId, @@ -519,10 +514,7 @@ describe('Web session model selection', () => { model: 'deepseek-reasoner', reasoningEffort: 'max', }) - await expect(requestOn(1, chat)).resolves.toEqual({ ...chat, temperature: 0.2, reasoningEffort: 'high' }) - const reasoner = await route(2) - expect(reasoner).toEqual({ provider: 'deepseek-official', model: 'deepseek-reasoner' }) - await expect(requestOn(2, reasoner)).resolves.toEqual({ ...reasoner, temperature: 0.2, reasoningEffort: 'max' }) + await expect(choose(2)).resolves.toEqual({ provider: 'deepseek-official', model: 'deepseek-reasoner', reasoningEffort: 'max' }) const unsupported = await remote.selectModel(request({ sessionId, diff --git a/packages/bundle/headless/src/index.ts b/packages/bundle/headless/src/index.ts index 93006eb810..cc51a73039 100644 --- a/packages/bundle/headless/src/index.ts +++ b/packages/bundle/headless/src/index.ts @@ -338,7 +338,7 @@ async function run(ctx: Context, config: Config, io: HeadlessIo): Promise // that DOES configure one has to join it here first // (@deepseek-ai/dsh-agent-preset-registry README, "Composing a child agent"). const setup = (agentCtx: Context): void => { - const selected: ModelSelectionRef = { current: selection, assembled: undefined } + const selected: ModelSelectionRef = { current: selection } installModelSelection(agentCtx, selected) } const sessionId = brandString(config.sessionId ?? `session-${randomUUID()}`) diff --git a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts index d43a6828d6..a1d1d28162 100644 --- a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts +++ b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts @@ -1675,7 +1675,7 @@ describe('default one-shot summarizer', () => { describe('automatic listener and loader composition', () => { function preStep(ctx: Context, owner: Agent, signal = SIGNAL) { return agentEvents(ctx, owner).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) } diff --git a/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts b/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts index 84117631aa..15638ed067 100644 --- a/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts +++ b/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts @@ -205,9 +205,9 @@ function overflowHistorySeed(): readonly SessionEvent[] { } describe('CBR-001: a real-loop checkpoint is a valid boundary on both sides', () => { - it('uses the model actually routed by agent/route for post-step pressure', async () => { + it('uses the model actually selected by agent/model for post-step pressure', async () => { const { ctx } = await harness(8) - ctx.on('agent/route', async (_payload, next) => ({ + ctx.on('agent/model', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock', })) try { @@ -380,7 +380,7 @@ describe('context-overflow recovery across the real loop and compaction-basic', await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(TokenMeter) ctx.llm.registerAdapter(['mock'], adapter) - ctx.on('agent/route', async (_payload, next) => ({ + ctx.on('agent/model', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock', })) await ctx.plugin(BasicCompactionEngine, { diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index d6b22860b9..ef3da9000f 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -310,7 +310,7 @@ async function agentInstructionsOf(agent: Agent): Promise { async function syncAgentInstructions(ctx: Context, agent: Agent): Promise { await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: testToolSignal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: testToolSignal }, async () => ({ kind: 'enter' as const, messages: [] }), ) } @@ -345,13 +345,13 @@ async function composeBaselinePrefix(ctx: Context, agent: TestAgent): Promise Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const claimed = claimInbox(agent, 'next-step') const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 2, route: { provider: 'test', model: 'test' }, signal }, + { messages: claimed, turn: 1, step: 2, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) const entered = decision.kind === 'enter' ? decision.messages : [] @@ -1724,7 +1724,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(ctx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const inserted = original.inbox.nextStep[0] @@ -1738,7 +1738,7 @@ describe('workspace context request injection', () => { const claimed = claimInbox(resumed, 'next-step') const decision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: claimed, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) if (decision.kind !== 'enter') throw new Error('recovered baseline was rejected') @@ -1773,7 +1773,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(ctx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const stale = original.inbox.nextStep[0] @@ -1788,7 +1788,7 @@ describe('workspace context request injection', () => { const staleClaim = claimInbox(resumed, 'next-step') const staleDecision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', - { messages: staleClaim, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: staleClaim, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: staleClaim }), ) @@ -1831,7 +1831,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(originalCtx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const stale = original.inbox.nextStep[0] @@ -1846,7 +1846,7 @@ describe('workspace context request injection', () => { const claimed = claimInbox(resumed, 'next-step') const decision = await agentEvents(resumedCtx, resumed).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: claimed, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) @@ -1959,7 +1959,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [prompt], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [prompt], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve(downstream), ) @@ -2551,7 +2551,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve(downstream), ) @@ -2673,7 +2673,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [prompt], turn: 2, step: 1, route: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [prompt], turn: 2, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [prompt] }), ) @@ -3137,7 +3137,7 @@ describe('workspace context request injection', () => { const reason = new Error('cancel prefix') const pending = agentEvents(ctx, await stubAgent(root)).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: controller.signal }, + { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: controller.signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) @@ -5770,7 +5770,7 @@ describe('workspace context inbox synchronization', () => { controller.abort(new Error('abort pre-step reconciliation')) await expect(agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: controller.signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: controller.signal }, async () => ({ kind: 'enter' as const, messages: [] }), )).rejects.toThrow('abort pre-step reconciliation') @@ -5889,7 +5889,7 @@ describe('workspace context inbox synchronization', () => { const downstream = { kind: 'enter' as const, messages: claimed } const decision = await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: claimed, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: testToolSignal }, + 'agent/pre-step', { messages: claimed, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: testToolSignal }, async () => downstream, ) diff --git a/packages/context/session-reference/README.i18n.yaml b/packages/context/session-reference/README.i18n.yaml index 3022c2b8f5..64a394e658 100644 --- a/packages/context/session-reference/README.i18n.yaml +++ b/packages/context/session-reference/README.i18n.yaml @@ -33,8 +33,8 @@ en: db349483e453caf7 zh: 70035c291e1efe84 /deepseek-ai-dsh-session-reference/understand-the-implementation/design-concept: - en: 364238fb1f73a8eb - zh: ecb21f01b1a15f77 + en: 7171fcac9b67e148 + zh: 0ccd05e624ca8ab9 /deepseek-ai-dsh-session-reference/understand-the-implementation/source-map: en: 7c7b413082507150 zh: 0229eb73d441b305 diff --git a/packages/context/session-reference/README.md b/packages/context/session-reference/README.md index 64f86e7e3c..32a387f879 100644 --- a/packages/context/session-reference/README.md +++ b/packages/context/session-reference/README.md @@ -70,7 +70,7 @@ Preparation reads each referenced session's current surface exactly once, when t The resolver discovers optional storage through `ctx.get("spillStore")` and saves only truncated references. Storage ownership is the target session; the source descriptor identifies the referenced session and label, without a fabricated tool call. Cancellation is checked after the asynchronous save and prevents publication even if an artifact was written. Artifact expiry remains the backend's existing policy. -The budget uses the step route that `agent/route` chose, which `agent/pre-step` carries. Direct `prepare` calls without a route use agent options; session headers do not select the budget model. +The budget uses the step model that `agent/model` chose, which `agent/pre-step` carries as `modelSelection`. Direct `prepare` calls without a model selection use agent options; session headers do not select the budget model. ### Source map diff --git a/packages/context/session-reference/README.zh.md b/packages/context/session-reference/README.zh.md index 546735ad59..129db83741 100644 --- a/packages/context/session-reference/README.zh.md +++ b/packages/context/session-reference/README.zh.md @@ -70,7 +70,7 @@ kind: "package-reference" 解析器通过 `ctx.get("spillStore")` 获取可选存储,只保存被截断的引用。存储归目标会话所有;来源信息标识被引用的源会话与标签,不伪造工具调用。异步保存后会检查取消,即使产物已写入,也会阻止发布。产物过期仍遵循后端既有策略。 -预算使用 `agent/route` 选定、由 `agent/pre-step` 携带的步骤路由。未传入路由的直接 `prepare` 调用使用 agent 选项;Session 请求头不决定预算模型。 +预算使用 `agent/model` 选定、由 `agent/pre-step` 以 `modelSelection` 携带的步骤模型。未传入模型选择的直接 `prepare` 调用使用 agent 选项;Session 请求头不决定预算模型。 ### 源码地图 diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index 007d5d6cb2..2d67bc8197 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -7,7 +7,7 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { Agent, PreStepDecision, StepRoute } from '@deepseek-ai/dsh-agent' +import type { Agent, ModelSelection, PreStepDecision } from '@deepseek-ai/dsh-agent' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { createUserMessage, freezeMessage, LlmError } from '@deepseek-ai/dsh-llm' import type { ContentBlock, LlmResolvedModelInfo, UserMessage } from '@deepseek-ai/dsh-llm' @@ -122,12 +122,12 @@ export class SessionReferenceResolver extends TypertRemoteService { 'SESSION_REFERENCE_INVALID_CONFIG', ) } - ctx.on('agent/pre-step', async ({ agent, route, signal }, next): Promise => { + ctx.on('agent/pre-step', async ({ agent, modelSelection, signal }, next): Promise => { const decision = await next() if (decision.kind === 'reject') return decision return { ...decision, - messages: await this.prepareDirectMessages(agent, route, decision.messages, signal), + messages: await this.prepareDirectMessages(agent, modelSelection, decision.messages, signal), } }, { prepend: true }) } @@ -136,14 +136,14 @@ export class SessionReferenceResolver extends TypertRemoteService { * Replace canonical mentions in direct user messages and place each prepared * snapshot immediately after the message that cited it. * @param agent - agent entering the model step. - * @param route - provider and model of the step. + * @param modelSelection - provider and model of the step. * @param messages - messages accepted by downstream pre-step listeners. * @param signal - active turn cancellation. * @returns direct messages followed by their session-reference context in citation order. */ private async prepareDirectMessages( agent: Agent, - route: StepRoute, + modelSelection: ModelSelection, messages: readonly UserMessage[], signal: AbortSignal, ): Promise { @@ -157,7 +157,7 @@ export class SessionReferenceResolver extends TypertRemoteService { return { type: 'text', text: parsed.text } }) if (references.length === 0) return [message] - const resolved = await this.prepare(agent, content, references, signal, route) + const resolved = await this.prepare(agent, content, references, signal, modelSelection) const direct = freezeMessage({ ...message, content: resolved.content }) /* v8 ignore if -- a parsed canonical mention always leaves one normalized reference */ if (resolved.additionalContext === undefined) { @@ -278,7 +278,7 @@ export class SessionReferenceResolver extends TypertRemoteService { /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the step route, or agent options for direct preparation. + * Automatic budgets use the step's model selection, or agent options for direct preparation. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -286,7 +286,7 @@ export class SessionReferenceResolver extends TypertRemoteService { * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. - * @param route - provider and model of the step admitting the message; omitted for direct preparation. + * @param modelSelection - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ async prepare( @@ -294,13 +294,13 @@ export class SessionReferenceResolver extends TypertRemoteService { content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, - route?: StepRoute, + modelSelection?: ModelSelection, ): Promise { const acceptedContent = structuredClone(content) const inputs = normalizeReferences(agent.id, references, this.config.maxReferences) if (inputs.length === 0) return { content: acceptedContent } assertNotCancelled(signal) - const maxReferenceBytes = await this.referenceBudget(agent, route, signal) + const maxReferenceBytes = await this.referenceBudget(agent, modelSelection, signal) assertNotCancelled(signal) let prepared: PreparedSource[] try { @@ -351,10 +351,14 @@ export class SessionReferenceResolver extends TypertRemoteService { return { content: acceptedContent, additionalContext } } - private async referenceBudget(agent: Agent, route: StepRoute | undefined, signal: AbortSignal | undefined): Promise { + private async referenceBudget( + agent: Agent, + modelSelection: ModelSelection | undefined, + signal: AbortSignal | undefined, + ): Promise { if (this.config.maxReferenceBytes !== undefined) return this.config.maxReferenceBytes - // Options seed direct preparation; the step route owns model-step preparation. - const { provider, model } = route ?? agent.options + // Options seed direct preparation; the step's model selection owns model-step preparation. + const { provider, model } = modelSelection ?? agent.options const llm = this.ctx.get('llm') if (provider === undefined || model === undefined || llm === undefined) return DEFAULT_MAX_REFERENCE_BYTES let info: LlmResolvedModelInfo diff --git a/packages/context/session-reference/tests/loader-composition.spec.ts b/packages/context/session-reference/tests/loader-composition.spec.ts index eaca6a673e..f387fdd1f7 100644 --- a/packages/context/session-reference/tests/loader-composition.spec.ts +++ b/packages/context/session-reference/tests/loader-composition.spec.ts @@ -77,7 +77,7 @@ describe('session-reference real Loader composition', () => { source: { kind: 'user' }, }) const decision = await agentEvents(ctx, agent).waterfall('agent/pre-step', { - messages: [direct], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: new AbortController().signal, + messages: [direct], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal, }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct] })) expect(decision.kind).toBe('enter') if (decision.kind !== 'enter') throw new Error('Expected admitted reference') diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index e1c4f6d9ec..643c868caa 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -466,7 +466,7 @@ describe('session reference spill outcomes', () => { }) const direct = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const pending = agentEvents(ctx, fakeAgent(target)).waterfall('agent/pre-step', - { messages: [direct], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: controller.signal }, + { messages: [direct], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: controller.signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct] })) const rejected = expect(pending).rejects.toThrow(expectCode('SESSION_REFERENCE_CANCELLED')) await started.promise @@ -533,12 +533,12 @@ describe('model-relative reference budgets', () => { else expect(resolve).toHaveBeenCalledWith('seed', 'seed', undefined) }) - it('uses the step route rather than agent options', async () => { + it('uses the step model selection rather than agent options', async () => { const { ctx, agent, source, resolve } = await setup() - let route = { provider: 'selected', model: 'large' } + let modelSelection = { provider: 'selected', model: 'large' } const message = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const signal = new AbortController().signal - const enter = () => agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, route, signal }, + const enter = () => agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, modelSelection, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [message] })) const first = await enter() expect(first.kind).toBe('enter') @@ -547,7 +547,7 @@ describe('model-relative reference budgets', () => { if (firstContext === undefined) throw new Error('expected reference context') expect(bytes({ content: [], additionalContext: firstContext })).toBe(160_000) expect(resolve).toHaveBeenLastCalledWith('selected', 'large', signal) - route = { provider: 'selected', model: 'small' } + modelSelection = { provider: 'selected', model: 'small' } resolve.mockResolvedValue({ provider: 'selected', id: 'small', name: 'small', context: { contextWindow: 8_000 } }) const second = await enter() if (second.kind !== 'enter' || second.messages[1] === undefined) throw new Error('expected reference context') @@ -621,7 +621,7 @@ describe('model-relative reference budgets', () => { expect(resolve).toHaveBeenLastCalledWith('seed', 'seed', undefined) const message = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const seed = { kind: 'enter' as const, messages: [message] } - await expect(agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, + await expect(agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, () => Promise.resolve(seed))).resolves.toBe(seed) }) @@ -877,7 +877,7 @@ describe('session reference discovery and preparation', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [direct, ordinary, plugin], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + { messages: [direct, ordinary, plugin], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct, ordinary, plugin] }), ) @@ -913,14 +913,14 @@ describe('session reference discovery and preparation', () => { await expect(agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [malformed], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + { messages: [malformed], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'reject' as const }), )).resolves.toEqual({ kind: 'reject' }) expect(readSurface).not.toHaveBeenCalled() await expect(agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [malformed], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + { messages: [malformed], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [malformed] }), )).rejects.toThrow(/invalid session reference URI/) }) diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index 2fe2f9dc6a..a50195aff8 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -98,7 +98,7 @@ async function fire( }) const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [proposed], turn, step, route: { provider: 'test', model: 'test' }, signal }, + { messages: [proposed], turn, step, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [proposed] }), ) if (decision.kind === 'enter') { diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index 636d592077..50990452e3 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -151,7 +151,7 @@ async function fire( ): Promise { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn, step, route: { provider: 'test', model: 'test' }, signal }, + { messages: [], turn, step, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 03b0a75c41..bd05cdf32e 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -18,8 +18,8 @@ en: 35a960c0100a6aa4 zh: 438e133fb4c24a9e /deepseek-ai-dsh-agent-loop/use-this-package/configure-declarative-agents: - en: 1da69e82fc23ccd0 - zh: f722cf3827b821bc + en: 88fdef94bc4103dd + zh: e2bfd093a4fa00b8 /deepseek-ai-dsh-agent-loop/use-this-package/create-or-resume-agents-programmatically: en: 82ec792637e8e57f zh: e32f8ec5ee17afcf @@ -45,8 +45,8 @@ en: 3c5721bc00a0bbf4 zh: 711f832343ffbb75 /deepseek-ai-dsh-agent-loop/understand-the-implementation/turn-and-step-flow: - en: 787a9f96297a6024 - zh: e9b34c0c7ff26e25 + en: 0063a07435bc4028 + zh: c873fd82c927a7c2 /deepseek-ai-dsh-agent-loop/understand-the-implementation/failure-and-cancellation: en: eea56903c4ff82f5 zh: c0d5abb5767780ed diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 4e27d6c0a8..09bf22f9b3 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -29,7 +29,7 @@ Mount `dsh-agent-loop` in any composition that should run agents. It supplies th ### Configure declarative agents -Agents declared in the config start automatically when the plugin loads. Each entry needs an `id` label; a model call additionally requires both `provider` and `model` (`agent/route` may supply a missing pair for each step). +Agents declared in the config start automatically when the plugin loads. Each entry needs an `id` label; a model call additionally requires both `provider` and `model` (`agent/model` may supply a missing pair for each step). ```yaml - name: '@deepseek-ai/dsh-agent-loop' @@ -117,7 +117,7 @@ The loop is the production acquisition point for session write handles. When `ct ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver chooses the step route through `agent/route`, prepares variables and runtime context on that route, then runs `agent/pre-step`; its fallback projects that context. A rejected decision or empty first batch opens no step. Cancellation during routing opens no step. After acceptance, `step/start` precedes asynchronous tool activation and final prompt assembly, both once per step. Each attempt then runs the `agent/request` waterfall and `prepareCall()` on the step route; a listener that returns another provider or model fails the step, and cancellation during either async phase commits neither the pending system prompt nor accepted users. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt with its owned context candidate replaced in place, and restores removed runtime context, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the step's route, tool set, and rendered assembly without repeating routing, tool activation, assembly, `agent/pre-step`, or user admission. The step-owned tool set is closed after the step's tool batch settles. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver chooses the step's provider, model, and reasoning effort through `agent/model`, prepares variables and runtime context with that selection, then runs `agent/pre-step`; its fallback projects that context. A rejected decision or empty first batch opens no step. Cancellation during model selection opens no step. After acceptance, `step/start` precedes asynchronous tool activation and final prompt assembly, both once per step. Each attempt then runs the `agent/request` waterfall and `prepareCall()` with the step's model selection; a listener that returns another provider, model, or reasoning effort fails the step, and cancellation during either async phase commits neither the pending system prompt nor accepted users. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt with its owned context candidate replaced in place, and restores removed runtime context, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the step's model selection, tool set, and rendered assembly without repeating model selection, tool activation, assembly, `agent/pre-step`, or user admission. The step-owned tool set is closed after the step's tool batch settles. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) Prompt admission uses the actual `prepareCall()` result, not the preceding `request/context`. With no system node, even an empty prompt is appended (reserving node 0 without a wire message). On an incapable route or at a new request series, a non-empty rendering is consolidated at the first system node: each non-empty later system node receives a logged per-node empty replacement, then the head is rewritten if needed. Dormant empty tails need no replacement and do not determine the effective text. Consolidation applies even when the latest effective text is unchanged. On a continuing `in-history` series, an unchanged effective prompt produces no event and a non-empty change appends. An empty rendering clears every non-empty later system node through a logged per-node empty replacement, then empties the head if needed, regardless of route or series state. No older instructions remain model-visible. An empty head with no active later system node means no prompt; repeated clears and resume leave it empty. A restored non-empty prompt follows the same route/series rule: a continuing capable route may append it, while an incapable route or new series refills the head. A step starts a series when the pre-step decision declares `startsRequestSeries` or `session.surface.contentGeneration` changed since attachment or the last request (a replacement or image-offload decision). Visible tool-schema changes force prompt consolidation only when the prepared route lacks `toolUpdate`. Routes supporting both tool and system-prompt updates can append a changed prompt and activate added tools without rewriting earlier messages. If another admission condition replaces a system node, the request starts a new series with current tool declarations. Resume and a provider or model swap alone continue the series; the prepared route still governs admission. Per-node empty replacements preserve intervening history without a surface delete operation. diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index ae052e9af1..6761613ee9 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 配置声明式 agent -配置中声明的 agent 会在插件加载时自动启动。每个条目需要一个 `id` 标签;模型调用还同时需要 `provider` 与 `model`(`agent/route` 可以为每个步骤补齐缺失的这一对值)。 +配置中声明的 agent 会在插件加载时自动启动。每个条目需要一个 `id` 标签;模型调用还同时需要 `provider` 与 `model`(`agent/model` 可以为每个步骤补齐缺失的这一对值)。 ```yaml - name: '@deepseek-ai/dsh-agent-loop' @@ -117,7 +117,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器通过 `agent/route` 选定步骤路由,在该路由上准备变量和运行时上下文,然后运行 `agent/pre-step`;fallback 投影该上下文。被拒绝的决定或空的首批输入不打开步骤。路由选择期间取消不会打开步骤。接纳后,`step/start` 先于异步工具激活与最终提示词组装,两者每个步骤各执行一次。每次尝试随后在步骤路由上运行 `agent/request` waterfall 与 `prepareCall()`;监听器若返回其他提供方或模型,步骤会失败,而在任一异步阶段取消都不会提交待定的系统提示词或已接纳用户消息。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次并原位替换循环自有上下文候选、恢复被移除的运行时上下文、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试复用该步骤的路由、工具集合与已渲染组装结果,不重复路由选择、工具激活、组装、`agent/pre-step` 或用户消息接纳。步骤拥有的工具集合在该步骤的工具批次结束后关闭。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器通过 `agent/model` 选定步骤的提供方、模型与推理强度,按该选择准备变量和运行时上下文,然后运行 `agent/pre-step`;fallback 投影该上下文。被拒绝的决定或空的首批输入不打开步骤。模型选择期间取消不会打开步骤。接纳后,`step/start` 先于异步工具激活与最终提示词组装,两者每个步骤各执行一次。每次尝试随后按步骤的模型选择运行 `agent/request` waterfall 与 `prepareCall()`;监听器若返回其他提供方、模型或推理强度,步骤会失败,而在任一异步阶段取消都不会提交待定的系统提示词或已接纳用户消息。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次并原位替换循环自有上下文候选、恢复被移除的运行时上下文、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试复用该步骤的模型选择、工具集合与已渲染组装结果,不重复模型选择、工具激活、组装、`agent/pre-step` 或用户消息接纳。步骤拥有的工具集合在该步骤的工具批次结束后关闭。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 提示词准入依据实际的 `prepareCall()` 结果,而非先前的 `request/context`。没有系统节点时,即使提示词为空也追加(预留第 0 号节点,但不产生协议消息)。在不具备能力的路由上或新请求序列开始时,非空渲染文本归并到首个系统节点:每个非空的后续系统节点分别收到有日志记录的空内容替换,随后按需重写头节点。未生效的空尾节点无需替换,也不决定有效文本。即使最新有效文本未变,也执行归并。延续中的 `in-history` 序列在有效提示词不变时不产生事件,非空变更则追加。无论路由或序列状态如何,空渲染文本都会通过有日志记录的逐节点空内容替换清除每个非空的后续系统节点,再按需清空头节点。模型不会继续看到旧指令。空头节点且没有生效的后续系统节点表示没有提示词;重复清除与恢复会话都保持为空。重新提供的非空提示词遵循同一路由/序列规则:延续中的具备能力路由可以追加它,不具备能力的路由或新序列则重新填充头节点。以下情况开启序列:pre-step 决定声明 `startsRequestSeries`,或 `session.surface.contentGeneration` 自附接或上次请求以来发生变化(替换或图片省略决定)。仅当已准备路由未声明 `toolUpdate` 时,可见工具 schema 变化才强制归并提示词。同时支持工具和系统提示词更新的路由可以追加变更后的提示词并激活新增工具,无需改写此前消息。如果其他准入条件替换系统节点,请求会以当前工具声明开启新序列。恢复与单纯的提供方或模型切换都延续序列;准入仍由已准备的路由决定。逐节点的空内容替换保留其间历史,无需 surface 删除操作。 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 25858436fc..2eac31c365 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -12,9 +12,9 @@ import type { AgentStatus, CancelOptions, InboxTarget, + ModelSelection, PreStepDecision, RequestErrorAction, - StepRoute, } from '@deepseek-ai/dsh-agent' import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm' @@ -64,10 +64,15 @@ type PreparedStep = kind: 'enter' messages: UserMessage[] startsRequestSeries?: true - route: StepRoute + modelSelection: ModelSelection preparation: PromptPreparation } +/** Name a provider, model, and reasoning effort in diagnostics. */ +function selectionLabel({ provider, model, reasoningEffort }: ModelSelection): string { + return `${provider}/${model} (reasoning effort ${reasoningEffort ?? 'unset'})` +} + /** Remove adapter-derived values before plugins propose the next request config. */ function requestProposal(header: EpochHeader): LlmCallConfig { if (header.adapterDefaults === undefined) return header.config @@ -277,11 +282,11 @@ export class ReactLoopAgent implements Agent { if (this.phase.kind !== 'running') throw new Error(`agent "${this.id}": pre-step outside running phase`) const signal = this.phase.abort.signal const claimed = this.inbox.claim(target, position.turn) - const route = await this.chooseRoute(position.turn, position.step, signal) - const preparation = await this.loopCtx.systemPrompt.prepare({ ...assembleContextFor(this, signal), route }) + const modelSelection = await this.chooseModel(position.turn, position.step, signal) + const preparation = await this.loopCtx.systemPrompt.prepare({ ...assembleContextFor(this, signal), modelSelection }) signal.throwIfAborted() const decision = await this.dispatch.waterfall( - 'agent/pre-step', { messages: claimed, ...position, route, signal }, + 'agent/pre-step', { messages: claimed, ...position, modelSelection, signal }, (): Promise => { const sections = renderContextSections(preparation) const context = this.runtimeContext.project(joinContextSections(sections), sections) @@ -293,21 +298,26 @@ export class ReactLoopAgent implements Agent { ) signal.throwIfAborted() if (decision.kind === 'reject') return decision - return { ...decision, route, preparation } + return { ...decision, modelSelection, preparation } } - /** Choose the provider and model that the proposed step keeps for every request attempt. */ - private async chooseRoute(turn: number, step: number, signal: AbortSignal): Promise { - const { provider, model } = this.requestBase() - const route = await this.dispatch.waterfall( - 'agent/route', { turn, step, signal }, - () => Promise.resolve({ provider, model }), + /** Choose the provider, model, and effort that the proposed step keeps for every request attempt. */ + private async chooseModel(turn: number, step: number, signal: AbortSignal): Promise { + const { provider, model, reasoningEffort } = this.requestBase() + const proposed: ModelSelection = { provider, model, ...reasoningEffort === undefined ? {} : { reasoningEffort } } + const selected = await this.dispatch.waterfall( + 'agent/model', { turn, step, signal }, + () => Promise.resolve(proposed), ) signal.throwIfAborted() - if (!route.provider || !route.model) { - throw new Error(`agent "${this.id}" has no provider/model: set AgentOptions.provider and AgentOptions.model or supply both via the agent/route waterfall`) + if (!selected.provider || !selected.model) { + throw new Error(`agent "${this.id}" has no provider/model: set AgentOptions.provider and AgentOptions.model or supply both via the agent/model waterfall`) } - return Object.freeze({ provider: route.provider, model: route.model }) + return Object.freeze({ + provider: selected.provider, + model: selected.model, + ...selected.reasoningEffort === undefined ? {} : { reasoningEffort: selected.reasoningEffort }, + }) } /** Whether the assembled tool schemas differ from the logged request header's. */ @@ -424,18 +434,18 @@ export class ReactLoopAgent implements Agent { const { turn, step, abort: { signal } } = this.phase signal.throwIfAborted() - const { route } = decision - const toolSet = await this.loopCtx.tools.resolve({ agent: this, route, signal }) + const { modelSelection } = decision + const toolSet = await this.loopCtx.tools.resolve({ agent: this, modelSelection, signal }) try { const assembly = await this.loopCtx.systemPrompt.assemble( - { ...assembleContextFor(this, signal), route, toolSet }, + { ...assembleContextFor(this, signal), modelSelection, toolSet }, decision.preparation, ) const renderedPrompt = renderPrompt(assembly) let firstAttempt = true while (true) { - const { config, preparedCall } = await this.prepareRequest(turn, step, route, signal) - const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, { ...assembleContextFor(this, signal), route }) + const { config, preparedCall } = await this.prepareRequest(turn, step, modelSelection, signal) + const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, { ...assembleContextFor(this, signal), modelSelection }) const sections = renderContextSections(currentContext) const context = this.runtimeContext.project(joinContextSections(sections), sections) signal.throwIfAborted() @@ -593,8 +603,9 @@ export class ReactLoopAgent implements Agent { /** * The config this loop instance proposes before plugins act: its declared - * route on the first request, restoring only an explicit effort owned by - * that exact model, then the logged header without adapter defaults. + * provider and model on the first request, restoring only an explicit + * effort owned by that exact model, then the logged header without adapter + * defaults. */ private requestBase(): LlmCallConfig { const persistedHeader = this.session.requestHeader() @@ -616,27 +627,24 @@ export class ReactLoopAgent implements Agent { } } - /** Resolve one attempt's config on the step route and bind its adapter before admitting model-visible input. */ + /** Resolve one attempt's config on the step's model selection and bind its adapter before admitting model-visible input. */ private async prepareRequest( turn: number, step: number, - route: StepRoute, + modelSelection: ModelSelection, signal: AbortSignal, ): Promise { - let seed = this.requestBase() - if (seed.provider !== route.provider || seed.model !== route.model) { - // An effort belongs to one model; another route starts from its own default. - const { reasoningEffort: _effort, ...controls } = seed - seed = { ...controls, provider: route.provider, model: route.model } - } - const seedConfig = deepFreeze(structuredClone(seed)) + const { provider: _provider, model: _model, reasoningEffort: _effort, ...controls } = this.requestBase() + const seedConfig = deepFreeze(structuredClone({ ...controls, ...modelSelection })) const proposedConfig = await this.dispatch.waterfall( 'agent/request', { turn, step, signal }, () => Promise.resolve(seedConfig), ) signal.throwIfAborted() - if (proposedConfig.provider !== route.provider || proposedConfig.model !== route.model) { - throw new Error(`agent "${this.id}": agent/request cannot replace the step route ${route.provider}/${route.model} with ${proposedConfig.provider}/${proposedConfig.model}; choose routes with the agent/route waterfall`) + if (proposedConfig.provider !== modelSelection.provider + || proposedConfig.model !== modelSelection.model + || proposedConfig.reasoningEffort !== modelSelection.reasoningEffort) { + throw new Error(`agent "${this.id}": agent/request cannot replace the step model selection ${selectionLabel(modelSelection)} with ${selectionLabel(proposedConfig)}; choose models with the agent/model waterfall`) } let config: LlmCallConfig let preparedCall: PreparedLlmCall | undefined diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 9fd38c9742..34e7879654 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -386,8 +386,8 @@ export class AgentLoop extends Service implements AgentFactory { }) }, 'agentLoop.transactions()') ctx.effect(() => ctx.agents.setFactory(this), 'agentLoop.setFactory()') - ctx.systemPrompt.variable('provider', context => context.route?.provider ?? context.agent?.options.provider) - ctx.systemPrompt.variable('model', context => context.route?.model ?? context.agent?.options.model) + ctx.systemPrompt.variable('provider', context => context.modelSelection?.provider ?? context.agent?.options.provider) + ctx.systemPrompt.variable('model', context => context.modelSelection?.model ?? context.agent?.options.model) for (const { id, sessionId, cwd, resumeSessionId, ...options } of this.config.agents) { const meta = cwd === undefined ? {} : { cwd } diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index 84d702d79c..cfad2fd312 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import LlmRuntime, { type RequestMessage, createUserMessage, ToolCallId, LlmError, MessageSource, ProviderRequestId, StreamChunk } from '@deepseek-ai/dsh-llm' +import LlmRuntime, { type RequestMessage, createUserMessage, ToolCallId, LlmError, MessageSource, ProviderRequestId, ReasoningEffortId, StreamChunk } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionEvent, SessionId, TurnEndReason, type UserMessage } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' @@ -450,17 +450,17 @@ describe('adapter registration, routing, and accepted-input ownership', () => { : undefined).toContain('has no provider/model') expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' ? turnEnd.data.reason.error.message - : undefined).toContain('agent/route') + : undefined).toContain('agent/model') expect(agent.session.snapshotEvents().some(event => event.type === 'step/start')).toBe(false) expect(adapter.requests).toHaveLength(0) }) - it('the agent/route waterfall can supply the model for a model-less agent', async () => { + it('the agent/model waterfall can supply the model for a model-less agent', async () => { const adapter = new MockAdapter([textResponse('routed')]) const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('a1'), {}) // no model — router plugin decides - ctx.on('agent/route', async (_payload, next) => { + ctx.on('agent/model', async (_payload, next) => { return { ...await next(), provider: 'mock', model: 'mock' } }) @@ -470,19 +470,22 @@ describe('adapter registration, routing, and accepted-input ownership', () => { expect(agent.session.deriveMessages().at(-1)?.content).toEqual([{ type: 'text', text: 'routed' }]) }) - it('agent/request cannot replace the step route', async () => { + it.each([ + ['provider', { provider: 'other' }, 'other/mock (reasoning effort unset)'], + ['reasoning effort', { reasoningEffort: ReasoningEffortId('high') }, 'mock/mock (reasoning effort high)'], + ] as const)('agent/request cannot replace the step %s', async (_field, replacement, replaced) => { const adapter = new MockAdapter([textResponse('never')]) const ctx = await harness(adapter) ctx.llm.registerAdapter(['other'], new MockAdapter([textResponse('never')])) const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) - ctx.on('agent/request', async (_payload, next) => ({ ...await next(), provider: 'other' })) + ctx.on('agent/request', async (_payload, next) => ({ ...await next(), ...replacement })) send(agent, 'go') await waitForIdle(ctx, agent) const turnEnd = agent.session.snapshotEvents().findLast(event => event.type === 'turn/end') expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' ? turnEnd.data.reason.error.message - : undefined).toContain('agent/request cannot replace the step route mock/mock with other/mock') + : undefined).toContain(`agent/request cannot replace the step model selection mock/mock (reasoning effort unset) with ${replaced}; choose models with the agent/model waterfall`) expect(agent.session.snapshotEvents().filter(event => ['request/header', 'system/message', 'user/message'].includes(event.type))) .toEqual([]) expect(adapter.requests).toHaveLength(0) diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index 6f992a1c68..193544367f 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -602,12 +602,12 @@ describe('agent loop', () => { expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed') }) - it('renders a {{model}} persona from the route an agent/route listener supplies', async () => { - // AgentOptions.model unset: the step route arrives through agent/route, + it('renders a {{model}} persona from the model an agent/model listener supplies', async () => { + // AgentOptions.model unset: the step model arrives through agent/model, // before prompt preparation, so the prompt variables already name it. const adapter = new MockAdapter([textResponse('ok')]) const ctx = await harness(adapter, 'You run on {{model}}.') - ctx.on('agent/route', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock' })) + ctx.on('agent/model', async (_payload, next) => ({ ...await next(), provider: 'mock', model: 'mock' })) const agent = await ctx.agentLoop.create(SessionId('a-late-model'), {}) send(agent, 'hi') @@ -1298,20 +1298,26 @@ describe('agent loop', () => { expect(texts).toContain('late steering') }) - it('agent/route waterfall switches models for the step; the switch is logged', async () => { - const adapter = new MockAdapter([textResponse('ok')]) + it('agent/model waterfall switches model and effort for the step; the switch is logged', async () => { + const low = ReasoningEffortId('low') + const high = ReasoningEffortId('high') + const adapter = new MockAdapter([textResponse('ok')], { + efforts: [{ id: low, name: 'Low' }, { id: high, name: 'High' }], + defaultEffort: high, + }) const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) - ctx.on('agent/route', async (_payload, next) => ({ ...await next(), model: 'other-model' })) + ctx.on('agent/model', async () => ({ provider: 'mock', model: 'other-model', reasoningEffort: low })) send(agent, 'hi') await waitForIdle(ctx, agent) - expect(adapter.requests[0]!.model).toBe('other-model') + expect(adapter.requests[0]).toMatchObject({ model: 'other-model', reasoningEffort: low }) // The header event records what the request ACTUALLY used — the switch is // a reconstructable fact, not silent drift. const headerEvent = agent.session.snapshotEvents().find(e => e.type === 'request/header') - expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model') + expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config) + .toMatchObject({ model: 'other-model', reasoningEffort: low }) }) it('agent/request waterfall replaces call controls with a replacement config; the change is logged', async () => { diff --git a/packages/core/agent-loop/tests/request-reconstruction.spec.ts b/packages/core/agent-loop/tests/request-reconstruction.spec.ts index 7c0fe9b60e..5f81fe1469 100644 --- a/packages/core/agent-loop/tests/request-reconstruction.spec.ts +++ b/packages/core/agent-loop/tests/request-reconstruction.spec.ts @@ -218,9 +218,9 @@ describe('request stability across the loop', () => { const adapter = new MockAdapter([textResponse('one'), textResponse('two')], reasoning) const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('effort'), { provider: 'mock', model: 'mock' }) - ctx.on('agent/request', async ({ turn }, next) => { - const config = await next() - return turn === 2 ? { ...config, reasoningEffort: ReasoningEffortId('max') } : config + ctx.on('agent/model', async ({ turn }, next) => { + const selection = await next() + return turn === 2 ? { ...selection, reasoningEffort: ReasoningEffortId('max') } : selection }) send(agent, 'first') @@ -294,9 +294,9 @@ describe('request stability across the loop', () => { provider: 'deepseek', model: 'deepseek-model', }) - ctx.on('agent/route', async ({ turn }, next) => { - const route = await next() - return turn === 2 ? { provider: 'other', model: 'other-model' } : route + ctx.on('agent/model', async ({ turn }, next) => { + const proposed = await next() + return turn === 2 ? { provider: 'other', model: 'other-model' } : proposed }) send(agent, 'first') @@ -326,9 +326,9 @@ describe('request stability across the loop', () => { model: 'deepseek-model', maxTokens: 4_096, }) - ctx.on('agent/route', async ({ turn }, next) => { - const route = await next() - return turn === 2 ? { provider: 'other', model: 'other-model' } : route + ctx.on('agent/model', async ({ turn }, next) => { + const proposed = await next() + return turn === 2 ? { provider: 'other', model: 'other-model' } : proposed }) send(agent, 'first') @@ -944,7 +944,7 @@ describe('request/context capacity records', () => { send(agent, 'first') await waitForIdle(ctx, agent) - ctx.on('agent/route', ({ agent: subject }, next) => subject === agent + ctx.on('agent/model', ({ agent: subject }, next) => subject === agent ? Promise.resolve({ provider: 'mock', model: 'large' }) : next()) send(agent, 'second') @@ -972,7 +972,7 @@ describe('request/context capacity records', () => { const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('capacity-clear'), { provider: 'mock', model: 'known' }) let model = 'known' - ctx.on('agent/route', ({ agent: subject }, next) => subject === agent + ctx.on('agent/model', ({ agent: subject }, next) => subject === agent ? Promise.resolve({ provider: 'mock', model }) : next()) diff --git a/packages/core/agent-loop/tests/system-prompt-admission.spec.ts b/packages/core/agent-loop/tests/system-prompt-admission.spec.ts index b904088576..24d7783174 100644 --- a/packages/core/agent-loop/tests/system-prompt-admission.spec.ts +++ b/packages/core/agent-loop/tests/system-prompt-admission.spec.ts @@ -39,7 +39,7 @@ async function harness(capable = new MockAdapter(Array.from({ length: 8 }, () => ctx.on('system-prompt/assemble', async (_assembly, _context, next) => ({ ...await next(), sections: [{ name: 'test', text: prompt, order: 0 }], })) - const selection: ModelSelectionRef = { current: { provider: 'capable', model: 'model' }, assembled: undefined } + const selection: ModelSelectionRef = { current: { provider: 'capable', model: 'model' } } const agent = await ctx.agentLoop.create(SessionId('admission'), { provider: 'capable', model: 'model' }) installModelSelection(agent.ctx, selection) ctx.on('llm/stream', (request, next) => { @@ -398,11 +398,11 @@ describe('prepared-route prompt admission', () => { expect(types.filter(type => ['system/message', 'user/message', 'request/header'].includes(type))).toEqual([]) }) - it('cancels during route before a step opens', async () => { + it('cancels during model selection before a step opens', async () => { const h = await harness() const entered = Promise.withResolvers() const release = Promise.withResolvers() - h.ctx.on('agent/route', async (_payload, next) => { + h.ctx.on('agent/model', async (_payload, next) => { expect(h.agent.session.snapshotEvents().map(event => event.type)).not.toContain('step/start') entered.resolve(undefined) await release.promise diff --git a/packages/core/agent-loop/tests/tool-updates.spec.ts b/packages/core/agent-loop/tests/tool-updates.spec.ts index 5b7e4157d2..4044aa1e92 100644 --- a/packages/core/agent-loop/tests/tool-updates.spec.ts +++ b/packages/core/agent-loop/tests/tool-updates.spec.ts @@ -114,35 +114,35 @@ describe('tool update emission', () => { }) describe('step-time tool activation', () => { - it('uses the step route for asynchronous conditions and rejects a historical name after removal', async () => { + it('uses the step model selection for asynchronous conditions and rejects a historical name after removal', async () => { const adapter = new MockAdapter([ toolCallResponse('allowed', 'conditional', {}), textResponse('done'), toolCallResponse('removed', 'conditional', {}), textResponse('done'), ]) const { ctx, agent } = await harness(adapter) - const routed: string[] = [] + const selectedModels: string[] = [] let calls = 0 let model = 'enabled' - ctx.on('agent/route', async (_payload, next) => ({ ...await next(), model })) + ctx.on('agent/model', async (_payload, next) => ({ ...await next(), model })) ctx.tools.register(defineContentToolFixture({ - name: 'conditional', description: 'Available on one route.', parameters: {}, + name: 'conditional', description: 'Available on one model.', parameters: {}, async execute(_args, exec) { expect(exec.agent?.session.requestHeader()?.config.model).toBe('enabled') calls++ return [{ type: 'text', text: 'done' }] }, - }), { when: async ({ route }) => { - expect(Object.isFrozen(route)).toBe(true) - routed.push(route.model) + }), { when: async ({ modelSelection }) => { + expect(Object.isFrozen(modelSelection)).toBe(true) + selectedModels.push(modelSelection.model) await Promise.resolve() - return route.model === 'enabled' + return modelSelection.model === 'enabled' } }) await send(agent, 'enabled') model = 'disabled' await send(agent, 'try the historical name') expect(calls).toBe(1) - expect(routed).toEqual(['enabled', 'enabled', 'disabled', 'disabled']) - expect(adapter.requests.map(request => request.model)).toEqual(routed) + expect(selectedModels).toEqual(['enabled', 'enabled', 'disabled', 'disabled']) + expect(adapter.requests.map(request => request.model)).toEqual(selectedModels) expect(developerEvents(agent).at(-1)?.data.message.content) .toEqual([{ type: 'tool-removal', toolName: 'conditional' }]) expect(agent.session.snapshotEvents().find(event => event.type === 'tool/result' && event.data.message.toolCallId === 'removed')?.data) @@ -167,17 +167,17 @@ describe('step-time tool activation', () => { expect(agent.session.snapshotEvents().filter(event => ['request/header', 'system/message', 'user/message'].includes(event.type))).toEqual([]) }) - it('keeps one route, tool set, and prompt across retries without admitting users again', async () => { + it('keeps one model selection, tool set, and prompt across retries without admitting users again', async () => { const adapter = new MockAdapter([ [{ type: 'finish', reason: { kind: 'error', failure: { code: 'SERVER', message: 'retry', status: 503 } } }], textResponse('done'), ]) const { ctx, agent } = await harness(adapter) let retried = false - const counts = { routes: 0, conditions: 0, admissions: 0 } + const counts = { selections: 0, conditions: 0, admissions: 0 } ctx.on('agent/pre-step', (_input, next) => { counts.admissions++; return next() }) - ctx.on('agent/route', async (_input, next) => { - counts.routes++ + ctx.on('agent/model', async (_input, next) => { + counts.selections++ return { ...await next(), model: retried ? 'second' : 'first' } }) ctx.on('agent/request-error', async (_input, next) => { @@ -191,14 +191,14 @@ describe('step-time tool activation', () => { }), { when: () => { counts.conditions++; return retried } }) ctx.systemPrompt.section({ name: 'retry:guidance', order: 0, complete: true, - text: context => `${context.route?.model}:${ctx.tools.schemas(agent, context.toolSet).map(tool => tool.name).join(',')}`, + text: context => `${context.modelSelection?.model}:${ctx.tools.schemas(agent, context.toolSet).map(tool => tool.name).join(',')}`, }) await send(agent, 'retry once') expect(adapter.requests.map(request => request.model)).toEqual(['first', 'first']) expect(adapter.requests.map(request => request.tools ?? [])).toEqual([[], []]) expect(adapter.requests.map(request => request.messages.find(message => message.role === 'system')?.content)) .toEqual([[{ type: 'text', text: 'first:' }], [{ type: 'text', text: 'first:' }]]) - expect(counts).toEqual({ routes: 1, conditions: 1, admissions: 1 }) + expect(counts).toEqual({ selections: 1, conditions: 1, admissions: 1 }) expect(agent.session.snapshotEvents().filter(event => event.type === 'user/message' && event.data.source.kind === 'user')).toHaveLength(1) }) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index e7e1759e5f..5d7936aae2 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2594a1e02adea801 zh: cae8860369728efb /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: - en: 5d700c9eed84bcf5 - zh: a0498f1814bfee05 + en: bb854bd10523e158 + zh: b59580450c764598 /deepseek-ai-dsh-agent/understand-the-implementation: en: ce7e776e9d516bdb zh: 59d2751743db7795 @@ -36,14 +36,14 @@ en: 7c850051d2857bfa zh: 4cab817553114e15 /deepseek-ai-dsh-agent/understand-the-implementation/step-admission: - en: edd4ed5033c294e7 - zh: 7c627497fe450702 + en: 324af18f63a4f537 + zh: eec28e7f8362a919 /deepseek-ai-dsh-agent/understand-the-implementation/durable-inbox: en: f6802c7f94f623b3 zh: cc3885db80765970 /deepseek-ai-dsh-agent/understand-the-implementation/source-map: - en: 8efa6e74d4dbe28e - zh: 6126170ac464703f + en: 7b78f956b98d7ef1 + zh: c9b063505ddd9f03 /deepseek-ai-dsh-agent/understand-the-implementation/registry-and-lifecycle: en: df92e97cedd0d02e zh: f6040c145bffd933 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 0ca04dd4e4..a7b91fc1b4 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -64,7 +64,7 @@ await handle.agent.whenIdle() ### Intercept or observe work in flight -The `agent/*` events let plugins act on live work without depending on the loop package. `agent/route` chooses each step's provider and model; `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). +The `agent/*` events let plugins act on live work without depending on the loop package. `agent/model` chooses each step's provider, model, and reasoning effort; `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). ----- @@ -82,9 +82,9 @@ The package is built on one separation: the public `Agent` surface and registry ### Step admission -`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. `agent/route` chooses the step's provider and model before `agent/pre-step`, whose payload carries that `route`. Acceptance does not commit the batch: after `step/start`, tool conditions, prompt assembly, `agent/request`, and `prepareCall()` must succeed before system and user messages are logged. Cancellation during routing opens no step, and cancellation during a later async phase commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. +`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. `agent/model` chooses the step's provider, model, and reasoning effort before `agent/pre-step`, whose payload carries that `modelSelection`. Acceptance does not commit the batch: after `step/start`, tool conditions, prompt assembly, `agent/request`, and `prepareCall()` must succeed before system and user messages are logged. Cancellation during model selection opens no step, and cancellation during a later async phase commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. -The step route supplies or replaces the creation-time options pair. Prompt preparation, `agent/pre-step`, tool conditions, and every request attempt in the step use it; an `agent/request` listener that returns another provider or model fails the step. `installModelSelection` captures its selection when `agent/route` runs, so a selection made during a step applies from the next step. +The step's model selection supplies or replaces the creation-time provider, model, and effort. Prompt preparation, `agent/pre-step`, tool conditions, and every request attempt in the step use it; an `agent/request` listener that returns another provider, model, or reasoning effort fails the step. `installModelSelection` returns its current selection, effort included, when `agent/model` runs, so a selection made during a step applies from the next step. ### Durable inbox @@ -101,7 +101,7 @@ The step route supplies or replaces the creation-time options pair. Prompt prepa | [`src/types.ts`](src/types.ts) | `AgentOptions`, cancellation causes, and inbox projection vocabulary | | [`src/dispatch.ts`](src/dispatch.ts) | `agentEvents` fused dispatcher and `assembleContextFor(agent)` | | [`src/consumed-work.ts`](src/consumed-work.ts) | `foldConsumedWork(events)`: what the log's consumed work became | -| [`src/model-selection.ts`](src/model-selection.ts) | `installModelSelection`: capturing a selection for step routing | +| [`src/model-selection.ts`](src/model-selection.ts) | `installModelSelection`: applying a selection to each step's model choice | | [`src/archive-admission.ts`](src/archive-admission.ts) | The `turn` family of the Workspace registry's archive admission: a running turn and its user-cause cancel | ### Registry and lifecycle diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index c8f9a23c29..becdb8417b 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -64,7 +64,7 @@ await handle.agent.whenIdle() ### 拦截或观察进行中的工作 -`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/route` 选定每个步骤的提供方与模型;`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 +`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/model` 选定每个步骤的提供方、模型与推理强度;`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 ----- @@ -82,9 +82,9 @@ await handle.agent.whenIdle() ### 步骤准入 -`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。`agent/route` 在 `agent/pre-step` 之前选定该步骤的提供方与模型,`agent/pre-step` 的 payload 携带该 `route`。接纳不等于提交:`step/start` 之后,工具条件、提示词组装、`agent/request` 与 `prepareCall()` 都成功后,才记录系统提示词与用户批次。在路由选择期间取消不会打开步骤,在之后任一异步阶段取消也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 +`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。`agent/model` 在 `agent/pre-step` 之前选定该步骤的提供方、模型与推理强度,`agent/pre-step` 的 payload 携带该 `modelSelection`。接纳不等于提交:`step/start` 之后,工具条件、提示词组装、`agent/request` 与 `prepareCall()` 都成功后,才记录系统提示词与用户批次。在模型选择期间取消不会打开步骤,在之后任一异步阶段取消也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 -步骤路由会补上或替换创建时 options 中的这对值。提示词准备、`agent/pre-step`、工具条件以及该步骤的每次请求尝试都使用它;`agent/request` 监听器若返回其他提供方或模型,步骤会失败。`installModelSelection` 在 `agent/route` 运行时捕获其选择,因此步骤进行中做出的选择从下一个步骤开始生效。 +步骤的模型选择会补上或替换创建时的提供方、模型与推理强度。提示词准备、`agent/pre-step`、工具条件以及该步骤的每次请求尝试都使用它;`agent/request` 监听器若返回其他提供方、模型或推理强度,步骤会失败。`installModelSelection` 在 `agent/model` 运行时返回当前选择(含推理强度),因此步骤进行中做出的选择从下一个步骤开始生效。 ### 持久 inbox @@ -101,7 +101,7 @@ await handle.agent.whenIdle() | [`src/types.ts`](src/types.ts) | `AgentOptions`、取消原因与收件箱投影词汇 | | [`src/dispatch.ts`](src/dispatch.ts) | `agentEvents` 融合分发器与 `assembleContextFor(agent)` | | [`src/consumed-work.ts`](src/consumed-work.ts) | `foldConsumedWork(events)`:日志消费掉的工作最终怎样了 | -| [`src/model-selection.ts`](src/model-selection.ts) | `installModelSelection`:为步骤路由捕获模型选择 | +| [`src/model-selection.ts`](src/model-selection.ts) | `installModelSelection`:把模型选择应用到每个步骤的模型决定 | | [`src/archive-admission.ts`](src/archive-admission.ts) | Workspace 注册表归档准入中的 `turn` 族:运行中的回合及其用户原因取消 | ### 注册表与生命周期 diff --git a/packages/core/agent/src/model-selection.ts b/packages/core/agent/src/model-selection.ts index eaf693beb0..d0e30909aa 100644 --- a/packages/core/agent/src/model-selection.ts +++ b/packages/core/agent/src/model-selection.ts @@ -4,13 +4,8 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { - boundContextSummary, - createUserMessage, - type LlmCallConfig, - type ReasoningEffortId, -} from '@deepseek-ai/dsh-llm' -import type { PreStepDecision, StepRoute } from './runtime-types.ts' +import { boundContextSummary, createUserMessage } from '@deepseek-ai/dsh-llm' +import type { ModelSelection, PreStepDecision } from './runtime-types.ts' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { @@ -18,35 +13,23 @@ declare module '@deepseek-ai/dsh-llm' { } } -/** Complete provider, model, and optional reasoning effort selected for one live Agent. */ -export interface ModelSelection { - /** Registered provider route. */ - provider: string - /** Provider-owned model id. */ - model: string - /** Adapter-owned reasoning effort, or provider/default behavior when absent. */ - reasoningEffort?: ReasoningEffortId -} - -/** Mutable model selection plus the value captured for the current step. */ +/** Mutable model selection taken by each step that starts. */ export interface ModelSelectionRef { - /** Model selected for the next step to start. */ + /** Model selected for the next step to start; undefined keeps the step's proposed selection. */ current: ModelSelection | undefined - /** Selection captured when the current step chose its route. */ - assembled: ModelSelection | undefined } -function sameRoute(left: StepRoute, right: StepRoute): boolean { +function sameModel(left: ModelSelection, right: ModelSelection): boolean { return left.provider === right.provider && left.model === right.model } -function routeLabel(route: StepRoute, other: StepRoute): string { - return route.provider === other.provider ? route.model : `${route.provider}/${route.model}` +function modelLabel(selection: ModelSelection, other: ModelSelection): string { + return selection.provider === other.provider ? selection.model : `${selection.provider}/${selection.model}` } -function modelSwitchNotice(previous: StepRoute, selected: StepRoute) { - const from = routeLabel(previous, selected) - const to = routeLabel(selected, previous) +function modelSwitchNotice(previous: ModelSelection, selected: ModelSelection) { + const from = modelLabel(previous, selected) + const to = modelLabel(selected, previous) return createUserMessage({ content: [{ type: 'text' as const, @@ -61,15 +44,14 @@ function modelSwitchNotice(previous: StepRoute, selected: StepRoute) { } /** - * Couple one mutable selection to Agent-scoped step routing. Each step - * captures the selection when `agent/route` chooses its provider and model, - * and every request attempt in that step applies the captured effort; a - * selection made during the step applies from the next step. An absent - * selected effort clears inherited effort, restoring the model's provider - * default. + * Couple one mutable selection to Agent-scoped step model choice. Each step + * takes the provider, model, and effort current when `agent/model` runs, and + * every request attempt in that step keeps them; a selection made during the + * step applies from the next step. An absent selected effort leaves the + * model's provider default. * * A provider/model change appends a durable user-role notice to the next - * admitted request. It compares the step route with the latest request + * admitted request. It compares the step's selection with the latest request * header; effort-only changes and empty no-request decisions add no notice. * Failure before header persistence repeats the notice on the next request. * @@ -78,44 +60,26 @@ function modelSwitchNotice(previous: StepRoute, selected: StepRoute) { * @returns Disposer for all scoped waterfall listeners. */ export function installModelSelection(agentCtx: Context, selection: ModelSelectionRef): () => void { - const disposeRoute = agentCtx.on('agent/route', async (_payload, next): Promise => { - const selected = selection.current === undefined ? undefined : { ...selection.current } - selection.assembled = selected - const route = await next() - return selected === undefined ? route : { provider: selected.provider, model: selected.model } + const disposeModel = agentCtx.on('agent/model', async (_payload, next): Promise => { + const selected = selection.current + const proposed = await next() + return selected === undefined ? proposed : { ...selected } }) - const disposeRequest = agentCtx.on( - 'agent/request', - async (_payload, next): Promise => { - const resolved = await next() - const selected = selection.assembled - // Another route listener may have replaced the captured route; its model keeps its own effort. - if (selected === undefined || !sameRoute(selected, resolved)) return resolved - const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved - return { - ...withoutInheritedEffort, - ...selected.reasoningEffort === undefined - ? {} - : { reasoningEffort: selected.reasoningEffort }, - } - }, - ) const disposeNotice = agentCtx.on( 'agent/pre-step', - async ({ agent, messages, route, signal, step }, next): Promise => { + async ({ agent, messages, modelSelection, signal, step }, next): Promise => { const decision = await next() if (decision.kind === 'reject' || signal.aborted) return decision // The loop skips an empty first step and an emptied offered continuation. if (decision.messages.length === 0 && (step === 1 || messages.length > 0)) return decision const previous = agent.session.requestHeader()?.config - if (previous === undefined || sameRoute(route, previous)) return decision - return { ...decision, messages: [...decision.messages, modelSwitchNotice(previous, route)] } + if (previous === undefined || sameModel(modelSelection, previous)) return decision + return { ...decision, messages: [...decision.messages, modelSwitchNotice(previous, modelSelection)] } }, { prepend: true }, ) return () => { - disposeRoute() - disposeRequest() + disposeModel() disposeNotice() } } diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index ec1c03a7c4..c710d95592 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -19,17 +19,19 @@ declare module '@deepseek-ai/dsh-system-prompt' { interface AssembleContext { /** Agent for this assembly; absent on diagnostics. When present, `scope` must identify the same agent. */ agent?: Agent - /** Provider and model of the step being assembled; absent outside a step. */ - route?: StepRoute + /** Model selection of the step being assembled; absent outside a step. */ + modelSelection?: ModelSelection } } -/** Provider and model that `agent/route` chose for one step and every request attempt in it. */ -export interface StepRoute { +/** Complete provider, model, and optional reasoning effort; `agent/model` fixes one for each step. */ +export interface ModelSelection { /** Registered provider route. */ - readonly provider: string - /** Model id interpreted by the provider adapter. */ - readonly model: string + provider: string + /** Provider-owned model id. */ + model: string + /** Adapter-owned reasoning effort, or provider/default behavior when absent. */ + reasoningEffort?: ReasoningEffortId } /** Merge-extensible agent creation options. Persona belongs to system-prompt sections. */ @@ -172,7 +174,7 @@ export type AssistantStreamFrame = declare module './types.ts' { interface Agent { - /** Creation-time request options; `agent/route` may choose another provider and model for each step. */ + /** Creation-time request options; `agent/model` may choose another provider, model, and effort for each step. */ readonly options: AgentOptions /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session @@ -323,20 +325,23 @@ declare module '@deepseek-ai/cordis' { * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. - * @param payload.route - the provider and model `agent/route` chose for this step. + * @param payload.modelSelection - the provider, model, and effort `agent/model` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ - 'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; route: StepRoute; signal: AbortSignal }, next: () => Promise): Promise + 'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; modelSelection: ModelSelection; signal: AbortSignal }, next: () => Promise): Promise /** - * Choose the provider and model for one proposed step. `await next()` - * yields the route the machine would use (agent options before this loop - * logs a request, the logged header afterwards); return a replacement to - * switch. The loop runs this once per proposed step, before context - * preparation and `agent/pre-step`. Prompt preparation, tool conditions, - * and every request attempt in the step use the result, so a later choice - * applies from the next step. Cancellation here opens no step. + * Choose the provider, model, and reasoning effort for one proposed step. + * `await next()` yields the selection the machine would use: agent options + * before this loop logs a request, the logged header afterwards, with an + * effort only when one was chosen for that exact model. Return a + * replacement to switch; an effort belongs to its model, so a replacement + * that changes the model names that model's effort or omits it for the + * provider default. The loop runs this once per proposed step, before + * context preparation and `agent/pre-step`. Prompt preparation, tool + * conditions, and every request attempt in the step use the result, so a + * later choice applies from the next step. Cancellation here opens no step. * @param payload.agent - the agent proposing the step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. @@ -344,14 +349,14 @@ declare module '@deepseek-ai/cordis' { * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ - 'agent/route'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise + 'agent/model'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise /** * Replace the frozen call configuration of one request attempt. `await - * next()` yields the config the machine would use on the step's - * `agent/route` result: agent options on the first request, the logged - * header afterwards, and no effort recorded for another model. Return a - * replacement to change call controls such as reasoning effort; returning - * another provider or model fails the step. On step admission, this runs + * next()` yields the step's `agent/model` selection with the machine's + * other call controls: agent options on the first request, the logged + * header afterwards. Return a replacement to change sampling controls such + * as `maxTokens`, `temperature`, or `stop`; returning another provider, + * model, or reasoning effort fails the step. On step admission, this runs * after prompt assembly and `step/start`, before the system prompt and * accepted user batch are committed, and again for each retry. * Cancellation here or during subsequent `prepareCall()` resolution diff --git a/packages/core/agent/tests/model-selection.spec.ts b/packages/core/agent/tests/model-selection.spec.ts index c0d028cefe..23663ee2e1 100644 --- a/packages/core/agent/tests/model-selection.spec.ts +++ b/packages/core/agent/tests/model-selection.spec.ts @@ -1,4 +1,4 @@ -/** Model selection chooses each step's route once; requests in that step keep it. */ +/** Model selection fixes each step's provider, model, and effort once; requests in that step keep them. */ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { @@ -7,9 +7,8 @@ import { type Agent, type ModelSelection, type ModelSelectionRef, - type StepRoute, } from '../src/index.ts' -import { createUserMessage, ReasoningEffortId, type LlmCallConfig } from '@deepseek-ai/dsh-llm' +import { createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' const contexts: Context[] = [] @@ -18,23 +17,21 @@ afterEach(async () => { }) const signal = new AbortController().signal const input = createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'user' } }) -const seedRoute: StepRoute = { provider: 'seed', model: 'seed' } +const seed: ModelSelection = { provider: 'seed', model: 'seed', reasoningEffort: ReasoningEffortId('max') } function harness(current?: ModelSelection, previous?: ModelSelection) { const ctx = new Context() contexts.push(ctx) - const selection: ModelSelectionRef = { current, assembled: undefined } + const selection: ModelSelectionRef = { current } const dispose = installModelSelection(ctx, selection) const agent = { session: Session.create(SessionId('model-selection')) } as Agent if (previous) agent.session.append('request/header', { header: { config: previous }, reason: 'initial' }) - const route = (step: number, seed: StepRoute = seedRoute) => - agentEvents(ctx, agent).waterfall('agent/route', { turn: 1, step, signal }, () => Promise.resolve(seed)) - const request = (step: number, seed: LlmCallConfig) => - agentEvents(ctx, agent).waterfall('agent/request', { turn: 1, step, signal }, () => Promise.resolve(seed)) - const preStep = (stepRoute: StepRoute, messages = [input], offered = [input], step = 1, stepSignal = signal) => - agentEvents(ctx, agent).waterfall('agent/pre-step', { turn: 1, step, messages: offered, route: stepRoute, signal: stepSignal }, + const choose = (step: number) => + agentEvents(ctx, agent).waterfall('agent/model', { turn: 1, step, signal }, () => Promise.resolve(seed)) + const preStep = (modelSelection: ModelSelection, messages = [input], offered = [input], step = 1, stepSignal = signal) => + agentEvents(ctx, agent).waterfall('agent/pre-step', { turn: 1, step, messages: offered, modelSelection, signal: stepSignal }, () => Promise.resolve({ kind: 'enter' as const, messages })) - return { ctx, agent, selection, dispose, route, request, preStep } + return { ctx, agent, selection, dispose, choose, preStep } } function notice(from: string, to: string) { @@ -42,56 +39,41 @@ function notice(from: string, to: string) { } describe('installModelSelection()', () => { - it('captures one selection per step for its route and every request effort, then disposes routing', async () => { + it('gives each step the current selection, effort included, then disposes', async () => { const h = harness() - expect(await h.route(1)).toBe(seedRoute) - const inherited: LlmCallConfig = { provider: 'alpha', model: 'a1', reasoningEffort: ReasoningEffortId('max'), temperature: 0.2 } - expect(await h.request(1, inherited)).toBe(inherited) + expect(await h.choose(1)).toBe(seed) - h.selection.current = { provider: 'alpha', model: 'a1', reasoningEffort: ReasoningEffortId('high') } - expect(await h.route(2)).toEqual({ provider: 'alpha', model: 'a1' }) + const high = { provider: 'alpha', model: 'a1', reasoningEffort: ReasoningEffortId('high') } + h.selection.current = high + const chosen = await h.choose(2) + expect(chosen).toEqual(high) + expect(chosen).not.toBe(high) + + // An absent selected effort leaves the provider default instead of inheriting the proposal's. h.selection.current = { provider: 'beta', model: 'b1' } - const selected = { ...inherited, reasoningEffort: ReasoningEffortId('high') } - expect(await h.request(2, inherited)).toEqual(selected) - expect(await h.request(2, inherited)).toEqual(selected) - - expect(await h.route(3)).toEqual({ provider: 'beta', model: 'b1' }) - expect(await h.request(3, { ...inherited, provider: 'beta', model: 'b1' })) - .toEqual({ provider: 'beta', model: 'b1', temperature: 0.2 }) + expect(await h.choose(3)).toEqual({ provider: 'beta', model: 'b1' }) h.dispose() - expect(await h.route(4)).toBe(seedRoute) - expect(await h.request(4, inherited)).toBe(inherited) + expect(await h.choose(4)).toBe(seed) }) - it('keeps the effort of a route that an outer listener replaced', async () => { - const h = harness({ provider: 'alpha', model: 'a1', reasoningEffort: ReasoningEffortId('high') }) - h.ctx.on('agent/route', async (_payload, next) => { - await next() - return { provider: 'gamma', model: 'g1' } - }, { prepend: true }) - expect(await h.route(1)).toEqual({ provider: 'gamma', model: 'g1' }) - const config: LlmCallConfig = { provider: 'gamma', model: 'g1', reasoningEffort: ReasoningEffortId('max') } - expect(await h.request(1, config)).toBe(config) - }) - - it('announces same-provider and cross-provider step routes', async () => { + it('announces same-provider and cross-provider model switches', async () => { const h = harness(undefined, { provider: 'alpha', model: 'a0' }) await expect(h.preStep({ provider: 'alpha', model: 'a1' })).resolves.toMatchObject({ messages: [input, notice('a0', 'a1')] }) await expect(h.preStep({ provider: 'beta', model: 'b1' })).resolves.toMatchObject({ messages: [input, notice('alpha/a0', 'beta/b1')] }) }) - it('preserves initial, unchanged, rejected, cancelled, and disposed decisions', async () => { + it('preserves initial, effort-only, rejected, cancelled, and disposed decisions', async () => { const h = harness() - const route = { provider: 'alpha', model: 'a0' } - await expect(h.preStep(route)).resolves.toEqual({ kind: 'enter', messages: [input] }) + const initial = { provider: 'alpha', model: 'a0' } + await expect(h.preStep(initial)).resolves.toEqual({ kind: 'enter', messages: [input] }) h.agent.session.append('request/header', { - header: { config: { ...route, reasoningEffort: ReasoningEffortId('high') } }, + header: { config: { ...initial, reasoningEffort: ReasoningEffortId('high') } }, reason: 'initial', }) - await expect(h.preStep(route)).resolves.toEqual({ kind: 'enter', messages: [input] }) + await expect(h.preStep({ ...initial, reasoningEffort: ReasoningEffortId('low') })).resolves.toEqual({ kind: 'enter', messages: [input] }) const switched = { provider: 'alpha', model: 'a1' } - await expect(agentEvents(h.ctx, h.agent).waterfall('agent/pre-step', { turn: 1, step: 3, messages: [], route: switched, signal }, + await expect(agentEvents(h.ctx, h.agent).waterfall('agent/pre-step', { turn: 1, step: 3, messages: [], modelSelection: switched, signal }, () => Promise.resolve({ kind: 'reject' as const }))).resolves.toEqual({ kind: 'reject' }) await expect(h.preStep(switched, [input], [input], 3, AbortSignal.abort())).resolves.toEqual({ kind: 'enter', messages: [input] }) h.dispose() @@ -100,9 +82,9 @@ describe('installModelSelection()', () => { it('preserves empty claims and announces an empty tool continuation', async () => { const h = harness(undefined, { provider: 'alpha', model: 'a0' }) - const route = { provider: 'alpha', model: 'a1' } - await expect(h.preStep(route, [])).resolves.toEqual({ kind: 'enter', messages: [] }) - await expect(h.preStep(route, [], [input], 2)).resolves.toEqual({ kind: 'enter', messages: [] }) - await expect(h.preStep(route, [], [], 2)).resolves.toMatchObject({ messages: [notice('a0', 'a1')] }) + const switched = { provider: 'alpha', model: 'a1' } + await expect(h.preStep(switched, [])).resolves.toEqual({ kind: 'enter', messages: [] }) + await expect(h.preStep(switched, [], [input], 2)).resolves.toEqual({ kind: 'enter', messages: [] }) + await expect(h.preStep(switched, [], [], 2)).resolves.toMatchObject({ messages: [notice('a0', 'a1')] }) }) }) diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index a3bf51caa5..9103091c77 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -21,8 +21,8 @@ en: 9d2e6caa39c53d62 zh: 096a777f828c7565 /deepseek-ai-dsh-tools/use-this-package/conditional-tools: - en: ddd6bd2f0cf93524 - zh: 17339d994d48bfa2 + en: 33618b68f90858c0 + zh: 10e20f40a5871555 /deepseek-ai-dsh-tools/use-this-package/configure-the-presentation-mode: en: 4e27c45ae889369e zh: 7a0cd7a9dc7fe139 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index f54f423bb4..d15bbaf35e 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -65,9 +65,9 @@ The unified schema DSL supports `string`, `number`, `integer`, `boolean`, `null` ### Conditional tools -`register(definition, { when })` evaluates a synchronous or asynchronous condition once for each model step. The condition receives `{ agent, route, signal }`, where `route` is the provider and model that `agent/route` chose for every request attempt in the step. False omits the tool from Native declarations, PTC bindings, and execution. A thrown condition fails step preparation as `TOOL_ACTIVATION_FAILED`; it is not treated as ordinary unavailability. Conditions must observe cancellation and must not change registrations or perform tool work. +`register(definition, { when })` evaluates a synchronous or asynchronous condition once for each model step. The condition receives `{ agent, modelSelection, signal }`, where `modelSelection` is the provider, model, and reasoning effort that `agent/model` chose for every request attempt in the step. False omits the tool from Native declarations, PTC bindings, and execution. A thrown condition fails step preparation as `TOOL_ACTIVATION_FAILED`; it is not treated as ordinary unavailability. Conditions must observe cancellation and must not change registrations or perform tool work. -`resolve({ agent, route, signal })` returns a step-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and every Native or PTC execution, then dispose it after the step's batch settles; retries in the step reuse it. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, cancellation, or same-name replacement prevent unstarted calls from using it. Started operations retain their cooperative cancellation obligations. Conditional calls without a resolved set return `UNKNOWN_TOOL`. +`resolve({ agent, modelSelection, signal })` returns a step-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and every Native or PTC execution, then dispose it after the step's batch settles; retries in the step reuse it. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, cancellation, or same-name replacement prevent unstarted calls from using it. Started operations retain their cooperative cancellation obligations. Conditional calls without a resolved set return `UNKNOWN_TOOL`. `get(name, scope, toolSet)` and `schemas(scope, toolSet)` inspect an admitted set; omitting `toolSet` inspects registered definitions without evaluating conditions. Tool guidance receives the same selection as `AssembleContext.toolSet`. A presentation transform cannot add or remove callable tools. diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index d0ea16d5da..3b60e0dbec 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -65,9 +65,9 @@ ctx.tools.register(defineTool({ ### 条件工具 -`register(definition, { when })` 为每个模型步骤计算一次同步或异步条件。条件接收 `{ agent, route, signal }`,其中 `route` 是 `agent/route` 为该步骤所有请求尝试选定的提供方与模型。返回 false 会从原生声明、PTC 绑定和执行集合中排除工具。条件抛错会以 `TOOL_ACTIVATION_FAILED` 中止步骤准备,不会被当成正常不可用。条件必须响应取消,不得改变注册或执行工具操作。 +`register(definition, { when })` 为每个模型步骤计算一次同步或异步条件。条件接收 `{ agent, modelSelection, signal }`,其中 `modelSelection` 是 `agent/model` 为该步骤所有请求尝试选定的提供方、模型与推理强度。返回 false 会从原生声明、PTC 绑定和执行集合中排除工具。条件抛错会以 `TOOL_ACTIVATION_FAILED` 中止步骤准备,不会被当成正常不可用。条件必须响应取消,不得改变注册或执行工具操作。 -`resolve({ agent, route, signal })` 返回步骤拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及每次原生或 PTC 执行,步骤的批次结束后释放;同一步骤内的重试复用它。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制、取消或同名替换会阻止尚未开始的调用继续使用它。已经开始的操作保留协作取消义务。没有已解析集合的条件工具调用返回 `UNKNOWN_TOOL`。 +`resolve({ agent, modelSelection, signal })` 返回步骤拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及每次原生或 PTC 执行,步骤的批次结束后释放;同一步骤内的重试复用它。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制、取消或同名替换会阻止尚未开始的调用继续使用它。已经开始的操作保留协作取消义务。没有已解析集合的条件工具调用返回 `UNKNOWN_TOOL`。 `get(name, scope, toolSet)` 和 `schemas(scope, toolSet)` 读取已准入集合;省略 `toolSet` 时只查看已注册定义,不计算条件。工具指导文本通过 `AssembleContext.toolSet` 接收同一集合。展示变换不能增删可调用工具。 diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index e51018b860..90d484052f 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -11,7 +11,7 @@ import { AnonymousEntries, NamedEntries, ScopedLayers, scopeOf, scopeTarget } fr import type { ScopeKey, ScopeLayer, Scoped } from '@deepseek-ai/dsh-scope' import type { ToolCallId, ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm' import { HarnessError } from '@deepseek-ai/dsh-llm' -import type { Agent, StepRoute } from '@deepseek-ai/dsh-agent' +import type { Agent, ModelSelection } from '@deepseek-ai/dsh-agent' import type { UserMessage } from '@deepseek-ai/dsh-session' import { assertNever, deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' import type { PromptSection, ToolProviderResult } from '@deepseek-ai/dsh-system-prompt' @@ -231,8 +231,8 @@ export interface ToolOutputDefinition { export interface ToolActivationContext { /** Agent preparing the step. */ readonly agent: Agent - /** Provider and model that every request attempt in the step uses. */ - readonly route: StepRoute + /** Provider, model, and reasoning effort that every request attempt in the step uses. */ + readonly modelSelection: ModelSelection /** Cancellation of step preparation; asynchronous conditions must observe it. */ readonly signal: AbortSignal } @@ -243,7 +243,7 @@ export interface ToolRegistrationOptions { * Decide whether the step's requests may call the tool. Omission enables * it. False excludes it from both declarations and dispatch; rejection fails * step preparation. Conditions must not mutate registrations or start tool work. - * @param context - preparing agent, step route, and cancellation signal. + * @param context - preparing agent, step model selection, and cancellation signal. * @returns whether the tool participates in this step. */ readonly when?: (context: ToolActivationContext) => boolean | Promise @@ -1311,7 +1311,7 @@ export class ToolRuntime extends Service { * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - preparing agent, step route, and cancellation. + * @param context - preparing agent, step model selection, and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise { diff --git a/packages/core/tools/tests/activation.spec.ts b/packages/core/tools/tests/activation.spec.ts index 168e0e12a3..c9c4125aca 100644 --- a/packages/core/tools/tests/activation.spec.ts +++ b/packages/core/tools/tests/activation.spec.ts @@ -19,7 +19,7 @@ async function setup() { await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) const agent = { id: SessionId('activation') } as Agent - const route = { provider: 'test', model: 'test' } + const modelSelection = { provider: 'test', model: 'test' } let scope!: Scope await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, { inject: ['tools'] })) const controller = new AbortController() @@ -30,8 +30,8 @@ async function setup() { async execute() { calls++; return 'done' }, }) const input = { agent, name: tool.name, arguments: {}, callId: ToolCallId('call'), signal: controller.signal } - const resolve = () => ctx.tools.resolve({ agent, route, signal: controller.signal }) - return { ctx, agent, route, scope, controller, tool, input, resolve, calls: () => calls } + const resolve = () => ctx.tools.resolve({ agent, modelSelection, signal: controller.signal }) + return { ctx, agent, modelSelection, scope, controller, tool, input, resolve, calls: () => calls } } it('activates and deactivates a registered tool without allowing historical calls', async () => { @@ -104,8 +104,8 @@ it('does not restore a registration removed during its asynchronous condition', it('propagates cancellation after an asynchronous condition settles', async () => { const h = await setup() const condition = Promise.withResolvers() - h.ctx.tools.register(h.tool, { when: ({ route, signal }) => { - expect(route).toBe(h.route) + h.ctx.tools.register(h.tool, { when: ({ modelSelection, signal }) => { + expect(modelSelection).toBe(h.modelSelection) expect(signal).toBe(h.controller.signal) return condition.promise } }) diff --git a/packages/core/tools/tests/ptc.spec.ts b/packages/core/tools/tests/ptc.spec.ts index 496b007a81..15045bf56f 100644 --- a/packages/core/tools/tests/ptc.spec.ts +++ b/packages/core/tools/tests/ptc.spec.ts @@ -187,7 +187,7 @@ describe('mode-aware wire contribution', () => { const unregister = ctx.tools.register(definition, { when: () => active }) for (const enabled of [false, true]) { active = enabled - const toolSet = await ctx.tools.resolve({ agent, route: { provider: 'test', model: 'test' }, signal: testToolSignal }) + const toolSet = await ctx.tools.resolve({ agent, modelSelection: { provider: 'test', model: 'test' }, signal: testToolSignal }) try { const assembly = await systemPrompt.assemble({ scope: agent, agent, toolSet }) const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? '' diff --git a/packages/experimental/webhook/src/session.ts b/packages/experimental/webhook/src/session.ts index ecc9b1b577..fc85f8bb87 100644 --- a/packages/experimental/webhook/src/session.ts +++ b/packages/experimental/webhook/src/session.ts @@ -7,7 +7,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import type { ModelSelection } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-default-model' import type {} from '@deepseek-ai/dsh-agent-preset-registry' -import { boundContextSummary, createUserMessage, errorChain, type LlmCallConfig } from '@deepseek-ai/dsh-llm' +import { boundContextSummary, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-permission-presets' import type { SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-session-title' @@ -90,16 +90,12 @@ function reportRollbackFailure(ctx: Context, subject: string, error: unknown): v /** Apply the creation-time selection until its first durable request header exists. */ function installInitialModelSelection(agentCtx: Context, selection: ModelSelection): void { - agentCtx.on('agent/request', async ({ agent }, next): Promise => { - const resolved = await next() + agentCtx.on('agent/model', async ({ agent }, next): Promise => { + const proposed = await next() if (agent.session.requestHeader() !== undefined - || resolved.provider !== selection.provider - || resolved.model !== selection.model) return resolved - const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved - return { - ...withoutInheritedEffort, - ...selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }, - } + || proposed.provider !== selection.provider + || proposed.model !== selection.model) return proposed + return { ...selection } }) } diff --git a/packages/experimental/webhook/tests/session.spec.ts b/packages/experimental/webhook/tests/session.spec.ts index 2585023fec..67fa2ede46 100644 --- a/packages/experimental/webhook/tests/session.spec.ts +++ b/packages/experimental/webhook/tests/session.spec.ts @@ -1,5 +1,6 @@ import type { Context } from '@deepseek-ai/cordis' -import { ReasoningEffortId, type LlmCallConfig } from '@deepseek-ai/dsh-llm' +import type { ModelSelection } from '@deepseek-ai/dsh-agent' +import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' import { afterEach, describe, expect, it, vi } from 'vitest' import { WebhookDeliveryId, @@ -182,19 +183,19 @@ async function create(test: SessionHarness, request = test.request): Promise Promise, -) => Promise { - const listener = test.modelListeners.get('agent/request') + next: () => Promise, +) => Promise { + const listener = test.modelListeners.get('agent/model') if (typeof listener !== 'function') { throw new Error('webhook Session did not install its initial model selection') } - const request = listener as ( + const choose = listener as ( payload: unknown, - next: () => Promise, - ) => Promise - return (_payload, next) => request({ agent: test.agent }, next) + next: () => Promise, + ) => Promise + return (_payload, next) => choose({ agent: test.agent }, next) } describe('webhook Session creation', () => { @@ -231,7 +232,7 @@ describe('webhook Session creation', () => { const withoutCap = harness() await create(withoutCap, { ...withoutCap.request, model: { provider: 'p', model: 'm' } }) expect(withoutCap.calls).not.toContain('default-model') - await expect(modelRequestListener(withoutCap)(undefined, async () => ({ + await expect(modelChoiceListener(withoutCap)(undefined, async () => ({ provider: 'p', model: 'm', reasoningEffort: ReasoningEffortId('inherited'), }))).resolves.toEqual({ provider: 'p', model: 'm' }) }) @@ -239,32 +240,32 @@ describe('webhook Session creation', () => { it('preserves default reasoning until the first request header is durable', async () => { const test = harness() await create(test) - const request = modelRequestListener(test) + const choose = modelChoiceListener(test) - await expect(request(undefined, async () => ({ + await expect(choose(undefined, async () => ({ provider: 'other-provider', model: 'default-model', reasoningEffort: ReasoningEffortId('other-provider-effort'), }))).resolves.toMatchObject({ reasoningEffort: 'other-provider-effort' }) - await expect(request(undefined, async () => ({ + await expect(choose(undefined, async () => ({ provider: 'default-provider', model: 'other-model', reasoningEffort: ReasoningEffortId('other-model-effort'), }))).resolves.toMatchObject({ reasoningEffort: 'other-model-effort' }) - const routed: unknown = await request(undefined, async () => ({ + const chosen: unknown = await choose(undefined, async () => ({ provider: 'default-provider', model: 'default-model', reasoningEffort: ReasoningEffortId('inherited'), })) - expect(routed).toEqual({ + expect(chosen).toEqual({ provider: 'default-provider', model: 'default-model', reasoningEffort: 'high', }) test.markRequestHeader() - await expect(request(undefined, async () => ({ + await expect(choose(undefined, async () => ({ provider: 'later-provider', model: 'later-model', reasoningEffort: ReasoningEffortId('later'), diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 43771aec8e..980d59e3b4 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2393,9 +2393,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'mention-carrying candidates in rank order.', }, { - signature: 'async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, route?: StepRoute, ): Promise', - description: 'Snapshot all references for one accepted direct message and return one aggregated durable context. Automatic budgets use the step route, or agent options for direct preparation. Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. Cancellation prevents context publication, including when storage completes after cancellation.', - parameters: [{ name: 'agent', description: 'target agent; references to it are rejected.' }, { name: 'content', description: 'already host-normalized readable message content.' }, { name: 'references', description: 'structured source sessions in mention order.' }, { name: 'signal', description: 'optional cancellation boundary for the active turn.' }, { name: 'route', description: 'provider and model of the step admitting the message; omitted for direct preparation.' }], + signature: 'async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, modelSelection?: ModelSelection, ): Promise', + description: 'Snapshot all references for one accepted direct message and return one aggregated durable context. Automatic budgets use the step\'s model selection, or agent options for direct preparation. Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. Cancellation prevents context publication, including when storage completes after cancellation.', + parameters: [{ name: 'agent', description: 'target agent; references to it are rejected.' }, { name: 'content', description: 'already host-normalized readable message content.' }, { name: 'references', description: 'structured source sessions in mention order.' }, { name: 'signal', description: 'optional cancellation boundary for the active turn.' }, { name: 'modelSelection', description: 'provider and model of the step admitting the message; omitted for direct preparation.' }], returns: 'detached content and optional referenced-session context.', }, ], @@ -3366,7 +3366,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { signature: 'async resolve(context: ToolActivationContext): Promise', description: 'Resolve conditions once for this step without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.', - parameters: [{ name: 'context', description: 'preparing agent, step route, and cancellation.' }], + parameters: [{ name: 'context', description: 'preparing agent, step model selection, and cancellation.' }], returns: 'the complete selection; the caller disposes it after its tool batch settles.', }, { @@ -3992,10 +3992,18 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'One message entered the live inbox.', parameters: [{ name: 'payload', description: '.message - the inserted message. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, + { + name: 'agent/model', + mode: 'waterfall', + signature: '\'agent/model\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', + summary: 'Choose the provider, model, and reasoning effort for one proposed step.', + description: 'Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model\'s effort or omits it for the provider default. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step.', + parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], + }, { name: 'agent/pre-step', mode: 'waterfall', - signature: '\'agent/pre-step\'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; route: StepRoute; signal: AbortSignal }, next: () => Promise): Promise', + signature: '\'agent/pre-step\'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; modelSelection: ModelSelection; signal: AbortSignal }, next: () => Promise): Promise', summary: 'Reject a proposed step or replace the messages that enter it.', description: 'Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages.', parameters: [{ name: 'payload', description: '.signal - the current turn\'s cancellation signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], @@ -4005,7 +4013,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ mode: 'waterfall', signature: '\'agent/request\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', summary: 'Replace the frozen call configuration of one request attempt.', - description: 'Replace the frozen call configuration of one request attempt. `await next()` yields the config the machine would use on the step\'s `agent/route` result: agent options on the first request, the logged header afterwards, and no effort recorded for another model. Return a replacement to change call controls such as reasoning effort; returning another provider or model fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages.', + description: 'Replace the frozen call configuration of one request attempt. `await next()` yields the step\'s `agent/model` selection with the machine\'s other call controls: agent options on the first request, the logged header afterwards. Return a replacement to change sampling controls such as `maxTokens`, `temperature`, or `stop`; returning another provider, model, or reasoning effort fails the step. On step admission, this runs after prompt assembly and `step/start`, before the system prompt and accepted user batch are committed, and again for each retry. Cancellation here or during subsequent `prepareCall()` resolution commits neither. The prepared call capability governs prompt admission. Model-visible content must use logged channels; this waterfall cannot mutate messages.', parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, { @@ -4016,14 +4024,6 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Handle one failed model-request attempt before the loop retries or closes its step. A listener returns `{ kind: \'retry\' }` without calling `next()` when it owns recovery, or calls `next()` to delegate. The default `undefined` leaves the failure terminal.', parameters: [{ name: 'payload', description: '.signal - the turn abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, - { - name: 'agent/route', - mode: 'waterfall', - signature: '\'agent/route\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', - summary: 'Choose the provider and model for one proposed step.', - description: 'Choose the provider and model for one proposed step. `await next()` yields the route the machine would use (agent options before this loop logs a request, the logged header afterwards); return a replacement to switch. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step.', - parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], - }, { name: 'agent/status', mode: 'emit', @@ -7572,10 +7572,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SshStreamEndpoint', declaration: 'export type SshStreamEndpoint = z.infer;', }, - { - name: 'StepRoute', - declaration: 'export interface StepRoute {\n readonly provider: string;\n readonly model: string;\n}', - }, { name: 'StorageBackend', declaration: 'export interface StorageBackend {\n readonly kv?: KvFacet;\n close(): Promise;\n}', @@ -7966,7 +7962,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolActivationContext', - declaration: 'export interface ToolActivationContext {\n readonly agent: Agent;\n readonly route: StepRoute;\n readonly signal: AbortSignal;\n}', + declaration: 'export interface ToolActivationContext {\n readonly agent: Agent;\n readonly modelSelection: ModelSelection;\n readonly signal: AbortSignal;\n}', }, { name: 'ToolAdditionBlock', diff --git a/packages/llm/llm-deepseek/tests/account-routing.spec.ts b/packages/llm/llm-deepseek/tests/account-routing.spec.ts index 1db78b540d..5bd8df5261 100644 --- a/packages/llm/llm-deepseek/tests/account-routing.spec.ts +++ b/packages/llm/llm-deepseek/tests/account-routing.spec.ts @@ -94,12 +94,12 @@ it('replaces the active provider only after the next step request binds', async const proceed = Promise.withResolvers() const streaming = Promise.withResolvers() let steps = 0 - ctx.on('agent/route', async (_event, next) => { - const route = await next() - if (++steps === 1) return route + ctx.on('agent/model', async (_event, next) => { + const proposed = await next() + if (++steps === 1) return proposed preparing.resolve(undefined) await proceed.promise - return { ...route, provider: 'deepseek-official' } + return { ...proposed, provider: 'deepseek-official' } }) ctx.on('llm/stream', async function* (request) { if (request.provider === 'deepseek-account') { @@ -251,11 +251,11 @@ it('ignores idle account history but uses the last bound route during a new turn expect(cancel).not.toHaveBeenCalled() const preparing = Promise.withResolvers() const proceed = Promise.withResolvers() - ctx.on('agent/route', async (_event, next) => { - const route = await next() + ctx.on('agent/model', async (_event, next) => { + const proposed = await next() preparing.resolve(undefined) await proceed.promise - return { ...route, provider: 'deepseek-official' } + return { ...proposed, provider: 'deepseek-official' } }) try { send(agent) diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index 9cc4193e1c..7283896dcf 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -454,7 +454,7 @@ describe('Cordis provider composition', () => { ctx.on('system-prompt/assemble', async (_assembly, _context, next) => ({ ...await next(), sections: [{ name: 'test', text: prompt, order: 0 }], })) - const selection: ModelSelectionRef = { current: { provider: 'deepseek-official', model: MODEL }, assembled: undefined } + const selection: ModelSelectionRef = { current: { provider: 'deepseek-official', model: MODEL } } const agent = await ctx.agentLoop.create(SessionId('capability-switch'), selection.current) installModelSelection(agent.ctx, selection) await send(agent, 'first') diff --git a/packages/llm/llm-retry/tests/retry.spec.ts b/packages/llm/llm-retry/tests/retry.spec.ts index 3ab84ba450..c493e97f7c 100644 --- a/packages/llm/llm-retry/tests/retry.spec.ts +++ b/packages/llm/llm-retry/tests/retry.spec.ts @@ -524,7 +524,7 @@ describe('provider-routed retry policy', () => { expect(adapter.requests.map(request => request.provider)).toEqual(['mock', 'other', 'other']) }) - it('selects an always policy from the provider chosen by agent/route', async () => { + it('selects an always policy from the provider chosen by agent/model', async () => { vi.useFakeTimers() const adapter = new ScriptedAdapter([ new LlmError('rerouted auth failed', 'AUTH'), @@ -533,7 +533,7 @@ describe('provider-routed retry policy', () => { ;({ ctx: context } = await harness(adapter, { other: alwaysConfig({ initialDelayMs: 1, maxDelayMs: 1, jitterRatio: 0 }), }, (ctx) => { - ctx.on('agent/route', async (_payload, next) => ({ + ctx.on('agent/model', async (_payload, next) => ({ ...await next(), provider: 'other', })) diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index cbbbf44fa6..562dedadf8 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -19,7 +19,7 @@ import type { PlanModeConfig } from '../src/index.ts' import type { PlanUnitState } from '../src/types.ts' const testToolSignal = new AbortController().signal -const TEST_ROUTE = { provider: 'test', model: 'test' } +const TEST_MODEL_SELECTION = { provider: 'test', model: 'test' } const TEST_PLAN_SECTION = 'Test plan mode instructions.' const PLAN_CONFIG = { section: TEST_PLAN_SECTION } satisfies PlanModeConfig @@ -76,7 +76,7 @@ async function agentWithSession( } async function assembleFor(ctx: Context, agent: Agent) { - const toolSet = await ctx.tools.resolve({ agent, route: TEST_ROUTE, signal: testToolSignal }) + const toolSet = await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal: testToolSignal }) return ctx.systemPrompt.assemble({ agent, scope: agent, toolSet }) } @@ -117,7 +117,7 @@ async function boundary(ctx: Context, agent: Agent & { session: Session }, type: const signal = new AbortController().signal const decision = await events.waterfall( 'agent/pre-step', - { messages: [message], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + { messages: [message], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [message] }), ) if (decision.kind === 'enter') { @@ -798,7 +798,7 @@ describe('exit_plan_mode', () => { async function callExit(ctx: Context, agent: Agent | undefined, plan = '# The plan\n\ndo things') { const signal = new AbortController().signal - const toolSet = agent === undefined ? undefined : await ctx.tools.resolve({ agent, route: TEST_ROUTE, signal }) + const toolSet = agent === undefined ? undefined : await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal }) return ctx.tools.execute({ ...toolSet === undefined ? {} : { toolSet }, callId: ToolCallId(`call-exit-${++callCounter}`), @@ -933,7 +933,7 @@ describe('exit_plan_mode', () => { const agent = await agentWithSession(ctx, 'ptc-exit', { active: true }) const result = await ctx.tools.execute({ - toolSet: await ctx.tools.resolve({ agent, route: TEST_ROUTE, signal: testToolSignal }), + toolSet: await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal: testToolSignal }), callId: ToolCallId(`call-exit-${++callCounter}`), name: RUN_CODE_NAME, arguments: { code: `return await tools.${EXIT_PLAN_MODE}({ plan: ${JSON.stringify(plan)} })`, description: 'Submit the plan for review' }, @@ -1083,7 +1083,7 @@ describe('exit_plan_mode', () => { const { ctx, agent, asked } = await setupWithReview({ selected: ['Approve'] }) const controller = new AbortController() const result = await ctx.tools.execute({ - toolSet: await ctx.tools.resolve({ agent, route: TEST_ROUTE, signal: testToolSignal }), + toolSet: await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal: testToolSignal }), callId: ToolCallId(`call-exit-${++callCounter}`), name: EXIT_PLAN_MODE, arguments: { plan: '# P' }, diff --git a/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts b/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts index 84814ab160..d7991f7c0c 100644 --- a/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts +++ b/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts @@ -220,7 +220,7 @@ describe('session-checkpoint-policy tool and step boundaries', () => { ctx.on('session/flush', (current) => { flushed.push(current.id) }) const signal = new AbortController().signal await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter', messages: [] }), ) expect(flushed).toEqual([session.id]) diff --git a/packages/skill/tool-skill/tests/tool-skill.spec.ts b/packages/skill/tool-skill/tests/tool-skill.spec.ts index d2d8ef53ed..b1bfb6776f 100644 --- a/packages/skill/tool-skill/tests/tool-skill.spec.ts +++ b/packages/skill/tool-skill/tests/tool-skill.spec.ts @@ -116,7 +116,7 @@ async function fireStep(ctx: Context, agent: Agent, turn: number, step: number): const signal = new AbortController().signal const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn, step, route: { provider: 'test', model: 'test' }, signal }, + { messages: [], turn, step, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { @@ -134,7 +134,7 @@ async function proposeStep( const signal = new AbortController().signal return await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages, turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + { messages, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages }), ) } @@ -166,7 +166,7 @@ async function composePrefix(ctx: Context, cwd: string, signal = new AbortContro async function composePrefixForAgent(ctx: Context, agent: Agent, signal = new AbortController().signal): Promise { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { @@ -1104,7 +1104,7 @@ describe('user-explicit invocation injection', () => { const signal = new AbortController().signal const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [gesture('/hidden-demo blocked step')], turn: 1, step: 1, route: { provider: 'test', model: 'test' }, signal }, + { messages: [gesture('/hidden-demo blocked step')], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, () => Promise.resolve({ kind: 'reject' as const }), ) expect(decision).toEqual({ kind: 'reject' }) diff --git a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts index 641b82384b..73facabf80 100644 --- a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts @@ -274,7 +274,7 @@ describe('SubagentModelSelectionConfig', () => { messages: [], turn: 1, step: 1, - route: { provider: 'test', model: 'test' }, + modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal, } await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next)) diff --git a/packages/test-support/loader-smoke/tests/fixtures/cli-mock-llm.ts b/packages/test-support/loader-smoke/tests/fixtures/cli-mock-llm.ts index 4dbdb23b0b..38f7e23537 100644 --- a/packages/test-support/loader-smoke/tests/fixtures/cli-mock-llm.ts +++ b/packages/test-support/loader-smoke/tests/fixtures/cli-mock-llm.ts @@ -72,8 +72,8 @@ export const inject = ['llm'] /** Register the keyless `cli-mock` adapter. */ export function apply(ctx: Context): void { ctx.llm.registerAdapter(['cli-mock'], new CliMockAdapter()) - ctx.on('agent/request', async ({ step }, next) => { - const config = await next() - return step === 2 ? { ...config, reasoningEffort: OFF } : config + ctx.on('agent/model', async ({ step }, next) => { + const selection = await next() + return step === 2 ? { ...selection, reasoningEffort: OFF } : selection }) } diff --git a/scripts/fixtures/python-sdk-dynamic-tools.mjs b/scripts/fixtures/python-sdk-dynamic-tools.mjs index f884b925a5..99fc3722db 100644 --- a/scripts/fixtures/python-sdk-dynamic-tools.mjs +++ b/scripts/fixtures/python-sdk-dynamic-tools.mjs @@ -14,7 +14,7 @@ export function apply(ctx) { render(_args, value) { return [{ type: 'text', text: value }] }, }, async execute() { return 'pong' }, - }, { when: async ({ route }) => active && route.provider === 'deepseek-official' }) + }, { when: async ({ modelSelection }) => active && modelSelection.provider === 'deepseek-official' }) ctx.on('tools/post-execute', async (exec, result, next) => { const downstream = await next() if (result.isError) return downstream diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 8c850099de..cc6c784e55 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -334,7 +334,6 @@ export const LINK_MAP: Readonly> = { InspectorJsonValue: 'extensions.md', MessageId: 'llm-streaming.md', ResumeAgentOptions: 'core.md', - StepRoute: 'core.md', SettleReason: 'core.md', AdapterRegistrationHandle: 'llm-streaming.md', DirectoryRegistrationHandle: 'llm-streaming.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 984bbb8ccd..01c3f8376b 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1548,17 +1548,17 @@ function renderLifecycle(): string { ' Note over Agent,Driver: claim pending next-step input plus one queued prompt', ` Driver-->>SDK: ${mermaidCode('agent/inbox/spliced')} pure deletion`, ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, - ` Driver->>Hooks: ${mermaidCode('agent/route')} waterfall chooses the step route`, - ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall on the step route`, - ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall with the step route`, + ` Driver->>Hooks: ${mermaidCode('agent/model')} waterfall chooses the step provider, model, and effort`, + ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall with the step model selection`, + ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall with the step model selection`, ' Hooks-->>Driver: authoritative reject or enter(messages)', ' alt proposed step rejected, first batch empty, or pre-step failed', ' Driver-->>Driver: claimed batch stays removed, the open turn spends no step', ' else enter proposed step', ` Driver->>Session: ${mermaidCode('step/start')}`, - ' Driver->>Tools: resolve({ agent, route, signal }) once per step', + ' Driver->>Tools: resolve({ agent, modelSelection, signal }) once per step', ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} with the step tool set`, - ` Driver->>Hooks: ${mermaidCode('agent/request')} waterfall on the step route`, + ` Driver->>Hooks: ${mermaidCode('agent/request')} waterfall with the step model selection`, ' Driver->>LLM: prepareCall(config, signal)', ' Note over Driver,LLM: cancellation during preparation commits neither system nor users', ' Note over Driver,Session: synchronous admission using the prepared call capability', @@ -1574,7 +1574,7 @@ function renderLifecycle(): string { ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`, ` Driver->>Hooks: ${mermaidCode('agent/request-error')} waterfall`, ' Hooks-->>Driver: return retry action or preserve the original error', - ' Note over Driver,LLM: retry in the open step: request and prepare again on the same route, tool set, and prompt without repeating pre-step or users', + ' Note over Driver,LLM: retry in the open step: request and prepare again with the same model selection, tool set, and prompt without repeating pre-step or users', ' else model request succeeded', ` Driver->>Session: ${mermaidCode('assistant/message')}`, ` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`, @@ -1598,7 +1598,7 @@ function renderLifecycle(): string { ' opt next-step input is pending', ' Driver-->>Driver: claim pending next-step input', ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, - ` Driver->>Hooks: ${mermaidCode('agent/route')} waterfall`, + ` Driver->>Hooks: ${mermaidCode('agent/model')} waterfall`, ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall`, ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`, ' Hooks-->>Driver: authoritative reject or enter(messages)', @@ -1611,7 +1611,7 @@ function renderLifecycle(): string { '', 'The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes, and embeds the exact compact timed stream. Empty content stays out of derived history. A failed, retried, cancelled, or stream-error attempt that reaches settlement without a surface message records its stream as `assistant/attempt`. Live `agent/assistant-stream` chunk frames are transient; replay reads either durable settlement, and a hard process loss before settlement leaves no durable attempt stream.', '', - '`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call on the step route and reconciles the retained rendered assembly before request derivation, without repeating routing, tool resolution, assembly, pre-step, or user admission.', + '`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 runs within the open step and retries only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative. Each retry prepares its call with the step model selection and reconciles the retained rendered assembly before request derivation, without repeating model selection, tool resolution, assembly, pre-step, or user admission.', '', '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.', '', diff --git a/scripts/python-snapshot-workflow-order.spec.ts b/scripts/python-snapshot-workflow-order.spec.ts index 6a6881797b..3461e5faf6 100644 --- a/scripts/python-snapshot-workflow-order.spec.ts +++ b/scripts/python-snapshot-workflow-order.spec.ts @@ -44,7 +44,7 @@ async function harness(direct = false) { runId: WorkflowRunId('run'), seq: 1, label: 'workflow-child', childId, }) const step = (overrides = {}) => agentEvents(ctx, agent).waterfall('agent/pre-step', { - turn: 1, step: 1, messages, route: { provider: 'test', model: 'test' }, signal: controller.signal, ...overrides, + turn: 1, step: 1, messages, modelSelection: { provider: 'test', model: 'test' }, signal: controller.signal, ...overrides, }, next) return { ctx, fiber, parent, other, session, agent, controller, decision, next, start, step } } diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 9c8493b0c3..87722d211c 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2153,7 +2153,7 @@ }, { "doc": "docs/subsystems/core.md", - "symbol": "StepRoute", + "symbol": "ModelSelection", "source": "packages/core/agent/src/runtime-types.ts" }, { diff --git a/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl b/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl index f53dd034a2..1ba3ffbed5 100644 --- a/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl +++ b/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Inspect the exact tools service","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788778145981,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788778145981,"index":0,"dt":[],"id":"inspect-tools-api","name":"cordis_inspect_query","args":["{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"]},{"type":"chunk","time":1788778145981,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}}},{"type":"chunk","time":1788778145981,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788778145981,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"inspect-tools-api"},"toolCallId":"inspect-tools-api","content":[{"type":"text","text":"{\n \"platform\": \"host\",\n \"provider\": \"Service\",\n \"method\": \"listService\",\n \"data\": {\n \"mode\": \"service\",\n \"service\": {\n \"key\": \"tools\",\n \"description\": \"Tool registry and execution pipeline. Scoped registrations shadow globals; one visibility resolver feeds presentation, lookup, and dispatch.\",\n \"access\": {\n \"optional\": {\n \"expression\": \"ctx.get(\\\"tools\\\")\",\n \"requiresUndefinedCheck\": true\n },\n \"hardDependency\": {\n \"inject\": [\n \"tools\"\n ],\n \"expression\": \"ctx.tools\"\n }\n },\n \"methods\": [\n {\n \"signature\": \"presentAs(mode: ToolPresentationMode): () => void\",\n \"description\": \"Present the calling scope's tools in `mode` instead of the deployment default. Nearest scope on the chain wins, so a preset's standing declaration covers every agent joined under it.\\n\\nScoped only, and one declaration per scope: this is how an agent preset composes PTC mode agents beside native ones in the same process, and a process-global override would be the `mode` config field instead.\",\n \"parameters\": [\n {\n \"name\": \"mode\",\n \"description\": \"the presentation the covered agents' models see.\"\n }\n ],\n \"returns\": \"the exact disposer that restores the deployment default.\"\n },\n {\n \"signature\": \"register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void\",\n \"description\": \"Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.\",\n \"parameters\": [\n {\n \"name\": \"definition\",\n \"description\": \"tool schema, execution, and optional finalization/presentation callbacks.\"\n },\n {\n \"name\": \"options\",\n \"description\": \"optional step-time activation condition.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the tool.\"\n },\n {\n \"signature\": \"restrict(filter: ToolRestriction): () => void\",\n \"description\": \"Restrict global tools for the calling agent scope. Empty filters, unknown names, scope-local names, and reserved transport names fail. Restrictions intersect; scoped registrations remain visible.\",\n \"parameters\": [\n {\n \"name\": \"filter\",\n \"description\": \"global-tool mask: `allow` (keep only) and/or `deny` (remove).\"\n }\n ],\n \"returns\": \"the exact disposer that lifts this restriction.\"\n },\n {\n \"signature\": \"guard(guard: ToolGuard): () => void\",\n \"description\": \"Register a monotonic guard after the extensible `tools/pre-execute` waterfall. A plain-context guard applies globally; one registered through `agent.ctx` applies only to that agent. Any matching guard may deny by returning a reason, while no guard can force-allow a call another guard denied. The exact effect disposer is returned for ordered ownership and HMR cleanup.\",\n \"parameters\": [\n {\n \"name\": \"guard\",\n \"description\": \"synchronous check; a returned string denies the execution.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the guard.\"\n },\n {\n \"signature\": \"get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined\",\n \"description\": \"Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.\",\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the tool name as registered.\"\n },\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission; omit only to inspect registered definitions.\"\n }\n ],\n \"returns\": \"the definition the scope resolves, or undefined when none is visible.\"\n },\n {\n \"signature\": \"async resolve(context: ToolActivationContext): Promise\",\n \"description\": \"Resolve conditions once for this step without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.\",\n \"parameters\": [\n {\n \"name\": \"context\",\n \"description\": \"preparing agent, step route, and cancellation.\"\n }\n ],\n \"returns\": \"the complete selection; the caller disposes it after its tool batch settles.\"\n },\n {\n \"signature\": \"schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]\",\n \"description\": \"Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.\",\n \"parameters\": [\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission, or omitted for registered-definition inspection.\"\n }\n ],\n \"returns\": \"one deep-cloned schema per visible tool.\"\n },\n {\n \"signature\": \"executionMode(exec: ToolExecutionInput): ToolExecutionMode\",\n \"description\": \"Classify a pending call through the caller's visible tool definition. Only an exact `true` is parallel; unknown, hidden, undeclared, invalid, or throwing classifiers are exclusive.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"call name, parsed arguments, and optional agent scope.\"\n }\n ],\n \"returns\": \"the fail-closed scheduling mode.\"\n },\n {\n \"signature\": \"async execute(exec: ToolExecutionInput): Promise\",\n \"description\": \"Execute through pre-policy, guards, around-dispatch, post-policy, definition-owned content finalization, and final notification. Tool and listener failures resolve as materialized error results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen snapshot final observers receive. Cancellation arriving after entry and before final result materialization skips a not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a successful started outcome with `ABORTED`; already-started work is still drained and may retain a tool-owned structured error.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"the typed same-process call input. The registry assigns its correlation token before policy begins.\"\n }\n ],\n \"returns\": \"the materialized final result.\"\n }\n ]\n },\n \"referencedTypes\": [\n {\n \"name\": \"Agent\",\n \"declaration\": \"export interface Agent {\\n readonly id: SessionId;\\n}\"\n },\n {\n \"name\": \"Branded\",\n \"declaration\": \"export type Branded = string & {\\n readonly [BRAND]: B;\\n};\"\n },\n {\n \"name\": \"DiffCallView\",\n \"declaration\": \"export interface DiffCallView {\\n card: 'diff';\\n title: string;\\n diffs: FileDiff[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"DiffResultView\",\n \"declaration\": \"export interface DiffResultView {\\n card: 'diff';\\n title?: string;\\n diffs: FileDiff[];\\n}\"\n },\n {\n \"name\": \"FileDiff\",\n \"declaration\": \"export interface FileDiff {\\n path: string;\\n oldText: string | null;\\n newText: string;\\n}\"\n },\n {\n \"name\": \"FileLocation\",\n \"declaration\": \"export interface FileLocation {\\n path: string;\\n line?: number;\\n}\"\n },\n {\n \"name\": \"GenericCallView\",\n \"declaration\": \"export interface GenericCallView {\\n card: 'generic';\\n title: string;\\n kind?: ToolCallKind;\\n rawInput?: unknown;\\n content?: ContentBlock[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"GenericResultView\",\n \"declaration\": \"export interface GenericResultView {\\n card: 'generic';\\n title?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"JsonSchemaNode\",\n \"declaration\": \"export interface JsonSchemaNode {\\n type?: JsonSchemaType;\\n oneOf?: JsonSchemaNode[];\\n properties?: Record;\\n required?: string[];\\n additionalProperties?: boolean;\\n items?: JsonSchemaNode;\\n enum?: JsonSchemaScalar[];\\n const?: JsonSchemaScalar;\\n description?: string;\\n title?: string;\\n default?: JsonValue;\\n examples?: JsonValue;\\n}\"\n },\n {\n \"name\": \"JsonSchemaScalar\",\n \"declaration\": \"export type JsonSchemaScalar = string | number | boolean | null;\"\n },\n {\n \"name\": \"JsonSchemaType\",\n \"declaration\": \"export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\"\n },\n {\n \"name\": \"JsonValue\",\n \"declaration\": \"export type JsonValue = null | boolean | number | string | JsonValue[] | {\\n [key: string]: JsonValue;\\n};\"\n },\n {\n \"name\": \"ReadFileLine\",\n \"declaration\": \"export interface ReadFileLine {\\n number: number;\\n text: string;\\n}\"\n },\n {\n \"name\": \"ReadResultView\",\n \"declaration\": \"export interface ReadResultView {\\n card: 'read';\\n title?: string;\\n path: string;\\n offset: number;\\n lines: ReadFileLine[];\\n totalLines: number;\\n lang?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"ResolvedToolSet\",\n \"declaration\": \"export interface ResolvedToolSet {\\n dispose(): void;\\n view(scope: ScopeKey | undefined): ReadonlyMap;\\n}\"\n },\n {\n \"name\": \"ScopeKey\",\n \"declaration\": \"export type ScopeKey = object;\"\n },\n {\n \"name\": \"SearchFileMatches\",\n \"declaration\": \"export interface SearchFileMatches {\\n path: string;\\n matches: SearchLineMatch[];\\n}\"\n },\n {\n \"name\": \"SearchLineMatch\",\n \"declaration\": \"export interface SearchLineMatch {\\n lineNumber: number;\\n line: string;\\n}\"\n },\n {\n \"name\": \"SearchMatchesResultView\",\n \"declaration\": \"export interface SearchMatchesResultView {\\n card: 'search';\\n shape: 'matches';\\n title?: string;\\n files: SearchFileMatches[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchPathsResultView\",\n \"declaration\": \"export interface SearchPathsResultView {\\n card: 'search';\\n shape: 'paths';\\n title?: string;\\n paths: string[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchResultView\",\n \"declaration\": \"export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;\"\n },\n {\n \"name\": \"SessionId\",\n \"declaration\": \"export type SessionId = Branded<'SessionId'>;\"\n },\n {\n \"name\": \"StepRoute\",\n \"declaration\": \"export interface StepRoute {\\n readonly provider: string;\\n readonly model: string;\\n}\"\n },\n {\n \"name\": \"TerminalCallView\",\n \"declaration\": \"export interface TerminalCallView {\\n card: 'terminal';\\n title: string;\\n description?: string;\\n cwd?: string;\\n}\"\n },\n {\n \"name\": \"TerminalResultView\",\n \"declaration\": \"export interface TerminalResultView {\\n card: 'terminal';\\n title?: string;\\n output?: string;\\n exitCode?: number;\\n signal?: string;\\n}\"\n },\n {\n \"name\": \"ToolActivationContext\",\n \"declaration\": \"export interface ToolActivationContext {\\n readonly agent: Agent;\\n readonly route: StepRoute;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolCallId\",\n \"declaration\": \"export type ToolCallId = Branded<'ToolCallId'>;\"\n },\n {\n \"name\": \"ToolCallKind\",\n \"declaration\": \"export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\"\n },\n {\n \"name\": \"ToolCallView\",\n \"declaration\": \"export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\"\n },\n {\n \"name\": \"ToolDefinition\",\n \"declaration\": \"export interface ToolDefinition extends ToolSchema {\\n readonly output: ToolOutputDefinition;\\n execute(args: unknown, exec: ToolRunContext): Promise;\\n projectContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n timeoutMs?: number;\\n isConcurrencySafe?(args: unknown): boolean;\\n presentCall?(args: unknown): ToolCallView | undefined;\\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\\n}\"\n },\n {\n \"name\": \"ToolErrorInfo\",\n \"declaration\": \"export interface ToolErrorInfo {\\n name: string;\\n code: string;\\n reason?: string;\\n}\"\n },\n {\n \"name\": \"ToolExecution\",\n \"declaration\": \"export interface ToolExecution extends ToolExecutionInput {\\n readonly rootCallId: ToolCallId;\\n readonly token: ToolExecutionToken;\\n}\"\n },\n {\n \"name\": \"ToolExecutionFailure\",\n \"declaration\": \"export interface ToolExecutionFailure {\\n readonly isError: true;\\n readonly error: ToolFailure;\\n readonly value?: never;\\n readonly content: ContentBlock[];\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: never;\\n}\"\n },\n {\n \"name\": \"ToolExecutionInput\",\n \"declaration\": \"export interface ToolExecutionInput {\\n readonly callId: ToolCallId;\\n readonly rootCallId?: ToolCallId;\\n readonly name: string;\\n readonly schema?: ToolSchema;\\n readonly arguments: unknown;\\n readonly agent?: Agent;\\n readonly toolSet?: ResolvedToolSet;\\n readonly parent?: ToolExecutionToken;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolExecutionMode\",\n \"declaration\": \"export type ToolExecutionMode = {\\n kind: 'parallel';\\n} | {\\n kind: 'exclusive';\\n};\"\n },\n {\n \"name\": \"ToolExecutionResult\",\n \"declaration\": \"export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\"\n },\n {\n \"name\": \"ToolExecutionSuccess\",\n \"declaration\": \"export interface ToolExecutionSuccess {\\n readonly isError: false;\\n readonly value: JsonValue;\\n readonly content: ContentBlock[];\\n readonly error?: never;\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: true;\\n}\"\n },\n {\n \"name\": \"ToolExecutionToken\",\n \"declaration\": \"export type ToolExecutionToken = symbol & {\\n readonly [toolExecutionTokenBrand]: true;\\n};\"\n },\n {\n \"name\": \"ToolFailure\",\n \"declaration\": \"export interface ToolFailure {\\n message: string;\\n info?: ToolErrorInfo;\\n}\"\n },\n {\n \"name\": \"ToolGuard\",\n \"declaration\": \"export type ToolGuard = (execution: Readonly) => string | undefined;\"\n },\n {\n \"name\": \"ToolOutputDefinition\",\n \"declaration\": \"export interface ToolOutputDefinition {\\n readonly schema: JsonSchemaNode;\\n render(args: unknown, value: JsonValue): ContentBlock[];\\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolPresentationMode\",\n \"declaration\": \"export type ToolPresentationMode = 'native' | 'ptc';\"\n },\n {\n \"name\": \"ToolRegistrationOptions\",\n \"declaration\": \"export interface ToolRegistrationOptions {\\n readonly when?: (context: ToolActivationContext) => boolean | Promise;\\n}\"\n },\n {\n \"name\": \"ToolRestriction\",\n \"declaration\": \"export interface ToolRestriction {\\n readonly allow?: readonly string[];\\n readonly deny?: readonly string[];\\n}\"\n },\n {\n \"name\": \"ToolResult\",\n \"declaration\": \"export interface ToolResult {\\n content: ContentBlock[];\\n isError: boolean;\\n meta?: JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolResultView\",\n \"declaration\": \"export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | SearchResultView | ReadResultView | WebResultView;\"\n },\n {\n \"name\": \"ToolRunContext\",\n \"declaration\": \"export interface ToolRunContext extends ToolExecution {\\n deferContext(context: UserMessage): void;\\n concludeTurn(): void;\\n}\"\n },\n {\n \"name\": \"ToolSchema\",\n \"declaration\": \"export interface ToolSchema {\\n deferLoading?: true;\\n name: string;\\n description: string;\\n parameters: Record;\\n}\"\n },\n {\n \"name\": \"UserMessage\",\n \"declaration\": \"export interface UserMessage extends MessageBase {\\n readonly role: 'user';\\n}\"\n },\n {\n \"name\": \"WebFetchResultView\",\n \"declaration\": \"export interface WebFetchResultView {\\n card: 'web';\\n kind: 'fetch';\\n title?: string;\\n url: string;\\n statusCode: number;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebResultView\",\n \"declaration\": \"export type WebResultView = WebSearchResultView | WebFetchResultView;\"\n },\n {\n \"name\": \"WebSearchResultView\",\n \"declaration\": \"export interface WebSearchResultView {\\n card: 'web';\\n kind: 'search';\\n title?: string;\\n sources: WebSource[];\\n answer?: string;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebSource\",\n \"declaration\": \"export interface WebSource {\\n url: string;\\n title?: string;\\n snippet?: string;\\n publishedAt?: string;\\n}\"\n }\n ]\n }\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"inspect-tools-api"},"toolCallId":"inspect-tools-api","content":[{"type":"text","text":"{\n \"platform\": \"host\",\n \"provider\": \"Service\",\n \"method\": \"listService\",\n \"data\": {\n \"mode\": \"service\",\n \"service\": {\n \"key\": \"tools\",\n \"description\": \"Tool registry and execution pipeline. Scoped registrations shadow globals; one visibility resolver feeds presentation, lookup, and dispatch.\",\n \"access\": {\n \"optional\": {\n \"expression\": \"ctx.get(\\\"tools\\\")\",\n \"requiresUndefinedCheck\": true\n },\n \"hardDependency\": {\n \"inject\": [\n \"tools\"\n ],\n \"expression\": \"ctx.tools\"\n }\n },\n \"methods\": [\n {\n \"signature\": \"presentAs(mode: ToolPresentationMode): () => void\",\n \"description\": \"Present the calling scope's tools in `mode` instead of the deployment default. Nearest scope on the chain wins, so a preset's standing declaration covers every agent joined under it.\\n\\nScoped only, and one declaration per scope: this is how an agent preset composes PTC mode agents beside native ones in the same process, and a process-global override would be the `mode` config field instead.\",\n \"parameters\": [\n {\n \"name\": \"mode\",\n \"description\": \"the presentation the covered agents' models see.\"\n }\n ],\n \"returns\": \"the exact disposer that restores the deployment default.\"\n },\n {\n \"signature\": \"register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void\",\n \"description\": \"Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.\",\n \"parameters\": [\n {\n \"name\": \"definition\",\n \"description\": \"tool schema, execution, and optional finalization/presentation callbacks.\"\n },\n {\n \"name\": \"options\",\n \"description\": \"optional step-time activation condition.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the tool.\"\n },\n {\n \"signature\": \"restrict(filter: ToolRestriction): () => void\",\n \"description\": \"Restrict global tools for the calling agent scope. Empty filters, unknown names, scope-local names, and reserved transport names fail. Restrictions intersect; scoped registrations remain visible.\",\n \"parameters\": [\n {\n \"name\": \"filter\",\n \"description\": \"global-tool mask: `allow` (keep only) and/or `deny` (remove).\"\n }\n ],\n \"returns\": \"the exact disposer that lifts this restriction.\"\n },\n {\n \"signature\": \"guard(guard: ToolGuard): () => void\",\n \"description\": \"Register a monotonic guard after the extensible `tools/pre-execute` waterfall. A plain-context guard applies globally; one registered through `agent.ctx` applies only to that agent. Any matching guard may deny by returning a reason, while no guard can force-allow a call another guard denied. The exact effect disposer is returned for ordered ownership and HMR cleanup.\",\n \"parameters\": [\n {\n \"name\": \"guard\",\n \"description\": \"synchronous check; a returned string denies the execution.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the guard.\"\n },\n {\n \"signature\": \"get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined\",\n \"description\": \"Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.\",\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the tool name as registered.\"\n },\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission; omit only to inspect registered definitions.\"\n }\n ],\n \"returns\": \"the definition the scope resolves, or undefined when none is visible.\"\n },\n {\n \"signature\": \"async resolve(context: ToolActivationContext): Promise\",\n \"description\": \"Resolve conditions once for this step without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.\",\n \"parameters\": [\n {\n \"name\": \"context\",\n \"description\": \"preparing agent, step model selection, and cancellation.\"\n }\n ],\n \"returns\": \"the complete selection; the caller disposes it after its tool batch settles.\"\n },\n {\n \"signature\": \"schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]\",\n \"description\": \"Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.\",\n \"parameters\": [\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission, or omitted for registered-definition inspection.\"\n }\n ],\n \"returns\": \"one deep-cloned schema per visible tool.\"\n },\n {\n \"signature\": \"executionMode(exec: ToolExecutionInput): ToolExecutionMode\",\n \"description\": \"Classify a pending call through the caller's visible tool definition. Only an exact `true` is parallel; unknown, hidden, undeclared, invalid, or throwing classifiers are exclusive.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"call name, parsed arguments, and optional agent scope.\"\n }\n ],\n \"returns\": \"the fail-closed scheduling mode.\"\n },\n {\n \"signature\": \"async execute(exec: ToolExecutionInput): Promise\",\n \"description\": \"Execute through pre-policy, guards, around-dispatch, post-policy, definition-owned content finalization, and final notification. Tool and listener failures resolve as materialized error results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen snapshot final observers receive. Cancellation arriving after entry and before final result materialization skips a not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a successful started outcome with `ABORTED`; already-started work is still drained and may retain a tool-owned structured error.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"the typed same-process call input. The registry assigns its correlation token before policy begins.\"\n }\n ],\n \"returns\": \"the materialized final result.\"\n }\n ]\n },\n \"referencedTypes\": [\n {\n \"name\": \"Agent\",\n \"declaration\": \"export interface Agent {\\n readonly id: SessionId;\\n}\"\n },\n {\n \"name\": \"Branded\",\n \"declaration\": \"export type Branded = string & {\\n readonly [BRAND]: B;\\n};\"\n },\n {\n \"name\": \"DiffCallView\",\n \"declaration\": \"export interface DiffCallView {\\n card: 'diff';\\n title: string;\\n diffs: FileDiff[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"DiffResultView\",\n \"declaration\": \"export interface DiffResultView {\\n card: 'diff';\\n title?: string;\\n diffs: FileDiff[];\\n}\"\n },\n {\n \"name\": \"FileDiff\",\n \"declaration\": \"export interface FileDiff {\\n path: string;\\n oldText: string | null;\\n newText: string;\\n}\"\n },\n {\n \"name\": \"FileLocation\",\n \"declaration\": \"export interface FileLocation {\\n path: string;\\n line?: number;\\n}\"\n },\n {\n \"name\": \"GenericCallView\",\n \"declaration\": \"export interface GenericCallView {\\n card: 'generic';\\n title: string;\\n kind?: ToolCallKind;\\n rawInput?: unknown;\\n content?: ContentBlock[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"GenericResultView\",\n \"declaration\": \"export interface GenericResultView {\\n card: 'generic';\\n title?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"JsonSchemaNode\",\n \"declaration\": \"export interface JsonSchemaNode {\\n type?: JsonSchemaType;\\n oneOf?: JsonSchemaNode[];\\n properties?: Record;\\n required?: string[];\\n additionalProperties?: boolean;\\n items?: JsonSchemaNode;\\n enum?: JsonSchemaScalar[];\\n const?: JsonSchemaScalar;\\n description?: string;\\n title?: string;\\n default?: JsonValue;\\n examples?: JsonValue;\\n}\"\n },\n {\n \"name\": \"JsonSchemaScalar\",\n \"declaration\": \"export type JsonSchemaScalar = string | number | boolean | null;\"\n },\n {\n \"name\": \"JsonSchemaType\",\n \"declaration\": \"export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\"\n },\n {\n \"name\": \"JsonValue\",\n \"declaration\": \"export type JsonValue = null | boolean | number | string | JsonValue[] | {\\n [key: string]: JsonValue;\\n};\"\n },\n {\n \"name\": \"ReadFileLine\",\n \"declaration\": \"export interface ReadFileLine {\\n number: number;\\n text: string;\\n}\"\n },\n {\n \"name\": \"ReadResultView\",\n \"declaration\": \"export interface ReadResultView {\\n card: 'read';\\n title?: string;\\n path: string;\\n offset: number;\\n lines: ReadFileLine[];\\n totalLines: number;\\n lang?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"ResolvedToolSet\",\n \"declaration\": \"export interface ResolvedToolSet {\\n dispose(): void;\\n view(scope: ScopeKey | undefined): ReadonlyMap;\\n}\"\n },\n {\n \"name\": \"ScopeKey\",\n \"declaration\": \"export type ScopeKey = object;\"\n },\n {\n \"name\": \"SearchFileMatches\",\n \"declaration\": \"export interface SearchFileMatches {\\n path: string;\\n matches: SearchLineMatch[];\\n}\"\n },\n {\n \"name\": \"SearchLineMatch\",\n \"declaration\": \"export interface SearchLineMatch {\\n lineNumber: number;\\n line: string;\\n}\"\n },\n {\n \"name\": \"SearchMatchesResultView\",\n \"declaration\": \"export interface SearchMatchesResultView {\\n card: 'search';\\n shape: 'matches';\\n title?: string;\\n files: SearchFileMatches[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchPathsResultView\",\n \"declaration\": \"export interface SearchPathsResultView {\\n card: 'search';\\n shape: 'paths';\\n title?: string;\\n paths: string[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchResultView\",\n \"declaration\": \"export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;\"\n },\n {\n \"name\": \"SessionId\",\n \"declaration\": \"export type SessionId = Branded<'SessionId'>;\"\n },\n {\n \"name\": \"TerminalCallView\",\n \"declaration\": \"export interface TerminalCallView {\\n card: 'terminal';\\n title: string;\\n description?: string;\\n cwd?: string;\\n}\"\n },\n {\n \"name\": \"TerminalResultView\",\n \"declaration\": \"export interface TerminalResultView {\\n card: 'terminal';\\n title?: string;\\n output?: string;\\n exitCode?: number;\\n signal?: string;\\n}\"\n },\n {\n \"name\": \"ToolActivationContext\",\n \"declaration\": \"export interface ToolActivationContext {\\n readonly agent: Agent;\\n readonly modelSelection: ModelSelection;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolCallId\",\n \"declaration\": \"export type ToolCallId = Branded<'ToolCallId'>;\"\n },\n {\n \"name\": \"ToolCallKind\",\n \"declaration\": \"export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\"\n },\n {\n \"name\": \"ToolCallView\",\n \"declaration\": \"export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\"\n },\n {\n \"name\": \"ToolDefinition\",\n \"declaration\": \"export interface ToolDefinition extends ToolSchema {\\n readonly output: ToolOutputDefinition;\\n execute(args: unknown, exec: ToolRunContext): Promise;\\n projectContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n timeoutMs?: number;\\n isConcurrencySafe?(args: unknown): boolean;\\n presentCall?(args: unknown): ToolCallView | undefined;\\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\\n}\"\n },\n {\n \"name\": \"ToolErrorInfo\",\n \"declaration\": \"export interface ToolErrorInfo {\\n name: string;\\n code: string;\\n reason?: string;\\n}\"\n },\n {\n \"name\": \"ToolExecution\",\n \"declaration\": \"export interface ToolExecution extends ToolExecutionInput {\\n readonly rootCallId: ToolCallId;\\n readonly token: ToolExecutionToken;\\n}\"\n },\n {\n \"name\": \"ToolExecutionFailure\",\n \"declaration\": \"export interface ToolExecutionFailure {\\n readonly isError: true;\\n readonly error: ToolFailure;\\n readonly value?: never;\\n readonly content: ContentBlock[];\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: never;\\n}\"\n },\n {\n \"name\": \"ToolExecutionInput\",\n \"declaration\": \"export interface ToolExecutionInput {\\n readonly callId: ToolCallId;\\n readonly rootCallId?: ToolCallId;\\n readonly name: string;\\n readonly schema?: ToolSchema;\\n readonly arguments: unknown;\\n readonly agent?: Agent;\\n readonly toolSet?: ResolvedToolSet;\\n readonly parent?: ToolExecutionToken;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolExecutionMode\",\n \"declaration\": \"export type ToolExecutionMode = {\\n kind: 'parallel';\\n} | {\\n kind: 'exclusive';\\n};\"\n },\n {\n \"name\": \"ToolExecutionResult\",\n \"declaration\": \"export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\"\n },\n {\n \"name\": \"ToolExecutionSuccess\",\n \"declaration\": \"export interface ToolExecutionSuccess {\\n readonly isError: false;\\n readonly value: JsonValue;\\n readonly content: ContentBlock[];\\n readonly error?: never;\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: true;\\n}\"\n },\n {\n \"name\": \"ToolExecutionToken\",\n \"declaration\": \"export type ToolExecutionToken = symbol & {\\n readonly [toolExecutionTokenBrand]: true;\\n};\"\n },\n {\n \"name\": \"ToolFailure\",\n \"declaration\": \"export interface ToolFailure {\\n message: string;\\n info?: ToolErrorInfo;\\n}\"\n },\n {\n \"name\": \"ToolGuard\",\n \"declaration\": \"export type ToolGuard = (execution: Readonly) => string | undefined;\"\n },\n {\n \"name\": \"ToolOutputDefinition\",\n \"declaration\": \"export interface ToolOutputDefinition {\\n readonly schema: JsonSchemaNode;\\n render(args: unknown, value: JsonValue): ContentBlock[];\\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolPresentationMode\",\n \"declaration\": \"export type ToolPresentationMode = 'native' | 'ptc';\"\n },\n {\n \"name\": \"ToolRegistrationOptions\",\n \"declaration\": \"export interface ToolRegistrationOptions {\\n readonly when?: (context: ToolActivationContext) => boolean | Promise;\\n}\"\n },\n {\n \"name\": \"ToolRestriction\",\n \"declaration\": \"export interface ToolRestriction {\\n readonly allow?: readonly string[];\\n readonly deny?: readonly string[];\\n}\"\n },\n {\n \"name\": \"ToolResult\",\n \"declaration\": \"export interface ToolResult {\\n content: ContentBlock[];\\n isError: boolean;\\n meta?: JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolResultView\",\n \"declaration\": \"export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | SearchResultView | ReadResultView | WebResultView;\"\n },\n {\n \"name\": \"ToolRunContext\",\n \"declaration\": \"export interface ToolRunContext extends ToolExecution {\\n deferContext(context: UserMessage): void;\\n concludeTurn(): void;\\n}\"\n },\n {\n \"name\": \"ToolSchema\",\n \"declaration\": \"export interface ToolSchema {\\n deferLoading?: true;\\n name: string;\\n description: string;\\n parameters: Record;\\n}\"\n },\n {\n \"name\": \"UserMessage\",\n \"declaration\": \"export interface UserMessage extends MessageBase {\\n readonly role: 'user';\\n}\"\n },\n {\n \"name\": \"WebFetchResultView\",\n \"declaration\": \"export interface WebFetchResultView {\\n card: 'web';\\n kind: 'fetch';\\n title?: string;\\n url: string;\\n statusCode: number;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebResultView\",\n \"declaration\": \"export type WebResultView = WebSearchResultView | WebFetchResultView;\"\n },\n {\n \"name\": \"WebSearchResultView\",\n \"declaration\": \"export interface WebSearchResultView {\\n card: 'web';\\n kind: 'search';\\n title?: string;\\n sources: WebSource[];\\n answer?: string;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebSource\",\n \"declaration\": \"export interface WebSource {\\n url: string;\\n title?: string;\\n snippet?: string;\\n publishedAt?: string;\\n}\"\n }\n ]\n }\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-subprocess-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788778146017,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788778146017,"index":0,"dt":[],"id":"inspect-subprocess-api","name":"cordis_inspect_query","args":["{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"]},{"type":"chunk","time":1788778146017,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"inspect-subprocess-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"}}},{"type":"chunk","time":1788778146017,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788778146017,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/model-switch-notice/model-switch-driver.mjs b/snapshots/session/model-switch-notice/model-switch-driver.mjs index 4ce42062b5..ade04ebf97 100644 --- a/snapshots/session/model-switch-notice/model-switch-driver.mjs +++ b/snapshots/session/model-switch-notice/model-switch-driver.mjs @@ -7,15 +7,15 @@ export const name = 'model-switch-driver' export const inject = ['agents'] /** - * Change the step route after `todo_write`; headless owns the selection notice. + * Change the step model after `todo_write`; headless owns the selection notice. * @param {import('@deepseek-ai/cordis').Context} ctx - composition context. */ export function apply(ctx) { ctx.on('session/event', (session, event) => { if (event.type === 'todo/write') switched.add(session) }) - ctx.on('agent/route', async ({ agent }, next) => { - const route = await next() - return switched.has(agent.session) ? SELECTED : route + ctx.on('agent/model', async ({ agent }, next) => { + const proposed = await next() + return switched.has(agent.session) ? SELECTED : proposed }) } From 8bae86d49d6789ec268af942f431010d7bbfcd99 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 13 Oct 2026 11:14:10 +0800 Subject: [PATCH 06/36] test(snapshots): drop exit_plan_mode from master's office scenarios Ordinary mode no longer declares exit_plan_mode, so the office scenarios that master recorded before this change pin the tool list and PTC SDK guidance without it. --- .../tool-schemas.expected.json | 16 ---------------- .../system-prompt.expected.md | 8 -------- 2 files changed, 24 deletions(-) diff --git a/snapshots/session/office-progressive-native/tool-schemas.expected.json b/snapshots/session/office-progressive-native/tool-schemas.expected.json index 79d6891abc..b9c653bab9 100644 --- a/snapshots/session/office-progressive-native/tool-schemas.expected.json +++ b/snapshots/session/office-progressive-native/tool-schemas.expected.json @@ -62,22 +62,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/office-progressive-ptc/system-prompt.expected.md b/snapshots/session/office-progressive-ptc/system-prompt.expected.md index 9d427282d8..95b6ce91ec 100644 --- a/snapshots/session/office-progressive-ptc/system-prompt.expected.md +++ b/snapshots/session/office-progressive-ptc/system-prompt.expected.md @@ -68,11 +68,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -269,9 +264,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: boolean; - }; get_goal: { goal: null; } | { From 28f196ffa198a3f7b879702248d6fd4c2f0a7b4a Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 13 Oct 2026 11:14:11 +0800 Subject: [PATCH 07/36] docs(agent-loop): name agent/model as the effort override A configured reasoning effort seeds the step's model selection, which agent/model may replace; agent/request can no longer change it. --- packages/core/agent-loop/README.i18n.yaml | 4 ++-- packages/core/agent-loop/README.md | 2 +- packages/core/agent-loop/README.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index bd05cdf32e..62ace68991 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -18,8 +18,8 @@ en: 35a960c0100a6aa4 zh: 438e133fb4c24a9e /deepseek-ai-dsh-agent-loop/use-this-package/configure-declarative-agents: - en: 88fdef94bc4103dd - zh: e2bfd093a4fa00b8 + en: da8766eafb9fadd1 + zh: cd7469ec602594b6 /deepseek-ai-dsh-agent-loop/use-this-package/create-or-resume-agents-programmatically: en: 82ec792637e8e57f zh: e32f8ec5ee17afcf diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 09bf22f9b3..c42100eae7 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -48,7 +48,7 @@ Agents declared in the config start automatically when the plugin loads. Each en | `maxParallelToolCalls` | `10` | Parallel-safe tool calls in flight per step; `1` is serial | | `agents[].id` | required | Stable label; a fresh session mints `${id}-session-` unless `sessionId` is set | | `agents[].provider` / `agents[].model` | — | Model route; both required before dispatch | -| `agents[].reasoningEffort` | — | Non-empty initial reasoning effort; `agent/request` may override it | +| `agents[].reasoningEffort` | — | Non-empty initial reasoning effort; `agent/model` may override it | | `agents[].maxTokens` | — | Positive per-request output-token cap | | `agents[].cwd` | — | Workspace directory for a fresh session | | `agents[].sessionId` | — | Exact identity: first use creates, a remount resumes materialized history | diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 6761613ee9..3427ef23c7 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -48,7 +48,7 @@ kind: "package-reference" | `maxParallelToolCalls` | `10` | 每个步骤同时在途的并行安全工具调用数;`1` 为串行 | | `agents[].id` | 必填 | 稳定标签;未设置 `sessionId` 时,全新会话会生成 `${id}-session-` | | `agents[].provider` / `agents[].model` | — | 模型路由;分发前两者都必须存在 | -| `agents[].reasoningEffort` | — | 非空的初始推理强度;`agent/request` 可以覆盖它 | +| `agents[].reasoningEffort` | — | 非空的初始推理强度;`agent/model` 可以覆盖它 | | `agents[].maxTokens` | — | 正数的逐请求输出 token 上限 | | `agents[].cwd` | — | 全新会话的工作目录 | | `agents[].sessionId` | — | 确切身份:首次使用创建,重新挂载时恢复已实体化的历史 | From 4f36177740026af563bf288b4cde986db7916de1 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 13 Oct 2026 17:04:55 +0800 Subject: [PATCH 08/36] feat(agent): publish step decisions as agent.step and add agent/step-boundary Each proposed step now dispatches the serial agent/step-boundary event after claiming input, then agent/model, and publishes the chosen model selection as the optional agent.step until the step ends or its proposal is rejected, fails, or is cancelled. agent/pre-step listeners, tool conditions, prompt sections, and the provider and model variables read agent.step, so the pre-step payload, AssembleContext, and ToolActivationContext carry no model selection field. Plan mode commits pending selections at the step boundary, before model choice, and still narrates the switch in the first admitted step. The system prompt assembles once after step/start, including runtime context, and system-prompt/prepare is removed. The runtime-context snapshot is admitted after the step's accepted messages, so a changed runtime context alone no longer opens a step. --- ...bles-and-tool-guidance-ownership.i18n.yaml | 4 +- ...t-variables-and-tool-guidance-ownership.md | 2 +- ...ariables-and-tool-guidance-ownership.zh.md | 2 +- ...6-07-05-reconstructable-requests.i18n.yaml | 4 +- .../2026-07-05-reconstructable-requests.md | 2 +- .../2026-07-05-reconstructable-requests.zh.md | 2 +- ...02-system-prompt-as-surface-node.i18n.yaml | 4 +- ...026-09-02-system-prompt-as-surface-node.md | 2 +- ...-09-02-system-prompt-as-surface-node.zh.md | 2 +- ...-model-chosen-before-preparation.i18n.yaml | 16 +- ...12-step-model-chosen-before-preparation.md | 17 +- ...step-model-chosen-before-preparation.zh.md | 17 +- apps/cli/tests/fixtures/dsh-badge/snapshot.ts | 2 +- docs/agent-lifecycle.md | 14 +- docs/agent-lifecycle.zh.md | 14 +- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 12 +- docs/architecture.zh.md | 12 +- docs/config-catalog.md | 6 +- docs/config-catalog.zh.md | 6 +- docs/event-producer-consumer.md | 32 +-- docs/event-producer-consumer.zh.md | 32 +-- docs/persistence-catalog.i18n.yaml | 12 +- docs/persistence-catalog.md | 6 +- docs/persistence-catalog.zh.md | 6 +- docs/persistence-schema.json | 4 +- docs/subsystems/core.i18n.yaml | 8 +- docs/subsystems/core.md | 66 ++++- docs/subsystems/core.zh.md | 66 ++++- docs/subsystems/plan.i18n.yaml | 14 +- docs/subsystems/plan.md | 22 +- docs/subsystems/plan.zh.md | 22 +- docs/subsystems/session-reference.md | 7 +- docs/subsystems/session-reference.zh.md | 7 +- docs/subsystems/system-prompt.md | 46 +--- docs/subsystems/system-prompt.zh.md | 46 +--- docs/subsystems/tools.md | 2 +- docs/subsystems/tools.zh.md | 2 +- .../conditional-tools/guide.i18n.yaml | 12 +- .../v0.2.1-alpha.2/conditional-tools/guide.md | 18 +- .../conditional-tools/guide.zh.md | 18 +- .../tests/archived-session-gate.host.spec.ts | 2 +- .../ui-model-selection/README.i18n.yaml | 4 +- packages/client/ui-model-selection/README.md | 2 +- .../client/ui-model-selection/README.zh.md | 2 +- .../tests/compaction-basic.spec.ts | 2 +- .../tests/agent-instructions.spec.ts | 30 +-- .../session-reference/README.i18n.yaml | 4 +- packages/context/session-reference/README.md | 2 +- .../context/session-reference/README.zh.md | 2 +- .../context/session-reference/src/index.ts | 26 +- .../tests/loader-composition.spec.ts | 2 +- .../tests/session-reference.spec.ts | 12 +- .../time-context/tests/time-context.spec.ts | 2 +- .../tmux-context/tests/tmux-context.spec.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 | 136 +++++------ packages/core/agent-loop/src/index.ts | 4 +- packages/core/agent-loop/tests/loop.spec.ts | 18 +- .../core/agent-loop/tests/step-model.spec.ts | 231 ++++++++++++++++++ .../agent-loop/tests/tool-updates.spec.ts | 11 +- packages/core/agent/README.i18n.yaml | 8 +- packages/core/agent/README.md | 6 +- packages/core/agent/README.zh.md | 6 +- packages/core/agent/src/model-selection.ts | 11 +- packages/core/agent/src/runtime-types.ts | 45 +++- .../core/agent/tests/model-selection.spec.ts | 27 +- packages/core/system-prompt/README.i18n.yaml | 4 +- packages/core/system-prompt/README.md | 2 +- packages/core/system-prompt/README.zh.md | 2 +- packages/core/system-prompt/src/index.ts | 74 +++--- .../system-prompt/tests/system-prompt.spec.ts | 24 ++ packages/core/tools/README.i18n.yaml | 4 +- packages/core/tools/README.md | 4 +- packages/core/tools/README.zh.md | 4 +- packages/core/tools/src/index.ts | 10 +- packages/core/tools/tests/activation.spec.ts | 9 +- packages/core/tools/tests/ptc.spec.ts | 2 +- .../extensions/tool-cordis/src/api-catalog.ts | 62 ++--- packages/plan/plan-mode/README.i18n.yaml | 12 +- packages/plan/plan-mode/README.md | 6 +- packages/plan/plan-mode/README.zh.md | 6 +- packages/plan/plan-mode/src/index.ts | 69 +++--- .../plan/plan-mode/tests/plan-mode.spec.ts | 46 ++-- .../tests/session-checkpoint-policy.spec.ts | 2 +- .../working-directory/README.i18n.yaml | 8 +- packages/session/working-directory/README.md | 4 +- .../session/working-directory/README.zh.md | 4 +- .../session/working-directory/src/index.ts | 2 +- .../tests/working-directory.spec.ts | 10 +- .../skill/tool-skill/tests/tool-skill.spec.ts | 8 +- .../tests/model-selection-settings.spec.ts | 1 - scripts/fixtures/python-sdk-dynamic-tools.mjs | 2 +- scripts/gen-cordis-catalog.ts | 2 +- scripts/gen-doc-graphs.ts | 14 +- .../python-snapshot-workflow-order.spec.ts | 2 +- scripts/type-equiv.manifest.json | 5 + 99 files changed, 965 insertions(+), 636 deletions(-) create mode 100644 packages/core/agent-loop/tests/step-model.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml index f331bc345e..1c7d61e281 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.i18n.yaml @@ -15,8 +15,8 @@ en: 46e67248692e333a zh: 51c5f2c6152c94d7 /agent-note-prompt-variables-and-tool-guidance-ownership/decision/prompt-variables: - en: f5cbf8a901143c06 - zh: 534836ed5176a8ec + en: b605f58d6fb3684a + zh: 294862fcf54e2665 /agent-note-prompt-variables-and-tool-guidance-ownership/decision/persona-as-the-order-0-section: en: c2d32c0ac5d28759 zh: 59cd252ba6da6e59 diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md index 73931b9c8e..ef6152c7dd 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md @@ -28,7 +28,7 @@ The assembled system prompt had four defects, all of one family: facts the harne Plugins register `{{name}}` values through `ctx.systemPrompt.variable(name, provider)`. Assembly resolves them into the waterfall-visible variable map. Rendering rejects unknown own-property references, registered providers that return `undefined`, malformed complete references, and unbalanced references that still contain a closing `}}`; a lone unmatched `{{` remains prose, and substituted values are not rescanned. Registration rejects invalid or duplicate variable names, and section names are unique. Sections may set `interpolate: false` to preserve generated documents literally; `tools:sdk` does so because tool descriptions and schemas may document their own `{{…}}` syntax. -`dsh-agent-loop` registers `provider` and `model` as pure projections of the assembly context: the step model selection that `agent/model` chose, or the agent's `options` pair outside a step. Example personas reference `{{model}}` so the model selection owns the model name. These variables remain on the loop plugin because they describe the agents it drives; a replacement loop supplies its own. The [Session working-directory decision](2026-09-13-session-working-directory.md) owns directory state and its literal user-context placement; the loop does not register `cwd`. +`dsh-agent-loop` registers `provider` and `model` as pure projections of the assembly context: the step model selection that `agent/model` chose, read from `agent.step`, or the agent's `options` pair outside a step. Example personas reference `{{model}}` so the model selection owns the model name. These variables remain on the loop plugin because they describe the agents it drives; a replacement loop supplies its own. The [Session working-directory decision](2026-09-13-session-working-directory.md) owns directory state and its literal user-context placement; the loop does not register `cwd`. ### Persona as the order-0 section diff --git a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md index 12944274fa..13306621d8 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md @@ -28,7 +28,7 @@ Status: implemented 插件通过 `ctx.systemPrompt.variable(name, provider)` 注册 `{{name}}` 值。组装过程将它们解析到 waterfall 可见的变量映射中。渲染阶段拒绝以下情况:引用未知的自有属性、已注册的提供方返回 `undefined`、格式错误的完整引用、以及仍包含闭合 `}}` 的不平衡引用;孤立的未匹配 `{{` 保留为行文,替换后的值不会被重新扫描。注册阶段拒绝无效或重复的变量名,section 名称也必须唯一。段可设置 `interpolate: false` 来原样保留生成的文档;`tools:sdk` 使用此设置,因为工具描述和 schema 可能会介绍自身的 `{{…}}` 语法。 -`dsh-agent-loop` 注册 `provider` 和 `model`,它们都是组装上下文的纯投影:步骤内取 `agent/model` 选定的步骤模型选择,步骤外取 agent 的 `options` 这一对值。示例 persona 引用 `{{model}}`,由模型选择拥有模型名称。这些变量保留在 loop 插件上,因为它们描述该循环驱动的 agent;替换循环自行提供自己的变量。[Session 工作目录决策](2026-09-13-session-working-directory.zh.md) 拥有目录状态及其字面用户上下文位置;循环不注册 `cwd`。 +`dsh-agent-loop` 注册 `provider` 和 `model`,它们都是组装上下文的纯投影:步骤内从 `agent.step` 读取 `agent/model` 选定的步骤模型选择,步骤外取 agent 的 `options` 这一对值。示例 persona 引用 `{{model}}`,由模型选择拥有模型名称。这些变量保留在 loop 插件上,因为它们描述该循环驱动的 agent;替换循环自行提供自己的变量。[Session 工作目录决策](2026-09-13-session-working-directory.zh.md) 拥有目录状态及其字面用户上下文位置;循环不注册 `cwd`。 ### Persona 作为 order-0 section 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 5809b9a8d4..84445dd681 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 @@ -15,8 +15,8 @@ en: 6da15cf986d59a91 zh: 40282908b54295f9 /agent-note-every-llm-request-is-reconstructable-from-the-session-log/decision/the-mechanism: - en: b053c2b01866a634 - zh: cb15fa3a7fdefe60 + en: ba24d551138e75ac + zh: f9288da86f510199 /agent-note-every-llm-request-is-reconstructable-from-the-session-log/decision/the-minicode-shape-adopted-with-the-event-log-as-the-source: en: e5f2ffaa3d7de0cc zh: 5ba6b36787a0e189 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 022f6dcb06..d9c1970a66 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md @@ -24,7 +24,7 @@ Prefix-cache stability is corollary #1, not the headline: an append-only log pro `EpochHeader` records the request's non-history state: call config and tool schemas. Writers omit `tools: []` and `adapterDefaults: {}`; current acceptance rejects those fields and any `header.system`, rather than repairing them. Whitespace-only system-message content, `config.stop: []`, and nested extensions remain intact. The [V3 canonical-envelope decision](2026-09-06-v3-canonical-session-envelopes.md) owns historical conversion. The rendered system prompt is derived history — the `system/message` event at surface node 0, per the [surface-node Agent Note](2026-09-02-system-prompt-as-surface-node.md) — so a prompt change is a surface replacement rather than a header change. Adapter-supplied effort and token defaults retain their `adapterDefaults` ownership; 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, lets `agent/model` choose the step's provider, model, and reasoning effort, prepares runtime context, and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, resolves the step's tools, assembles the system prompt, commits a changed prompt as the `system/message` append or node-0 replacement, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. `agent/request` may replace only the frozen call config's sampling controls; the provider, model, and reasoning effort stay the step's model selection. The loop records the owed initial, resume, change, or series full snapshot, builds `GenerateOptions` from derived messages (system message first) and that header with no `system` field, and freezes it while leaving `AbortSignal` live. The [request-freeze evidence reference](../../../../packages/core/agent-loop/README.md) owns reuse of completed message freezes and per-request local header freezing. 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, commits pending selections at `agent/step-boundary`, lets `agent/model` choose the step's provider, model, and reasoning effort as `agent.step`, and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, resolves the step's tools, assembles the system prompt and runtime context, commits a changed prompt as the `system/message` append or node-0 replacement, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. `agent/request` may replace only the frozen call config's sampling controls; the provider, model, and reasoning effort stay the step's model selection. The loop records the owed initial, resume, change, or series full snapshot, builds `GenerateOptions` from derived messages (system message first) and that header with no `system` field, and freezes it while leaving `AbortSignal` live. The [request-freeze evidence reference](../../../../packages/core/agent-loop/README.md) owns reuse of completed message freezes and per-request local header freezing. 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. 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 9b94859d12..f0a84c3d44 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 @@ -24,7 +24,7 @@ Status: implemented `EpochHeader` 记录请求的非历史状态:调用配置和工具 schema。写入方省略 `tools: []` 与 `adapterDefaults: {}`;当前接纳拒绝这些字段以及任何 `header.system`,而不修复它们。仅含空白的系统消息内容、`config.stop: []` 与嵌套扩展保持原样。[V3 规范信封决策](2026-09-06-v3-canonical-session-envelopes.zh.md)负责历史转换。渲染后的系统提示词是派生历史——surface 第 0 号节点上的 `system/message` 事件,见[surface 节点 Agent Note](2026-09-02-system-prompt-as-surface-node.zh.md)——因此提示词变更是 surface 替换而不是 header 变更。适配器提供的推理强度与 token 默认值会保留其 `adapterDefaults` 来源信息;Web 从日志恢复模型选择时会省略适配器持有的推理强度,因此下一次解析不会把相同的有效配置重新归类为显式选择并产生虚假变更。`request/header` 始终写入完整快照:首个循环实例使用 reason `initial`,后续实例使用 `resume`,实例内变更使用 `change`,内容未变的封装显式开启消息序列或跟随表层替换时使用 `series`。如果发生变化的请求同时开启序列,`change` 快照会携带 `startsSeries: true`,无需重复 header 即可保留这两个独立事实。普通的仅追加后续 Turn、同一序列内后续的 Step 与重试沿用最新快照。`foldRequestHeader` 选择最新快照。旧的 `request/header-delta` 事件和已移除的 `fallback` reason 在追加或加载时都会被拒绝。 -每个拟议步骤先领取其 inbox 批次,由 `agent/model` 选定该步骤的提供方、模型与推理强度,准备运行时上下文,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,解析该步骤的工具并组装系统提示词,把变化的提示词作为 `system/message` 追加或第 0 号节点替换提交,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。`agent/request` 只能替换冻结调用配置中的采样控制参数;提供方、模型与推理强度保持为步骤的模型选择。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息(系统消息在先)与该不含 `system` 字段的 header 构建 `GenerateOptions`,冻结请求但保持 `AbortSignal` 活跃。[请求冻结证据说明](../../../../packages/core/agent-loop/README.zh.md)拥有消息完整冻结的复用规则和每次请求的本地 header 冻结规则。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 +每个拟议步骤先领取其 inbox 批次,在 `agent/step-boundary` 提交待生效的选择,由 `agent/model` 选定该步骤的提供方、模型与推理强度并发布为 `agent.step`,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,解析该步骤的工具并组装系统提示词与运行时上下文,把变化的提示词作为 `system/message` 追加或第 0 号节点替换提交,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。`agent/request` 只能替换冻结调用配置中的采样控制参数;提供方、模型与推理强度保持为步骤的模型选择。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息(系统消息在先)与该不含 `system` 字段的 header 构建 `GenerateOptions`,冻结请求但保持 `AbortSignal` 活跃。[请求冻结证据说明](../../../../packages/core/agent-loop/README.zh.md)拥有消息完整冻结的复用规则和每次请求的本地 header 冻结规则。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 **已打开步骤是重建边界。** 进入步骤的 `user/message` 批次与任何新写入的 `request/header` 都位于请求分派之前。原子领取后发生的注入加入后续请求;必须影响本次请求的监听器则通过 `agent/pre-step` 返回消息。header 重建选择该步骤的 `request/header`,或在无新 header 写入时沿用前一个快照。 diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml index ba1077a0ec..e1477a5f0e 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml @@ -18,8 +18,8 @@ en: a217a08932938062 zh: 4924d99d55d9c973 /agent-note-the-system-prompt-is-surface-node-0/decision/ownership-in-the-loop: - en: 1626e01049f6d312 - zh: bb000a96944c8168 + en: ca45857bcd9424eb + zh: 37247c6966423dcb /agent-note-the-system-prompt-is-surface-node-0/decision/consumers: en: 39f9f4acffcccdc6 zh: 36b23a57e7d28950 diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md index dbcdaea1f2..6c61cbfcb4 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md @@ -36,7 +36,7 @@ When the initial rendered prompt is empty, the loop reserves an empty system hea `dsh-agent-loop` owns `SystemPromptProjection` beside `RuntimeContextProjection` in `packages/core/agent-loop/src/runtime-context.ts`. It reads the surviving `system/message` nodes from the current surface on every projection, so a compaction or replacement that ran earlier in the same step is already reflected. `project(rendered, { inHistory, startsSeries })` returns `{ message, intent }` — `intent` is `{ surfaceOp: 'append' }` when no system node survives or when the [in-history rule](../feature/2026-09-02-in-history-system-prompt-replacement.md) applies, otherwise a replacement of exactly the latest surviving system node — or `undefined` when the latest node already holds the rendered text. -In `packages/core/agent-loop/src/agent.ts`, `step()` renders the prompt with `renderPrompt(assembly)` after `step/start` and projects it on each attempt after `agent/request` and `prepareCall()`, so a compaction provider's replacement inside `agent/pre-step` or retry recovery is visible to reconciliation; the `system/message` is committed before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `agent/model` waterfall → `systemPrompt.prepare()` → `agent/pre-step` waterfall → `step/start` → resolve tools → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → commit `system/message` (when changed) → commit `user/message`s → `request/header` → `request/context` → stream. +In `packages/core/agent-loop/src/agent.ts`, `step()` renders the prompt with `renderPrompt(assembly)` after `step/start` and projects it on each attempt after `agent/request` and `prepareCall()`, so a compaction provider's replacement inside `agent/pre-step` or retry recovery is visible to reconciliation; the `system/message` is committed before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `agent/step-boundary` → `agent/model` waterfall (published as `agent.step`) → `agent/pre-step` waterfall → `step/start` → resolve tools → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → commit `system/message` (when changed) → commit `user/message`s and a changed runtime-context snapshot → `request/header` → `request/context` → stream. `dsh-token-meter` anchors usage to the priced surface immediately before the successful `assistant/message`, not to `step/start`. The loop admits the system prompt and user messages after step start, and retry recovery can replace nodes before rebuilding the request. Capturing that current surface includes every admitted input once; the embedded provider output remains separately priced so durable assistant rewrites retain their signed delta. The open step stores only turn and step for lifecycle validation, not a second node snapshot. diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md index fada9e3085..9bfb9df062 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md @@ -36,7 +36,7 @@ Status: implemented `dsh-agent-loop` 在 `packages/core/agent-loop/src/runtime-context.ts` 中与 `RuntimeContextProjection` 并列拥有 `SystemPromptProjection`。它在每次投影时从当前 surface 读取存活的 `system/message` 节点,因此同一步骤中更早运行的压缩或替换已经反映在内。`project(rendered, { inHistory, startsSeries })` 返回 `{ message, intent }`——没有系统节点存活或[历史内规则](../feature/2026-09-02-in-history-system-prompt-replacement.zh.md)适用时 `intent` 为 `{ surfaceOp: 'append' }`,否则是对最新存活系统节点的精确替换——最新节点已持有渲染文本时返回 `undefined`。 -在 `packages/core/agent-loop/src/agent.ts` 中,`step()` 在 `step/start` 之后用 `renderPrompt(assembly)` 渲染提示词,并在每次尝试的 `agent/request` 与 `prepareCall()` 之后投影它,因此压缩提供者在 `agent/pre-step` 内或重试恢复中做出的替换对协调可见;`system/message` 在该步骤的 `user/message` 事件之前提交,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `agent/model` waterfall → `systemPrompt.prepare()` → `agent/pre-step` waterfall → `step/start` → 解析工具 → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → 提交 `system/message`(有变化时) → 提交各条 `user/message` → `request/header` → `request/context` → 流式请求。 +在 `packages/core/agent-loop/src/agent.ts` 中,`step()` 在 `step/start` 之后用 `renderPrompt(assembly)` 渲染提示词,并在每次尝试的 `agent/request` 与 `prepareCall()` 之后投影它,因此压缩提供者在 `agent/pre-step` 内或重试恢复中做出的替换对协调可见;`system/message` 在该步骤的 `user/message` 事件之前提交,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `agent/step-boundary` → `agent/model` waterfall(发布为 `agent.step`) → `agent/pre-step` waterfall → `step/start` → 解析工具 → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → 提交 `system/message`(有变化时) → 提交各条 `user/message` 与变化后的运行时上下文快照 → `request/header` → `request/context` → 流式请求。 `dsh-token-meter` 把用量锚定到成功的 `assistant/message` 之前的已计价 surface,而不是 `step/start`。循环在步骤开始之后接纳系统提示词与用户消息,重试恢复还可能在重建请求之前替换节点。捕获当前 surface 会让每个已接纳输入恰好计入一次;内嵌的提供方输出仍单独计价,因此持久 assistant 改写保留其带符号增量。开放步骤只保存 turn 与 step 以验证生命周期,不保存第二份节点快照。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml index 3559e84201..829d4efb0f 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml @@ -6,17 +6,17 @@ en: f068fddb192978d2 zh: 601deb72d3d90263 /agent-note-choose-the-step-model-before-step-preparation/problem: - en: cb8d6f058dd5f47d - zh: bb70e1cfe6880da5 + en: 1c3fbc5343be9e19 + zh: ee1c1c032074f2b6 /agent-note-choose-the-step-model-before-step-preparation/decision: - en: d0ee43966ff59a93 - zh: 4f69bc120de87c44 + en: 5c62c30a1810dcf8 + zh: 5146e199e13b2dfb /agent-note-choose-the-step-model-before-step-preparation/alternatives-considered: - en: 3114082393f6a55f - zh: a3790bd3b18658e0 + en: e69897cbb8e51ea2 + zh: c71acdfffb7d0d60 /agent-note-choose-the-step-model-before-step-preparation/consequences: - en: c553f9931c8c467b - zh: 0d77c5c71d266d27 + en: bf8a702bc7559c51 + zh: e81657ff8566e16b /agent-note-choose-the-step-model-before-step-preparation/related: en: 00ef1147a7852c0a zh: 4bd89960e08b6eda diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md index c9a6c8dde9..1c7f236cbe 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md @@ -6,29 +6,34 @@ English | [中文](2026-10-12-step-model-chosen-before-preparation.zh.md) ## Problem -Tool availability can depend on the route of the request that declares the tools: `web_search` must stay off routes without search credentials, and plan or team state can withhold other tools. Message preparation needs the same model: session references size snapshots by the model's context window, and model selection announces a switch. The loop assembled tools and prompt sections before `agent/pre-step` and decided the provider, model, and reasoning effort only in `agent/request` after `step/start`, so earlier consumers predicted them from model-selection state. A listener that replaced them in `agent/request`, including on a retry, made the assembled prompt and tool catalog describe another model. +Tool availability can depend on the route of the request that declares the tools: `web_search` must stay off routes without search credentials, and plan or team state can withhold other tools. Message preparation needs the same model: session references size snapshots by the model's context window, and model selection announces a switch. The loop assembled tools and prompt sections before `agent/pre-step` and decided the provider, model, and reasoning effort only in `agent/request` after `step/start`, so earlier consumers predicted them from model-selection state. A listener that replaced them in `agent/request`, including on a retry, made the assembled prompt and tool catalog describe another model. Plan state had the same problem: it was committed inside `agent/pre-step`, so plan guidance predicted it from the pending selection. ## Decision -The provider, model, and reasoning effort are a step fact, chosen together as the user chooses them before sending a message. After claiming input, the loop dispatches `agent/model` once per proposed step. Its default comes from the agent options before this loop logs a request and from the logged header afterwards, with an effort only when one was chosen for that exact model; `installModelSelection` returns its current selection there. The loop passes the resulting `ModelSelection` to `system-prompt/prepare` as `AssembleContext.modelSelection`, to `agent/pre-step` as `payload.modelSelection`, and to tool conditions as `ToolActivationContext.modelSelection`. The `{{provider}}` and `{{model}}` prompt variables read it. +The provider, model, and reasoning effort are a step fact, chosen together as the user chooses them before sending a message. After claiming input, the loop dispatches the serial `agent/step-boundary` event, where plugins commit selections that apply from this step, such as a pending plan-mode switch. It then dispatches `agent/model` once per proposed step. Its default comes from the agent options before this loop logs a request and from the logged header afterwards, with an effort only when one was chosen for that exact model; `installModelSelection` returns its current selection there. The loop publishes the result as `agent.step` and clears it when the step ends or its proposal is rejected, fails, or is cancelled. `agent/pre-step` listeners, tool conditions, prompt sections, and the `{{provider}}` and `{{model}}` variables read the selection from the agent. -After `agent/pre-step` accepts the step and `step/start` opens it, the loop resolves conditional tools and assembles the prompt once. Each request attempt then runs `agent/request` and `prepareCall()` immediately before admission. `agent/request` may change sampling controls; a result with another provider, model, or reasoning effort fails the step. Retries reuse the step's model selection, tool set, and rendered assembly, and the step-owned tool set closes after the step's tool batch settles. A selection made during a step applies from the next step. +After `agent/pre-step` accepts the step and `step/start` opens it, the loop resolves conditional tools and assembles the prompt once: sections, variables, runtime context, and tool declarations. The runtime-context snapshot is admitted after the step's accepted messages. Each request attempt then runs `agent/request` and `prepareCall()` immediately before admission. `agent/request` may change sampling controls; a result with another provider, model, or reasoning effort fails the step. Retries reuse the step's model selection, tool set, and rendered assembly, and the step-owned tool set closes after the step's tool batch settles. A selection made during a step applies from the next step. ## Alternatives considered - **Bind the route in `agent/request` before `agent/pre-step` and expose `Agent.currentRoute()`.** The prepared call captures the adapter registration and connection settings, so holding it across compaction, hooks, and session reads ignores settings changed meanwhile, and adapters were prepared for steps that `agent/pre-step` rejects. The getter was valid only inside a step and threw elsewhere, and every Agent implementation and test double had to carry it. -- **Record the model in `agent/pre-step`.** `system-prompt/prepare` runs before that waterfall, and model consumers inside it would depend on listener order. +- **Choose the model inside `agent/pre-step`.** Pre-step listeners consume the model for reference budgets and switch notices. Deciding and consuming it in one waterfall makes the value each listener sees depend on registration order. +- **Pass the selection to each consumer as a parameter.** `AssembleContext`, the pre-step payload, and `ToolActivationContext` each needed a field, and every later step decision would add one to all three. `agent.step` gives them one source. - **Register the model selection on the Agent without an event.** It adds a single-consumer method to the generic `Agent` interface and removes the listener path that supplies a model for agents created without one. - **Keep the decision in `agent/request` and predict it for earlier consumers.** A prediction diverges whenever a listener other than model selection changes the model. - **Choose only the provider and model per step and leave reasoning effort to `agent/request`.** An effort is valid only for the model it was chosen for. The split required `installModelSelection` to capture the selection in one waterfall and apply its effort in another only when no other listener had replaced the model, and it let a retry change effort within a step. +- **Prepare runtime context before `agent/pre-step` in a separate `system-prompt/prepare` phase.** It kept the runtime context between the claimed input and messages added by pre-step listeners, but split assembly into two hooks and made a changed runtime context alone open a step. +- **Commit pending plan selections inside `agent/pre-step`.** Phases and listeners that ran before the commit saw the previous plan state, and model choice could not depend on plan mode. ## Consequences - Tool conditions, prompt variables, reference budgets, and switch notices read the provider and model that the request header records. - `prepareCall()` stays adjacent to dispatch, so its adapter registration and connection snapshot cover only header logging and streaming. - A step cannot fail over to another provider or change reasoning effort on retry; a policy that needs this must run model selection, tool resolution, and assembly again for the retried attempt. -- The model selection cannot depend on `agent/pre-step` outcomes. Plan state commits inside that waterfall, so a plan-specific model would require committing plan selections before model selection. -- `agent/pre-step` listeners and direct dispatchers must handle the required `modelSelection` field. +- `agent.step` is undefined between steps and during `agent/model`; work that outlives its step reads it at its start. +- `agent/model` listeners can read plan state because the boundary commits it first, but model choice still cannot depend on `agent/pre-step` outcomes. +- A pending plan-mode selection is committed even when `agent/pre-step` rejects the step; its notice joins the next admitted step. +- The runtime-context snapshot follows the step's accepted messages, and a changed runtime context alone does not open a step. ## Related diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md index 09ef27ac4f..e5ea4da203 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md @@ -6,29 +6,34 @@ Status: implemented ## 问题 -工具是否可用可能取决于声明这些工具的请求所用的路由:`web_search` 不得出现在没有搜索凭据的路由上,计划或团队状态也可能撤下其他工具。消息准备同样需要这一模型:会话引用按模型的上下文窗口确定快照大小,模型选择会通告模型切换。循环原先在 `agent/pre-step` 之前组装工具与提示词段落,直到 `step/start` 之后才在 `agent/request` 中决定提供方、模型与推理强度,因此更早的消费方只能依据模型选择状态预测它们。若监听器在 `agent/request` 中(包括在重试时)替换它们,已组装的提示词与工具目录就会描述另一个模型。 +工具是否可用可能取决于声明这些工具的请求所用的路由:`web_search` 不得出现在没有搜索凭据的路由上,计划或团队状态也可能撤下其他工具。消息准备同样需要这一模型:会话引用按模型的上下文窗口确定快照大小,模型选择会通告模型切换。循环原先在 `agent/pre-step` 之前组装工具与提示词段落,直到 `step/start` 之后才在 `agent/request` 中决定提供方、模型与推理强度,因此更早的消费方只能依据模型选择状态预测它们。若监听器在 `agent/request` 中(包括在重试时)替换它们,已组装的提示词与工具目录就会描述另一个模型。计划状态也有同样的问题:它在 `agent/pre-step` 内提交,计划指引只能依据待提交的选择预测。 ## 决策 -提供方、模型与推理强度是步骤级事实,像用户在发送消息前那样一起选定。领取输入之后,循环为每个拟议步骤派发一次 `agent/model`。其默认值在本循环记录请求之前取自 agent 选项,之后取自已记录的请求头,且只有为该确切模型选定过的推理强度才会保留;`installModelSelection` 在这里返回其当前选择。循环把得到的 `ModelSelection` 作为 `AssembleContext.modelSelection` 传给 `system-prompt/prepare`,作为 `payload.modelSelection` 传给 `agent/pre-step`,作为 `ToolActivationContext.modelSelection` 传给工具条件。提示词变量 `{{provider}}` 与 `{{model}}` 读取该选择。 +提供方、模型与推理强度是步骤级事实,像用户在发送消息前那样一起选定。领取输入之后,循环派发串行事件 `agent/step-boundary`,插件在此提交从本步骤起生效的选择,例如待提交的计划模式切换。随后循环为每个拟议步骤派发一次 `agent/model`。其默认值在本循环记录请求之前取自 agent 选项,之后取自已记录的请求头,且只有为该确切模型选定过的推理强度才会保留;`installModelSelection` 在这里返回其当前选择。循环把结果发布为 `agent.step`,并在步骤结束或提案被拒绝、失败、取消时清除。`agent/pre-step` 监听器、工具条件、提示词段落以及 `{{provider}}` 与 `{{model}}` 变量都从 agent 读取该选择。 -`agent/pre-step` 接纳步骤且 `step/start` 打开步骤之后,循环解析条件工具并组装提示词,各执行一次。之后每次请求尝试都在准入之前紧接着运行 `agent/request` 与 `prepareCall()`。`agent/request` 可以修改采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。重试复用该步骤的模型选择、工具集合与已渲染组装结果,步骤拥有的工具集合在该步骤的工具批次结束后关闭。步骤进行中做出的选择从下一个步骤开始生效。 +`agent/pre-step` 接纳步骤且 `step/start` 打开步骤之后,循环解析条件工具并一次性组装提示词:段落、变量、运行时上下文与工具声明。运行时上下文快照在该步骤已接纳的消息之后提交。之后每次请求尝试都在准入之前紧接着运行 `agent/request` 与 `prepareCall()`。`agent/request` 可以修改采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。重试复用该步骤的模型选择、工具集合与已渲染组装结果,步骤拥有的工具集合在该步骤的工具批次结束后关闭。步骤进行中做出的选择从下一个步骤开始生效。 ## 考虑过的替代方案 - **在 `agent/pre-step` 之前通过 `agent/request` 绑定路由,并提供 `Agent.currentRoute()`。** 已准备调用会捕获适配器注册与连接设置,因此在压缩、钩子与会话读取期间一直持有它,会忽略期间修改的设置;被 `agent/pre-step` 拒绝的步骤也会准备适配器。该 getter 只在步骤内有效、在其他时刻抛错,且每个 Agent 实现与测试替身都必须提供它。 -- **在 `agent/pre-step` 内记录模型。** `system-prompt/prepare` 在该 waterfall 之前运行,而 waterfall 内的模型消费方将依赖监听器顺序。 +- **在 `agent/pre-step` 内选定模型。** pre-step 监听器自身就要用模型计算引用预算和切换通告。在同一个 waterfall 中既决定又使用模型,每个监听器看到的值就取决于注册顺序。 +- **把选择作为参数传给每个消费方。** `AssembleContext`、pre-step payload 与 `ToolActivationContext` 各需一个字段,之后每增加一项步骤决定都要同时改这三处。`agent.step` 为它们提供单一来源。 - **不使用事件,直接在 Agent 上登记模型选择。** 这会给通用 `Agent` 接口增加只有单一消费方的方法,并移除为创建时没有模型的 agent 提供模型的监听器途径。 - **决定留在 `agent/request`,为更早的消费方预测它。** 只要模型选择之外的监听器修改模型,预测就会偏离。 - **每个步骤只选定提供方与模型,推理强度留给 `agent/request`。** 推理强度只对选定它的模型有效。拆开后,`installModelSelection` 必须在一个 waterfall 中捕获选择,再在另一个 waterfall 中、且仅当其他监听器没有替换模型时应用推理强度;重试也可以在步骤内修改推理强度。 +- **在 `agent/pre-step` 之前用单独的 `system-prompt/prepare` 阶段准备运行时上下文。** 它把运行时上下文保留在已领取输入与 pre-step 监听器追加的消息之间,但把组装拆成了两个钩子,并让仅运行时上下文变化就能打开一个步骤。 +- **在 `agent/pre-step` 内提交待生效的计划选择。** 提交之前运行的阶段和监听器看到的是旧的计划状态,模型选择也无法依据计划模式。 ## 后果 - 工具条件、提示词变量、引用预算与切换通告读取的提供方与模型,与请求头记录的一致。 - `prepareCall()` 紧邻分发,因此其适配器注册与连接快照只覆盖请求头记录与流式请求。 - 步骤无法在重试时切换到其他提供方或修改推理强度;需要这种能力的策略必须为重试的尝试重新执行模型选择、工具解析与组装。 -- 模型选择不能依赖 `agent/pre-step` 的结果。计划状态在该 waterfall 内提交,因此按计划模式选择模型需要先在模型选择之前提交计划选择。 -- `agent/pre-step` 监听器与直接派发方必须处理必填的 `modelSelection` 字段。 +- `agent.step` 在两个步骤之间以及 `agent/model` 期间为 undefined;跨步骤运行的工作要在开始时读取它。 +- `agent/model` 监听器可以读取计划状态,因为步骤边界会先提交它;但模型选择仍不能依赖 `agent/pre-step` 的结果。 +- 即使 `agent/pre-step` 拒绝了该步骤,待生效的计划模式选择也已提交;其通告会出现在下一个被接纳的步骤中。 +- 运行时上下文快照位于该步骤已接纳的消息之后,仅运行时上下文变化不会打开步骤。 ## 相关 diff --git a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts index f6674047bf..c84912a9f1 100644 --- a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts +++ b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts @@ -43,7 +43,7 @@ try { } const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, + { messages: [], turn: 1, step: 1, signal: new AbortController().signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const catalog = decision.kind === 'enter' diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index b1d099df0b..c91c486556 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -25,22 +25,22 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/model waterfall chooses the step provider, model, and effort - Driver->>Prompt: system-prompt/prepare waterfall with the step model selection - Driver->>Hooks: agent/pre-step waterfall with the step model selection + Driver->>Hooks: agent/step-boundary serial commits selections pending for this step + Driver->>Hooks: agent/model waterfall chooses provider, model, and effort, published as agent.step + Driver->>Hooks: agent/pre-step waterfall reads agent.step Hooks-->>Driver: authoritative reject or enter(messages) alt proposed step rejected, first batch empty, or pre-step failed Driver-->>Driver: claimed batch stays removed, the open turn spends no step else enter proposed step Driver->>Session: step/start - Driver->>Tools: resolve({ agent, modelSelection, signal }) once per step - Driver->>Prompt: system-prompt/assemble with the step tool set + Driver->>Tools: resolve({ agent, signal }) once per step + Driver->>Prompt: system-prompt/assemble contexts, variables, sections, and the step tool set Driver->>Hooks: agent/request waterfall with the step model selection Driver->>LLM: prepareCall(config, signal) Note over Driver,LLM: cancellation during preparation commits neither system nor users Note over Driver,Session: synchronous admission using the prepared call capability Driver->>Session: system/message ordered per-node reconciliation - Driver->>Session: user/message per entered message + Driver->>Session: user/message per entered message, then a changed runtime-context snapshot Driver->>Session: request/header and request/context as needed Driver->>Driver: derive and freeze request from the log Driver->>LLM: bound prepared call through llm/stream waterfall @@ -75,8 +75,8 @@ sequenceDiagram opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message + Driver->>Hooks: agent/step-boundary serial Driver->>Hooks: agent/model waterfall - Driver->>Prompt: system-prompt/prepare waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) end diff --git a/docs/agent-lifecycle.zh.md b/docs/agent-lifecycle.zh.md index ebb6dbec73..4172d114eb 100644 --- a/docs/agent-lifecycle.zh.md +++ b/docs/agent-lifecycle.zh.md @@ -27,22 +27,22 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/model waterfall chooses the step provider, model, and effort - Driver->>Prompt: system-prompt/prepare waterfall with the step model selection - Driver->>Hooks: agent/pre-step waterfall with the step model selection + Driver->>Hooks: agent/step-boundary serial commits selections pending for this step + Driver->>Hooks: agent/model waterfall chooses provider, model, and effort, published as agent.step + Driver->>Hooks: agent/pre-step waterfall reads agent.step Hooks-->>Driver: authoritative reject or enter(messages) alt proposed step rejected, first batch empty, or pre-step failed Driver-->>Driver: claimed batch stays removed, the open turn spends no step else enter proposed step Driver->>Session: step/start - Driver->>Tools: resolve({ agent, modelSelection, signal }) once per step - Driver->>Prompt: system-prompt/assemble with the step tool set + Driver->>Tools: resolve({ agent, signal }) once per step + Driver->>Prompt: system-prompt/assemble contexts, variables, sections, and the step tool set Driver->>Hooks: agent/request waterfall with the step model selection Driver->>LLM: prepareCall(config, signal) Note over Driver,LLM: cancellation during preparation commits neither system nor users Note over Driver,Session: synchronous admission using the prepared call capability Driver->>Session: system/message ordered per-node reconciliation - Driver->>Session: user/message per entered message + Driver->>Session: user/message per entered message, then a changed runtime-context snapshot Driver->>Session: request/header and request/context as needed Driver->>Driver: derive and freeze request from the log Driver->>LLM: bound prepared call through llm/stream waterfall @@ -77,8 +77,8 @@ sequenceDiagram opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message + Driver->>Hooks: agent/step-boundary serial Driver->>Hooks: agent/model waterfall - Driver->>Prompt: system-prompt/prepare waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) end diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index e3e6bbdaa4..8091ef489e 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -24,8 +24,8 @@ en: e89802f066e4955d zh: ea2fb4bef94e086d /deepseek-harness-architecture/turn-flow: - en: 5001f8affe8d84f0 - zh: de2632709bb4e93a + en: 0f496f867565ac9b + zh: 1c015bb06ce0a4b4 /deepseek-harness-architecture/session-log: en: a2e35c43438fec6d zh: e27bdac8e9feff32 diff --git a/docs/architecture.md b/docs/architecture.md index 3c120ed3b9..f5ad4e118c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -83,16 +83,16 @@ A **step** is one model request plus the tools it calls. A **turn** is zero or m ```text turn/start claim next-step input plus one queued message - agent/model -> step provider/model/effort - prepare variables + runtime context - -> agent/pre-step; project runtime context at fallback + agent/step-boundary -> commit pending selections + agent/model -> agent.step (provider/model/effort) + -> agent/pre-step reject | enter(messages, startsRequestSeries?) reject, or a first enter rewritten empty -> close the turn with no step step/start - resolve conditional tools + assemble prompt + resolve conditional tools + assemble prompt and context agent/request -> prepareCall reconcile system/message using the prepared call capability - append entered messages as user/message; reconcile retained runtime context + append entered messages as user/message, then changed runtime context log request/header and request/context as needed derive and freeze model history from the log stream the bound prepared call -> llm/stream -> agent/assistant-stream start @@ -109,7 +109,7 @@ turn/end One inbox feeds the driver; injected context waits for a waking message. AgentLoop’s durable `inbox` projection exposes pending input without live Agents. -`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/model` fixes the step's provider, model, and effort before `agent/pre-step`; accepted steps resolve tools and assemble once. Each attempt's `agent/request` may change only sampling, and `prepareCall()` binds the adapter before prompt and user admission; cancellation in either commits neither. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming; retries reuse the selection, tools, and assembly. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). +`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/step-boundary` commits pending selections, then `agent/model` publishes `agent.step` (provider, model, effort) before `agent/pre-step`; accepted steps resolve tools and assemble once. Each attempt's `agent/request` may change only sampling, and `prepareCall()` binds the adapter before prompt and user admission; cancellation in either commits neither. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming; retries reuse the selection, tools, and assembly. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). The loop sends immutable requests with live cancellation and reuses freeze evidence for frozen identities; [agent-loop](../packages/core/agent-loop/README.md) owns construction and cancellation causes. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 1d8e3718b9..c66ed3b344 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -87,16 +87,16 @@ AgentLoop 在启动已排队工作前等待串行 `agent/created`,初始化失 ```text turn/start claim next-step input plus one queued message - agent/model -> step provider/model/effort - prepare variables + runtime context - -> agent/pre-step; project runtime context at fallback + agent/step-boundary -> commit pending selections + agent/model -> agent.step (provider/model/effort) + -> agent/pre-step reject | enter(messages, startsRequestSeries?) reject, or a first enter rewritten empty -> close the turn with no step step/start - resolve conditional tools + assemble prompt + resolve conditional tools + assemble prompt and context agent/request -> prepareCall reconcile system/message using the prepared call capability - append entered messages as user/message; reconcile retained runtime context + append entered messages as user/message, then changed runtime context log request/header and request/context as needed derive and freeze model history from the log stream the bound prepared call -> llm/stream -> agent/assistant-stream start @@ -113,7 +113,7 @@ turn/end 输入通过同一个 inbox 到达驱动器;注入的上下文等待一条唤醒消息。AgentLoop 的持久 `inbox` 投影使待处理输入在没有活跃 Agent 时仍可读取。 -`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。`agent/model` 在 `agent/pre-step` 之前固定该步骤的提供方、模型与推理强度;被接纳的步骤随后解析工具并组装一次。每次尝试的 `agent/request` 只能修改采样控制参数,`prepareCall()` 在提示词与用户消息准入前绑定适配器;在任一阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求;重试复用模型选择、工具与组装结果。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 +`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。`agent/step-boundary` 提交待生效的选择,随后 `agent/model` 在 `agent/pre-step` 之前发布 `agent.step`(提供方、模型、推理强度);被接纳的步骤随后解析工具并组装一次。每次尝试的 `agent/request` 只能修改采样控制参数,`prepareCall()` 在提示词与用户消息准入前绑定适配器;在任一阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求;重试复用模型选择、工具与组装结果。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 循环发送不可变请求,同时保持取消有效,仅对完全冻结的对象复用冻结证据;[agent-loop](../packages/core/agent-loop/README.zh.md) 负责请求构建与取消原因。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 442dc7bc66..01d8364f5a 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2387,7 +2387,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` -- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:68`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -3492,7 +3492,7 @@ export interface Config { ## `@deepseek-ai/dsh-system-prompt` -- `source`: [`packages/core/system-prompt/src/index.ts:269`](../packages/core/system-prompt/src/index.ts) +- `source`: [`packages/core/system-prompt/src/index.ts:262`](../packages/core/system-prompt/src/index.ts) ```ts config-catalog /** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */ @@ -4171,7 +4171,7 @@ export interface Config { ## `@deepseek-ai/dsh-tools` - `inject`: `systemPrompt` -- `source`: [`packages/core/tools/src/index.ts:735`](../packages/core/tools/src/index.ts) +- `source`: [`packages/core/tools/src/index.ts:733`](../packages/core/tools/src/index.ts) ```ts config-catalog /** Plugin config: how the registered tools are presented to the model. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index f8a8c0c93f..7c09b28857 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2389,7 +2389,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` -- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:68`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -3494,7 +3494,7 @@ export interface Config { ## `@deepseek-ai/dsh-system-prompt` -- `source`: [`packages/core/system-prompt/src/index.ts:269`](../packages/core/system-prompt/src/index.ts) +- `source`: [`packages/core/system-prompt/src/index.ts:262`](../packages/core/system-prompt/src/index.ts) ```ts config-catalog /** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */ @@ -4173,7 +4173,7 @@ export interface Config { ## `@deepseek-ai/dsh-tools` - `inject`: `systemPrompt` -- `source`: [`packages/core/tools/src/index.ts:735`](../packages/core/tools/src/index.ts) +- `source`: [`packages/core/tools/src/index.ts:733`](../packages/core/tools/src/index.ts) ```ts config-catalog /** Plugin config: how the registered tools are presented to the model. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index ac302aefdd..18eb0fdfc5 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -10,19 +10,20 @@ 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:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:273`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:282`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:319`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../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/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:352`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:373`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `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), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:426`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:284`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:293`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:456`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:330`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../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/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:379`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:344`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:416`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:303`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/step-boundary` | `serial` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`plan-mode`](../packages/plan/plan-mode) | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:444`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | @@ -72,9 +73,8 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:158`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | -| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime` | -| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:44`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | -| `system-prompt/prepare` | `waterfall` | [`packages/core/system-prompt/src/index.ts:38`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`working-directory`](../packages/session/working-directory) | +| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) | +| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `tools/change` | `emit` | [`packages/core/tools/src/index.ts:216`](../packages/core/tools/src/index.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:172`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:184`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index cb221a48b9..9d6c5c669a 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -12,19 +12,20 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:273`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:282`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:319`](../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), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../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/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:352`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:373`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `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), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:426`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:284`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:293`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:456`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:330`](../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), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../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/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:379`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:344`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:416`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:303`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/step-boundary` | `serial` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`plan-mode`](../packages/plan/plan-mode) | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:444`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | @@ -74,9 +75,8 @@ | `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:158`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | -| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime` | -| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:44`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | -| `system-prompt/prepare` | `waterfall` | [`packages/core/system-prompt/src/index.ts:38`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`working-directory`](../packages/session/working-directory) | +| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) | +| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `tools/change` | `emit` | [`packages/core/tools/src/index.ts:216`](../packages/core/tools/src/index.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:172`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:184`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 647cb8b746..09b61ca9b7 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -153,8 +153,8 @@ en: 4294f78d26ed985b zh: 4294f78d26ed985b /session-persistence-event-catalog/events/plan/plan-mode-log-only: - en: f23bf0e5e6408adf - zh: a9442b4c5cdeef0b + en: 862175bfe8692ef7 + zh: a8ab123bf674cf77 /session-persistence-event-catalog/events/request: en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 @@ -1278,8 +1278,8 @@ en: f43a635a14568780 zh: 8d22226b045122eb /session-persistence-event-catalog/resolved-persistence-types/toolrestriction: - en: 0a56a07b1de985b4 - zh: 886c512054d12ad6 + en: 739d19df365ed5df + zh: b1e41e56995fe238 /session-persistence-event-catalog/resolved-persistence-types/toolresultmessage: en: 2258683c3cfa4ce3 zh: 5663aa76c911761b @@ -1389,8 +1389,8 @@ en: a74e3dfa51c987af zh: 6c3c87974d7a7260 /session-persistence-event-catalog/resolved-persistence-types/active~2: - en: 1bc41f689438a051 - zh: babdc92cc0ad089a + en: a3de6a6fe9672c7a + zh: a357481e27b3b81f /session-persistence-event-catalog/resolved-persistence-types/agentpreset: en: b8a0f8aac9708056 zh: f5f004bd205b41e1 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 1b2381bca8..0fd493b8b3 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -732,7 +732,7 @@ Source: [`packages/interaction/permission-presets/src/index.ts:59`](../packages/ 'plan/mode': { active: boolean } ``` -Source: [`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) +Source: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -5158,7 +5158,7 @@ Sources: [`packages/llm/llm/src/types.ts:127`](../packages/llm/llm/src/types.ts) SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -Sources: [`packages/core/tools/src/index.ts:761`](../packages/core/tools/src/index.ts) +Sources: [`packages/core/tools/src/index.ts:759`](../packages/core/tools/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -5734,7 +5734,7 @@ Array of `unknown` (opaque). SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -Sources: [`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) +Sources: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index e839ff1ce7..dc9db33cbd 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -734,7 +734,7 @@ export type SessionEvent = { 'plan/mode': { active: boolean } ``` -来源:[`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -5160,7 +5160,7 @@ SHA-256: `43e311235aa537df1bacdd92d144df8a952337a76e9ac892cdf670f1a797bad8` SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -来源:[`packages/core/tools/src/index.ts:761`](../packages/core/tools/src/index.ts) +来源:[`packages/core/tools/src/index.ts:759`](../packages/core/tools/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5736,7 +5736,7 @@ SHA-256: `b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7` SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -来源:[`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index aaebcb31cb..e53cc6a7dc 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -22809,7 +22809,7 @@ "digest": "20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5", "names": [], "sources": [ - "packages/plan/plan-mode/src/index.ts:51" + "packages/plan/plan-mode/src/index.ts:52" ] }, { @@ -23218,7 +23218,7 @@ "packages/core/tools/src/index.ts#ToolRestriction" ], "sources": [ - "packages/core/tools/src/index.ts:761" + "packages/core/tools/src/index.ts:759" ] }, { diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 35c730cee9..ba5927d5d8 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -12,14 +12,14 @@ en: ab09a38b4e1f0883 zh: 81e2d14c4036ab6c /core/the-agent-handle: - en: fbcbf559b0362d11 - zh: e2cc3f4e28f23687 + en: c0339e2de0246e58 + zh: 9e1def25d117ac0a /core/initiating-agent: en: 6c8c47ac78de2dde zh: c9d527a25a85d1d9 /core/interception-decisions: - en: f50b0e1933657f39 - zh: 961a69f1247951df + en: 4bfb9b4426027b9e + zh: f4af79c9c18afa94 /core/sessions: en: 9a38f693a00fa80d zh: d0f66664ac85ae64 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 34fc5d394d..6adb8ce35e 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -63,6 +63,13 @@ interface Agent { readonly id: SessionId /** Creation-time request options; `agent/model` may choose another provider, model, and effort for each step. */ readonly options: AgentOptions + /** + * The step the driver is preparing or running. The driver publishes it + * after `agent/model` and clears it when the step ends or its proposal is + * rejected, fails, or is cancelled, so it is undefined between steps and + * during `agent/model`. Work that outlives its step reads it at its start. + */ + readonly step?: AgentStep | undefined /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -208,7 +215,7 @@ interface AgentOptions { Each step requires `provider` and `model` after `agent/model`, which may supply or replace the options' provider, model, and effort. An explicit `reasoningEffort` seeds the first step's selection for that model; exact-model resolution validates it, while omission allows the adapter default to materialize. When present, `maxTokens` must be a positive safe integer and caps every conversation-model request; omission allows the exact-model adapter default to materialize before the request header, or otherwise leaves provider behavior unchanged. An agent-scoped `deployment:persona-prefix` prompt section may shadow the global default persona. -The step keeps its model selection for prompt preparation, `agent/pre-step`, tool conditions, and every request attempt; `agent/request` may change only sampling controls such as `maxTokens`, `temperature`, and `stop`: +The driver publishes the step's selection as `agent.step`, which `agent/pre-step`, tool conditions, prompt assembly, and every request attempt read; `agent/request` may change only sampling controls such as `maxTokens`, `temperature`, and `stop`: ```ts type-equiv /** Complete provider, model, and optional reasoning effort; `agent/model` fixes one for each step. */ @@ -222,6 +229,14 @@ interface ModelSelection { } ``` +```ts type-equiv +/** Decisions the driver fixed for one proposed or running step. */ +interface AgentStep { + /** Provider, model, and reasoning effort that every request attempt in the step uses. */ + readonly modelSelection: ModelSelection +} +``` + The inbox is the delivery vocabulary — two ordered pending-message lists the agent owns as a durable projection: ```ts type-equiv @@ -325,7 +340,7 @@ Pre-step decisions use the same identified `UserMessage` type as durable user-ro Source: [`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts) -`agent/pre-step` receives one payload carrying the exclusive claimed batch (`messages`), the proposed step's coordinates (`turn`, `step`), its `modelSelection`, and the current turn's cancellation `signal`. The initial proposal runs inside an open turn before any step; a tool continuation may submit an empty claimed batch between steps: +`agent/pre-step` receives one payload carrying the exclusive claimed batch (`messages`), the proposed step's coordinates (`turn`, `step`), and the current turn's cancellation `signal`; `payload.agent.step` already holds the step's model selection. The initial proposal runs inside an open turn before any step; a tool continuation may submit an empty claimed batch between steps: It returns a `PreStepDecision`. Reject opens no step. Enter supplies the complete message batch appended after `step/start`; claimed messages omitted by the final decision remain removed, while input inserted after the claim stays pending: @@ -943,7 +958,7 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/model` — waterfall -Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step. +Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, after `agent/step-boundary` and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step. ```ts cordis-catalog /** @@ -953,10 +968,11 @@ Choose the provider, model, and reasoning effort for one proposed step. `await n * effort only when one was chosen for that exact model. Return a * replacement to switch; an effort belongs to its model, so a replacement * that changes the model names that model's effort or omits it for the - * provider default. The loop runs this once per proposed step, before - * context preparation and `agent/pre-step`. Prompt preparation, tool - * conditions, and every request attempt in the step use the result, so a - * later choice applies from the next step. Cancellation here opens no step. + * provider default. The loop runs this once per proposed step, after + * `agent/step-boundary` and before `agent/pre-step`, then publishes the + * result as `agent.step`. Pre-step listeners, tool conditions, prompt + * assembly, and every request attempt in the step use it, so a later + * choice applies from the next step. Cancellation here opens no step. * @param payload.agent - the agent proposing the step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. @@ -975,22 +991,22 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/pre-step` — waterfall -Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages. +Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages. `payload.agent.step` already holds the model selection that `agent/model` chose for this step. ```ts cordis-catalog /** * Reject a proposed step or replace the messages that enter it. Calling - * `next()` preserves the current messages. + * `next()` preserves the current messages. `payload.agent.step` already + * holds the model selection that `agent/model` chose for this step. * @param payload.agent - the agent proposing the step. * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. - * @param payload.modelSelection - the provider, model, and effort `agent/model` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; modelSelection: ModelSelection; signal: AbortSignal }, next: () => Promise): Promise +'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise ``` Types: [Scoped](scope.md) · [UserMessage](session.md) @@ -1083,6 +1099,34 @@ Types: [Scoped](scope.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + + +#### `agent/step-boundary` — serial + +A proposed step reached its boundary: the loop claimed its input and is about to choose its model. Listeners commit selections that take effect from this step, such as a pending plan-mode switch, so `agent/model`, `agent/pre-step`, tool conditions, and prompt assembly read one state. Runs once per proposed step; a throw fails the proposal, and cancellation opens no step. + +```ts cordis-catalog +/** + * A proposed step reached its boundary: the loop claimed its input and is + * about to choose its model. Listeners commit selections that take effect + * from this step, such as a pending plan-mode switch, so `agent/model`, + * `agent/pre-step`, tool conditions, and prompt assembly read one state. + * Runs once per proposed step; a throw fails the proposal, and + * cancellation opens no step. + * @param payload.agent - the agent proposing the step. + * @param payload.turn - the turn that will own the step. + * @param payload.step - the step proposed by the loop. + * @param payload.signal - the current turn's explicit abort signal. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode serial + */ +'agent/step-boundary'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }): Promise | void +``` + +Types: [Scoped](scope.md) + +Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + #### `agent/turn-stopping` — serial diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 59c3b51e19..e090274546 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -67,6 +67,13 @@ interface Agent { readonly id: SessionId /** Creation-time request options; `agent/model` may choose another provider, model, and effort for each step. */ readonly options: AgentOptions + /** + * The step the driver is preparing or running. The driver publishes it + * after `agent/model` and clears it when the step ends or its proposal is + * rejected, fails, or is cancelled, so it is undefined between steps and + * during `agent/model`. Work that outlives its step reads it at its start. + */ + readonly step?: AgentStep | undefined /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -212,7 +219,7 @@ interface AgentOptions { 每个步骤在 `agent/model` 之后都要求 `provider` 与 `model` 都存在;该 waterfall 可以补上或替换 options 中的提供方、模型与推理强度。显式 `reasoningEffort` 会为该模型的首个步骤选择提供初始值;确切模型解析会校验该值,省略时则允许填入适配器默认值。提供 `maxTokens` 时,它必须是正安全整数,并限制每次对话模型请求的输出;省略时,系统会在写入请求 header 前填入确切模型的适配器默认值,否则提供方行为保持不变。agent 作用域的 `deployment:persona-prefix` 提示词段落可以遮蔽全局默认 persona。 -步骤在提示词准备、`agent/pre-step`、工具条件以及每次请求尝试中都沿用其模型选择;`agent/request` 只能修改 `maxTokens`、`temperature`、`stop` 等采样控制参数: +驱动把该步骤的模型选择发布为 `agent.step`,供 `agent/pre-step`、工具条件、提示词组装以及每次请求尝试读取;`agent/request` 只能修改 `maxTokens`、`temperature`、`stop` 等采样控制参数: ```ts type-equiv /** Complete provider, model, and optional reasoning effort; `agent/model` fixes one for each step. */ @@ -226,6 +233,14 @@ interface ModelSelection { } ``` +```ts type-equiv +/** Decisions the driver fixed for one proposed or running step. */ +interface AgentStep { + /** Provider, model, and reasoning effort that every request attempt in the step uses. */ + readonly modelSelection: ModelSelection +} +``` + inbox 即投递词汇——agent 以持久投影形式拥有的两条有序待处理消息列表: ```ts type-equiv @@ -333,7 +348,7 @@ pre-step 决策使用与持久 user-role 输入相同、带标识的 `UserMessag 源码:[`packages/core/agent/src/types.ts`](../../packages/core/agent/src/types.ts) -`agent/pre-step` 接收一个 payload,携带独占的已领取批次(`messages`)、拟进入步骤的坐标(`turn`、`step`)、其模型选择 `modelSelection` 与当前轮次的取消 `signal`。首次提案在已打开的轮次内、任何步骤开始前运行;工具 continuation 可以在步骤之间提交空的已领取批次: +`agent/pre-step` 接收一个 payload,携带独占的已领取批次(`messages`)、拟进入步骤的坐标(`turn`、`step`)与当前轮次的取消 `signal`;`payload.agent.step` 已持有该步骤的模型选择。首次提案在已打开的轮次内、任何步骤开始前运行;工具 continuation 可以在步骤之间提交空的已领取批次: 它返回 `PreStepDecision`。reject 不会打开步骤。enter 提供在 `step/start` 后追加的完整消息批次;最终决策省略的已领取消息保持已删除,而领取后插入的输入仍留待后续处理: @@ -955,7 +970,7 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/model` — waterfall -Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step. +Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, after `agent/step-boundary` and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step. ```ts cordis-catalog /** @@ -965,10 +980,11 @@ Choose the provider, model, and reasoning effort for one proposed step. `await n * effort only when one was chosen for that exact model. Return a * replacement to switch; an effort belongs to its model, so a replacement * that changes the model names that model's effort or omits it for the - * provider default. The loop runs this once per proposed step, before - * context preparation and `agent/pre-step`. Prompt preparation, tool - * conditions, and every request attempt in the step use the result, so a - * later choice applies from the next step. Cancellation here opens no step. + * provider default. The loop runs this once per proposed step, after + * `agent/step-boundary` and before `agent/pre-step`, then publishes the + * result as `agent.step`. Pre-step listeners, tool conditions, prompt + * assembly, and every request attempt in the step use it, so a later + * choice applies from the next step. Cancellation here opens no step. * @param payload.agent - the agent proposing the step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. @@ -987,22 +1003,22 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/pre-step` — waterfall -Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages. +Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages. `payload.agent.step` already holds the model selection that `agent/model` chose for this step. ```ts cordis-catalog /** * Reject a proposed step or replace the messages that enter it. Calling - * `next()` preserves the current messages. + * `next()` preserves the current messages. `payload.agent.step` already + * holds the model selection that `agent/model` chose for this step. * @param payload.agent - the agent proposing the step. * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. - * @param payload.modelSelection - the provider, model, and effort `agent/model` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ -'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; modelSelection: ModelSelection; signal: AbortSignal }, next: () => Promise): Promise +'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise ``` Types: [Scoped](scope.zh.md) · [UserMessage](session.zh.md) @@ -1095,6 +1111,34 @@ Types: [Scoped](scope.zh.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + + +#### `agent/step-boundary` — serial + +A proposed step reached its boundary: the loop claimed its input and is about to choose its model. Listeners commit selections that take effect from this step, such as a pending plan-mode switch, so `agent/model`, `agent/pre-step`, tool conditions, and prompt assembly read one state. Runs once per proposed step; a throw fails the proposal, and cancellation opens no step. + +```ts cordis-catalog +/** + * A proposed step reached its boundary: the loop claimed its input and is + * about to choose its model. Listeners commit selections that take effect + * from this step, such as a pending plan-mode switch, so `agent/model`, + * `agent/pre-step`, tool conditions, and prompt assembly read one state. + * Runs once per proposed step; a throw fails the proposal, and + * cancellation opens no step. + * @param payload.agent - the agent proposing the step. + * @param payload.turn - the turn that will own the step. + * @param payload.step - the step proposed by the loop. + * @param payload.signal - the current turn's explicit abort signal. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode serial + */ +'agent/step-boundary'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }): Promise | void +``` + +Types: [Scoped](scope.zh.md) + +Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + #### `agent/turn-stopping` — serial diff --git a/docs/subsystems/plan.i18n.yaml b/docs/subsystems/plan.i18n.yaml index e5ce0f0902..17f616e621 100644 --- a/docs/subsystems/plan.i18n.yaml +++ b/docs/subsystems/plan.i18n.yaml @@ -8,15 +8,15 @@ /plan-mode/logged-state-and-recovery: en: dd1e8ba31e6fd535 zh: a22dbccc60c73bc9 -/plan-mode/pending-selections-and-the-pre-step-append: - en: 8d7e5b7824921ed5 - zh: 910fad43593f29f4 +/plan-mode/pending-selections-and-the-step-boundary-append: + en: a62c24bf1e46c0ff + zh: bbe0ff492ee1be65 /plan-mode/configuration: en: ee04468005fae8e1 zh: 1347d554102951f2 /plan-mode/the-exit-tool-and-the-plan-command: - en: b5bbc440552d7ade - zh: 17fb1cfed1bc48ef + en: 6739f69a1b71b495 + zh: a538adbe4c85b529 /plan-mode/the-service: - en: 07c3eec12e0dc75c - zh: 183d73f6672e2c5a + en: c798c709c5cb6454 + zh: bac179e6fd51a98f diff --git a/docs/subsystems/plan.md b/docs/subsystems/plan.md index cc25cfa64b..d37cf01a7f 100644 --- a/docs/subsystems/plan.md +++ b/docs/subsystems/plan.md @@ -10,11 +10,11 @@ Source: [`packages/plan/plan-mode/src/index.ts`](../../packages/plan/plan-mode/s `plan/mode` (`{ active: boolean }`) is a log-only, whole-value-replace [session event](session.md): durable and replayable, never in the model transcript. The optionally registered `plan` unit folds committed mode, command settlement, and the mode recorded at the latest request header. `ctx.planMode` reads that state through `stateOf()`; the first dependent access fails if the registry, `plan` key, or `turnBoundary` key is absent. Clients receive only `{ active, pending }`; resume, fork, and compaction recover both from the log. The complete event declaration is in the [persistence log event catalog](../persistence-catalog.md). -## Pending selections and the pre-step append +## Pending selections and the step-boundary append -Because every session event is turn-enclosed, a user selection remains pending until the next accepted in-turn pre-step appends it before request derivation, in whichever turn that occurs. A selection never forces continuation, so one made after a turn's final accepted pre-step is appended in a later turn. `set(agent, active)` records the pending selection (a no-op when the target equals the logged-or-already-pending state), and `get(agent)` returns `{ active: boolean; pending?: boolean }`: the logged state used to assemble the current step plus the selected state waiting to be appended. +Because every session event is turn-enclosed, `set(agent, active)` appends a selection immediately only between turns. During an open turn the selection remains pending until the next step boundary appends it, in whichever turn that occurs. A selection never forces continuation, so one made after a turn's final step boundary is appended in a later turn. `set` is a no-op when the target equals the logged-or-already-pending state, and `get(agent)` returns `{ active: boolean; pending?: boolean }`: the logged state used by the current step plus the selected state waiting to be appended. -The only append point while an agent is running is a prepended `agent/pre-step` listener. It observes every proposed request step, including turn 1 step 1 and request-recovery retries, calls downstream listeners first, and appends only after they accept the step. Prompt admission happens before a turn and cannot append `plan/mode`, so a selection made at the prompt is appended by the first accepted in-turn pre-step of the turn it starts. An append failure cannot block the turn, and the selection remains pending for a later accepted in-turn pre-step. An appended user selection also records one plugin-sourced `user/message` notice, but only when the last logged request header described the other state, so the model is told exactly when its context changed and never redundantly. A selection made after a turn's final accepted pre-step remains process-local and is lost if the process exits before another accepted in-turn pre-step ([README limitation](../../packages/plan/plan-mode/README.md#known-limitations-and-deferred-work)). +The only append point while an agent is running is an `agent/step-boundary` listener. It runs once for every proposed step, including turn 1 step 1, after the step claims its input and before `agent/model`, so model choice, `agent/pre-step`, tool conditions, and plan guidance read the committed state; same-step request-recovery retries do not run it. An append failure fails the proposal and keeps the selection pending for a later boundary. An appended user selection also records one plugin-sourced `user/message` notice in the first admitted step, but only when the last logged request header described the other state, so the model is told exactly when its context changed and never redundantly. A selection made after a turn's final step boundary remains process-local and is lost if the process exits before another boundary ([README limitation](../../packages/plan/plan-mode/README.md#known-limitations-and-deferred-work)). ## Configuration @@ -30,13 +30,13 @@ A missing, blank, or non-string `section` and any unknown key fail at plugin loa ## The exit tool and the `/plan` command -[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) stays registered while plan mode is inactive, so entering or leaving plan mode changes only the prompt section, never the request tool catalog; execution outside plan mode fails. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. +[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is admitted only while the committed plan state is active, so entering or leaving plan mode changes the request tool declarations and the plan guidance together; Native and PTC execution use the same admitted set, and a call outside plan mode returns `UNKNOWN_TOOL`. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next step boundary. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. When [`ctx.commands`](commands.md) is composed, the plugin registers `/plan [off|message]`: bare `/plan` selects plan mode, any other non-empty message selects it and then submits the text through `agent.steer()` so it becomes the next step's ordinary logged user message under plan guidance, and the exact argument `off` selects inactive, which also cancels a pending entry before it is appended and becomes visible to a request. ## The service -`ctx.planMode` owns the logged plan state, applies and narrates selected state at step start, and owns the `plan:policy` section, the `/plan` command, and the stable exit tool; `get`/`set` signatures are in the generated [service catalog](#ctxplanmode--planmodecontroller). +`ctx.planMode` owns the logged plan state, applies selected state at the step boundary and narrates it in the admitted step, and owns the `plan:policy` section, the `/plan` command, and the conditional exit tool; `get`/`set` signatures are in the generated [service catalog](#ctxplanmode--planmodecontroller). @@ -55,7 +55,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ```ts cordis-catalog /** * Read the logged plan state and any selected state awaiting the next - * accepted in-turn pre-step. + * step boundary. * * @param agent The agent to read. * @returns Current logged state plus a pending selection, when present. @@ -64,17 +64,17 @@ get(agent: Agent): { active: boolean; pending?: boolean } /** * Select whether plan mode should be active. Between turns the method - * appends the change immediately because no in-turn pre-step will run until + * appends the change immediately because no step boundary will run until * another prompt starts a turn. The open-turn fold is the idle signal: * agent status stays `running` through post-turn checkpointing, when no - * further in-turn pre-step runs. During an open turn the selection remains - * pending until the next accepted in-turn pre-step. Repeated selection of - * the current or already-pending state is a no-op. + * further step boundary runs. During an open turn the selection remains + * pending until the next step boundary. Repeated selection of the current + * or already-pending state is a no-op. * * @param agent The agent to switch. * @param active Whether plan mode should be active. * @returns what happened: `committed` (logged now), `queued` (awaiting the - * next accepted in-turn pre-step), `cancelled` (an opposite pending selection + * next step boundary), `cancelled` (an opposite pending selection * was cleared; the logged state already matches), or `noop` (already in that * state). */ diff --git a/docs/subsystems/plan.zh.md b/docs/subsystems/plan.zh.md index 24047c0e48..dd97ec0a0c 100644 --- a/docs/subsystems/plan.zh.md +++ b/docs/subsystems/plan.zh.md @@ -10,11 +10,11 @@ `plan/mode`(`{ active: boolean }`)是仅记日志、整值替换的[会话事件](session.zh.md):持久且可回放,绝不进入模型 transcript(文本记录)。可选注册的 `plan` 单元折叠已提交模式、命令结算结果和最近一次请求头记录的模式。`ctx.planMode` 通过 `stateOf()` 读取该状态;注册表、`plan` key 或 `turnBoundary` key 缺失时,第一次依赖它们的访问会失败。客户端只接收 `{ active, pending }`;恢复、fork 与压缩(compaction)都能从日志恢复两者。完整事件声明见[持久化日志事件目录](../persistence-catalog.zh.md)。 -## 待生效选择与 pre-step 追加 +## 待生效选择与步骤边界追加 -由于每个会话事件都位于轮次之内,用户选择会保持待生效状态,直到下一个被接受的轮内 pre-step 在派生请求之前追加该选择,无论该 pre-step 位于哪个轮次。选择不会强制续行,因此在某轮最后一个被接受的 pre-step 之后作出的选择会在之后的轮次追加。`set(agent, active)` 记录待生效选择(目标值与已记录或已在等待的状态相同时不做任何事),`get(agent)` 返回 `{ active: boolean; pending?: boolean }`:用于组装当前步骤的已记录状态,以及等待追加的已选状态。 +由于每个会话事件都位于轮次之内,`set(agent, active)` 只在轮次之间立即追加选择。轮次进行中,选择保持待生效状态,直到下一个步骤边界追加它,无论该边界位于哪个轮次。选择不会强制续行,因此在某轮最后一个步骤边界之后作出的选择会在之后的轮次追加。目标值与已记录或已在等待的状态相同时,`set` 不做任何事;`get(agent)` 返回 `{ active: boolean; pending?: boolean }`:当前步骤使用的已记录状态,以及等待追加的已选状态。 -agent 运行时,唯一的追加点是前置(prepend)注册的 `agent/pre-step` 监听器。它会观察每个候选请求步骤,包括第 1 轮第 1 步和请求恢复重试;它先调用下游监听器,只在下游接受该步骤后追加。提示词准入发生在轮次开启之前,无法追加 `plan/mode`,因此在提示词处作出的选择由它开启的轮次内第一个被接受的 pre-step 追加。追加失败不能阻塞轮次,且该选择会继续等待之后被接受的轮内 pre-step。追加用户选择时还会记录一条插件来源的 `user/message` 通知,但仅当最后记录的请求头描述的是另一种状态时才记录,因此模型恰好在上下文变化时收到通知,且绝不重复。在某轮最后一个被接受的 pre-step 之后作出的选择只存在于进程内;如果进程在另一个被接受的轮内 pre-step 之前退出,该选择会丢失([README 限制](../../packages/plan/plan-mode/README.zh.md#known-limitations-and-deferred-work))。 +agent 运行时,唯一的追加点是 `agent/step-boundary` 监听器。它对每个拟议步骤运行一次(包括第 1 轮第 1 步),时机在该步骤领取输入之后、`agent/model` 之前,因此模型选择、`agent/pre-step`、工具条件与计划指引读到的都是已提交状态;同一步骤内的请求恢复重试不会运行它。追加失败会使该提案失败,选择继续等待之后的步骤边界。追加用户选择时还会在第一个被接纳的步骤中记录一条插件来源的 `user/message` 通知,但仅当最后记录的请求头描述的是另一种状态时才记录,因此模型恰好在上下文变化时收到通知,且绝不重复。在某轮最后一个步骤边界之后作出的选择只存在于进程内;如果进程在下一个步骤边界之前退出,该选择会丢失([README 限制](../../packages/plan/plan-mode/README.zh.md#known-limitations-and-deferred-work))。 ## 配置 @@ -30,13 +30,13 @@ interface PlanModeConfig { ## 退出工具与 `/plan` 命令 -[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 在计划模式未激活时仍保持注册,因此进入或离开计划模式只改变提示词段落,绝不改变请求的工具目录;在计划模式之外执行会失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 +[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 只在已提交的计划状态处于激活时被准入,因此进入或离开计划模式会同时改变请求的工具声明与计划指引;原生与 PTC 执行使用同一准入集合,在计划模式之外调用会返回 `UNKNOWN_TOOL`。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个步骤边界追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 当 [`ctx.commands`](commands.zh.md) 被组合时,插件注册 `/plan [off|message]`:单独的 `/plan` 选择计划模式;任何其他非空消息先选择计划模式,再通过 `agent.steer()` 提交该文本,使其在计划指引下成为下一步骤的普通已记录用户消息;确切参数 `off` 选择未激活,这还会在待生效条目被追加并对请求可见之前将其取消。 ## 服务 -`ctx.planMode` 拥有已记录的计划状态,在步骤开始时应用并叙述选中的状态,还拥有 `plan:policy` 段落、`/plan` 命令和稳定注册的退出工具;`get`/`set` 签名见生成的[服务目录](#ctxplanmode--planmodecontroller)。 +`ctx.planMode` 拥有已记录的计划状态,在步骤边界应用选中的状态并在被接纳的步骤中叙述,还拥有 `plan:policy` 段落、`/plan` 命令和按条件准入的退出工具;`get`/`set` 签名见生成的[服务目录](#ctxplanmode--planmodecontroller)。 @@ -55,7 +55,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ```ts cordis-catalog /** * Read the logged plan state and any selected state awaiting the next - * accepted in-turn pre-step. + * step boundary. * * @param agent The agent to read. * @returns Current logged state plus a pending selection, when present. @@ -64,17 +64,17 @@ get(agent: Agent): { active: boolean; pending?: boolean } /** * Select whether plan mode should be active. Between turns the method - * appends the change immediately because no in-turn pre-step will run until + * appends the change immediately because no step boundary will run until * another prompt starts a turn. The open-turn fold is the idle signal: * agent status stays `running` through post-turn checkpointing, when no - * further in-turn pre-step runs. During an open turn the selection remains - * pending until the next accepted in-turn pre-step. Repeated selection of - * the current or already-pending state is a no-op. + * further step boundary runs. During an open turn the selection remains + * pending until the next step boundary. Repeated selection of the current + * or already-pending state is a no-op. * * @param agent The agent to switch. * @param active Whether plan mode should be active. * @returns what happened: `committed` (logged now), `queued` (awaiting the - * next accepted in-turn pre-step), `cancelled` (an opposite pending selection + * next step boundary), `cancelled` (an opposite pending selection * was cleared; the logged state already matches), or `noop` (already in that * state). */ diff --git a/docs/subsystems/session-reference.md b/docs/subsystems/session-reference.md index 517b395729..56db8ea11b 100644 --- a/docs/subsystems/session-reference.md +++ b/docs/subsystems/session-reference.md @@ -205,7 +205,7 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the step's model selection, or agent options for direct preparation. + * Automatic budgets use the model of the agent's current step, or agent options outside a step. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -213,13 +213,12 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. - * @param modelSelection - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ -async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, modelSelection?: ModelSelection, ): Promise +async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, ): Promise ``` -Types: [Agent](core.md) · [ContentBlock](llm-streaming.md) · [ModelSelection](core.md) +Types: [Agent](core.md) · [ContentBlock](llm-streaming.md) Source: [`packages/context/session-reference/src/index.ts`](../../packages/context/session-reference/src/index.ts) diff --git a/docs/subsystems/session-reference.zh.md b/docs/subsystems/session-reference.zh.md index f76a9a7371..ccac4a0b7a 100644 --- a/docs/subsystems/session-reference.zh.md +++ b/docs/subsystems/session-reference.zh.md @@ -205,7 +205,7 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the step's model selection, or agent options for direct preparation. + * Automatic budgets use the model of the agent's current step, or agent options outside a step. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -213,13 +213,12 @@ async listCandidates( agent: Agent, query: string = '', limit: number = this.con * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. - * @param modelSelection - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ -async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, modelSelection?: ModelSelection, ): Promise +async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, ): Promise ``` -Types: [Agent](core.zh.md) · [ContentBlock](llm-streaming.zh.md) · [ModelSelection](core.zh.md) +Types: [Agent](core.zh.md) · [ContentBlock](llm-streaming.zh.md) Source: [`packages/context/session-reference/src/index.ts`](../../packages/context/session-reference/src/index.ts) diff --git a/docs/subsystems/system-prompt.md b/docs/subsystems/system-prompt.md index 76d9fed53e..0eda0c8ae2 100644 --- a/docs/subsystems/system-prompt.md +++ b/docs/subsystems/system-prompt.md @@ -189,24 +189,20 @@ variable(name: string, provider: (context: AssembleContext) => string | undefine * @param context - the same scope and current plugin-defined assembly fields. * @returns the accepted assembly with current runtime-context provider text. */ -refreshContext(assembly: T, context: AssembleContext = {}): T +refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly /** - * Prepare variables and runtime facts before accepting a step. No tool - * conditions or prompt sections are evaluated in this phase. - * @param context - calling scope and request cancellation. - * @returns prepared inputs after the preparation waterfall. + * Assemble global and scoped providers, detach tool parameters, apply + * canonical ordering, then run the presentation waterfall. Scoped sections + * and variables shadow globals. The waterfall's text is authoritative except + * that an effective complete section is restored afterwards as the sole + * prompt section, current suppression removes optional contexts, and + * required contexts keep their provider values; tool declarations stay + * provider-owned. + * @param context - the optional scope, step tool set, and plugin-defined assembly fields. + * @returns the post-waterfall assembly with ordered tool declarations. */ -async prepare(context: AssembleContext = {}): Promise - -/** - * Assemble prompt sections and tool declarations after request preparation. - * The presentation waterfall cannot replace provider-owned tools. - * @param context - calling scope, route-bound agent, and resolved tools. - * @param preparation - accepted variables and runtime facts; prepared here when omitted. - * @returns the complete assembly with ordered tool declarations. - */ -async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise +async assemble(context: AssembleContext = {}): Promise ``` Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) @@ -256,25 +252,5 @@ Emitted when any prompt provider changes. This registry notification is unfilter 'system-prompt/change'(): void ``` -Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) - - - -#### `system-prompt/prepare` — waterfall - -Prepare variables and runtime context before step admission. - -```ts cordis-catalog -/** - * Prepare variables and runtime context before step admission. - * @param preparation - registered variables and context contributions. - * @param context - calling scope and cancellation. - * @mode waterfall - */ -'system-prompt/prepare'(this: Scoped, preparation: PromptPreparation, context: AssembleContext, next: () => Promise): Promise -``` - -Types: [Scoped](scope.md) - Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) diff --git a/docs/subsystems/system-prompt.zh.md b/docs/subsystems/system-prompt.zh.md index 12ce785206..3ea3ae2732 100644 --- a/docs/subsystems/system-prompt.zh.md +++ b/docs/subsystems/system-prompt.zh.md @@ -189,24 +189,20 @@ variable(name: string, provider: (context: AssembleContext) => string | undefine * @param context - the same scope and current plugin-defined assembly fields. * @returns the accepted assembly with current runtime-context provider text. */ -refreshContext(assembly: T, context: AssembleContext = {}): T +refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly /** - * Prepare variables and runtime facts before accepting a step. No tool - * conditions or prompt sections are evaluated in this phase. - * @param context - calling scope and request cancellation. - * @returns prepared inputs after the preparation waterfall. + * Assemble global and scoped providers, detach tool parameters, apply + * canonical ordering, then run the presentation waterfall. Scoped sections + * and variables shadow globals. The waterfall's text is authoritative except + * that an effective complete section is restored afterwards as the sole + * prompt section, current suppression removes optional contexts, and + * required contexts keep their provider values; tool declarations stay + * provider-owned. + * @param context - the optional scope, step tool set, and plugin-defined assembly fields. + * @returns the post-waterfall assembly with ordered tool declarations. */ -async prepare(context: AssembleContext = {}): Promise - -/** - * Assemble prompt sections and tool declarations after request preparation. - * The presentation waterfall cannot replace provider-owned tools. - * @param context - calling scope, route-bound agent, and resolved tools. - * @param preparation - accepted variables and runtime facts; prepared here when omitted. - * @returns the complete assembly with ordered tool declarations. - */ -async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise +async assemble(context: AssembleContext = {}): Promise ``` Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) @@ -256,25 +252,5 @@ Emitted when any prompt provider changes. This registry notification is unfilter 'system-prompt/change'(): void ``` -Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) - - - -#### `system-prompt/prepare` — waterfall - -Prepare variables and runtime context before step admission. - -```ts cordis-catalog -/** - * Prepare variables and runtime context before step admission. - * @param preparation - registered variables and context contributions. - * @param context - calling scope and cancellation. - * @mode waterfall - */ -'system-prompt/prepare'(this: Scoped, preparation: PromptPreparation, context: AssembleContext, next: () => Promise): Promise -``` - -Types: [Scoped](scope.zh.md) - Source: [`packages/core/system-prompt/src/index.ts`](../../packages/core/system-prompt/src/index.ts) diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index 5350cc8f7d..7aff5f398b 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -569,7 +569,7 @@ get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - preparing agent, step model selection, and cancellation. + * @param context - preparing agent and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 5d33028bde..39a93905fe 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -569,7 +569,7 @@ get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - preparing agent, step model selection, and cancellation. + * @param context - preparing agent and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml index d97d05ce94..c2b1b153ac 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md /: - en: b56fc42e23dfd970 - zh: cbe86c0b3af8eee7 + en: d8520be9ef9ace75 + zh: 7aaf5e3eff54b19d /update-step-model-selection-conditional-tools-and-prompt-hooks: en: 81e0b8c4355e86a3 zh: 2563f89226c11cfb /update-step-model-selection-conditional-tools-and-prompt-hooks/change: - en: b2a7c15a9971ce4a - zh: ef217bd430dfb48f + en: be511d31b6f02e4f + zh: b25075b04ef28234 /update-step-model-selection-conditional-tools-and-prompt-hooks/migration: - en: f818cf83d987ae4b - zh: 7d4f431cdb10dd91 + en: c849786a9f5e5100 + zh: 15aa7729b7802ed4 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md index cff2857104..ab52391610 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "Step provider, model, and reasoning-effort selection moves from `agent/request` to `agent/model`, and custom tool and prompt plugins must use step-owned tool admission." +description: "Each step's provider, model, and reasoning effort come from `agent/model` through `agent.step`, plan selections commit at `agent/step-boundary`, and custom tool and prompt plugins must use step-owned tool admission." --- # Update step model selection, conditional tools, and prompt hooks @@ -9,16 +9,16 @@ English | [中文](guide.zh.md) ## Change -`agent/model` returns each step's `ModelSelection` (provider, model, and optional reasoning effort) before `system-prompt/prepare` and `agent/pre-step`. Prompt preparation, `agent/pre-step` through its new `modelSelection` payload field, tool conditions, and every request attempt in the step use that selection. `agent/request` still runs for each attempt after prompt assembly and `step/start`, but it may change only sampling controls such as `maxTokens`, `temperature`, and `stop`; returning another provider, model, or reasoning effort fails the step. An agent without options provider and model must receive them from `agent/model`. Plugins that replaced the provider, model, or effort in `agent/request`, including on a retry, are affected. `installModelSelection` applies its selection through `agent/model`, and `ModelSelectionRef` no longer has `assembled`. +`agent/model` returns each step's `ModelSelection` (provider, model, and optional reasoning effort) after the new serial `agent/step-boundary` event and before `agent/pre-step`. The loop publishes it as `agent.step` until the step ends; `agent/pre-step` listeners, tool conditions, prompt sections, and every request attempt read it there. `agent/request` still runs for each attempt after prompt assembly and `step/start`, but it may change only sampling controls such as `maxTokens`, `temperature`, and `stop`; returning another provider, model, or reasoning effort fails the step. An agent without options provider and model must receive them from `agent/model`. Plugins that replaced the provider, model, or effort in `agent/request`, including on a retry, are affected. `installModelSelection` applies its selection through `agent/model`, and `ModelSelectionRef` no longer has `assembled`. -Runtime context preparation uses `system-prompt/prepare`; `system-prompt/assemble` receives presentation fields without a tool array. Tool declarations remain owned by registered providers. Conditional tools require a resolved step set for execution, including nested PTC calls. Replacing a registration does not authorize an outstanding call to run the replacement. +`system-prompt/assemble` runs once per step after `step/start` and receives presentation fields without a tool array; tool declarations remain owned by registered providers. Pre-step decisions no longer contain the runtime-context message: the snapshot is admitted after the step's accepted messages, and a changed runtime context alone no longer opens a step. Conditional tools require a resolved step set for execution, including nested PTC calls. Replacing a registration does not authorize an outstanding call to run the replacement. -`exit_plan_mode` is offered only while committed plan mode is active. A failed plan-state write stops step admission and keeps the pending selection. Existing Sessions require no format migration. +`exit_plan_mode` is offered only while committed plan mode is active. A plan selection made during a turn is committed at the next `agent/step-boundary`, even when `agent/pre-step` rejects that step; a failed write fails the proposal and keeps the selection pending. Existing Sessions require no format migration. ## Migration -1. Move provider, model, and reasoning-effort replacement from `agent/request` listeners to `agent/model` listeners that return `{ provider, model, reasoningEffort? }`; an omitted effort uses the model's provider default. Keep only sampling changes in `agent/request`. Read the selection from `payload.modelSelection` in `agent/pre-step` and from `AssembleContext.modelSelection` in prompt providers. -2. Declare tool conditions with `ctx.tools.register(definition, { when })`; the condition receives `{ agent, modelSelection, signal }`. -3. Move runtime-context preparation listeners to `system-prompt/prepare`. Keep presentation changes in `system-prompt/assemble` and stop replacing its tool list. -4. For programmatic conditional calls, resolve `{ agent, modelSelection, signal }` through `ctx.tools.resolve()`, pass the resulting `toolSet` to assembly and execution, and dispose it after the batch settles. AgentLoop does this once per step for model calls. Pass `context.toolSet` when tool guidance queries `ctx.tools.get()` or `schemas()`. -5. Remove `assembled` from `ModelSelectionRef` objects, and add `modelSelection` to `agent/pre-step` payloads that tests dispatch directly. Verify that inactive tools are absent from declarations, that a historical name returns `UNKNOWN_TOOL` without reaching the implementation, and that an `agent/request` listener changing the model or effort ends the turn with an error naming `agent/model`. +1. Move provider, model, and reasoning-effort replacement from `agent/request` listeners to `agent/model` listeners that return `{ provider, model, reasoningEffort? }`; an omitted effort uses the model's provider default. Keep only sampling changes in `agent/request`. Read the step's selection from `agent.step` in `agent/pre-step` listeners, tool conditions, and prompt providers. +2. Declare tool conditions with `ctx.tools.register(definition, { when })`; the condition receives `{ agent, signal }`. +3. Keep presentation changes in `system-prompt/assemble` and stop replacing its tool list. Do not look for the runtime-context message in `agent/pre-step` decisions. +4. For programmatic conditional calls, resolve `{ agent, signal }` through `ctx.tools.resolve()`, pass the resulting `toolSet` to assembly and execution, and dispose it after the batch settles. AgentLoop does this once per step for model calls. Pass `context.toolSet` when tool guidance queries `ctx.tools.get()` or `schemas()`. +5. Commit state that applies from the next step in an `agent/step-boundary` listener. Remove `assembled` from `ModelSelectionRef` objects, and set `step` on test Agents whose pre-step listeners read the model. Verify that inactive tools are absent from declarations, that a historical name returns `UNKNOWN_TOOL` without reaching the implementation, and that an `agent/request` listener changing the model or effort ends the turn with an error naming `agent/model`. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md index 01fa5cfec8..4c2b6bbba4 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "步骤的提供方、模型与推理强度选择从 `agent/request` 移到 `agent/model`,自定义工具和提示词插件必须使用步骤拥有的工具准入集合。" +description: "每个步骤的提供方、模型与推理强度由 `agent/model` 决定并通过 `agent.step` 读取,计划选择在 `agent/step-boundary` 提交,自定义工具和提示词插件必须使用步骤拥有的工具准入集合。" --- # 更新步骤模型选择、条件工具与提示词钩子 @@ -9,16 +9,16 @@ description: "步骤的提供方、模型与推理强度选择从 `agent/request ## 变更 -`agent/model` 在 `system-prompt/prepare` 与 `agent/pre-step` 之前返回每个步骤的 `ModelSelection`(提供方、模型与可选的推理强度)。提示词准备、`agent/pre-step`(通过新增的 payload 字段 `modelSelection`)、工具条件以及该步骤的每次请求尝试都使用这一选择。`agent/request` 仍在提示词组装与 `step/start` 之后为每次尝试运行,但只能修改 `maxTokens`、`temperature`、`stop` 等采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。options 中没有提供方与模型的 agent 必须由 `agent/model` 提供。在 `agent/request` 中替换提供方、模型或推理强度的插件(包括在重试时替换的插件)会受到影响。`installModelSelection` 通过 `agent/model` 应用其选择,`ModelSelectionRef` 不再包含 `assembled`。 +`agent/model` 在新增的串行事件 `agent/step-boundary` 之后、`agent/pre-step` 之前返回每个步骤的 `ModelSelection`(提供方、模型与可选的推理强度)。循环把它发布为 `agent.step`,直到步骤结束;`agent/pre-step` 监听器、工具条件、提示词段落以及每次请求尝试都从这里读取。`agent/request` 仍在提示词组装与 `step/start` 之后为每次尝试运行,但只能修改 `maxTokens`、`temperature`、`stop` 等采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。options 中没有提供方与模型的 agent 必须由 `agent/model` 提供。在 `agent/request` 中替换提供方、模型或推理强度的插件(包括在重试时替换的插件)会受到影响。`installModelSelection` 通过 `agent/model` 应用其选择,`ModelSelectionRef` 不再包含 `assembled`。 -运行时上下文准备使用 `system-prompt/prepare`;`system-prompt/assemble` 接收不含工具数组的展示字段。工具声明仍由已注册提供方持有。条件工具执行需要已解析的步骤集合,包括嵌套 PTC 调用。替换注册不会授权尚未执行的旧调用使用新实现。 +`system-prompt/assemble` 在 `step/start` 之后每个步骤运行一次,接收不含工具数组的展示字段;工具声明仍由已注册提供方持有。pre-step 决策中不再包含运行时上下文消息:快照在该步骤已接纳的消息之后提交,仅运行时上下文变化也不再打开步骤。条件工具执行需要已解析的步骤集合,包括嵌套 PTC 调用。替换注册不会授权尚未执行的旧调用使用新实现。 -`exit_plan_mode` 只在已提交的计划模式启用时提供。计划状态写入失败会停止步骤接纳并保留待提交选择。现有 Session 无需格式迁移。 +`exit_plan_mode` 只在已提交的计划模式启用时提供。轮次进行中作出的计划选择在下一个 `agent/step-boundary` 提交,即使 `agent/pre-step` 拒绝了该步骤;写入失败会使该提案失败并保留待提交选择。现有 Session 无需格式迁移。 ## 迁移 -1. 把 `agent/request` 监听器中的提供方、模型与推理强度替换移到返回 `{ provider, model, reasoningEffort? }` 的 `agent/model` 监听器;省略推理强度时使用该模型的提供方默认值。`agent/request` 只保留采样参数的修改。在 `agent/pre-step` 中从 `payload.modelSelection` 读取选择,在提示词提供方中从 `AssembleContext.modelSelection` 读取选择。 -2. 使用 `ctx.tools.register(definition, { when })` 声明工具条件;条件接收 `{ agent, modelSelection, signal }`。 -3. 将运行时上下文准备监听器迁移到 `system-prompt/prepare`。展示变更留在 `system-prompt/assemble`,停止替换它的工具列表。 -4. 程序化调用条件工具时,通过 `ctx.tools.resolve()` 解析 `{ agent, modelSelection, signal }`,将返回的 `toolSet` 传给组装与执行,并在批次结束后释放。AgentLoop 会为模型调用在每个步骤完成一次这些操作。工具指导查询 `ctx.tools.get()` 或 `schemas()` 时传入 `context.toolSet`。 -5. 从 `ModelSelectionRef` 对象中删除 `assembled`,并为测试直接派发的 `agent/pre-step` payload 补上 `modelSelection`。验证未启用工具不出现在声明中,使用历史名称调用会返回 `UNKNOWN_TOOL` 且不会进入实现,并验证修改模型或推理强度的 `agent/request` 监听器会让轮次以指向 `agent/model` 的错误结束。 +1. 把 `agent/request` 监听器中的提供方、模型与推理强度替换移到返回 `{ provider, model, reasoningEffort? }` 的 `agent/model` 监听器;省略推理强度时使用该模型的提供方默认值。`agent/request` 只保留采样参数的修改。在 `agent/pre-step` 监听器、工具条件与提示词提供方中从 `agent.step` 读取步骤的模型选择。 +2. 使用 `ctx.tools.register(definition, { when })` 声明工具条件;条件接收 `{ agent, signal }`。 +3. 展示变更留在 `system-prompt/assemble`,停止替换它的工具列表。不要在 `agent/pre-step` 的决策中查找运行时上下文消息。 +4. 程序化调用条件工具时,通过 `ctx.tools.resolve()` 解析 `{ agent, signal }`,将返回的 `toolSet` 传给组装与执行,并在批次结束后释放。AgentLoop 会为模型调用在每个步骤完成一次这些操作。工具指导查询 `ctx.tools.get()` 或 `schemas()` 时传入 `context.toolSet`。 +5. 从下一个步骤起生效的状态在 `agent/step-boundary` 监听器中提交。从 `ModelSelectionRef` 对象中删除 `assembled`;若测试中的 pre-step 监听器读取模型,为测试 Agent 设置 `step`。验证未启用工具不出现在声明中,使用历史名称调用会返回 `UNKNOWN_TOOL` 且不会进入实现,并验证修改模型或推理强度的 `agent/request` 监听器会让轮次以指向 `agent/model` 的错误结束。 diff --git a/packages/api/session-controller/tests/archived-session-gate.host.spec.ts b/packages/api/session-controller/tests/archived-session-gate.host.spec.ts index 3c9d962f9e..79bad41b7c 100644 --- a/packages/api/session-controller/tests/archived-session-gate.host.spec.ts +++ b/packages/api/session-controller/tests/archived-session-gate.host.spec.ts @@ -47,7 +47,7 @@ async function liveAgent(ctx: Context, session: Session): Promise { /** Propose one model step for the Agent; the innermost decision enters. */ const proposed = (ctx: Context, agent: Agent) => ctx.waterfall( 'agent/pre-step', - { agent, messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, + { agent, messages: [], turn: 1, step: 1, signal: new AbortController().signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index f9e88d76d0..84def19bb7 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -33,8 +33,8 @@ en: 14acd4692e923480 zh: ff89aed852aa0da8 /deepseek-ai-dsh-client-ui-model-selection/model-experience: - en: 782f79ed910f426a - zh: 54a2e3e32a747544 + en: da858b97c79bf854 + zh: d0f7996f88679175 /deepseek-ai-dsh-client-ui-model-selection/model-experience/kv-cache-effect: en: 68e54c00412a40d1 zh: 0ac96f57fd194d96 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index a32460cdb9..cc0b6725e8 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -86,7 +86,7 @@ Read these pages when the model surface is not enough. They move from the browse ## Model Experience -Indirectly, through the `session.selectModel` selection both entries submit: the Host snapshots the complete `ModelSelection` at the next prompt-assembly boundary and owns the model-visible effect, while a running step keeps its assembled selection. +Indirectly, through the `session.selectModel` selection both entries submit: the Host applies the complete `ModelSelection` when the next step chooses its model and owns the model-visible effect, while a running step keeps the selection it started with. #### KV Cache effect diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index 21b13ec2d5..a65645f690 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -86,7 +86,7 @@ composer 的 `ModelSelect` 与 `/model` 选项构建器共用[提供方排序](s ## 模型体验 -两个入口提交的 `session.selectModel` 选择会间接影响模型:Host 会在下一次提示词组装边界为完整的 `ModelSelection` 创建快照,并负责使其对模型生效;运行中的步骤则保留已组装的选择。 +两个入口提交的 `session.selectModel` 选择会间接影响模型:Host 会在下一个步骤选择模型时应用完整的 `ModelSelection`,并负责使其对模型生效;运行中的步骤则保留开始时的选择。 #### KV Cache 影响 diff --git a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts index a1d1d28162..3736aa5c5e 100644 --- a/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts +++ b/packages/compaction/compaction-basic/tests/compaction-basic.spec.ts @@ -1675,7 +1675,7 @@ describe('default one-shot summarizer', () => { describe('automatic listener and loader composition', () => { function preStep(ctx: Context, owner: Agent, signal = SIGNAL) { return agentEvents(ctx, owner).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) } diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index ef3da9000f..721866df73 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -310,7 +310,7 @@ async function agentInstructionsOf(agent: Agent): Promise { async function syncAgentInstructions(ctx: Context, agent: Agent): Promise { await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: testToolSignal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, signal: testToolSignal }, async () => ({ kind: 'enter' as const, messages: [] }), ) } @@ -345,13 +345,13 @@ async function composeBaselinePrefix(ctx: Context, agent: TestAgent): Promise Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const claimed = claimInbox(agent, 'next-step') const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 2, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: claimed, turn: 1, step: 2, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) const entered = decision.kind === 'enter' ? decision.messages : [] @@ -1724,7 +1724,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(ctx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const inserted = original.inbox.nextStep[0] @@ -1738,7 +1738,7 @@ describe('workspace context request injection', () => { const claimed = claimInbox(resumed, 'next-step') const decision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) if (decision.kind !== 'enter') throw new Error('recovered baseline was rejected') @@ -1773,7 +1773,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(ctx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const stale = original.inbox.nextStep[0] @@ -1788,7 +1788,7 @@ describe('workspace context request injection', () => { const staleClaim = claimInbox(resumed, 'next-step') const staleDecision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', - { messages: staleClaim, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: staleClaim, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: staleClaim }), ) @@ -1831,7 +1831,7 @@ describe('workspace context request injection', () => { const original = await stubAgent(root) await agentEvents(originalCtx, original).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) const stale = original.inbox.nextStep[0] @@ -1846,7 +1846,7 @@ describe('workspace context request injection', () => { const claimed = claimInbox(resumed, 'next-step') const decision = await agentEvents(resumedCtx, resumed).waterfall( 'agent/pre-step', - { messages: claimed, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: claimed }), ) @@ -1959,7 +1959,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [prompt], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [prompt], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve(downstream), ) @@ -2551,7 +2551,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [], turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve(downstream), ) @@ -2673,7 +2673,7 @@ describe('workspace context request injection', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [prompt], turn: 2, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: AbortSignal.timeout(requestTimeoutMs) }, + { messages: [prompt], turn: 2, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, () => Promise.resolve({ kind: 'enter' as const, messages: [prompt] }), ) @@ -3137,7 +3137,7 @@ describe('workspace context request injection', () => { const reason = new Error('cancel prefix') const pending = agentEvents(ctx, await stubAgent(root)).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: controller.signal }, + { messages: [], turn: 1, step: 1, signal: controller.signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) @@ -5770,7 +5770,7 @@ describe('workspace context inbox synchronization', () => { controller.abort(new Error('abort pre-step reconciliation')) await expect(agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: controller.signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, signal: controller.signal }, async () => ({ kind: 'enter' as const, messages: [] }), )).rejects.toThrow('abort pre-step reconciliation') @@ -5889,7 +5889,7 @@ describe('workspace context inbox synchronization', () => { const downstream = { kind: 'enter' as const, messages: claimed } const decision = await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: claimed, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: testToolSignal }, + 'agent/pre-step', { messages: claimed, turn: 1, step: 1, signal: testToolSignal }, async () => downstream, ) diff --git a/packages/context/session-reference/README.i18n.yaml b/packages/context/session-reference/README.i18n.yaml index 64a394e658..d54bf729b6 100644 --- a/packages/context/session-reference/README.i18n.yaml +++ b/packages/context/session-reference/README.i18n.yaml @@ -33,8 +33,8 @@ en: db349483e453caf7 zh: 70035c291e1efe84 /deepseek-ai-dsh-session-reference/understand-the-implementation/design-concept: - en: 7171fcac9b67e148 - zh: 0ccd05e624ca8ab9 + en: 1c50eff549fbb26f + zh: 8caefc6c2634ced0 /deepseek-ai-dsh-session-reference/understand-the-implementation/source-map: en: 7c7b413082507150 zh: 0229eb73d441b305 diff --git a/packages/context/session-reference/README.md b/packages/context/session-reference/README.md index 32a387f879..f5187910c9 100644 --- a/packages/context/session-reference/README.md +++ b/packages/context/session-reference/README.md @@ -70,7 +70,7 @@ Preparation reads each referenced session's current surface exactly once, when t The resolver discovers optional storage through `ctx.get("spillStore")` and saves only truncated references. Storage ownership is the target session; the source descriptor identifies the referenced session and label, without a fabricated tool call. Cancellation is checked after the asynchronous save and prevents publication even if an artifact was written. Artifact expiry remains the backend's existing policy. -The budget uses the step model that `agent/model` chose, which `agent/pre-step` carries as `modelSelection`. Direct `prepare` calls without a model selection use agent options; session headers do not select the budget model. +The budget uses the step model that `agent/model` chose, which the agent exposes as `agent.step` during `agent/pre-step`. Direct `prepare` calls outside a step use agent options; session headers do not select the budget model. ### Source map diff --git a/packages/context/session-reference/README.zh.md b/packages/context/session-reference/README.zh.md index 129db83741..f17baaebce 100644 --- a/packages/context/session-reference/README.zh.md +++ b/packages/context/session-reference/README.zh.md @@ -70,7 +70,7 @@ kind: "package-reference" 解析器通过 `ctx.get("spillStore")` 获取可选存储,只保存被截断的引用。存储归目标会话所有;来源信息标识被引用的源会话与标签,不伪造工具调用。异步保存后会检查取消,即使产物已写入,也会阻止发布。产物过期仍遵循后端既有策略。 -预算使用 `agent/model` 选定、由 `agent/pre-step` 以 `modelSelection` 携带的步骤模型。未传入模型选择的直接 `prepare` 调用使用 agent 选项;Session 请求头不决定预算模型。 +预算使用 `agent/model` 选定的步骤模型,`agent/pre-step` 期间 agent 通过 `agent.step` 公开它。步骤之外的直接 `prepare` 调用使用 agent 选项;Session 请求头不决定预算模型。 ### 源码地图 diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index 2d67bc8197..34ff2f7ba9 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -7,7 +7,7 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import type { Agent, ModelSelection, PreStepDecision } from '@deepseek-ai/dsh-agent' +import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { createUserMessage, freezeMessage, LlmError } from '@deepseek-ai/dsh-llm' import type { ContentBlock, LlmResolvedModelInfo, UserMessage } from '@deepseek-ai/dsh-llm' @@ -122,12 +122,12 @@ export class SessionReferenceResolver extends TypertRemoteService { 'SESSION_REFERENCE_INVALID_CONFIG', ) } - ctx.on('agent/pre-step', async ({ agent, modelSelection, signal }, next): Promise => { + ctx.on('agent/pre-step', async ({ agent, signal }, next): Promise => { const decision = await next() if (decision.kind === 'reject') return decision return { ...decision, - messages: await this.prepareDirectMessages(agent, modelSelection, decision.messages, signal), + messages: await this.prepareDirectMessages(agent, decision.messages, signal), } }, { prepend: true }) } @@ -136,14 +136,12 @@ export class SessionReferenceResolver extends TypertRemoteService { * Replace canonical mentions in direct user messages and place each prepared * snapshot immediately after the message that cited it. * @param agent - agent entering the model step. - * @param modelSelection - provider and model of the step. * @param messages - messages accepted by downstream pre-step listeners. * @param signal - active turn cancellation. * @returns direct messages followed by their session-reference context in citation order. */ private async prepareDirectMessages( agent: Agent, - modelSelection: ModelSelection, messages: readonly UserMessage[], signal: AbortSignal, ): Promise { @@ -157,7 +155,7 @@ export class SessionReferenceResolver extends TypertRemoteService { return { type: 'text', text: parsed.text } }) if (references.length === 0) return [message] - const resolved = await this.prepare(agent, content, references, signal, modelSelection) + const resolved = await this.prepare(agent, content, references, signal) const direct = freezeMessage({ ...message, content: resolved.content }) /* v8 ignore if -- a parsed canonical mention always leaves one normalized reference */ if (resolved.additionalContext === undefined) { @@ -278,7 +276,7 @@ export class SessionReferenceResolver extends TypertRemoteService { /** * Snapshot all references for one accepted direct message and return one aggregated durable context. - * Automatic budgets use the step's model selection, or agent options for direct preparation. + * Automatic budgets use the model of the agent's current step, or agent options outside a step. * Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. * Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. * Cancellation prevents context publication, including when storage completes after cancellation. @@ -286,7 +284,6 @@ export class SessionReferenceResolver extends TypertRemoteService { * @param content - already host-normalized readable message content. * @param references - structured source sessions in mention order. * @param signal - optional cancellation boundary for the active turn. - * @param modelSelection - provider and model of the step admitting the message; omitted for direct preparation. * @returns detached content and optional referenced-session context. */ async prepare( @@ -294,13 +291,12 @@ export class SessionReferenceResolver extends TypertRemoteService { content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, - modelSelection?: ModelSelection, ): Promise { const acceptedContent = structuredClone(content) const inputs = normalizeReferences(agent.id, references, this.config.maxReferences) if (inputs.length === 0) return { content: acceptedContent } assertNotCancelled(signal) - const maxReferenceBytes = await this.referenceBudget(agent, modelSelection, signal) + const maxReferenceBytes = await this.referenceBudget(agent, signal) assertNotCancelled(signal) let prepared: PreparedSource[] try { @@ -351,14 +347,10 @@ export class SessionReferenceResolver extends TypertRemoteService { return { content: acceptedContent, additionalContext } } - private async referenceBudget( - agent: Agent, - modelSelection: ModelSelection | undefined, - signal: AbortSignal | undefined, - ): Promise { + private async referenceBudget(agent: Agent, signal: AbortSignal | undefined): Promise { if (this.config.maxReferenceBytes !== undefined) return this.config.maxReferenceBytes - // Options seed direct preparation; the step's model selection owns model-step preparation. - const { provider, model } = modelSelection ?? agent.options + // Options seed preparation outside a step; the step's model selection owns step preparation. + const { provider, model } = agent.step?.modelSelection ?? agent.options const llm = this.ctx.get('llm') if (provider === undefined || model === undefined || llm === undefined) return DEFAULT_MAX_REFERENCE_BYTES let info: LlmResolvedModelInfo diff --git a/packages/context/session-reference/tests/loader-composition.spec.ts b/packages/context/session-reference/tests/loader-composition.spec.ts index f387fdd1f7..3c8cfa6e15 100644 --- a/packages/context/session-reference/tests/loader-composition.spec.ts +++ b/packages/context/session-reference/tests/loader-composition.spec.ts @@ -77,7 +77,7 @@ describe('session-reference real Loader composition', () => { source: { kind: 'user' }, }) const decision = await agentEvents(ctx, agent).waterfall('agent/pre-step', { - messages: [direct], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal, + messages: [direct], turn: 1, step: 1, signal: new AbortController().signal, }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct] })) expect(decision.kind).toBe('enter') if (decision.kind !== 'enter') throw new Error('Expected admitted reference') diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index 643c868caa..a69b71e998 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -466,7 +466,7 @@ describe('session reference spill outcomes', () => { }) const direct = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const pending = agentEvents(ctx, fakeAgent(target)).waterfall('agent/pre-step', - { messages: [direct], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: controller.signal }, + { messages: [direct], turn: 1, step: 1, signal: controller.signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct] })) const rejected = expect(pending).rejects.toThrow(expectCode('SESSION_REFERENCE_CANCELLED')) await started.promise @@ -538,7 +538,7 @@ describe('model-relative reference budgets', () => { let modelSelection = { provider: 'selected', model: 'large' } const message = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const signal = new AbortController().signal - const enter = () => agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, modelSelection, signal }, + const enter = () => agentEvents(ctx, { ...agent, step: { modelSelection } }).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [message] })) const first = await enter() expect(first.kind).toBe('enter') @@ -621,7 +621,7 @@ describe('model-relative reference budgets', () => { expect(resolve).toHaveBeenLastCalledWith('seed', 'seed', undefined) const message = createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: formatSessionReferenceMention({ sessionId: source.id }) }] }) const seed = { kind: 'enter' as const, messages: [message] } - await expect(agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal }, + await expect(agentEvents(ctx, agent).waterfall('agent/pre-step', { messages: [message], turn: 1, step: 1, signal: new AbortController().signal }, () => Promise.resolve(seed))).resolves.toBe(seed) }) @@ -877,7 +877,7 @@ describe('session reference discovery and preparation', () => { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [direct, ordinary, plugin], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: [direct, ordinary, plugin], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [direct, ordinary, plugin] }), ) @@ -913,14 +913,14 @@ describe('session reference discovery and preparation', () => { await expect(agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [malformed], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: [malformed], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'reject' as const }), )).resolves.toEqual({ kind: 'reject' }) expect(readSurface).not.toHaveBeenCalled() await expect(agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [malformed], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: [malformed], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [malformed] }), )).rejects.toThrow(/invalid session reference URI/) }) diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index a50195aff8..92499007d1 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -98,7 +98,7 @@ async function fire( }) const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [proposed], turn, step, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: [proposed], turn, step, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [proposed] }), ) if (decision.kind === 'enter') { diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index 50990452e3..ae15f20a46 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -151,7 +151,7 @@ async function fire( ): Promise { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn, step, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: [], turn, step, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 62ace68991..43cddfd1dd 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -45,8 +45,8 @@ en: 3c5721bc00a0bbf4 zh: 711f832343ffbb75 /deepseek-ai-dsh-agent-loop/understand-the-implementation/turn-and-step-flow: - en: 0063a07435bc4028 - zh: c873fd82c927a7c2 + en: db754159572b2c69 + zh: c9358e9df71ea589 /deepseek-ai-dsh-agent-loop/understand-the-implementation/failure-and-cancellation: en: eea56903c4ff82f5 zh: c0d5abb5767780ed diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index c42100eae7..1db9b2c0c6 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -117,7 +117,7 @@ The loop is the production acquisition point for session write handles. When `ct ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver chooses the step's provider, model, and reasoning effort through `agent/model`, prepares variables and runtime context with that selection, then runs `agent/pre-step`; its fallback projects that context. A rejected decision or empty first batch opens no step. Cancellation during model selection opens no step. After acceptance, `step/start` precedes asynchronous tool activation and final prompt assembly, both once per step. Each attempt then runs the `agent/request` waterfall and `prepareCall()` with the step's model selection; a listener that returns another provider, model, or reasoning effort fails the step, and cancellation during either async phase commits neither the pending system prompt nor accepted users. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt with its owned context candidate replaced in place, and restores removed runtime context, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the step's model selection, tool set, and rendered assembly without repeating model selection, tool activation, assembly, `agent/pre-step`, or user admission. The step-owned tool set is closed after the step's tool batch settles. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver dispatches `agent/step-boundary`, chooses the step's provider, model, and reasoning effort through `agent/model`, publishes them as `agent.step`, then runs `agent/pre-step`, whose fallback enters the claimed batch unchanged. A rejected decision or empty first batch opens no step; a changed runtime context alone does not open one. Cancellation at the boundary or during model selection opens no step. `agent.step` is cleared when the step ends or its proposal is rejected, fails, or is cancelled. After acceptance, `step/start` precedes asynchronous tool activation and one prompt assembly of sections, variables, runtime context, and tool declarations, both once per step. Each attempt then runs the `agent/request` waterfall and `prepareCall()` with the step's model selection; a listener that returns another provider, model, or reasoning effort fails the step, and cancellation during either async phase commits neither the pending system prompt nor accepted users. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt, then appends the runtime-context snapshot when it changed or was removed, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the step's model selection, tool set, and rendered assembly without repeating model selection, tool activation, assembly, `agent/pre-step`, or user admission. The step-owned tool set is closed after the step's tool batch settles. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) Prompt admission uses the actual `prepareCall()` result, not the preceding `request/context`. With no system node, even an empty prompt is appended (reserving node 0 without a wire message). On an incapable route or at a new request series, a non-empty rendering is consolidated at the first system node: each non-empty later system node receives a logged per-node empty replacement, then the head is rewritten if needed. Dormant empty tails need no replacement and do not determine the effective text. Consolidation applies even when the latest effective text is unchanged. On a continuing `in-history` series, an unchanged effective prompt produces no event and a non-empty change appends. An empty rendering clears every non-empty later system node through a logged per-node empty replacement, then empties the head if needed, regardless of route or series state. No older instructions remain model-visible. An empty head with no active later system node means no prompt; repeated clears and resume leave it empty. A restored non-empty prompt follows the same route/series rule: a continuing capable route may append it, while an incapable route or new series refills the head. A step starts a series when the pre-step decision declares `startsRequestSeries` or `session.surface.contentGeneration` changed since attachment or the last request (a replacement or image-offload decision). Visible tool-schema changes force prompt consolidation only when the prepared route lacks `toolUpdate`. Routes supporting both tool and system-prompt updates can append a changed prompt and activate added tools without rewriting earlier messages. If another admission condition replaces a system node, the request starts a new series with current tool declarations. Resume and a provider or model swap alone continue the series; the prepared route still governs admission. Per-node empty replacements preserve intervening history without a surface delete operation. diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 3427ef23c7..03b5f3b15f 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -117,7 +117,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器通过 `agent/model` 选定步骤的提供方、模型与推理强度,按该选择准备变量和运行时上下文,然后运行 `agent/pre-step`;fallback 投影该上下文。被拒绝的决定或空的首批输入不打开步骤。模型选择期间取消不会打开步骤。接纳后,`step/start` 先于异步工具激活与最终提示词组装,两者每个步骤各执行一次。每次尝试随后按步骤的模型选择运行 `agent/request` waterfall 与 `prepareCall()`;监听器若返回其他提供方、模型或推理强度,步骤会失败,而在任一异步阶段取消都不会提交待定的系统提示词或已接纳用户消息。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次并原位替换循环自有上下文候选、恢复被移除的运行时上下文、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试复用该步骤的模型选择、工具集合与已渲染组装结果,不重复模型选择、工具激活、组装、`agent/pre-step` 或用户消息接纳。步骤拥有的工具集合在该步骤的工具批次结束后关闭。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器派发 `agent/step-boundary`,通过 `agent/model` 选定步骤的提供方、模型与推理强度并发布为 `agent.step`,然后运行 `agent/pre-step`,其 fallback 原样接纳已领取批次。被拒绝的决定或空的首批输入不打开步骤;仅运行时上下文变化也不会打开步骤。在步骤边界或模型选择期间取消不会打开步骤。步骤结束或提案被拒绝、失败、取消时,`agent.step` 会被清除。接纳后,`step/start` 先于异步工具激活与一次提示词组装(段落、变量、运行时上下文与工具声明),两者每个步骤各执行一次。每次尝试随后按步骤的模型选择运行 `agent/request` waterfall 与 `prepareCall()`;监听器若返回其他提供方、模型或推理强度,步骤会失败,而在任一异步阶段取消都不会提交待定的系统提示词或已接纳用户消息。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次,随后在运行时上下文变化或被移除时追加其快照、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试复用该步骤的模型选择、工具集合与已渲染组装结果,不重复模型选择、工具激活、组装、`agent/pre-step` 或用户消息接纳。步骤拥有的工具集合在该步骤的工具批次结束后关闭。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 提示词准入依据实际的 `prepareCall()` 结果,而非先前的 `request/context`。没有系统节点时,即使提示词为空也追加(预留第 0 号节点,但不产生协议消息)。在不具备能力的路由上或新请求序列开始时,非空渲染文本归并到首个系统节点:每个非空的后续系统节点分别收到有日志记录的空内容替换,随后按需重写头节点。未生效的空尾节点无需替换,也不决定有效文本。即使最新有效文本未变,也执行归并。延续中的 `in-history` 序列在有效提示词不变时不产生事件,非空变更则追加。无论路由或序列状态如何,空渲染文本都会通过有日志记录的逐节点空内容替换清除每个非空的后续系统节点,再按需清空头节点。模型不会继续看到旧指令。空头节点且没有生效的后续系统节点表示没有提示词;重复清除与恢复会话都保持为空。重新提供的非空提示词遵循同一路由/序列规则:延续中的具备能力路由可以追加它,不具备能力的路由或新序列则重新填充头节点。以下情况开启序列:pre-step 决定声明 `startsRequestSeries`,或 `session.surface.contentGeneration` 自附接或上次请求以来发生变化(替换或图片省略决定)。仅当已准备路由未声明 `toolUpdate` 时,可见工具 schema 变化才强制归并提示词。同时支持工具和系统提示词更新的路由可以追加变更后的提示词并激活新增工具,无需改写此前消息。如果其他准入条件替换系统节点,请求会以当前工具声明开启新序列。恢复与单纯的提供方或模型切换都延续序列;准入仍由已准备的路由决定。逐节点的空内容替换保留其间历史,无需 surface 删除操作。 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 2eac31c365..0592cdf9b6 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -10,6 +10,7 @@ import type { AgentEventDispatch, AgentOptions, AgentStatus, + AgentStep, CancelOptions, InboxTarget, ModelSelection, @@ -31,7 +32,7 @@ import { createScope } from '@deepseek-ai/dsh-scope' import type { EpochHeader, RequestContext, Session, SessionId, SessionSeq, TurnEndReason, UserMessage } from '@deepseek-ai/dsh-session' import { canonicalHeader, headerEquals, ToolCallRecovery } from '@deepseek-ai/dsh-session' import { joinContextSections, renderContextSections, renderPrompt } from '@deepseek-ai/dsh-system-prompt' -import type { PromptAssembly, PromptPreparation } from '@deepseek-ai/dsh-system-prompt' +import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-session-projection' import type { Context } from '@deepseek-ai/cordis' import { ReactLoopInbox } from './inbox.ts' @@ -65,7 +66,6 @@ type PreparedStep = messages: UserMessage[] startsRequestSeries?: true modelSelection: ModelSelection - preparation: PromptPreparation } /** Name a provider, model, and reasoning effort in diagnostics. */ @@ -122,6 +122,8 @@ export class ReactLoopAgent implements Agent { /** Whether this loop instance has appended its initial/resume request anchor. */ private requestHeaderLogged = false + /** Decisions published for the step being proposed or run; cleared between steps. */ + private currentStep: AgentStep | undefined /** Surface generation at attachment or the preceding built request. */ private requestSurfaceGeneration: number private readonly runtimeContext: RuntimeContextProjection @@ -154,6 +156,10 @@ export class ReactLoopAgent implements Agent { return this.phase.kind === 'idle' || this.phase.kind === 'maintenance' ? 'idle' : 'running' } + get step(): AgentStep | undefined { + return this.currentStep + } + /** Commit a phase and publish its externally visible status transition. */ private setPhase(next: Phase): void { const previousStatus = this.status @@ -282,23 +288,17 @@ export class ReactLoopAgent implements Agent { if (this.phase.kind !== 'running') throw new Error(`agent "${this.id}": pre-step outside running phase`) const signal = this.phase.abort.signal const claimed = this.inbox.claim(target, position.turn) - const modelSelection = await this.chooseModel(position.turn, position.step, signal) - const preparation = await this.loopCtx.systemPrompt.prepare({ ...assembleContextFor(this, signal), modelSelection }) + await this.dispatch.serial('agent/step-boundary', { ...position, signal }) signal.throwIfAborted() + const modelSelection = await this.chooseModel(position.turn, position.step, signal) + this.currentStep = Object.freeze({ modelSelection }) const decision = await this.dispatch.waterfall( - 'agent/pre-step', { messages: claimed, ...position, modelSelection, signal }, - (): Promise => { - const sections = renderContextSections(preparation) - const context = this.runtimeContext.project(joinContextSections(sections), sections) - return Promise.resolve({ - kind: 'enter', - messages: context === undefined ? claimed : [...claimed, context], - }) - }, + 'agent/pre-step', { messages: claimed, ...position, signal }, + () => Promise.resolve({ kind: 'enter', messages: claimed }), ) signal.throwIfAborted() if (decision.kind === 'reject') return decision - return { ...decision, modelSelection, preparation } + return { ...decision, modelSelection } } /** Choose the provider, model, and effort that the proposed step keeps for every request attempt. */ @@ -348,47 +348,51 @@ export class ReactLoopAgent implements Agent { while (true) { signal.throwIfAborted() const step = phase.step + 1 - const decision = await this.preStep(target, { turn, step }) - if (decision.kind === 'reject') { - turnEnds = { kind: 'blocked' } - return false - } - if (turnEnds && decision.messages.length === 0) break - // A removed waking message or an enter decision rewritten to empty - // still owns the initial turn boundary, but it spends no model call. - if (phase.step === 0 && decision.messages.length === 0) { - turnEnds = { kind: 'completed' } - return false - } - signal.throwIfAborted() - this.session.append('step/start', { turn, step }) - phase.step = step - const toolRecovery = new ToolCallRecovery() - const stopRecovery = this.ctx.on('session/event', (session, event) => { - if (session === this.session) toolRecovery.observe(event) - }) try { - // max-tokens is sticky: once any step hits the ceiling, later steps - // that complete normally must not downgrade the turn outcome. - const stepEnd = await this.step(decision) - // max-tokens stays sticky: a later completed step must not - // downgrade the turn outcome. - if (turnEnds === null || turnEnds.kind !== 'max-tokens') turnEnds = stepEnd - } catch (error: unknown) { + const decision = await this.preStep(target, { turn, step }) + if (decision.kind === 'reject') { + turnEnds = { kind: 'blocked' } + return false + } + if (turnEnds && decision.messages.length === 0) break + // A removed waking message or an enter decision rewritten to empty + // still owns the initial turn boundary, but it spends no model call. + if (phase.step === 0 && decision.messages.length === 0) { + turnEnds = { kind: 'completed' } + return false + } + signal.throwIfAborted() + this.session.append('step/start', { turn, step }) + phase.step = step + const toolRecovery = new ToolCallRecovery() + const stopRecovery = this.ctx.on('session/event', (session, event) => { + if (session === this.session) toolRecovery.observe(event) + }) try { - for (const event of toolRecovery.results()) { - this.session.append('tool/result', event.data, { - surfaceOp: 'append', - ...event.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: event.sourceEventSeqs }, - }) + // max-tokens is sticky: once any step hits the ceiling, later steps + // that complete normally must not downgrade the turn outcome. + const stepEnd = await this.runStep(decision) + // max-tokens stays sticky: a later completed step must not + // downgrade the turn outcome. + if (turnEnds === null || turnEnds.kind !== 'max-tokens') turnEnds = stepEnd + } catch (error: unknown) { + try { + for (const event of toolRecovery.results()) { + this.session.append('tool/result', event.data, { + surfaceOp: 'append', + ...event.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: event.sourceEventSeqs }, + }) + } + } catch (recoveryError: unknown) { + throw new AggregateError([error, recoveryError], 'Step failed and its pending tool results could not be recorded', { cause: error }) } - } catch (recoveryError: unknown) { - throw new AggregateError([error, recoveryError], 'Step failed and its pending tool results could not be recorded', { cause: error }) + throw error + } finally { + stopRecovery() + this.session.append('step/end', { turn, step }) } - throw error } finally { - stopRecovery() - this.session.append('step/end', { turn, step }) + this.currentStep = undefined } signal.throwIfAborted() if (turnEnds && this.inbox.nextStep.length === 0) { @@ -428,24 +432,21 @@ export class ReactLoopAgent implements Agent { return true } - private async step(decision: Extract): Promise { + private async runStep(decision: Extract): 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 signal.throwIfAborted() - const { modelSelection } = decision - const toolSet = await this.loopCtx.tools.resolve({ agent: this, modelSelection, signal }) + const toolSet = await this.loopCtx.tools.resolve({ agent: this, signal }) try { - const assembly = await this.loopCtx.systemPrompt.assemble( - { ...assembleContextFor(this, signal), modelSelection, toolSet }, - decision.preparation, - ) + const assembleContext = { ...assembleContextFor(this, signal), toolSet } + const assembly = await this.loopCtx.systemPrompt.assemble(assembleContext) const renderedPrompt = renderPrompt(assembly) let firstAttempt = true while (true) { - const { config, preparedCall } = await this.prepareRequest(turn, step, modelSelection, signal) - const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, { ...assembleContextFor(this, signal), modelSelection }) + const { config, preparedCall } = await this.prepareRequest(turn, step, decision.modelSelection, signal) + const currentContext = this.loopCtx.systemPrompt.refreshContext(assembly, assembleContext) const sections = renderContextSections(currentContext) const context = this.runtimeContext.project(joinContextSections(sections), sections) signal.throwIfAborted() @@ -459,22 +460,11 @@ export class ReactLoopAgent implements Agent { for (const { message, intent } of commits) { this.session.append('system/message', { turn, step, message }, intent) } - let contextAdmitted = false if (firstAttempt) { - for (const message of decision.messages) { - if (message.source.kind === 'runtime-context') { - if (context !== undefined && !contextAdmitted) { - this.session.append('user/message', context, { surfaceOp: 'append' }) - contextAdmitted = true - } - } else { - this.session.append('user/message', message, { surfaceOp: 'append' }) - } - } - } - if (context !== undefined && !contextAdmitted) { - this.session.append('user/message', context, { surfaceOp: 'append' }) + for (const message of decision.messages) this.session.append('user/message', message, { surfaceOp: 'append' }) } + // The runtime-context snapshot follows the admitted batch. + if (context !== undefined) this.session.append('user/message', context, { surfaceOp: 'append' }) firstAttempt = false const request = this.buildRequest(config, preparedCall, assembly.tools, { turn, step }, startsRequestSeries, signal) const live = new AssistantStreamAttempt( diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 34e7879654..85b4ab9162 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -386,8 +386,8 @@ export class AgentLoop extends Service implements AgentFactory { }) }, 'agentLoop.transactions()') ctx.effect(() => ctx.agents.setFactory(this), 'agentLoop.setFactory()') - ctx.systemPrompt.variable('provider', context => context.modelSelection?.provider ?? context.agent?.options.provider) - ctx.systemPrompt.variable('model', context => context.modelSelection?.model ?? context.agent?.options.model) + ctx.systemPrompt.variable('provider', context => context.agent?.step?.modelSelection.provider ?? context.agent?.options.provider) + ctx.systemPrompt.variable('model', context => context.agent?.step?.modelSelection.model ?? context.agent?.options.model) for (const { id, sessionId, cwd, resumeSessionId, ...options } of this.config.agents) { const meta = cwd === undefined ? {} : { cwd } diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index 193544367f..6bcc77323b 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -796,7 +796,7 @@ describe('agent loop', () => { } }) - it('replaces a stale owned snapshot at its accepted position and admits it once', async () => { + it('admits the runtime-context snapshot current at admission after the accepted batch', async () => { const adapter = new MockAdapter([textResponse('done')]) const ctx = await harness(adapter) try { @@ -807,16 +807,20 @@ describe('agent loop', () => { const decision = await next() current = 'after' if (decision.kind === 'reject') return decision - const context = decision.messages.find(message => message.source.kind === 'runtime-context')! - return { ...decision, messages: [context, ...decision.messages.filter(message => message !== context), context] } + expect(decision.messages.map(message => message.source.kind)).toEqual(['user']) + const appended = createUserMessage({ content: [{ type: 'text', text: 'appended' }], source: { kind: 'user' } }) + return { ...decision, messages: [...decision.messages, appended] } }) send(agent, 'accepted user') await agent.whenIdle() const users = adapter.requests[0]?.messages.filter(message => message.role === 'user') ?? [] - expect(users.map(message => message.source?.kind)).toEqual(['runtime-context', 'user']) - expect(users[0]?.content).toEqual([{ type: 'text', text: 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nafter' }]) - expect(users[1]?.content).toEqual([{ type: 'text', text: 'accepted user' }]) - expect(agent.session.snapshotEvents().filter(event => event.type === 'user/message')).toHaveLength(2) + expect(users.map(message => message.content)).toEqual([ + [{ type: 'text', text: 'accepted user' }], + [{ type: 'text', text: 'appended' }], + [{ type: 'text', text: 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nafter' }], + ]) + expect(users.at(-1)?.source?.kind).toBe('runtime-context') + expect(agent.session.snapshotEvents().filter(event => event.type === 'user/message')).toHaveLength(3) } finally { await ctx.fiber.dispose() } diff --git a/packages/core/agent-loop/tests/step-model.spec.ts b/packages/core/agent-loop/tests/step-model.spec.ts new file mode 100644 index 0000000000..97f345c280 --- /dev/null +++ b/packages/core/agent-loop/tests/step-model.spec.ts @@ -0,0 +1,231 @@ +/** Each proposed step commits boundary selections, then publishes its model selection as `agent.step`. */ +import { afterEach, describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools' +import AgentRegistry, { type Agent, type AgentStep } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts' + +const contexts: Context[] = [] +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() +}) + +async function harness(adapter: MockAdapter): Promise { + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(LlmRuntime) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(AgentRegistry) + await ctx.plugin(AgentLoop, { agents: [] }) + ctx.llm.registerAdapter(['mock'], adapter) + return ctx +} + +function send(agent: Agent, text: string): void { + agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })) +} + +function eventTypes(agent: Agent): string[] { + return agent.session.snapshotEvents().map(event => event.type) +} + +function lastTurnEnd(agent: Agent) { + const event = agent.session.snapshotEvents().findLast(entry => entry.type === 'turn/end') + return event?.type === 'turn/end' ? event.data.reason : undefined +} + +describe('agent.step', () => { + it('publishes one frozen selection from agent/model through its step and clears it between steps', async () => { + const adapter = new MockAdapter([toolCallResponse('c1', 'probe', {}), textResponse('done')]) + const ctx = await harness(adapter) + const agent = await ctx.agentLoop.create(SessionId('step-visibility'), { provider: 'mock', model: 'mock' }) + const seen = { + boundary: [] as (AgentStep | undefined)[], + model: [] as (AgentStep | undefined)[], + preStep: [] as (AgentStep | undefined)[], + condition: [] as (AgentStep | undefined)[], + section: [] as (AgentStep | undefined)[], + request: [] as (AgentStep | undefined)[], + execute: [] as (AgentStep | undefined)[], + stopping: [] as (AgentStep | undefined)[], + } + ctx.on('agent/step-boundary', ({ agent: subject }) => { seen.boundary.push(subject.step) }) + ctx.on('agent/model', async ({ agent: subject }, next) => { + seen.model.push(subject.step) + return next() + }) + ctx.on('agent/pre-step', async ({ agent: subject }, next) => { + seen.preStep.push(subject.step) + return next() + }) + ctx.on('agent/request', async ({ agent: subject }, next) => { + seen.request.push(subject.step) + return next() + }) + ctx.on('agent/turn-stopping', ({ agent: subject }) => { seen.stopping.push(subject.step) }) + ctx.systemPrompt.section({ + name: 'probe', + order: 0, + text: (context) => { + seen.section.push(context.agent?.step) + return '' + }, + }) + ctx.tools.register(defineContentToolFixture({ + name: 'probe', description: 'Record the calling step.', parameters: {}, + async execute(_args, exec) { + seen.execute.push(exec.agent?.step) + return [] + }, + }), { + when: ({ agent: subject }) => { + seen.condition.push(subject.step) + return true + }, + }) + + send(agent, 'go') + await agent.whenIdle() + + expect(seen.boundary).toEqual([undefined, undefined]) + expect(seen.model).toEqual([undefined, undefined]) + const [first, second] = seen.preStep + expect(first).toEqual({ modelSelection: { provider: 'mock', model: 'mock' } }) + expect(Object.isFrozen(first)).toBe(true) + expect(Object.isFrozen(first?.modelSelection)).toBe(true) + expect(second).toEqual(first) + expect(second).not.toBe(first) + for (const phase of [seen.condition, seen.section, seen.request]) { + expect(phase).toHaveLength(2) + expect(phase[0]).toBe(first) + expect(phase[1]).toBe(second) + } + expect(seen.execute).toHaveLength(1) + expect(seen.execute[0]).toBe(first) + expect(seen.stopping).toEqual([undefined]) + expect(agent.step).toBeUndefined() + }) + + it('clears the selection when a proposal is rejected or fails', async () => { + const adapter = new MockAdapter([]) + const ctx = await harness(adapter) + const agent = await ctx.agentLoop.create(SessionId('step-cleared'), { provider: 'mock', model: 'mock' }) + let outcome: 'reject' | 'throw' = 'reject' + ctx.on('agent/pre-step', async (_payload, next) => { + await next() + if (outcome === 'throw') throw new Error('pre-step failed') + return { kind: 'reject' } + }) + + send(agent, 'rejected') + await agent.whenIdle() + expect(agent.step).toBeUndefined() + expect(lastTurnEnd(agent)?.kind).toBe('blocked') + + outcome = 'throw' + send(agent, 'failed') + await agent.whenIdle() + expect(agent.step).toBeUndefined() + expect(lastTurnEnd(agent)?.kind).toBe('error') + expect(adapter.requests).toEqual([]) + }) +}) + +describe('agent/step-boundary', () => { + it('runs after the claim and before agent/model once per proposed step', async () => { + const adapter = new MockAdapter([toolCallResponse('c1', 'noop', {}), textResponse('done')]) + const ctx = await harness(adapter) + const agent = await ctx.agentLoop.create(SessionId('boundary-order'), { provider: 'mock', model: 'mock' }) + ctx.tools.register(defineContentToolFixture({ + name: 'noop', description: 'Do nothing.', parameters: {}, + execute: async () => [], + })) + const order: string[] = [] + ctx.on('agent/inbox/claimed', () => { order.push('claimed') }) + ctx.on('agent/step-boundary', ({ step }) => { order.push(`boundary:${String(step)}`) }) + ctx.on('agent/model', async ({ step }, next) => { + order.push(`model:${String(step)}`) + return next() + }) + ctx.on('agent/pre-step', async ({ step }, next) => { + order.push(`pre-step:${String(step)}`) + return next() + }) + + send(agent, 'go') + await agent.whenIdle() + + expect(order).toEqual(['claimed', 'boundary:1', 'model:1', 'pre-step:1', 'boundary:2', 'model:2', 'pre-step:2']) + }) + + it('fails the proposal before model choice when a listener throws', async () => { + const adapter = new MockAdapter([]) + const ctx = await harness(adapter) + const agent = await ctx.agentLoop.create(SessionId('boundary-failure'), { provider: 'mock', model: 'mock' }) + let modelChosen = false + ctx.on('agent/step-boundary', () => { throw new Error('boundary commit failed') }) + ctx.on('agent/model', async (_payload, next) => { + modelChosen = true + return next() + }) + + send(agent, 'go') + await agent.whenIdle() + + expect(modelChosen).toBe(false) + const reason = lastTurnEnd(agent) + expect(reason?.kind === 'error' ? reason.error.message : undefined).toContain('boundary commit failed') + expect(eventTypes(agent)).not.toContain('step/start') + expect(adapter.requests).toEqual([]) + }) + + it('opens no step when the turn is cancelled during the boundary', async () => { + const adapter = new MockAdapter([]) + const ctx = await harness(adapter) + const agent = await ctx.agentLoop.create(SessionId('boundary-cancel'), { provider: 'mock', model: 'mock' }) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + ctx.on('agent/step-boundary', async () => { + entered.resolve(undefined) + await release.promise + }) + + send(agent, 'cancelled') + await entered.promise + agent.cancel({ kind: 'user' }) + release.resolve(undefined) + await agent.whenIdle() + + expect(lastTurnEnd(agent)?.kind).toBe('aborted') + expect(eventTypes(agent)).not.toContain('step/start') + expect(agent.step).toBeUndefined() + expect(adapter.requests).toEqual([]) + }) +}) + +describe('runtime context admission', () => { + it('opens no step for a removed wake even when the runtime context changed', async () => { + const adapter = new MockAdapter([]) + const ctx = await harness(adapter) + ctx.systemPrompt.context({ name: 'fact', order: 0, text: 'changed' }) + const agent = await ctx.agentLoop.create(SessionId('context-only'), { provider: 'mock', model: 'mock' }) + // The driver claims synchronously on wake, so the insertion observer removes the message first. + ctx.on('agent/inbox/inserted', ({ agent: subject, message }) => { subject.inbox.remove(message.id) }) + + send(agent, 'removed wake') + await agent.whenIdle() + + expect(adapter.requests).toEqual([]) + expect(eventTypes(agent)).toContain('turn/start') + expect(eventTypes(agent)).not.toContain('step/start') + expect(eventTypes(agent)).not.toContain('user/message') + }) +}) diff --git a/packages/core/agent-loop/tests/tool-updates.spec.ts b/packages/core/agent-loop/tests/tool-updates.spec.ts index 4044aa1e92..09d201f6ff 100644 --- a/packages/core/agent-loop/tests/tool-updates.spec.ts +++ b/packages/core/agent-loop/tests/tool-updates.spec.ts @@ -131,11 +131,12 @@ describe('step-time tool activation', () => { calls++ return [{ type: 'text', text: 'done' }] }, - }), { when: async ({ modelSelection }) => { - expect(Object.isFrozen(modelSelection)).toBe(true) - selectedModels.push(modelSelection.model) + }), { when: async ({ agent: subject }) => { + const selection = subject.step?.modelSelection + expect(Object.isFrozen(selection)).toBe(true) + selectedModels.push(selection?.model ?? '') await Promise.resolve() - return modelSelection.model === 'enabled' + return selection?.model === 'enabled' } }) await send(agent, 'enabled') model = 'disabled' @@ -191,7 +192,7 @@ describe('step-time tool activation', () => { }), { when: () => { counts.conditions++; return retried } }) ctx.systemPrompt.section({ name: 'retry:guidance', order: 0, complete: true, - text: context => `${context.modelSelection?.model}:${ctx.tools.schemas(agent, context.toolSet).map(tool => tool.name).join(',')}`, + text: context => `${context.agent?.step?.modelSelection.model}:${ctx.tools.schemas(agent, context.toolSet).map(tool => tool.name).join(',')}`, }) await send(agent, 'retry once') expect(adapter.requests.map(request => request.model)).toEqual(['first', 'first']) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 5d7936aae2..c2df453d65 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2594a1e02adea801 zh: cae8860369728efb /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: - en: bb854bd10523e158 - zh: b59580450c764598 + en: f5045f7c9f1c2f7a + zh: bc6ceeb549eb0f4d /deepseek-ai-dsh-agent/understand-the-implementation: en: ce7e776e9d516bdb zh: 59d2751743db7795 @@ -36,8 +36,8 @@ en: 7c850051d2857bfa zh: 4cab817553114e15 /deepseek-ai-dsh-agent/understand-the-implementation/step-admission: - en: 324af18f63a4f537 - zh: eec28e7f8362a919 + en: 0271968a215a5b72 + zh: 36e7535632a166dc /deepseek-ai-dsh-agent/understand-the-implementation/durable-inbox: en: f6802c7f94f623b3 zh: cc3885db80765970 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index a7b91fc1b4..9ac3fa06e8 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -64,7 +64,7 @@ await handle.agent.whenIdle() ### Intercept or observe work in flight -The `agent/*` events let plugins act on live work without depending on the loop package. `agent/model` chooses each step's provider, model, and reasoning effort; `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). +The `agent/*` events let plugins act on live work without depending on the loop package. `agent/step-boundary` commits selections that apply from the next step, such as a pending plan-mode switch; `agent/model` chooses each step's provider, model, and reasoning effort, which the agent then exposes as `agent.step`; `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). ----- @@ -82,9 +82,9 @@ The package is built on one separation: the public `Agent` surface and registry ### Step admission -`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. `agent/model` chooses the step's provider, model, and reasoning effort before `agent/pre-step`, whose payload carries that `modelSelection`. Acceptance does not commit the batch: after `step/start`, tool conditions, prompt assembly, `agent/request`, and `prepareCall()` must succeed before system and user messages are logged. Cancellation during model selection opens no step, and cancellation during a later async phase commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. +`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. `agent/step-boundary` and `agent/model` run before `agent/pre-step`, so pre-step listeners read the step's model selection from `agent.step`. Acceptance does not commit the batch: after `step/start`, tool conditions, prompt assembly, `agent/request`, and `prepareCall()` must succeed before system and user messages are logged. Cancellation at the boundary or during model selection opens no step, and cancellation during a later async phase commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. -The step's model selection supplies or replaces the creation-time provider, model, and effort. Prompt preparation, `agent/pre-step`, tool conditions, and every request attempt in the step use it; an `agent/request` listener that returns another provider, model, or reasoning effort fails the step. `installModelSelection` returns its current selection, effort included, when `agent/model` runs, so a selection made during a step applies from the next step. +The step's model selection supplies or replaces the creation-time provider, model, and effort. The driver publishes it as `agent.step` after `agent/model` and clears it when the step ends or its proposal is rejected, fails, or is cancelled; `agent/pre-step`, tool conditions, prompt assembly, and every request attempt in the step read it. An `agent/request` listener that returns another provider, model, or reasoning effort fails the step. `installModelSelection` returns its current selection, effort included, when `agent/model` runs, so a selection made during a step applies from the next step. ### Durable inbox diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index becdb8417b..72256e0cc1 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -64,7 +64,7 @@ await handle.agent.whenIdle() ### 拦截或观察进行中的工作 -`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/model` 选定每个步骤的提供方、模型与推理强度;`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 +`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/step-boundary` 提交从本步骤起生效的选择,例如待提交的计划模式切换;`agent/model` 选定每个步骤的提供方、模型与推理强度,agent 随后通过 `agent.step` 公开它;`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 ----- @@ -82,9 +82,9 @@ await handle.agent.whenIdle() ### 步骤准入 -`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。`agent/model` 在 `agent/pre-step` 之前选定该步骤的提供方、模型与推理强度,`agent/pre-step` 的 payload 携带该 `modelSelection`。接纳不等于提交:`step/start` 之后,工具条件、提示词组装、`agent/request` 与 `prepareCall()` 都成功后,才记录系统提示词与用户批次。在模型选择期间取消不会打开步骤,在之后任一异步阶段取消也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 +`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。`agent/step-boundary` 与 `agent/model` 在 `agent/pre-step` 之前运行,因此 pre-step 监听器从 `agent.step` 读取该步骤的模型选择。接纳不等于提交:`step/start` 之后,工具条件、提示词组装、`agent/request` 与 `prepareCall()` 都成功后,才记录系统提示词与用户批次。在步骤边界或模型选择期间取消不会打开步骤,在之后任一异步阶段取消也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 -步骤的模型选择会补上或替换创建时的提供方、模型与推理强度。提示词准备、`agent/pre-step`、工具条件以及该步骤的每次请求尝试都使用它;`agent/request` 监听器若返回其他提供方、模型或推理强度,步骤会失败。`installModelSelection` 在 `agent/model` 运行时返回当前选择(含推理强度),因此步骤进行中做出的选择从下一个步骤开始生效。 +步骤的模型选择会补上或替换创建时的提供方、模型与推理强度。驱动在 `agent/model` 之后把它发布为 `agent.step`,并在步骤结束或提案被拒绝、失败、取消时清除;`agent/pre-step`、工具条件、提示词组装以及该步骤的每次请求尝试都读取它。`agent/request` 监听器若返回其他提供方、模型或推理强度,步骤会失败。`installModelSelection` 在 `agent/model` 运行时返回当前选择(含推理强度),因此步骤进行中做出的选择从下一个步骤开始生效。 ### 持久 inbox diff --git a/packages/core/agent/src/model-selection.ts b/packages/core/agent/src/model-selection.ts index d0e30909aa..1c04bdf103 100644 --- a/packages/core/agent/src/model-selection.ts +++ b/packages/core/agent/src/model-selection.ts @@ -51,8 +51,8 @@ function modelSwitchNotice(previous: ModelSelection, selected: ModelSelection) { * model's provider default. * * A provider/model change appends a durable user-role notice to the next - * admitted request. It compares the step's selection with the latest request - * header; effort-only changes and empty no-request decisions add no notice. + * admitted request. It compares `agent.step` with the latest request header; + * effort-only changes and empty no-request decisions add no notice. * Failure before header persistence repeats the notice on the next request. * * @param agentCtx - The selected Agent's scoped context. @@ -67,14 +67,15 @@ export function installModelSelection(agentCtx: Context, selection: ModelSelecti }) const disposeNotice = agentCtx.on( 'agent/pre-step', - async ({ agent, messages, modelSelection, signal, step }, next): Promise => { + async ({ agent, messages, signal, step }, next): Promise => { const decision = await next() if (decision.kind === 'reject' || signal.aborted) return decision // The loop skips an empty first step and an emptied offered continuation. if (decision.messages.length === 0 && (step === 1 || messages.length > 0)) return decision + const selected = agent.step?.modelSelection const previous = agent.session.requestHeader()?.config - if (previous === undefined || sameModel(modelSelection, previous)) return decision - return { ...decision, messages: [...decision.messages, modelSwitchNotice(previous, modelSelection)] } + if (selected === undefined || previous === undefined || sameModel(selected, previous)) return decision + return { ...decision, messages: [...decision.messages, modelSwitchNotice(previous, selected)] } }, { prepend: true }, ) diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index c710d95592..3a8111c1e8 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -19,8 +19,6 @@ declare module '@deepseek-ai/dsh-system-prompt' { interface AssembleContext { /** Agent for this assembly; absent on diagnostics. When present, `scope` must identify the same agent. */ agent?: Agent - /** Model selection of the step being assembled; absent outside a step. */ - modelSelection?: ModelSelection } } @@ -34,6 +32,12 @@ export interface ModelSelection { reasoningEffort?: ReasoningEffortId } +/** Decisions the driver fixed for one proposed or running step. */ +export interface AgentStep { + /** Provider, model, and reasoning effort that every request attempt in the step uses. */ + readonly modelSelection: ModelSelection +} + /** Merge-extensible agent creation options. Persona belongs to system-prompt sections. */ export interface AgentOptions { /** Provider route (must have a registered adapter at call time). */ @@ -176,6 +180,13 @@ declare module './types.ts' { interface Agent { /** Creation-time request options; `agent/model` may choose another provider, model, and effort for each step. */ readonly options: AgentOptions + /** + * The step the driver is preparing or running. The driver publishes it + * after `agent/model` and clears it when the step ends or its proposal is + * rejected, fails, or is cancelled, so it is undefined between steps and + * during `agent/model`. Work that outlives its step reads it at its start. + */ + readonly step?: AgentStep | undefined /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session /** Agent-owned access to durable pending work. */ @@ -320,17 +331,32 @@ declare module '@deepseek-ai/cordis' { // ---- the machine's extension points ---- /** * Reject a proposed step or replace the messages that enter it. Calling - * `next()` preserves the current messages. + * `next()` preserves the current messages. `payload.agent.step` already + * holds the model selection that `agent/model` chose for this step. * @param payload.agent - the agent proposing the step. * @param payload.messages - messages removed from the inbox for this step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. - * @param payload.modelSelection - the provider, model, and effort `agent/model` chose for this step. * @param payload.signal - the current turn's cancellation signal. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. * @mode waterfall */ - 'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; modelSelection: ModelSelection; signal: AbortSignal }, next: () => Promise): Promise + 'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise + /** + * A proposed step reached its boundary: the loop claimed its input and is + * about to choose its model. Listeners commit selections that take effect + * from this step, such as a pending plan-mode switch, so `agent/model`, + * `agent/pre-step`, tool conditions, and prompt assembly read one state. + * Runs once per proposed step; a throw fails the proposal, and + * cancellation opens no step. + * @param payload.agent - the agent proposing the step. + * @param payload.turn - the turn that will own the step. + * @param payload.step - the step proposed by the loop. + * @param payload.signal - the current turn's explicit abort signal. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode serial + */ + 'agent/step-boundary'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }): Promise | void /** * Choose the provider, model, and reasoning effort for one proposed step. * `await next()` yields the selection the machine would use: agent options @@ -338,10 +364,11 @@ declare module '@deepseek-ai/cordis' { * effort only when one was chosen for that exact model. Return a * replacement to switch; an effort belongs to its model, so a replacement * that changes the model names that model's effort or omits it for the - * provider default. The loop runs this once per proposed step, before - * context preparation and `agent/pre-step`. Prompt preparation, tool - * conditions, and every request attempt in the step use the result, so a - * later choice applies from the next step. Cancellation here opens no step. + * provider default. The loop runs this once per proposed step, after + * `agent/step-boundary` and before `agent/pre-step`, then publishes the + * result as `agent.step`. Pre-step listeners, tool conditions, prompt + * assembly, and every request attempt in the step use it, so a later + * choice applies from the next step. Cancellation here opens no step. * @param payload.agent - the agent proposing the step. * @param payload.turn - the turn that will own the step. * @param payload.step - the step proposed by the loop. diff --git a/packages/core/agent/tests/model-selection.spec.ts b/packages/core/agent/tests/model-selection.spec.ts index 23663ee2e1..fc453c0c8f 100644 --- a/packages/core/agent/tests/model-selection.spec.ts +++ b/packages/core/agent/tests/model-selection.spec.ts @@ -5,6 +5,7 @@ import { agentEvents, installModelSelection, type Agent, + type AgentStep, type ModelSelection, type ModelSelectionRef, } from '../src/index.ts' @@ -24,13 +25,25 @@ function harness(current?: ModelSelection, previous?: ModelSelection) { contexts.push(ctx) const selection: ModelSelectionRef = { current } const dispose = installModelSelection(ctx, selection) - const agent = { session: Session.create(SessionId('model-selection')) } as Agent + const state: { session: Session; step?: AgentStep } = { session: Session.create(SessionId('model-selection')) } + const agent = state as Agent if (previous) agent.session.append('request/header', { header: { config: previous }, reason: 'initial' }) const choose = (step: number) => agentEvents(ctx, agent).waterfall('agent/model', { turn: 1, step, signal }, () => Promise.resolve(seed)) - const preStep = (modelSelection: ModelSelection, messages = [input], offered = [input], step = 1, stepSignal = signal) => - agentEvents(ctx, agent).waterfall('agent/pre-step', { turn: 1, step, messages: offered, modelSelection, signal: stepSignal }, - () => Promise.resolve({ kind: 'enter' as const, messages })) + /** Dispatch pre-step for a step whose published model selection is `modelSelection`. */ + const preStep = ( + modelSelection: ModelSelection | undefined, + messages = [input], + offered = [input], + step = 1, + stepSignal = signal, + decision: 'enter' | 'reject' = 'enter', + ) => { + if (modelSelection === undefined) delete state.step + else state.step = { modelSelection } + return agentEvents(ctx, agent).waterfall('agent/pre-step', { turn: 1, step, messages: offered, signal: stepSignal }, + () => Promise.resolve(decision === 'enter' ? { kind: 'enter' as const, messages } : { kind: 'reject' as const })) + } return { ctx, agent, selection, dispose, choose, preStep } } @@ -63,7 +76,7 @@ describe('installModelSelection()', () => { await expect(h.preStep({ provider: 'beta', model: 'b1' })).resolves.toMatchObject({ messages: [input, notice('alpha/a0', 'beta/b1')] }) }) - it('preserves initial, effort-only, rejected, cancelled, and disposed decisions', async () => { + it('preserves initial, effort-only, unpublished, rejected, cancelled, and disposed decisions', async () => { const h = harness() const initial = { provider: 'alpha', model: 'a0' } await expect(h.preStep(initial)).resolves.toEqual({ kind: 'enter', messages: [input] }) @@ -72,9 +85,9 @@ describe('installModelSelection()', () => { reason: 'initial', }) await expect(h.preStep({ ...initial, reasoningEffort: ReasoningEffortId('low') })).resolves.toEqual({ kind: 'enter', messages: [input] }) + await expect(h.preStep(undefined)).resolves.toEqual({ kind: 'enter', messages: [input] }) const switched = { provider: 'alpha', model: 'a1' } - await expect(agentEvents(h.ctx, h.agent).waterfall('agent/pre-step', { turn: 1, step: 3, messages: [], modelSelection: switched, signal }, - () => Promise.resolve({ kind: 'reject' as const }))).resolves.toEqual({ kind: 'reject' }) + await expect(h.preStep(switched, [], [], 3, signal, 'reject')).resolves.toEqual({ kind: 'reject' }) await expect(h.preStep(switched, [input], [input], 3, AbortSignal.abort())).resolves.toEqual({ kind: 'enter', messages: [input] }) h.dispose() await expect(h.preStep(switched)).resolves.toEqual({ kind: 'enter', messages: [input] }) diff --git a/packages/core/system-prompt/README.i18n.yaml b/packages/core/system-prompt/README.i18n.yaml index 8abb19e207..ed2d640874 100644 --- a/packages/core/system-prompt/README.i18n.yaml +++ b/packages/core/system-prompt/README.i18n.yaml @@ -21,8 +21,8 @@ en: 87e28893e6cf58d7 zh: 06f476b38c4d2038 /deepseek-ai-dsh-system-prompt/use-this-package/contribute-a-prompt-section: - en: 1d970a1e99cd71bb - zh: 62f30c25e82bdbea + en: d9185fd5c60cf3d5 + zh: 54a816d078495344 /deepseek-ai-dsh-system-prompt/use-this-package/contribute-a-prompt-variable: en: b3e4c9b4ced59488 zh: d80c791e72bd5821 diff --git a/packages/core/system-prompt/README.md b/packages/core/system-prompt/README.md index 70c465cdaf..890e5e983b 100644 --- a/packages/core/system-prompt/README.md +++ b/packages/core/system-prompt/README.md @@ -67,7 +67,7 @@ Set `interpolate: false` on a section or dynamic context to preserve its text li `refreshContext(assembly, context)` refreshes registered runtime facts after pre-step and route preparation. It preserves accepted sections, tools, variables, and contexts contributed only by the assembly waterfall, applies current optional-context suppression, and restores missing required entries. Put changing facts in context providers; registered context text is read again before admission. -`prepare(context)` resolves variables and runtime facts through `system-prompt/prepare` before step admission. After `agent/pre-step` accepts the step and commits its selections, `assemble(context, preparation)` resolves sections and tool declarations. Presentation listeners receive sections, contexts, and variables; tools remain provider-owned. Tool-aware section callbacks use `context.toolSet` to inspect the same step selection as execution. +The agent loop calls `assemble(context)` once per step after `step/start`, when the step's model selection (`context.agent.step`) and admitted tool set (`context.toolSet`) are fixed. Presentation listeners receive sections, contexts, and variables; tools remain provider-owned. Tool-aware section callbacks use `context.toolSet` to inspect the same step selection as execution. ### Contribute a prompt variable diff --git a/packages/core/system-prompt/README.zh.md b/packages/core/system-prompt/README.zh.md index 1ec9b81050..f831e8c1c0 100644 --- a/packages/core/system-prompt/README.zh.md +++ b/packages/core/system-prompt/README.zh.md @@ -67,7 +67,7 @@ ctx.systemPrompt.section({ `refreshContext(assembly, context)` 在 pre-step 与路由准备之后刷新已注册的运行时事实。它保留已接纳的段、工具、变量及仅由组装 waterfall 添加的上下文,应用当前的可选上下文抑制,并恢复缺失的必需条目。将变化的事实放在上下文 provider 中;已注册上下文的文本会在准入前再次读取。 -`prepare(context)` 在步骤接纳前通过 `system-prompt/prepare` 解析变量与运行时事实。`agent/pre-step` 接纳步骤并提交其选择后,`assemble(context, preparation)` 解析段落与工具声明。展示监听器接收段落、上下文与变量;工具声明仍由提供方持有。依赖工具的段落回调通过 `context.toolSet` 读取与执行相同的步骤集合。 +agent loop 在每个步骤的 `step/start` 之后调用一次 `assemble(context)`,此时该步骤的模型选择(`context.agent.step`)与准入工具集合(`context.toolSet`)都已确定。展示监听器接收段落、上下文与变量;工具声明仍由提供方持有。依赖工具的段落回调通过 `context.toolSet` 读取与执行相同的步骤集合。 ### 贡献提示词变量 diff --git a/packages/core/system-prompt/src/index.ts b/packages/core/system-prompt/src/index.ts index 9032691280..6abf8bbc0b 100644 --- a/packages/core/system-prompt/src/index.ts +++ b/packages/core/system-prompt/src/index.ts @@ -29,13 +29,6 @@ declare module '@deepseek-ai/cordis' { * @mode waterfall */ 'system-prompt/assemble'(this: Scoped, assembly: PromptPresentation, context: AssembleContext, next: () => Promise): Promise - /** - * Prepare variables and runtime context before step admission. - * @param preparation - registered variables and context contributions. - * @param context - calling scope and cancellation. - * @mode waterfall - */ - 'system-prompt/prepare'(this: Scoped, preparation: PromptPreparation, context: AssembleContext, next: () => Promise): Promise /** * Emitted when any prompt provider changes. This registry notification is * unfiltered because a global change affects every scope. @@ -124,18 +117,18 @@ export interface ToolProviderResult { readonly knownNames?: readonly string[] } -/** Prepared runtime facts and variables; context text remains uninterpolated. */ -export interface PromptPreparation { +/** + * Prompt text contributions that the assembly waterfall may transform. + * Sections and contexts remain uninterpolated until rendered; tool + * declarations are owned by their providers. + */ +export interface PromptPresentation { + sections: AssembledSection[] contexts: AssembledContext[] variables: Record } -/** Prompt text contributions; tool declarations are owned by their providers. */ -export interface PromptPresentation extends PromptPreparation { - sections: AssembledSection[] -} - -/** Completed model inputs, including provider-owned tool declarations. */ +/** Completed model inputs: the presentation plus tool declarations in canonical order. */ export interface PromptAssembly extends PromptPresentation { tools: ToolSchema[] } @@ -338,7 +331,7 @@ export function joinContextSections(sections: readonly ContextSnapshotSection[]) * @param assembly - the assembly whose contexts and variables to render. * @returns one entry per contributing context that rendered to non-empty text. */ -export function renderContextSections(assembly: PromptPreparation): ContextSnapshotSection[] { +export function renderContextSections(assembly: PromptAssembly): ContextSnapshotSection[] { return assembly.contexts .map(context => ({ name: context.name, @@ -590,7 +583,7 @@ export class SystemPrompt extends Service { * @param context - the same scope and current plugin-defined assembly fields. * @returns the accepted assembly with current runtime-context provider text. */ - refreshContext(assembly: T, context: AssembleContext = {}): T { + refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly { const providers = this.layers.merge(context.scope, layer => layer.contexts) const suppressed = !this.layers.global.runtimeContextSuppressors.isEmpty() || this.layers.chainLayers(context.scope).some(layer => !layer.runtimeContextSuppressors.isEmpty()) @@ -613,12 +606,18 @@ export class SystemPrompt extends Service { } /** - * Prepare variables and runtime facts before accepting a step. No tool - * conditions or prompt sections are evaluated in this phase. - * @param context - calling scope and request cancellation. - * @returns prepared inputs after the preparation waterfall. + * Assemble global and scoped providers, detach tool parameters, apply + * canonical ordering, then run the presentation waterfall. Scoped sections + * and variables shadow globals. The waterfall's text is authoritative except + * that an effective complete section is restored afterwards as the sole + * prompt section, current suppression removes optional contexts, and + * required contexts keep their provider values; tool declarations stay + * provider-owned. + * @param context - the optional scope, step tool set, and plugin-defined assembly fields. + * @returns the post-waterfall assembly with ordered tool declarations. */ - async prepare(context: AssembleContext = {}): Promise { + // Keep configuration failures on the declared asynchronous error path. + async assemble(context: AssembleContext = {}): Promise { const scope = context.scope const scopeLayers = this.layers.chainLayers(scope) const runtimeContextSuppressed = !this.layers.global.runtimeContextSuppressors.isEmpty() @@ -634,28 +633,6 @@ export class SystemPrompt extends Service { variables[name] = provider(context) } } - const contexts = [...this.layers.merge(scope, layer => layer.contexts).values()] - .filter(entry => !runtimeContextSuppressed || entry.required === true) - .sort((a, b) => a.order - b.order) - .map(entry => resolveContext(entry, context)) - const preparation = { contexts, variables } - return this.ctx.waterfall(scopeTarget(this, scope), 'system-prompt/prepare', preparation, context, - () => Promise.resolve(preparation)) - } - - /** - * Assemble prompt sections and tool declarations after request preparation. - * The presentation waterfall cannot replace provider-owned tools. - * @param context - calling scope, route-bound agent, and resolved tools. - * @param preparation - accepted variables and runtime facts; prepared here when omitted. - * @returns the complete assembly with ordered tool declarations. - */ - async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise { - const prepared = preparation ?? await this.prepare(context) - const scope = context.scope - const scopeLayers = this.layers.chainLayers(scope) - const runtimeContextSuppressed = !this.layers.global.runtimeContextSuppressors.isEmpty() - || scopeLayers.some(layer => !layer.runtimeContextSuppressors.isEmpty()) // Scoped sections shadow globals before the deterministic order sort. const sectionByName = this.layers.merge(scope, layer => layer.sections) const contextByName = this.layers.merge(scope, layer => layer.contexts) @@ -695,7 +672,14 @@ export class SystemPrompt extends Service { return assembled }) const tools = orderTools(collected, this.toolOrder, knownNames) - const assembly: PromptPresentation = { ...prepared, sections } + const assembly: PromptPresentation = { + sections, + contexts: [...contextByName.values()] + .filter(entry => !runtimeContextSuppressed || entry.required === true) + .sort((a, b) => a.order - b.order) + .map(entry => resolveContext(entry, context)), + variables, + } const transformed = await this.ctx.waterfall( scopeTarget(this, scope), 'system-prompt/assemble', assembly, context, () => Promise.resolve(assembly), diff --git a/packages/core/system-prompt/tests/system-prompt.spec.ts b/packages/core/system-prompt/tests/system-prompt.spec.ts index a8bef706d1..33fbb153c7 100644 --- a/packages/core/system-prompt/tests/system-prompt.spec.ts +++ b/packages/core/system-prompt/tests/system-prompt.spec.ts @@ -51,6 +51,30 @@ describe('SystemPrompt', () => { await ctx.fiber.dispose() } }) + it('keeps required contexts at their provider values after presentation listeners', async () => { + const ctx = new Context() + try { + await ctx.plugin(SystemPrompt) + ctx.systemPrompt.context({ name: 'directory', order: 0, required: true, text: 'Directory: /project' }) + ctx.systemPrompt.context({ name: 'optional', order: 1, text: 'optional' }) + let rewrite = true + ctx.on('system-prompt/assemble', async (_assembly, _context, next) => { + const accepted = await next() + return rewrite + ? { ...accepted, contexts: accepted.contexts.map(entry => ({ ...entry, text: 'rewritten' })) } + : { ...accepted, contexts: accepted.contexts.filter(entry => entry.name !== 'directory') } + }) + expect((await ctx.systemPrompt.assemble()).contexts).toEqual([ + { name: 'directory', text: 'Directory: /project' }, { name: 'optional', text: 'rewritten' }, + ]) + rewrite = false + expect((await ctx.systemPrompt.assemble()).contexts).toEqual([ + { name: 'optional', text: 'optional' }, { name: 'directory', text: 'Directory: /project' }, + ]) + } finally { + await ctx.fiber.dispose() + } + }) it('refreshes registered context without reassembling accepted sections, schemas, variables, or expert additions', async () => { const ctx = new Context() try { diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index 9103091c77..c0d8299e41 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -21,8 +21,8 @@ en: 9d2e6caa39c53d62 zh: 096a777f828c7565 /deepseek-ai-dsh-tools/use-this-package/conditional-tools: - en: 33618b68f90858c0 - zh: 10e20f40a5871555 + en: 1f8835ef3c0e16d2 + zh: 0e5fe6d06b403188 /deepseek-ai-dsh-tools/use-this-package/configure-the-presentation-mode: en: 4e27c45ae889369e zh: 7a0cd7a9dc7fe139 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index d15bbaf35e..e4fd422699 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -65,9 +65,9 @@ The unified schema DSL supports `string`, `number`, `integer`, `boolean`, `null` ### Conditional tools -`register(definition, { when })` evaluates a synchronous or asynchronous condition once for each model step. The condition receives `{ agent, modelSelection, signal }`, where `modelSelection` is the provider, model, and reasoning effort that `agent/model` chose for every request attempt in the step. False omits the tool from Native declarations, PTC bindings, and execution. A thrown condition fails step preparation as `TOOL_ACTIVATION_FAILED`; it is not treated as ordinary unavailability. Conditions must observe cancellation and must not change registrations or perform tool work. +`register(definition, { when })` evaluates a synchronous or asynchronous condition once for each model step. The condition receives `{ agent, signal }`; `agent.step.modelSelection` is the provider, model, and reasoning effort that `agent/model` chose for every request attempt in the step. False omits the tool from Native declarations, PTC bindings, and execution. A thrown condition fails step preparation as `TOOL_ACTIVATION_FAILED`; it is not treated as ordinary unavailability. Conditions must observe cancellation and must not change registrations or perform tool work. -`resolve({ agent, modelSelection, signal })` returns a step-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and every Native or PTC execution, then dispose it after the step's batch settles; retries in the step reuse it. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, cancellation, or same-name replacement prevent unstarted calls from using it. Started operations retain their cooperative cancellation obligations. Conditional calls without a resolved set return `UNKNOWN_TOOL`. +`resolve({ agent, signal })` returns a step-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and every Native or PTC execution, then dispose it after the step's batch settles; retries in the step reuse it. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, cancellation, or same-name replacement prevent unstarted calls from using it. Started operations retain their cooperative cancellation obligations. Conditional calls without a resolved set return `UNKNOWN_TOOL`. `get(name, scope, toolSet)` and `schemas(scope, toolSet)` inspect an admitted set; omitting `toolSet` inspects registered definitions without evaluating conditions. Tool guidance receives the same selection as `AssembleContext.toolSet`. A presentation transform cannot add or remove callable tools. diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index 3b60e0dbec..61c3f64bf6 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -65,9 +65,9 @@ ctx.tools.register(defineTool({ ### 条件工具 -`register(definition, { when })` 为每个模型步骤计算一次同步或异步条件。条件接收 `{ agent, modelSelection, signal }`,其中 `modelSelection` 是 `agent/model` 为该步骤所有请求尝试选定的提供方、模型与推理强度。返回 false 会从原生声明、PTC 绑定和执行集合中排除工具。条件抛错会以 `TOOL_ACTIVATION_FAILED` 中止步骤准备,不会被当成正常不可用。条件必须响应取消,不得改变注册或执行工具操作。 +`register(definition, { when })` 为每个模型步骤计算一次同步或异步条件。条件接收 `{ agent, signal }`;`agent.step.modelSelection` 是 `agent/model` 为该步骤所有请求尝试选定的提供方、模型与推理强度。返回 false 会从原生声明、PTC 绑定和执行集合中排除工具。条件抛错会以 `TOOL_ACTIVATION_FAILED` 中止步骤准备,不会被当成正常不可用。条件必须响应取消,不得改变注册或执行工具操作。 -`resolve({ agent, modelSelection, signal })` 返回步骤拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及每次原生或 PTC 执行,步骤的批次结束后释放;同一步骤内的重试复用它。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制、取消或同名替换会阻止尚未开始的调用继续使用它。已经开始的操作保留协作取消义务。没有已解析集合的条件工具调用返回 `UNKNOWN_TOOL`。 +`resolve({ agent, signal })` 返回步骤拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及每次原生或 PTC 执行,步骤的批次结束后释放;同一步骤内的重试复用它。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制、取消或同名替换会阻止尚未开始的调用继续使用它。已经开始的操作保留协作取消义务。没有已解析集合的条件工具调用返回 `UNKNOWN_TOOL`。 `get(name, scope, toolSet)` 和 `schemas(scope, toolSet)` 读取已准入集合;省略 `toolSet` 时只查看已注册定义,不计算条件。工具指导文本通过 `AssembleContext.toolSet` 接收同一集合。展示变换不能增删可调用工具。 diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index 90d484052f..aa50a31ecd 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -11,7 +11,7 @@ import { AnonymousEntries, NamedEntries, ScopedLayers, scopeOf, scopeTarget } fr import type { ScopeKey, ScopeLayer, Scoped } from '@deepseek-ai/dsh-scope' import type { ToolCallId, ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm' import { HarnessError } from '@deepseek-ai/dsh-llm' -import type { Agent, ModelSelection } from '@deepseek-ai/dsh-agent' +import type { Agent } from '@deepseek-ai/dsh-agent' import type { UserMessage } from '@deepseek-ai/dsh-session' import { assertNever, deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' import type { PromptSection, ToolProviderResult } from '@deepseek-ai/dsh-system-prompt' @@ -229,10 +229,8 @@ export interface ToolOutputDefinition { /** Inputs for a tool's step-time activation condition. */ export interface ToolActivationContext { - /** Agent preparing the step. */ + /** Agent preparing the step; `agent.step` holds the step's model selection. */ readonly agent: Agent - /** Provider, model, and reasoning effort that every request attempt in the step uses. */ - readonly modelSelection: ModelSelection /** Cancellation of step preparation; asynchronous conditions must observe it. */ readonly signal: AbortSignal } @@ -243,7 +241,7 @@ export interface ToolRegistrationOptions { * Decide whether the step's requests may call the tool. Omission enables * it. False excludes it from both declarations and dispatch; rejection fails * step preparation. Conditions must not mutate registrations or start tool work. - * @param context - preparing agent, step model selection, and cancellation signal. + * @param context - preparing agent and cancellation signal. * @returns whether the tool participates in this step. */ readonly when?: (context: ToolActivationContext) => boolean | Promise @@ -1311,7 +1309,7 @@ export class ToolRuntime extends Service { * Resolve conditions once for this step without changing shared registrations. * Cancellation or a rejected condition publishes no partial selection. Removed * registrations cannot be restored by a late condition result. - * @param context - preparing agent, step model selection, and cancellation. + * @param context - preparing agent and cancellation. * @returns the complete selection; the caller disposes it after its tool batch settles. */ async resolve(context: ToolActivationContext): Promise { diff --git a/packages/core/tools/tests/activation.spec.ts b/packages/core/tools/tests/activation.spec.ts index c9c4125aca..2c591987b7 100644 --- a/packages/core/tools/tests/activation.spec.ts +++ b/packages/core/tools/tests/activation.spec.ts @@ -19,7 +19,6 @@ async function setup() { await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) const agent = { id: SessionId('activation') } as Agent - const modelSelection = { provider: 'test', model: 'test' } let scope!: Scope await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, { inject: ['tools'] })) const controller = new AbortController() @@ -30,8 +29,8 @@ async function setup() { async execute() { calls++; return 'done' }, }) const input = { agent, name: tool.name, arguments: {}, callId: ToolCallId('call'), signal: controller.signal } - const resolve = () => ctx.tools.resolve({ agent, modelSelection, signal: controller.signal }) - return { ctx, agent, modelSelection, scope, controller, tool, input, resolve, calls: () => calls } + const resolve = () => ctx.tools.resolve({ agent, signal: controller.signal }) + return { ctx, agent, scope, controller, tool, input, resolve, calls: () => calls } } it('activates and deactivates a registered tool without allowing historical calls', async () => { @@ -104,8 +103,8 @@ it('does not restore a registration removed during its asynchronous condition', it('propagates cancellation after an asynchronous condition settles', async () => { const h = await setup() const condition = Promise.withResolvers() - h.ctx.tools.register(h.tool, { when: ({ modelSelection, signal }) => { - expect(modelSelection).toBe(h.modelSelection) + h.ctx.tools.register(h.tool, { when: ({ agent, signal }) => { + expect(agent).toBe(h.agent) expect(signal).toBe(h.controller.signal) return condition.promise } }) diff --git a/packages/core/tools/tests/ptc.spec.ts b/packages/core/tools/tests/ptc.spec.ts index 15045bf56f..dbd633de86 100644 --- a/packages/core/tools/tests/ptc.spec.ts +++ b/packages/core/tools/tests/ptc.spec.ts @@ -187,7 +187,7 @@ describe('mode-aware wire contribution', () => { const unregister = ctx.tools.register(definition, { when: () => active }) for (const enabled of [false, true]) { active = enabled - const toolSet = await ctx.tools.resolve({ agent, modelSelection: { provider: 'test', model: 'test' }, signal: testToolSignal }) + const toolSet = await ctx.tools.resolve({ agent, signal: testToolSignal }) try { const assembly = await systemPrompt.assemble({ scope: agent, agent, toolSet }) const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? '' diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index b3553b8aee..56ab68c929 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1660,15 +1660,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'get(agent: Agent): { active: boolean; pending?: boolean }', - description: 'Read the logged plan state and any selected state awaiting the next accepted in-turn pre-step.', + description: 'Read the logged plan state and any selected state awaiting the next step boundary.', parameters: [{ name: 'agent', description: 'The agent to read.' }], returns: 'Current logged state plus a pending selection, when present.', }, { signature: 'set(agent: Agent, active: boolean): \'committed\' | \'queued\' | \'cancelled\' | \'noop\'', - description: 'Select whether plan mode should be active. Between turns the method appends the change immediately because no in-turn pre-step will run until another prompt starts a turn. The open-turn fold is the idle signal: agent status stays `running` through post-turn checkpointing, when no further in-turn pre-step runs. During an open turn the selection remains pending until the next accepted in-turn pre-step. Repeated selection of the current or already-pending state is a no-op.', + description: 'Select whether plan mode should be active. Between turns the method appends the change immediately because no step boundary will run until another prompt starts a turn. The open-turn fold is the idle signal: agent status stays `running` through post-turn checkpointing, when no further step boundary runs. During an open turn the selection remains pending until the next step boundary. Repeated selection of the current or already-pending state is a no-op.', parameters: [{ name: 'agent', description: 'The agent to switch.' }, { name: 'active', description: 'Whether plan mode should be active.' }], - returns: 'what happened: `committed` (logged now), `queued` (awaiting the next accepted in-turn pre-step), `cancelled` (an opposite pending selection was cleared; the logged state already matches), or `noop` (already in that state).', + returns: 'what happened: `committed` (logged now), `queued` (awaiting the next step boundary), `cancelled` (an opposite pending selection was cleared; the logged state already matches), or `noop` (already in that state).', }, ], }, @@ -2393,9 +2393,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'mention-carrying candidates in rank order.', }, { - signature: 'async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, modelSelection?: ModelSelection, ): Promise', - description: 'Snapshot all references for one accepted direct message and return one aggregated durable context. Automatic budgets use the step\'s model selection, or agent options for direct preparation. Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. Cancellation prevents context publication, including when storage completes after cancellation.', - parameters: [{ name: 'agent', description: 'target agent; references to it are rejected.' }, { name: 'content', description: 'already host-normalized readable message content.' }, { name: 'references', description: 'structured source sessions in mention order.' }, { name: 'signal', description: 'optional cancellation boundary for the active turn.' }, { name: 'modelSelection', description: 'provider and model of the step admitting the message; omitted for direct preparation.' }], + signature: 'async prepare( agent: Agent, content: ContentBlock[], references: SessionReferenceInput[], signal?: AbortSignal, ): Promise', + description: 'Snapshot all references for one accepted direct message and return one aggregated durable context. Automatic budgets use the model of the agent\'s current step, or agent options outside a step. Missing model capacity or adapter uses 64 KiB; other metadata lookup failures and cancellation reject preparation. Truncated previews include omission facts and a full-snapshot spill locator, or an explicit unavailable notice. Cancellation prevents context publication, including when storage completes after cancellation.', + parameters: [{ name: 'agent', description: 'target agent; references to it are rejected.' }, { name: 'content', description: 'already host-normalized readable message content.' }, { name: 'references', description: 'structured source sessions in mention order.' }, { name: 'signal', description: 'optional cancellation boundary for the active turn.' }], returns: 'detached content and optional referenced-session context.', }, ], @@ -3095,22 +3095,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the exact Cordis effect disposer.', }, { - signature: 'refreshContext(assembly: T, context: AssembleContext = {}): T', + signature: 'refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly', description: 'Refresh accepted registered runtime facts for request admission. Contexts added only by the assembly waterfall retain their accepted values. Current suppression removes optional contexts, and missing required registrations are restored in registry order. Sections, tools, and interpolation variables retain their accepted values during this refresh.', parameters: [{ name: 'assembly', description: 'accepted assembly for this scope and step.' }, { name: 'context', description: 'the same scope and current plugin-defined assembly fields.' }], returns: 'the accepted assembly with current runtime-context provider text.', }, { - signature: 'async prepare(context: AssembleContext = {}): Promise', - description: 'Prepare variables and runtime facts before accepting a step. No tool conditions or prompt sections are evaluated in this phase.', - parameters: [{ name: 'context', description: 'calling scope and request cancellation.' }], - returns: 'prepared inputs after the preparation waterfall.', - }, - { - signature: 'async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise', - description: 'Assemble prompt sections and tool declarations after request preparation. The presentation waterfall cannot replace provider-owned tools.', - parameters: [{ name: 'context', description: 'calling scope, route-bound agent, and resolved tools.' }, { name: 'preparation', description: 'accepted variables and runtime facts; prepared here when omitted.' }], - returns: 'the complete assembly with ordered tool declarations.', + signature: 'async assemble(context: AssembleContext = {}): Promise', + description: 'Assemble global and scoped providers, detach tool parameters, apply canonical ordering, then run the presentation waterfall. Scoped sections and variables shadow globals. The waterfall\'s text is authoritative except that an effective complete section is restored afterwards as the sole prompt section, current suppression removes optional contexts, and required contexts keep their provider values; tool declarations stay provider-owned.', + parameters: [{ name: 'context', description: 'the optional scope, step tool set, and plugin-defined assembly fields.' }], + returns: 'the post-waterfall assembly with ordered tool declarations.', }, ], }, @@ -3354,7 +3348,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { signature: 'async resolve(context: ToolActivationContext): Promise', description: 'Resolve conditions once for this step without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.', - parameters: [{ name: 'context', description: 'preparing agent, step model selection, and cancellation.' }], + parameters: [{ name: 'context', description: 'preparing agent and cancellation.' }], returns: 'the complete selection; the caller disposes it after its tool batch settles.', }, { @@ -3985,15 +3979,15 @@ export const EVENT_API: readonly EventApiEntry[] = [ mode: 'waterfall', signature: '\'agent/model\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', summary: 'Choose the provider, model, and reasoning effort for one proposed step.', - description: 'Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model\'s effort or omits it for the provider default. The loop runs this once per proposed step, before context preparation and `agent/pre-step`. Prompt preparation, tool conditions, and every request attempt in the step use the result, so a later choice applies from the next step. Cancellation here opens no step.', + description: 'Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model\'s effort or omits it for the provider default. The loop runs this once per proposed step, after `agent/step-boundary` and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step.', parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, { name: 'agent/pre-step', mode: 'waterfall', - signature: '\'agent/pre-step\'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; modelSelection: ModelSelection; signal: AbortSignal }, next: () => Promise): Promise', + signature: '\'agent/pre-step\'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', summary: 'Reject a proposed step or replace the messages that enter it.', - description: 'Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages.', + description: 'Reject a proposed step or replace the messages that enter it. Calling `next()` preserves the current messages. `payload.agent.step` already holds the model selection that `agent/model` chose for this step.', parameters: [{ name: 'payload', description: '.signal - the current turn\'s cancellation signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, { @@ -4020,6 +4014,14 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Agent status changed (`idle` ⇄ `running`). A waking delivery enters `running` synchronously after reserving cancellation; `idle` means no driver remains scheduled or active.', parameters: [{ name: 'payload', description: '.status - the status just entered (the transition\'s destination). Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, + { + name: 'agent/step-boundary', + mode: 'serial', + signature: '\'agent/step-boundary\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }): Promise | void', + summary: 'A proposed step reached its boundary: the loop claimed its input and is about to choose its model.', + description: 'A proposed step reached its boundary: the loop claimed its input and is about to choose its model. Listeners commit selections that take effect from this step, such as a pending plan-mode switch, so `agent/model`, `agent/pre-step`, tool conditions, and prompt assembly read one state. Runs once per proposed step; a throw fails the proposal, and cancellation opens no step.', + parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], + }, { name: 'agent/turn-stopping', mode: 'serial', @@ -4436,14 +4438,6 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Emitted when any prompt provider changes. This registry notification is unfiltered because a global change affects every scope.', parameters: [], }, - { - name: 'system-prompt/prepare', - mode: 'waterfall', - signature: '\'system-prompt/prepare\'(this: Scoped, preparation: PromptPreparation, context: AssembleContext, next: () => Promise): Promise', - summary: 'Prepare variables and runtime context before step admission.', - description: 'Prepare variables and runtime context before step admission.', - parameters: [{ name: 'preparation', description: 'registered variables and context contributions.' }, { name: 'context', description: 'calling scope and cancellation.' }], - }, { name: 'tools/change', mode: 'emit', @@ -6384,13 +6378,9 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'PromptOrigin', declaration: 'export type PromptOrigin = {\n kind: \'composer\';\n} | {\n kind: \'plugin\';\n name: string;\n};', }, - { - name: 'PromptPreparation', - declaration: 'export interface PromptPreparation {\n contexts: AssembledContext[];\n variables: Record;\n}', - }, { name: 'PromptPresentation', - declaration: 'export interface PromptPresentation extends PromptPreparation {\n sections: AssembledSection[];\n}', + declaration: 'export interface PromptPresentation {\n sections: AssembledSection[];\n contexts: AssembledContext[];\n variables: Record;\n}', }, { name: 'PromptSection', @@ -7778,7 +7768,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SystemPrompt', - declaration: 'export class SystemPrompt extends Service {\n static Config: z;\n constructor(ctx: Context, config: Config);\n section(section: PromptSection): () => void;\n getSectionOrder(name: PromptSectionOrderName): number;\n getContextOrder(name: PromptContextOrderName): number;\n context(context: PromptContext): () => void;\n suppressRuntimeContext(): () => void;\n tools(provider: (context: AssembleContext) => ToolProviderResult): () => void;\n variable(name: string, provider: (context: AssembleContext) => string | undefined): () => void;\n refreshContext(assembly: T, context: AssembleContext = {}): T;\n async prepare(context: AssembleContext = {}): Promise;\n async assemble(context: AssembleContext = {}, preparation?: PromptPreparation): Promise;\n}', + declaration: 'export class SystemPrompt extends Service {\n static Config: z;\n constructor(ctx: Context, config: Config);\n section(section: PromptSection): () => void;\n getSectionOrder(name: PromptSectionOrderName): number;\n getContextOrder(name: PromptContextOrderName): number;\n context(context: PromptContext): () => void;\n suppressRuntimeContext(): () => void;\n tools(provider: (context: AssembleContext) => ToolProviderResult): () => void;\n variable(name: string, provider: (context: AssembleContext) => string | undefined): () => void;\n refreshContext(assembly: PromptAssembly, context: AssembleContext = {}): PromptAssembly;\n async assemble(context: AssembleContext = {}): Promise;\n}', }, { name: 'SystemPromptMessageSource', @@ -7966,7 +7956,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolActivationContext', - declaration: 'export interface ToolActivationContext {\n readonly agent: Agent;\n readonly modelSelection: ModelSelection;\n readonly signal: AbortSignal;\n}', + declaration: 'export interface ToolActivationContext {\n readonly agent: Agent;\n readonly signal: AbortSignal;\n}', }, { name: 'ToolAdditionBlock', diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index 9fadebb38e..33b681c436 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -39,14 +39,14 @@ en: 0acc88b042a99380 zh: e4cf66b77f2fc7ae /deepseek-ai-dsh-plan-mode/understand-the-implementation/durable-state-and-step-boundary-appends: - en: 6d0adadc354f211e - zh: 86fa49a9f4377368 + en: 1d2abc9a8ef4a1bf + zh: e09bc45a1d94934f /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-plan-command: en: a7bf35c2a9da52bc zh: dea9f4b3a41f1a6d /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-exit-tool: - en: 86b26413acb2e835 - zh: a84d876efefa5bea + en: cd036af680065de1 + zh: eed170bfef995d80 /deepseek-ai-dsh-plan-mode/understand-the-implementation/session-projection-unit: en: 74cd6bdf50af51f5 zh: 67609cf7202ececb @@ -99,8 +99,8 @@ en: 9d9626fbf4cdc8de zh: 8237cbc3ca048024 /deepseek-ai-dsh-plan-mode/known-limitations-and-deferred-work: - en: a87aabfede0087fd - zh: 201e9b3766980005 + en: 985f29a245876400 + zh: f7c9d7ed6eab1f55 /deepseek-ai-dsh-plan-mode/known-limitations-and-deferred-work/dev-note: en: 7de02cd33a767bd6 zh: d9e54003f230f725 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 26b24ed4c3..2c642ee0be 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -82,7 +82,7 @@ Plan mode is a product package, not a capability seam: there is no swappable bac ### Durable state and step-boundary appends -The package persists one log-only whole-value event, `plan/mode`, and the last logged value is the state. A mode change appends immediately when no turn is open; during an open turn it stays pending until the next accepted in-turn pre-step — the only append point while an agent runs — and an append failure stops step admission while retaining the pending selection. The `set`/`get` service methods and their exact return states live in [`src/index.ts`](src/index.ts) and read the registered `plan` projection; the first dependent access fails explicitly when the registry or key is absent. +The package persists one log-only whole-value event, `plan/mode`, and the last logged value is the state. A mode change appends immediately when no turn is open; during an open turn it stays pending until the next step boundary — the only append point while an agent runs, before the step chooses its model — and an append failure fails that proposal while retaining the pending selection. The `set`/`get` service methods and their exact return states live in [`src/index.ts`](src/index.ts) and read the registered `plan` projection; the first dependent access fails explicitly when the registry or key is absent. ### The `/plan` command @@ -90,7 +90,7 @@ The command child activates only when a commands service is composed. It maps ba ### The exit tool -`exit_plan_mode` is conditionally admitted only while the committed plan state is active. Entering or leaving changes the tool declarations and plan guidance together; Native and PTC execution use the same admitted set. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. +`exit_plan_mode` is conditionally admitted only while the committed plan state is active. Entering or leaving changes the tool declarations and plan guidance together; Native and PTC execution use the same admitted set. An approved review records a silent pending exit that the next step boundary appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. ### Session projection unit @@ -182,7 +182,7 @@ Entering plan mode adds the exit tool through the route’s tool-update protocol These limits describe when plan mode does not behave as you might expect or needs extra care. They are current package constraints, not a roadmap. - **Guidance, not enforcement** — plan mode restrains through text only; deployments that need enforced restrictions configure sandbox mode and approval policy independently. -- **Pending selections are process-local** — a selection made after the turn's final accepted pre-step is lost if the process exits before another accepted in-turn pre-step; the UI must reapply it. +- **Pending selections are process-local** — a selection made after the turn's final step boundary is lost if the process exits before another step boundary; the UI must reapply it. - **No creation-time plan option** — forked agents inherit logged plan state, while newly spawned agents begin inactive. - **Live children cannot open the review** — a child owned by another live agent fails the `exit_plan_mode` call and is told to include the unresolved decision in its final result; durable fork lineage alone does not prevent a session resumed as a runtime root from opening the review. - **One specialized review renderer** — only the Web UI has a `plan-review` presentation; another interaction provider presents the same request through its generic option flow. diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index 3239d57803..758a5153db 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -82,7 +82,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 持久状态与步骤边界追加 -本包持久化一条仅记日志、整值替换的事件 `plan/mode`,最后一条已记录值即为状态。没有打开的轮次时立即记录模式变化;轮次内则等待下一个被接纳的 pre-step。写入失败会停止步骤接纳并保留待提交选择。`set`/`get` 的精确返回状态见 [`src/index.ts`](src/index.ts);它们读取已注册的 `plan` 投影,缺少注册表或投影键时在首次依赖访问处明确失败。 +本包持久化一条仅记日志、整值替换的事件 `plan/mode`,最后一条已记录值即为状态。没有打开的轮次时立即记录模式变化;轮次内则等待下一个步骤边界,这是 agent 运行时唯一的写入点,位于该步骤选择模型之前。写入失败会使该提案失败,并保留待提交选择。`set`/`get` 的精确返回状态见 [`src/index.ts`](src/index.ts);它们读取已注册的 `plan` 投影,缺少注册表或投影键时在首次依赖访问处明确失败。 ### `/plan` 命令 @@ -90,7 +90,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 退出工具 -`exit_plan_mode` 只在已提交的计划状态为 active 时准入。进入或离开会同时改变工具声明与计划指导;原生和 PTC 执行使用同一准入集合。批准评审后记录静默的待退出选择,由下一个被接纳的轮次内 pre-step 提交,当前工具批次的剩余调用保留计划指导。没有用户问答通道,或评审期间服务重载时,调用失败;`/plan off` 仍可手动退出。 +`exit_plan_mode` 只在已提交的计划状态为 active 时准入。进入或离开会同时改变工具声明与计划指导;原生和 PTC 执行使用同一准入集合。批准评审后记录静默的待退出选择,由下一个步骤边界提交,当前工具批次的剩余调用保留计划指导。没有用户问答通道,或评审期间服务重载时,调用失败;`/plan off` 仍可手动退出。 ### 会话投影单元 @@ -182,7 +182,7 @@ schema 仅在启用时按 ToolRuntime 模式计入开销;每份计划参数与 这些限制描述计划模式在哪些情况下不符合你的预期,或需要额外的注意。它们是当前包约束,不是路线图。 - **引导而非强制**——计划模式只通过文本约束;需要强制限制的部署要分别配置沙箱模式与审批策略。 -- **待生效选择只存在于进程内**——某轮最后一个被接受的 pre-step 之后作出的选择,若进程在另一个被接受的轮内 pre-step 之前退出就会丢失;UI 必须重新应用它。 +- **待生效选择只存在于进程内**——某轮最后一个步骤边界之后作出的选择,若进程在下一个步骤边界之前退出就会丢失;UI 必须重新应用它。 - **没有创建时 plan 选项**——fork 的 agent 继承已记录的计划状态,新 spawn 的 agent 则从未激活开始。 - **存活的子级无法打开评审**——由另一个存活 agent 所有的子级调用 `exit_plan_mode` 会失败,并被要求把尚未解决的决策包含进最终结果;仅有持久化 fork 谱系并不能阻止恢复为运行时根的会话打开该评审。 - **只有一个专用评审渲染器**——只有 Web UI 具备 `plan-review` 呈现;其他交互提供方通过其通用选项流程呈现同一请求。 diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index e99f53f95a..717f459661 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -7,10 +7,11 @@ * state. * * The `plan` projection folds the session log, so resume and fork restore the - * state. User selections remain pending until the next accepted in-turn - * pre-step. The service appends `plan/mode` from `agent/pre-step` before - * step-time tool conditions and plan guidance read that committed state. - * Same-step retries do not commit pending selections. + * state. User selections made during a turn remain pending until the next + * step boundary. The service appends `plan/mode` from `agent/step-boundary`, + * before the step chooses its model, so `agent/model`, `agent/pre-step`, tool + * conditions, and plan guidance read the committed state. Same-step retries + * do not commit pending selections. * * The exit tool is admitted only for requests whose committed plan state is * active. Native declarations, PTC bindings, and execution share that selection. @@ -177,32 +178,40 @@ export class PlanModeController extends Service { private readonly section: string /** - * Latest selection per session awaiting the next accepted in-turn pre-step. + * Latest selection per session awaiting the next step boundary. * `narrate` is true for user selections and false for the exit tool, whose * result already narrates the transition. */ private readonly pendingIntents = new WeakMap() + /** Sessions whose boundary-committed user switch still owes a notice in an admitted step. */ + private readonly unannounced = new WeakSet() constructor(ctx: Context, config: PlanModeConfig = { section: '' }) { super(ctx, 'planMode') this.section = resolveConfig(config).section let disposed = false - // Pre-step is outside Session.append publication, so it can append the - // log-only mode event inside an open turn without re-entering the session. - // A failed append remains pending and stops admission before guidance or - // tool availability could describe an uncommitted state. + // The step boundary is outside Session.append publication, so it can append + // the log-only mode event inside an open turn without re-entering the + // session. A failed append remains pending and fails the proposal before + // model choice, guidance, or tool availability could read an uncommitted state. + ctx.on('agent/step-boundary', ({ agent }) => { + const pending = this.pendingIntents.get(agent.session) + if (pending === undefined) return + this.onBoundary(agent.session) + if (pending.narrate) this.unannounced.add(agent.session) + else this.unannounced.delete(agent.session) + }) + // The notice joins the first admitted step after the commit; a rejected + // proposal leaves it owed to the next one. ctx.on('agent/pre-step', async ( { agent, signal }, next, ): Promise => { const decision = await next() - const pending = this.pendingIntents.get(agent.session) - if (decision.kind === 'reject' || signal.aborted || pending === undefined) return decision - const narration = this.narration(agent.session, pending.active) - this.onBoundary(agent.session) - return !pending.narrate || narration === undefined - ? decision - : { ...decision, messages: [...decision.messages, narration] } + if (decision.kind === 'reject' || signal.aborted || !this.unannounced.has(agent.session)) return decision + this.unannounced.delete(agent.session) + const narration = this.narration(agent.session, this.loggedActive(agent.session)) + return narration === undefined ? decision : { ...decision, messages: [...decision.messages, narration] } }) ctx.effect(() => () => { disposed = true }, 'dsh-plan-mode: close service lifetime') @@ -239,7 +248,7 @@ export class PlanModeController extends Service { return { kind: 'success', text: 'Plan mode entry cancelled.' } case 'noop': // Repeat the queued wording while an exit still awaits the - // next accepted pre-step; only a truly inactive session reads + // next step boundary; only a truly inactive session reads // idempotent. return this.loggedActive(agent.session) ? { kind: 'success', text: 'Leaving plan mode (applies from the next step).' } @@ -328,8 +337,8 @@ export class PlanModeController extends Service { } throw cause } - // A review may outlive this plugin fiber. Without its pre-step listener, - // an approved selection could never be appended, so fail and keep planning. + // A review may outlive this plugin fiber. Without its step-boundary + // listener, an approved selection could never be appended, so fail and keep planning. if (disposed) { throw new Error('the plan-mode service was reloaded while the plan was under review; present the plan again') } @@ -342,8 +351,8 @@ export class PlanModeController extends Service { : `The user chose to keep planning; their feedback: ${feedback}`) } // Keep plan guidance for the rest of this assistant tool batch. The - // silent selection is appended at the next accepted in-turn pre-step, - // before its tool and prompt assembly. + // silent selection is appended at the next step boundary, before that + // step chooses its model, tools, and prompt. this.pendingIntents.set(agent.session, { active: false, narrate: false }) return { approved: true } }, @@ -384,7 +393,7 @@ export class PlanModeController extends Service { /** * Read the logged plan state and any selected state awaiting the next - * accepted in-turn pre-step. + * step boundary. * * @param agent The agent to read. * @returns Current logged state plus a pending selection, when present. @@ -397,17 +406,17 @@ export class PlanModeController extends Service { /** * Select whether plan mode should be active. Between turns the method - * appends the change immediately because no in-turn pre-step will run until + * appends the change immediately because no step boundary will run until * another prompt starts a turn. The open-turn fold is the idle signal: * agent status stays `running` through post-turn checkpointing, when no - * further in-turn pre-step runs. During an open turn the selection remains - * pending until the next accepted in-turn pre-step. Repeated selection of - * the current or already-pending state is a no-op. + * further step boundary runs. During an open turn the selection remains + * pending until the next step boundary. Repeated selection of the current + * or already-pending state is a no-op. * * @param agent The agent to switch. * @param active Whether plan mode should be active. * @returns what happened: `committed` (logged now), `queued` (awaiting the - * next accepted in-turn pre-step), `cancelled` (an opposite pending selection + * next step boundary), `cancelled` (an opposite pending selection * was cleared; the logged state already matches), or `noop` (already in that * state). */ @@ -433,7 +442,7 @@ export class PlanModeController extends Service { return 'committed' } - /** Append one pending selection before the next request assembly. */ + /** Append one pending selection at a step boundary. */ private onBoundary(session: Session): void { const pending = this.pendingIntents.get(session) if (pending === undefined) return @@ -443,8 +452,8 @@ export class PlanModeController extends Service { return } session.append('plan/mode', { active: target }) - // Delete only after append succeeds so a later accepted in-turn pre-step - // can retry a failed durable write. + // Delete only after append succeeds so a later step boundary can retry a + // failed durable write. this.pendingIntents.delete(session) } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 562dedadf8..cc9e21b61d 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -19,7 +19,6 @@ import type { PlanModeConfig } from '../src/index.ts' import type { PlanUnitState } from '../src/types.ts' const testToolSignal = new AbortController().signal -const TEST_MODEL_SELECTION = { provider: 'test', model: 'test' } const TEST_PLAN_SECTION = 'Test plan mode instructions.' const PLAN_CONFIG = { section: TEST_PLAN_SECTION } satisfies PlanModeConfig @@ -36,8 +35,8 @@ function registerQuestionAnswerer(ctx: Context, answerer: QuestionAnswerer): () * Drives the REAL plugin: mounts `dsh-plan-mode` beside real `SystemPrompt` and * `ToolRuntime` services, with fake Agents carrying real `Session`s and a * real scoped `agent.ctx` minted through `createScope`. - * Request boundaries are simulated by dispatching the real pre-step waterfall - * and the following `step/start` session event used by the loop. + * Request boundaries are simulated by dispatching the real step-boundary and + * pre-step events and the following `step/start` session event used by the loop. */ async function agentWithSession( @@ -76,7 +75,7 @@ async function agentWithSession( } async function assembleFor(ctx: Context, agent: Agent) { - const toolSet = await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal: testToolSignal }) + const toolSet = await ctx.tools.resolve({ agent, signal: testToolSignal }) return ctx.systemPrompt.assemble({ agent, scope: agent, toolSet }) } @@ -106,19 +105,25 @@ async function setup(config: PlanModeConfig = PLAN_CONFIG): Promise { } /** - * Dispatch pre-step processing and optionally its following step-start commit. + * Dispatch a step boundary, its pre-step processing, and optionally the following step-start commit. */ -async function boundary(ctx: Context, agent: Agent & { session: Session }, type: 'pre-step' | 'step-start'): Promise { +async function boundary( + ctx: Context, + agent: Agent & { session: Session }, + type: 'pre-step' | 'step-start', + proposal: 'enter' | 'reject' = 'enter', +): Promise { const events = agentEvents(ctx, agent) const message = createUserMessage({ content: [{ type: 'text', text: 'boundary probe' }], source: { kind: 'user' }, }) const signal = new AbortController().signal + await events.serial('agent/step-boundary', { turn: 1, step: 1, signal }) const decision = await events.waterfall( 'agent/pre-step', - { messages: [message], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, - () => Promise.resolve({ kind: 'enter' as const, messages: [message] }), + { messages: [message], turn: 1, step: 1, signal }, + () => Promise.resolve(proposal === 'enter' ? { kind: 'enter' as const, messages: [message] } : { kind: 'reject' as const }), ) if (decision.kind === 'enter') { for (const message of decision.messages.slice(1)) { @@ -327,7 +332,7 @@ describe('the boundary flush', () => { expect(agent.session.snapshotEvents().some(event => event.type === 'plan/mode')).toBe(false) }) - it('flushes from pre-step before the following step/start', async () => { + it('flushes at the step boundary before the following step/start', async () => { const ctx = await setup() const agent = await agentWithSession(ctx) openTurn(agent.session) @@ -337,7 +342,7 @@ describe('the boundary flush', () => { expect(ctx.planMode.get(agent)).toEqual({ active: true }) }) - it('removes the pre-step flush when the plugin fiber is disposed', async () => { + it('removes the boundary flush when the plugin fiber is disposed', async () => { const ctx = new Context() await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) @@ -400,6 +405,19 @@ describe('the boundary flush', () => { expect(noticeTexts(agent.session)).toEqual(['The user switched this session back to the default mode.']) }) + it('commits at a rejected proposal and owes the notice to the next admitted step', async () => { + const ctx = await setup() + const agent = await agentWithSession(ctx) + header(agent.session) + openTurn(agent.session) + ctx.planMode.set(agent, true) + await boundary(ctx, agent, 'pre-step', 'reject') + expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) + expect(noticeTexts(agent.session)).toEqual([]) + await boundary(ctx, agent, 'pre-step') + expect(noticeTexts(agent.session)).toEqual(['The user switched this session to plan mode.']) + }) + it('stays silent when the header already reflects the flushed mode', async () => { const ctx = await setup() const agent = await agentWithSession(ctx) @@ -439,7 +457,7 @@ describe('the boundary flush', () => { expect(ctx.planMode.get(agent).pending).toBeUndefined() }) - it('rejects a pre-step append failure and keeps the intent pending', async () => { + it('rejects a boundary append failure and keeps the intent pending', async () => { const ctx = await setup() const warn = vi.fn() ctx.logger.warn = warn as never @@ -798,7 +816,7 @@ describe('exit_plan_mode', () => { async function callExit(ctx: Context, agent: Agent | undefined, plan = '# The plan\n\ndo things') { const signal = new AbortController().signal - const toolSet = agent === undefined ? undefined : await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal }) + const toolSet = agent === undefined ? undefined : await ctx.tools.resolve({ agent, signal }) return ctx.tools.execute({ ...toolSet === undefined ? {} : { toolSet }, callId: ToolCallId(`call-exit-${++callCounter}`), @@ -933,7 +951,7 @@ describe('exit_plan_mode', () => { const agent = await agentWithSession(ctx, 'ptc-exit', { active: true }) const result = await ctx.tools.execute({ - toolSet: await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal: testToolSignal }), + toolSet: await ctx.tools.resolve({ agent, signal: testToolSignal }), callId: ToolCallId(`call-exit-${++callCounter}`), name: RUN_CODE_NAME, arguments: { code: `return await tools.${EXIT_PLAN_MODE}({ plan: ${JSON.stringify(plan)} })`, description: 'Submit the plan for review' }, @@ -1083,7 +1101,7 @@ describe('exit_plan_mode', () => { const { ctx, agent, asked } = await setupWithReview({ selected: ['Approve'] }) const controller = new AbortController() const result = await ctx.tools.execute({ - toolSet: await ctx.tools.resolve({ agent, modelSelection: TEST_MODEL_SELECTION, signal: testToolSignal }), + toolSet: await ctx.tools.resolve({ agent, signal: testToolSignal }), callId: ToolCallId(`call-exit-${++callCounter}`), name: EXIT_PLAN_MODE, arguments: { plan: '# P' }, diff --git a/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts b/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts index d7991f7c0c..654b1ab18f 100644 --- a/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts +++ b/packages/session/session-checkpoint-policy/tests/session-checkpoint-policy.spec.ts @@ -220,7 +220,7 @@ describe('session-checkpoint-policy tool and step boundaries', () => { ctx.on('session/flush', (current) => { flushed.push(current.id) }) const signal = new AbortController().signal await agentEvents(ctx, agent).waterfall( - 'agent/pre-step', { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, + 'agent/pre-step', { messages: [], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter', messages: [] }), ) expect(flushed).toEqual([session.id]) diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index 2a03b75013..a593c37b80 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -18,8 +18,8 @@ en: 0cd615b8f987f950 zh: ccf4964df789011c /deepseek-ai-dsh-working-directory/understand-the-implementation: - en: 6f7b264aef175243 - zh: e2798c0aab0eb21b + en: f0458147d29631b1 + zh: 6a288670dd084ffb /deepseek-ai-dsh-working-directory/further-exploration: en: eabff683146786c8 zh: 7997dec17802ef64 @@ -39,8 +39,8 @@ en: f5a095acef81df3b zh: 758796edbc4337fc /deepseek-ai-dsh-working-directory/known-limitations-and-deferred-work: - en: 17ecae217e34f3cd - zh: 92d52f4ced97d044 + en: a0f7bcd972f4a4fb + zh: 051ec0eb0fa92bea /deepseek-ai-dsh-working-directory/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: a4b126f9a4eaca6f diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 8866317c01..1f54ad8c92 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -39,7 +39,7 @@ Mount alongside `fs`, `sessionProjections`, and `systemPrompt`. `defaultDirector
Implementation internals — click to expand -The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. `system-prompt/prepare` validates the current directory before step admission and before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. +The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. No runtime invariant companion is published because the service reads its only directory state from the Session projection and checks filesystem validity at use. @@ -77,7 +77,7 @@ Directory transitions append context without replacing the stable system-prompt -- **Missing original project** — when the current directory and the original project are both unavailable, step preparation rejects every model turn, including chat-only turns. The service does not choose or recreate a repository. Restore the original directory, or use SDK `setWorkingDirectory` (`set_working_directory` in Python) or `ctx.workingDirectory.set` to select an existing absolute directory before retrying. Existing shells retain their process-local directories. +- **Missing original project** — when the current directory and the original project are both unavailable, prompt assembly rejects every model turn, including chat-only turns. The service does not choose or recreate a repository. Restore the original directory, or use SDK `setWorkingDirectory` (`set_working_directory` in Python) or `ctx.workingDirectory.set` to select an existing absolute directory before retrying. Existing shells retain their process-local directories. ### Dev Note diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index f3e65358b5..ad92f21b59 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -39,7 +39,7 @@ kind: "package-reference"
实现细节 — 点击展开 -Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。`system-prompt/prepare` 在步骤接纳以及发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 +Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。 @@ -77,7 +77,7 @@ Session 投影拥有当前目录,并通过 Session observation 暴露它,因 -- **原始项目缺失** — 当前目录与原始项目均不可用时,步骤准备会拒绝每个模型轮次,包括纯聊天轮次。服务不会另选或重建仓库。请先恢复原始目录,或通过 SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`)或 `ctx.workingDirectory.set` 选择现有的绝对目录,再重试。已有 shell 保留各自进程的目录。 +- **原始项目缺失** — 当前目录与原始项目均不可用时,提示词组装会拒绝每个模型轮次,包括纯聊天轮次。服务不会另选或重建仓库。请先恢复原始目录,或通过 SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`)或 `ctx.workingDirectory.set` 选择现有的绝对目录,再重试。已有 shell 保留各自进程的目录。 ### 开发备注 diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index 90156169ed..7346feb274 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -94,7 +94,7 @@ export class WorkingDirectoryService extends Service { interpolate: false, text: context => context.agent === undefined ? '' : this.contextText(context.agent.session), }) - ctx.on('system-prompt/prepare', async (_assembly, context, next) => { + ctx.on('system-prompt/assemble', async (_assembly, context, next) => { if (context.agent === undefined) return next() await this.ensure(context.agent, context.signal) const assembly = await next() diff --git a/packages/session/working-directory/tests/working-directory.spec.ts b/packages/session/working-directory/tests/working-directory.spec.ts index a3fd4281b5..dbd6775312 100644 --- a/packages/session/working-directory/tests/working-directory.spec.ts +++ b/packages/session/working-directory/tests/working-directory.spec.ts @@ -9,7 +9,7 @@ import WorkingDirectory, { type Config as WorkingDirectoryConfig } from '@deepse import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' import { SessionId } from '@deepseek-ai/dsh-session' import { ToolCallId } from '@deepseek-ai/dsh-llm' -import { renderContextSnapshot, renderPrompt, type AssembleContext, type PromptPreparation } from '@deepseek-ai/dsh-system-prompt' +import { renderContextSnapshot, renderPrompt } from '@deepseek-ai/dsh-system-prompt' import * as WorkingDirectoryTool from '@deepseek-ai/dsh-tool-working-directory' async function fixture(config?: (root: string) => WorkingDirectoryConfig) { @@ -177,13 +177,9 @@ describe('Session working directories', () => { })]) }) - it.each((['system-prompt/prepare', 'system-prompt/assemble'] as const).flatMap(event => - (['remove', 'replace'] as const).map(change => ({ event, change })), - ))('retains required current-directory context after $event can $change it', async ({ event, change }) => { + it.each(['remove', 'replace'] as const)('retains required current-directory context after an assembly transform can %s it', async (change) => { await using f = await fixture() - f.ctx.on(event, async ( - _assembly: Assembly, _context: AssembleContext, next: () => Promise, - ) => { + f.ctx.on('system-prompt/assemble', async (_assembly, _context, next) => { const assembled = await next() return { ...assembled, diff --git a/packages/skill/tool-skill/tests/tool-skill.spec.ts b/packages/skill/tool-skill/tests/tool-skill.spec.ts index b1bfb6776f..e3362cda0a 100644 --- a/packages/skill/tool-skill/tests/tool-skill.spec.ts +++ b/packages/skill/tool-skill/tests/tool-skill.spec.ts @@ -116,7 +116,7 @@ async function fireStep(ctx: Context, agent: Agent, turn: number, step: number): const signal = new AbortController().signal const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn, step, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: [], turn, step, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { @@ -134,7 +134,7 @@ async function proposeStep( const signal = new AbortController().signal return await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages, turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages, turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter' as const, messages }), ) } @@ -166,7 +166,7 @@ async function composePrefix(ctx: Context, cwd: string, signal = new AbortContro async function composePrefixForAgent(ctx: Context, agent: Agent, signal = new AbortController().signal): Promise { const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: [], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) if (decision.kind === 'enter') { @@ -1104,7 +1104,7 @@ describe('user-explicit invocation injection', () => { const signal = new AbortController().signal const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', - { messages: [gesture('/hidden-demo blocked step')], turn: 1, step: 1, modelSelection: { provider: 'test', model: 'test' }, signal }, + { messages: [gesture('/hidden-demo blocked step')], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'reject' as const }), ) expect(decision).toEqual({ kind: 'reject' }) diff --git a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts index 4f5b02bd1d..66ec1314e2 100644 --- a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts @@ -275,7 +275,6 @@ describe('SubagentModelSelectionConfig', () => { messages: [], turn: 1, step: 1, - modelSelection: { provider: 'test', model: 'test' }, signal: new AbortController().signal, } await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next)) diff --git a/scripts/fixtures/python-sdk-dynamic-tools.mjs b/scripts/fixtures/python-sdk-dynamic-tools.mjs index 99fc3722db..83b8439ac7 100644 --- a/scripts/fixtures/python-sdk-dynamic-tools.mjs +++ b/scripts/fixtures/python-sdk-dynamic-tools.mjs @@ -14,7 +14,7 @@ export function apply(ctx) { render(_args, value) { return [{ type: 'text', text: value }] }, }, async execute() { return 'pong' }, - }, { when: async ({ modelSelection }) => active && modelSelection.provider === 'deepseek-official' }) + }, { when: async ({ agent }) => active && agent.step?.modelSelection.provider === 'deepseek-official' }) ctx.on('tools/post-execute', async (exec, result, next) => { const downstream = await next() if (result.isError) return downstream diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 7b886ad3fd..41d6cf8657 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -320,6 +320,7 @@ export const LINK_MAP: Readonly> = { AgentFactory: 'core.md', AgentHandle: 'core.md', ModelSelection: 'core.md', + AgentStep: 'core.md', AllowedModelRoute: 'subagent.md', SubagentModelSelectionSettings: 'subagent.md', AgentOptions: 'core.md', @@ -941,7 +942,6 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { ToolRegistrationOptions: 'conditional registration options are owned by packages/core/tools/README.md', ResolvedToolSet: 'step-owned admission is owned by packages/core/tools/README.md', PromptAssembly: 'assembly result is owned by packages/core/system-prompt/README.md', - PromptPreparation: 'preparation inputs are owned by packages/core/system-prompt/README.md', PromptPresentation: 'presentation inputs are owned by packages/core/system-prompt/README.md', RequestRunId: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts', RpcReceipt: 'carrier-layer receipt is owned by packages/client/connection/src/rpc.ts', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 01c3f8376b..8191d85fd3 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1548,22 +1548,22 @@ function renderLifecycle(): string { ' Note over Agent,Driver: claim pending next-step input plus one queued prompt', ` Driver-->>SDK: ${mermaidCode('agent/inbox/spliced')} pure deletion`, ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, - ` Driver->>Hooks: ${mermaidCode('agent/model')} waterfall chooses the step provider, model, and effort`, - ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall with the step model selection`, - ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall with the step model selection`, + ` Driver->>Hooks: ${mermaidCode('agent/step-boundary')} serial commits selections pending for this step`, + ` Driver->>Hooks: ${mermaidCode('agent/model')} waterfall chooses provider, model, and effort, published as agent.step`, + ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall reads agent.step`, ' Hooks-->>Driver: authoritative reject or enter(messages)', ' alt proposed step rejected, first batch empty, or pre-step failed', ' Driver-->>Driver: claimed batch stays removed, the open turn spends no step', ' else enter proposed step', ` Driver->>Session: ${mermaidCode('step/start')}`, - ' Driver->>Tools: resolve({ agent, modelSelection, signal }) once per step', - ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} with the step tool set`, + ' Driver->>Tools: resolve({ agent, signal }) once per step', + ` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} contexts, variables, sections, and the step tool set`, ` Driver->>Hooks: ${mermaidCode('agent/request')} waterfall with the step model selection`, ' Driver->>LLM: prepareCall(config, signal)', ' Note over Driver,LLM: cancellation during preparation commits neither system nor users', ' Note over Driver,Session: synchronous admission using the prepared call capability', ` Driver->>Session: ${mermaidCode('system/message')} ordered per-node reconciliation`, - ` Driver->>Session: ${mermaidCode('user/message')} per entered message`, + ` Driver->>Session: ${mermaidCode('user/message')} per entered message, then a changed runtime-context snapshot`, ` Driver->>Session: ${mermaidCode('request/header')} and ${mermaidCode('request/context')} as needed`, ' Driver->>Driver: derive and freeze request from the log', ` Driver->>LLM: bound prepared call through ${mermaidCode('llm/stream')} waterfall`, @@ -1598,8 +1598,8 @@ function renderLifecycle(): string { ' opt next-step input is pending', ' Driver-->>Driver: claim pending next-step input', ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, + ` Driver->>Hooks: ${mermaidCode('agent/step-boundary')} serial`, ` Driver->>Hooks: ${mermaidCode('agent/model')} waterfall`, - ` Driver->>Prompt: ${mermaidCode('system-prompt/prepare')} waterfall`, ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`, ' Hooks-->>Driver: authoritative reject or enter(messages)', ' end', diff --git a/scripts/python-snapshot-workflow-order.spec.ts b/scripts/python-snapshot-workflow-order.spec.ts index 3461e5faf6..b82796cb52 100644 --- a/scripts/python-snapshot-workflow-order.spec.ts +++ b/scripts/python-snapshot-workflow-order.spec.ts @@ -44,7 +44,7 @@ async function harness(direct = false) { runId: WorkflowRunId('run'), seq: 1, label: 'workflow-child', childId, }) const step = (overrides = {}) => agentEvents(ctx, agent).waterfall('agent/pre-step', { - turn: 1, step: 1, messages, modelSelection: { provider: 'test', model: 'test' }, signal: controller.signal, ...overrides, + turn: 1, step: 1, messages, signal: controller.signal, ...overrides, }, next) return { ctx, fiber, parent, other, session, agent, controller, decision, next, start, step } } diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 997dd53cfe..bd35522ab7 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2181,6 +2181,11 @@ "symbol": "ModelSelection", "source": "packages/core/agent/src/runtime-types.ts" }, + { + "doc": "docs/subsystems/core.md", + "symbol": "AgentStep", + "source": "packages/core/agent/src/runtime-types.ts" + }, { "doc": "docs/subsystems/feedback.md", "symbol": "MessageFeedbackVersion", From 7d0059280251b47bff323e548c4e2992fb457f92 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 13 Oct 2026 17:05:03 +0800 Subject: [PATCH 09/36] test(snapshots): admit the runtime context after the step batch The runtime-context snapshot now follows the messages that agent/pre-step admitted, so recorded sessions swap it with pre-step additions such as time context and skill notices. cordis-inspect-jsdoc records the new agent.step and agent/step-boundary declarations. --- .../cordis-inspect-jsdoc/session.v4.jsonl | 2 +- .../session.v4.jsonl | 6 +++--- .../session.v4.jsonl | 4 ++-- .../session.v4.jsonl | 4 ++-- .../office-authoring-checker/session.v4.jsonl | 4 ++-- .../office-progressive-native/session.v4.jsonl | 4 ++-- .../office-progressive-ptc/session.v4.jsonl | 4 ++-- .../writer.expected.jsonl | 16 ++++++++-------- .../office-render-tools/writer.expected.jsonl | 16 ++++++++-------- .../office-sidecar-instructions/session.v4.jsonl | 4 ++-- .../office-skills-no-renderer/session.v4.jsonl | 4 ++-- snapshots/session/office-skills/session.v4.jsonl | 4 ++-- snapshots/session/skill-load/session.v4.jsonl | 4 ++-- .../session/windows-acl-skill/session.v4.jsonl | 4 ++-- snapshots/web/approval-composer/session.v4.jsonl | 4 ++-- .../web/changed-files-turn/session.v4.jsonl | 4 ++-- snapshots/web/code-language/session.v4.jsonl | 4 ++-- .../web/deepseek-messages-chat/session.v4.jsonl | 4 ++-- snapshots/web/feedback-command/session.v4.jsonl | 4 ++-- snapshots/web/file-upload-round/session.v4.jsonl | 4 ++-- snapshots/web/fresh-round-trip/session.v4.jsonl | 4 ++-- .../web/goal-multi-turn-actions/session.v4.jsonl | 4 ++-- snapshots/web/lifecycle-chrome/session.v4.jsonl | 4 ++-- snapshots/web/live-interactions/session.v4.jsonl | 4 ++-- .../official-subagent-bundle/session.v4.jsonl | 4 ++-- .../web/optional-string-editor/session.v4.jsonl | 4 ++-- .../permission-policy-context/session.v4.jsonl | 4 ++-- snapshots/web/plan-review/session.v4.jsonl | 4 ++-- snapshots/web/present-svg/session.v4.jsonl | 4 ++-- snapshots/web/present/session.v4.jsonl | 4 ++-- .../web/ptc-escalation-approved/session.v4.jsonl | 4 ++-- snapshots/web/ptc-round/session.v4.jsonl | 4 ++-- snapshots/web/question-composer/session.v4.jsonl | 4 ++-- snapshots/web/steering/session.v4.jsonl | 4 ++-- snapshots/web/turn-tail-actions/session.v4.jsonl | 4 ++-- snapshots/web/web-search-round/session.v4.jsonl | 4 ++-- 36 files changed, 84 insertions(+), 84 deletions(-) diff --git a/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl b/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl index 1ba3ffbed5..d1ef80a30a 100644 --- a/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl +++ b/snapshots/session/cordis-inspect-jsdoc/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Inspect the exact tools service","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788778145981,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788778145981,"index":0,"dt":[],"id":"inspect-tools-api","name":"cordis_inspect_query","args":["{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"]},{"type":"chunk","time":1788778145981,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}}},{"type":"chunk","time":1788778145981,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788778145981,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"inspect-tools-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"tools\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"inspect-tools-api"},"toolCallId":"inspect-tools-api","content":[{"type":"text","text":"{\n \"platform\": \"host\",\n \"provider\": \"Service\",\n \"method\": \"listService\",\n \"data\": {\n \"mode\": \"service\",\n \"service\": {\n \"key\": \"tools\",\n \"description\": \"Tool registry and execution pipeline. Scoped registrations shadow globals; one visibility resolver feeds presentation, lookup, and dispatch.\",\n \"access\": {\n \"optional\": {\n \"expression\": \"ctx.get(\\\"tools\\\")\",\n \"requiresUndefinedCheck\": true\n },\n \"hardDependency\": {\n \"inject\": [\n \"tools\"\n ],\n \"expression\": \"ctx.tools\"\n }\n },\n \"methods\": [\n {\n \"signature\": \"presentAs(mode: ToolPresentationMode): () => void\",\n \"description\": \"Present the calling scope's tools in `mode` instead of the deployment default. Nearest scope on the chain wins, so a preset's standing declaration covers every agent joined under it.\\n\\nScoped only, and one declaration per scope: this is how an agent preset composes PTC mode agents beside native ones in the same process, and a process-global override would be the `mode` config field instead.\",\n \"parameters\": [\n {\n \"name\": \"mode\",\n \"description\": \"the presentation the covered agents' models see.\"\n }\n ],\n \"returns\": \"the exact disposer that restores the deployment default.\"\n },\n {\n \"signature\": \"register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void\",\n \"description\": \"Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.\",\n \"parameters\": [\n {\n \"name\": \"definition\",\n \"description\": \"tool schema, execution, and optional finalization/presentation callbacks.\"\n },\n {\n \"name\": \"options\",\n \"description\": \"optional step-time activation condition.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the tool.\"\n },\n {\n \"signature\": \"restrict(filter: ToolRestriction): () => void\",\n \"description\": \"Restrict global tools for the calling agent scope. Empty filters, unknown names, scope-local names, and reserved transport names fail. Restrictions intersect; scoped registrations remain visible.\",\n \"parameters\": [\n {\n \"name\": \"filter\",\n \"description\": \"global-tool mask: `allow` (keep only) and/or `deny` (remove).\"\n }\n ],\n \"returns\": \"the exact disposer that lifts this restriction.\"\n },\n {\n \"signature\": \"guard(guard: ToolGuard): () => void\",\n \"description\": \"Register a monotonic guard after the extensible `tools/pre-execute` waterfall. A plain-context guard applies globally; one registered through `agent.ctx` applies only to that agent. Any matching guard may deny by returning a reason, while no guard can force-allow a call another guard denied. The exact effect disposer is returned for ordered ownership and HMR cleanup.\",\n \"parameters\": [\n {\n \"name\": \"guard\",\n \"description\": \"synchronous check; a returned string denies the execution.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the guard.\"\n },\n {\n \"signature\": \"get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined\",\n \"description\": \"Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.\",\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the tool name as registered.\"\n },\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission; omit only to inspect registered definitions.\"\n }\n ],\n \"returns\": \"the definition the scope resolves, or undefined when none is visible.\"\n },\n {\n \"signature\": \"async resolve(context: ToolActivationContext): Promise\",\n \"description\": \"Resolve conditions once for this step without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.\",\n \"parameters\": [\n {\n \"name\": \"context\",\n \"description\": \"preparing agent, step model selection, and cancellation.\"\n }\n ],\n \"returns\": \"the complete selection; the caller disposes it after its tool batch settles.\"\n },\n {\n \"signature\": \"schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]\",\n \"description\": \"Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.\",\n \"parameters\": [\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission, or omitted for registered-definition inspection.\"\n }\n ],\n \"returns\": \"one deep-cloned schema per visible tool.\"\n },\n {\n \"signature\": \"executionMode(exec: ToolExecutionInput): ToolExecutionMode\",\n \"description\": \"Classify a pending call through the caller's visible tool definition. Only an exact `true` is parallel; unknown, hidden, undeclared, invalid, or throwing classifiers are exclusive.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"call name, parsed arguments, and optional agent scope.\"\n }\n ],\n \"returns\": \"the fail-closed scheduling mode.\"\n },\n {\n \"signature\": \"async execute(exec: ToolExecutionInput): Promise\",\n \"description\": \"Execute through pre-policy, guards, around-dispatch, post-policy, definition-owned content finalization, and final notification. Tool and listener failures resolve as materialized error results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen snapshot final observers receive. Cancellation arriving after entry and before final result materialization skips a not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a successful started outcome with `ABORTED`; already-started work is still drained and may retain a tool-owned structured error.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"the typed same-process call input. The registry assigns its correlation token before policy begins.\"\n }\n ],\n \"returns\": \"the materialized final result.\"\n }\n ]\n },\n \"referencedTypes\": [\n {\n \"name\": \"Agent\",\n \"declaration\": \"export interface Agent {\\n readonly id: SessionId;\\n}\"\n },\n {\n \"name\": \"Branded\",\n \"declaration\": \"export type Branded = string & {\\n readonly [BRAND]: B;\\n};\"\n },\n {\n \"name\": \"DiffCallView\",\n \"declaration\": \"export interface DiffCallView {\\n card: 'diff';\\n title: string;\\n diffs: FileDiff[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"DiffResultView\",\n \"declaration\": \"export interface DiffResultView {\\n card: 'diff';\\n title?: string;\\n diffs: FileDiff[];\\n}\"\n },\n {\n \"name\": \"FileDiff\",\n \"declaration\": \"export interface FileDiff {\\n path: string;\\n oldText: string | null;\\n newText: string;\\n}\"\n },\n {\n \"name\": \"FileLocation\",\n \"declaration\": \"export interface FileLocation {\\n path: string;\\n line?: number;\\n}\"\n },\n {\n \"name\": \"GenericCallView\",\n \"declaration\": \"export interface GenericCallView {\\n card: 'generic';\\n title: string;\\n kind?: ToolCallKind;\\n rawInput?: unknown;\\n content?: ContentBlock[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"GenericResultView\",\n \"declaration\": \"export interface GenericResultView {\\n card: 'generic';\\n title?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"JsonSchemaNode\",\n \"declaration\": \"export interface JsonSchemaNode {\\n type?: JsonSchemaType;\\n oneOf?: JsonSchemaNode[];\\n properties?: Record;\\n required?: string[];\\n additionalProperties?: boolean;\\n items?: JsonSchemaNode;\\n enum?: JsonSchemaScalar[];\\n const?: JsonSchemaScalar;\\n description?: string;\\n title?: string;\\n default?: JsonValue;\\n examples?: JsonValue;\\n}\"\n },\n {\n \"name\": \"JsonSchemaScalar\",\n \"declaration\": \"export type JsonSchemaScalar = string | number | boolean | null;\"\n },\n {\n \"name\": \"JsonSchemaType\",\n \"declaration\": \"export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\"\n },\n {\n \"name\": \"JsonValue\",\n \"declaration\": \"export type JsonValue = null | boolean | number | string | JsonValue[] | {\\n [key: string]: JsonValue;\\n};\"\n },\n {\n \"name\": \"ReadFileLine\",\n \"declaration\": \"export interface ReadFileLine {\\n number: number;\\n text: string;\\n}\"\n },\n {\n \"name\": \"ReadResultView\",\n \"declaration\": \"export interface ReadResultView {\\n card: 'read';\\n title?: string;\\n path: string;\\n offset: number;\\n lines: ReadFileLine[];\\n totalLines: number;\\n lang?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"ResolvedToolSet\",\n \"declaration\": \"export interface ResolvedToolSet {\\n dispose(): void;\\n view(scope: ScopeKey | undefined): ReadonlyMap;\\n}\"\n },\n {\n \"name\": \"ScopeKey\",\n \"declaration\": \"export type ScopeKey = object;\"\n },\n {\n \"name\": \"SearchFileMatches\",\n \"declaration\": \"export interface SearchFileMatches {\\n path: string;\\n matches: SearchLineMatch[];\\n}\"\n },\n {\n \"name\": \"SearchLineMatch\",\n \"declaration\": \"export interface SearchLineMatch {\\n lineNumber: number;\\n line: string;\\n}\"\n },\n {\n \"name\": \"SearchMatchesResultView\",\n \"declaration\": \"export interface SearchMatchesResultView {\\n card: 'search';\\n shape: 'matches';\\n title?: string;\\n files: SearchFileMatches[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchPathsResultView\",\n \"declaration\": \"export interface SearchPathsResultView {\\n card: 'search';\\n shape: 'paths';\\n title?: string;\\n paths: string[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchResultView\",\n \"declaration\": \"export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;\"\n },\n {\n \"name\": \"SessionId\",\n \"declaration\": \"export type SessionId = Branded<'SessionId'>;\"\n },\n {\n \"name\": \"TerminalCallView\",\n \"declaration\": \"export interface TerminalCallView {\\n card: 'terminal';\\n title: string;\\n description?: string;\\n cwd?: string;\\n}\"\n },\n {\n \"name\": \"TerminalResultView\",\n \"declaration\": \"export interface TerminalResultView {\\n card: 'terminal';\\n title?: string;\\n output?: string;\\n exitCode?: number;\\n signal?: string;\\n}\"\n },\n {\n \"name\": \"ToolActivationContext\",\n \"declaration\": \"export interface ToolActivationContext {\\n readonly agent: Agent;\\n readonly modelSelection: ModelSelection;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolCallId\",\n \"declaration\": \"export type ToolCallId = Branded<'ToolCallId'>;\"\n },\n {\n \"name\": \"ToolCallKind\",\n \"declaration\": \"export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\"\n },\n {\n \"name\": \"ToolCallView\",\n \"declaration\": \"export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\"\n },\n {\n \"name\": \"ToolDefinition\",\n \"declaration\": \"export interface ToolDefinition extends ToolSchema {\\n readonly output: ToolOutputDefinition;\\n execute(args: unknown, exec: ToolRunContext): Promise;\\n projectContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n timeoutMs?: number;\\n isConcurrencySafe?(args: unknown): boolean;\\n presentCall?(args: unknown): ToolCallView | undefined;\\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\\n}\"\n },\n {\n \"name\": \"ToolErrorInfo\",\n \"declaration\": \"export interface ToolErrorInfo {\\n name: string;\\n code: string;\\n reason?: string;\\n}\"\n },\n {\n \"name\": \"ToolExecution\",\n \"declaration\": \"export interface ToolExecution extends ToolExecutionInput {\\n readonly rootCallId: ToolCallId;\\n readonly token: ToolExecutionToken;\\n}\"\n },\n {\n \"name\": \"ToolExecutionFailure\",\n \"declaration\": \"export interface ToolExecutionFailure {\\n readonly isError: true;\\n readonly error: ToolFailure;\\n readonly value?: never;\\n readonly content: ContentBlock[];\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: never;\\n}\"\n },\n {\n \"name\": \"ToolExecutionInput\",\n \"declaration\": \"export interface ToolExecutionInput {\\n readonly callId: ToolCallId;\\n readonly rootCallId?: ToolCallId;\\n readonly name: string;\\n readonly schema?: ToolSchema;\\n readonly arguments: unknown;\\n readonly agent?: Agent;\\n readonly toolSet?: ResolvedToolSet;\\n readonly parent?: ToolExecutionToken;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolExecutionMode\",\n \"declaration\": \"export type ToolExecutionMode = {\\n kind: 'parallel';\\n} | {\\n kind: 'exclusive';\\n};\"\n },\n {\n \"name\": \"ToolExecutionResult\",\n \"declaration\": \"export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\"\n },\n {\n \"name\": \"ToolExecutionSuccess\",\n \"declaration\": \"export interface ToolExecutionSuccess {\\n readonly isError: false;\\n readonly value: JsonValue;\\n readonly content: ContentBlock[];\\n readonly error?: never;\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: true;\\n}\"\n },\n {\n \"name\": \"ToolExecutionToken\",\n \"declaration\": \"export type ToolExecutionToken = symbol & {\\n readonly [toolExecutionTokenBrand]: true;\\n};\"\n },\n {\n \"name\": \"ToolFailure\",\n \"declaration\": \"export interface ToolFailure {\\n message: string;\\n info?: ToolErrorInfo;\\n}\"\n },\n {\n \"name\": \"ToolGuard\",\n \"declaration\": \"export type ToolGuard = (execution: Readonly) => string | undefined;\"\n },\n {\n \"name\": \"ToolOutputDefinition\",\n \"declaration\": \"export interface ToolOutputDefinition {\\n readonly schema: JsonSchemaNode;\\n render(args: unknown, value: JsonValue): ContentBlock[];\\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolPresentationMode\",\n \"declaration\": \"export type ToolPresentationMode = 'native' | 'ptc';\"\n },\n {\n \"name\": \"ToolRegistrationOptions\",\n \"declaration\": \"export interface ToolRegistrationOptions {\\n readonly when?: (context: ToolActivationContext) => boolean | Promise;\\n}\"\n },\n {\n \"name\": \"ToolRestriction\",\n \"declaration\": \"export interface ToolRestriction {\\n readonly allow?: readonly string[];\\n readonly deny?: readonly string[];\\n}\"\n },\n {\n \"name\": \"ToolResult\",\n \"declaration\": \"export interface ToolResult {\\n content: ContentBlock[];\\n isError: boolean;\\n meta?: JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolResultView\",\n \"declaration\": \"export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | SearchResultView | ReadResultView | WebResultView;\"\n },\n {\n \"name\": \"ToolRunContext\",\n \"declaration\": \"export interface ToolRunContext extends ToolExecution {\\n deferContext(context: UserMessage): void;\\n concludeTurn(): void;\\n}\"\n },\n {\n \"name\": \"ToolSchema\",\n \"declaration\": \"export interface ToolSchema {\\n deferLoading?: true;\\n name: string;\\n description: string;\\n parameters: Record;\\n}\"\n },\n {\n \"name\": \"UserMessage\",\n \"declaration\": \"export interface UserMessage extends MessageBase {\\n readonly role: 'user';\\n}\"\n },\n {\n \"name\": \"WebFetchResultView\",\n \"declaration\": \"export interface WebFetchResultView {\\n card: 'web';\\n kind: 'fetch';\\n title?: string;\\n url: string;\\n statusCode: number;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebResultView\",\n \"declaration\": \"export type WebResultView = WebSearchResultView | WebFetchResultView;\"\n },\n {\n \"name\": \"WebSearchResultView\",\n \"declaration\": \"export interface WebSearchResultView {\\n card: 'web';\\n kind: 'search';\\n title?: string;\\n sources: WebSource[];\\n answer?: string;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebSource\",\n \"declaration\": \"export interface WebSource {\\n url: string;\\n title?: string;\\n snippet?: string;\\n publishedAt?: string;\\n}\"\n }\n ]\n }\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"inspect-tools-api"},"toolCallId":"inspect-tools-api","content":[{"type":"text","text":"{\n \"platform\": \"host\",\n \"provider\": \"Service\",\n \"method\": \"listService\",\n \"data\": {\n \"mode\": \"service\",\n \"service\": {\n \"key\": \"tools\",\n \"description\": \"Tool registry and execution pipeline. Scoped registrations shadow globals; one visibility resolver feeds presentation, lookup, and dispatch.\",\n \"access\": {\n \"optional\": {\n \"expression\": \"ctx.get(\\\"tools\\\")\",\n \"requiresUndefinedCheck\": true\n },\n \"hardDependency\": {\n \"inject\": [\n \"tools\"\n ],\n \"expression\": \"ctx.tools\"\n }\n },\n \"methods\": [\n {\n \"signature\": \"presentAs(mode: ToolPresentationMode): () => void\",\n \"description\": \"Present the calling scope's tools in `mode` instead of the deployment default. Nearest scope on the chain wins, so a preset's standing declaration covers every agent joined under it.\\n\\nScoped only, and one declaration per scope: this is how an agent preset composes PTC mode agents beside native ones in the same process, and a process-global override would be the `mode` config field instead.\",\n \"parameters\": [\n {\n \"name\": \"mode\",\n \"description\": \"the presentation the covered agents' models see.\"\n }\n ],\n \"returns\": \"the exact disposer that restores the deployment default.\"\n },\n {\n \"signature\": \"register(definition: ToolDefinition, options: ToolRegistrationOptions = {}): () => void\",\n \"description\": \"Register globally or in the calling agent scope. Scoped tools shadow globals; duplicates within one layer and the reserved `run_code` name fail.\",\n \"parameters\": [\n {\n \"name\": \"definition\",\n \"description\": \"tool schema, execution, and optional finalization/presentation callbacks.\"\n },\n {\n \"name\": \"options\",\n \"description\": \"optional step-time activation condition.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the tool.\"\n },\n {\n \"signature\": \"restrict(filter: ToolRestriction): () => void\",\n \"description\": \"Restrict global tools for the calling agent scope. Empty filters, unknown names, scope-local names, and reserved transport names fail. Restrictions intersect; scoped registrations remain visible.\",\n \"parameters\": [\n {\n \"name\": \"filter\",\n \"description\": \"global-tool mask: `allow` (keep only) and/or `deny` (remove).\"\n }\n ],\n \"returns\": \"the exact disposer that lifts this restriction.\"\n },\n {\n \"signature\": \"guard(guard: ToolGuard): () => void\",\n \"description\": \"Register a monotonic guard after the extensible `tools/pre-execute` waterfall. A plain-context guard applies globally; one registered through `agent.ctx` applies only to that agent. Any matching guard may deny by returning a reason, while no guard can force-allow a call another guard denied. The exact effect disposer is returned for ordered ownership and HMR cleanup.\",\n \"parameters\": [\n {\n \"name\": \"guard\",\n \"description\": \"synchronous check; a returned string denies the execution.\"\n }\n ],\n \"returns\": \"the exact disposer that unregisters the guard.\"\n },\n {\n \"signature\": \"get(name: string, scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolDefinition | undefined\",\n \"description\": \"Look up a tool as one scope sees it (scoped shadows global; a restricted-away global reads as absent). Presenters pass the calling agent so the rendered card matches the definition that actually executed.\",\n \"parameters\": [\n {\n \"name\": \"name\",\n \"description\": \"the tool name as registered.\"\n },\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission; omit only to inspect registered definitions.\"\n }\n ],\n \"returns\": \"the definition the scope resolves, or undefined when none is visible.\"\n },\n {\n \"signature\": \"async resolve(context: ToolActivationContext): Promise\",\n \"description\": \"Resolve conditions once for this step without changing shared registrations. Cancellation or a rejected condition publishes no partial selection. Removed registrations cannot be restored by a late condition result.\",\n \"parameters\": [\n {\n \"name\": \"context\",\n \"description\": \"preparing agent and cancellation.\"\n }\n ],\n \"returns\": \"the complete selection; the caller disposes it after its tool batch settles.\"\n },\n {\n \"signature\": \"schemas(scope?: ScopeKey, toolSet?: ResolvedToolSet): ToolSchema[]\",\n \"description\": \"Project visible definitions onto the allowlisted model-facing schema fields, excluding execution and presentation callbacks.\",\n \"parameters\": [\n {\n \"name\": \"scope\",\n \"description\": \"the viewing scope (the agent); omitted = the global view.\"\n },\n {\n \"name\": \"toolSet\",\n \"description\": \"step admission, or omitted for registered-definition inspection.\"\n }\n ],\n \"returns\": \"one deep-cloned schema per visible tool.\"\n },\n {\n \"signature\": \"executionMode(exec: ToolExecutionInput): ToolExecutionMode\",\n \"description\": \"Classify a pending call through the caller's visible tool definition. Only an exact `true` is parallel; unknown, hidden, undeclared, invalid, or throwing classifiers are exclusive.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"call name, parsed arguments, and optional agent scope.\"\n }\n ],\n \"returns\": \"the fail-closed scheduling mode.\"\n },\n {\n \"signature\": \"async execute(exec: ToolExecutionInput): Promise\",\n \"description\": \"Execute through pre-policy, guards, around-dispatch, post-policy, definition-owned content finalization, and final notification. Tool and listener failures resolve as materialized error results; an invisible tool reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen snapshot final observers receive. Cancellation arriving after entry and before final result materialization skips a not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a successful started outcome with `ABORTED`; already-started work is still drained and may retain a tool-owned structured error.\",\n \"parameters\": [\n {\n \"name\": \"exec\",\n \"description\": \"the typed same-process call input. The registry assigns its correlation token before policy begins.\"\n }\n ],\n \"returns\": \"the materialized final result.\"\n }\n ]\n },\n \"referencedTypes\": [\n {\n \"name\": \"Agent\",\n \"declaration\": \"export interface Agent {\\n readonly id: SessionId;\\n}\"\n },\n {\n \"name\": \"Branded\",\n \"declaration\": \"export type Branded = string & {\\n readonly [BRAND]: B;\\n};\"\n },\n {\n \"name\": \"DiffCallView\",\n \"declaration\": \"export interface DiffCallView {\\n card: 'diff';\\n title: string;\\n diffs: FileDiff[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"DiffResultView\",\n \"declaration\": \"export interface DiffResultView {\\n card: 'diff';\\n title?: string;\\n diffs: FileDiff[];\\n}\"\n },\n {\n \"name\": \"FileDiff\",\n \"declaration\": \"export interface FileDiff {\\n path: string;\\n oldText: string | null;\\n newText: string;\\n}\"\n },\n {\n \"name\": \"FileLocation\",\n \"declaration\": \"export interface FileLocation {\\n path: string;\\n line?: number;\\n}\"\n },\n {\n \"name\": \"GenericCallView\",\n \"declaration\": \"export interface GenericCallView {\\n card: 'generic';\\n title: string;\\n kind?: ToolCallKind;\\n rawInput?: unknown;\\n content?: ContentBlock[];\\n locations?: FileLocation[];\\n}\"\n },\n {\n \"name\": \"GenericResultView\",\n \"declaration\": \"export interface GenericResultView {\\n card: 'generic';\\n title?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"JsonSchemaNode\",\n \"declaration\": \"export interface JsonSchemaNode {\\n type?: JsonSchemaType;\\n oneOf?: JsonSchemaNode[];\\n properties?: Record;\\n required?: string[];\\n additionalProperties?: boolean;\\n items?: JsonSchemaNode;\\n enum?: JsonSchemaScalar[];\\n const?: JsonSchemaScalar;\\n description?: string;\\n title?: string;\\n default?: JsonValue;\\n examples?: JsonValue;\\n}\"\n },\n {\n \"name\": \"JsonSchemaScalar\",\n \"declaration\": \"export type JsonSchemaScalar = string | number | boolean | null;\"\n },\n {\n \"name\": \"JsonSchemaType\",\n \"declaration\": \"export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\"\n },\n {\n \"name\": \"JsonValue\",\n \"declaration\": \"export type JsonValue = null | boolean | number | string | JsonValue[] | {\\n [key: string]: JsonValue;\\n};\"\n },\n {\n \"name\": \"ReadFileLine\",\n \"declaration\": \"export interface ReadFileLine {\\n number: number;\\n text: string;\\n}\"\n },\n {\n \"name\": \"ReadResultView\",\n \"declaration\": \"export interface ReadResultView {\\n card: 'read';\\n title?: string;\\n path: string;\\n offset: number;\\n lines: ReadFileLine[];\\n totalLines: number;\\n lang?: string;\\n content?: ContentBlock[];\\n}\"\n },\n {\n \"name\": \"ResolvedToolSet\",\n \"declaration\": \"export interface ResolvedToolSet {\\n dispose(): void;\\n view(scope: ScopeKey | undefined): ReadonlyMap;\\n}\"\n },\n {\n \"name\": \"ScopeKey\",\n \"declaration\": \"export type ScopeKey = object;\"\n },\n {\n \"name\": \"SearchFileMatches\",\n \"declaration\": \"export interface SearchFileMatches {\\n path: string;\\n matches: SearchLineMatch[];\\n}\"\n },\n {\n \"name\": \"SearchLineMatch\",\n \"declaration\": \"export interface SearchLineMatch {\\n lineNumber: number;\\n line: string;\\n}\"\n },\n {\n \"name\": \"SearchMatchesResultView\",\n \"declaration\": \"export interface SearchMatchesResultView {\\n card: 'search';\\n shape: 'matches';\\n title?: string;\\n files: SearchFileMatches[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchPathsResultView\",\n \"declaration\": \"export interface SearchPathsResultView {\\n card: 'search';\\n shape: 'paths';\\n title?: string;\\n paths: string[];\\n truncated: boolean;\\n total: number;\\n}\"\n },\n {\n \"name\": \"SearchResultView\",\n \"declaration\": \"export type SearchResultView = SearchMatchesResultView | SearchPathsResultView;\"\n },\n {\n \"name\": \"SessionId\",\n \"declaration\": \"export type SessionId = Branded<'SessionId'>;\"\n },\n {\n \"name\": \"TerminalCallView\",\n \"declaration\": \"export interface TerminalCallView {\\n card: 'terminal';\\n title: string;\\n description?: string;\\n cwd?: string;\\n}\"\n },\n {\n \"name\": \"TerminalResultView\",\n \"declaration\": \"export interface TerminalResultView {\\n card: 'terminal';\\n title?: string;\\n output?: string;\\n exitCode?: number;\\n signal?: string;\\n}\"\n },\n {\n \"name\": \"ToolActivationContext\",\n \"declaration\": \"export interface ToolActivationContext {\\n readonly agent: Agent;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolCallId\",\n \"declaration\": \"export type ToolCallId = Branded<'ToolCallId'>;\"\n },\n {\n \"name\": \"ToolCallKind\",\n \"declaration\": \"export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\"\n },\n {\n \"name\": \"ToolCallView\",\n \"declaration\": \"export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\"\n },\n {\n \"name\": \"ToolDefinition\",\n \"declaration\": \"export interface ToolDefinition extends ToolSchema {\\n readonly output: ToolOutputDefinition;\\n execute(args: unknown, exec: ToolRunContext): Promise;\\n projectContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\\n timeoutMs?: number;\\n isConcurrencySafe?(args: unknown): boolean;\\n presentCall?(args: unknown): ToolCallView | undefined;\\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\\n}\"\n },\n {\n \"name\": \"ToolErrorInfo\",\n \"declaration\": \"export interface ToolErrorInfo {\\n name: string;\\n code: string;\\n reason?: string;\\n}\"\n },\n {\n \"name\": \"ToolExecution\",\n \"declaration\": \"export interface ToolExecution extends ToolExecutionInput {\\n readonly rootCallId: ToolCallId;\\n readonly token: ToolExecutionToken;\\n}\"\n },\n {\n \"name\": \"ToolExecutionFailure\",\n \"declaration\": \"export interface ToolExecutionFailure {\\n readonly isError: true;\\n readonly error: ToolFailure;\\n readonly value?: never;\\n readonly content: ContentBlock[];\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: never;\\n}\"\n },\n {\n \"name\": \"ToolExecutionInput\",\n \"declaration\": \"export interface ToolExecutionInput {\\n readonly callId: ToolCallId;\\n readonly rootCallId?: ToolCallId;\\n readonly name: string;\\n readonly schema?: ToolSchema;\\n readonly arguments: unknown;\\n readonly agent?: Agent;\\n readonly toolSet?: ResolvedToolSet;\\n readonly parent?: ToolExecutionToken;\\n readonly signal: AbortSignal;\\n}\"\n },\n {\n \"name\": \"ToolExecutionMode\",\n \"declaration\": \"export type ToolExecutionMode = {\\n kind: 'parallel';\\n} | {\\n kind: 'exclusive';\\n};\"\n },\n {\n \"name\": \"ToolExecutionResult\",\n \"declaration\": \"export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\"\n },\n {\n \"name\": \"ToolExecutionSuccess\",\n \"declaration\": \"export interface ToolExecutionSuccess {\\n readonly isError: false;\\n readonly value: JsonValue;\\n readonly content: ContentBlock[];\\n readonly error?: never;\\n readonly meta?: JsonValue;\\n readonly additionalContexts?: UserMessage[];\\n readonly concludesTurn?: true;\\n}\"\n },\n {\n \"name\": \"ToolExecutionToken\",\n \"declaration\": \"export type ToolExecutionToken = symbol & {\\n readonly [toolExecutionTokenBrand]: true;\\n};\"\n },\n {\n \"name\": \"ToolFailure\",\n \"declaration\": \"export interface ToolFailure {\\n message: string;\\n info?: ToolErrorInfo;\\n}\"\n },\n {\n \"name\": \"ToolGuard\",\n \"declaration\": \"export type ToolGuard = (execution: Readonly) => string | undefined;\"\n },\n {\n \"name\": \"ToolOutputDefinition\",\n \"declaration\": \"export interface ToolOutputDefinition {\\n readonly schema: JsonSchemaNode;\\n render(args: unknown, value: JsonValue): ContentBlock[];\\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolPresentationMode\",\n \"declaration\": \"export type ToolPresentationMode = 'native' | 'ptc';\"\n },\n {\n \"name\": \"ToolRegistrationOptions\",\n \"declaration\": \"export interface ToolRegistrationOptions {\\n readonly when?: (context: ToolActivationContext) => boolean | Promise;\\n}\"\n },\n {\n \"name\": \"ToolRestriction\",\n \"declaration\": \"export interface ToolRestriction {\\n readonly allow?: readonly string[];\\n readonly deny?: readonly string[];\\n}\"\n },\n {\n \"name\": \"ToolResult\",\n \"declaration\": \"export interface ToolResult {\\n content: ContentBlock[];\\n isError: boolean;\\n meta?: JsonValue;\\n}\"\n },\n {\n \"name\": \"ToolResultView\",\n \"declaration\": \"export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | SearchResultView | ReadResultView | WebResultView;\"\n },\n {\n \"name\": \"ToolRunContext\",\n \"declaration\": \"export interface ToolRunContext extends ToolExecution {\\n deferContext(context: UserMessage): void;\\n concludeTurn(): void;\\n}\"\n },\n {\n \"name\": \"ToolSchema\",\n \"declaration\": \"export interface ToolSchema {\\n deferLoading?: true;\\n name: string;\\n description: string;\\n parameters: Record;\\n}\"\n },\n {\n \"name\": \"UserMessage\",\n \"declaration\": \"export interface UserMessage extends MessageBase {\\n readonly role: 'user';\\n}\"\n },\n {\n \"name\": \"WebFetchResultView\",\n \"declaration\": \"export interface WebFetchResultView {\\n card: 'web';\\n kind: 'fetch';\\n title?: string;\\n url: string;\\n statusCode: number;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebResultView\",\n \"declaration\": \"export type WebResultView = WebSearchResultView | WebFetchResultView;\"\n },\n {\n \"name\": \"WebSearchResultView\",\n \"declaration\": \"export interface WebSearchResultView {\\n card: 'web';\\n kind: 'search';\\n title?: string;\\n sources: WebSource[];\\n answer?: string;\\n truncated: boolean;\\n}\"\n },\n {\n \"name\": \"WebSource\",\n \"declaration\": \"export interface WebSource {\\n url: string;\\n title?: string;\\n snippet?: string;\\n publishedAt?: string;\\n}\"\n }\n ]\n }\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-subprocess-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788778146017,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788778146017,"index":0,"dt":[],"id":"inspect-subprocess-api","name":"cordis_inspect_query","args":["{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"]},{"type":"chunk","time":1788778146017,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"inspect-subprocess-api","name":"cordis_inspect_query","arguments":"{\"platform\":\"host\",\"provider\":\"Service\",\"method\":\"listService\",\"input\":{\"service\":\"subprocess\"}}"}}},{"type":"chunk","time":1788778146017,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788778146017,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/deepseek-messages-input-history/session.v4.jsonl b/snapshots/session/deepseek-messages-input-history/session.v4.jsonl index 8f0a4dd9d0..fa51dd2dce 100644 --- a/snapshots/session/deepseek-messages-input-history/session.v4.jsonl +++ b/snapshots/session/deepseek-messages-input-history/session.v4.jsonl @@ -8,9 +8,9 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"source":{"kind":"plugin:messages-input-history-snapshot"},"content":[{"type":"text","text":"Background subagent finished. Its closing message: Saved child answer."},{"type":"reasoning","text":"unforwarded-child-thought"},{"type":"tool-call","id":"unforwarded-child-call","name":"bash","arguments":"{}"}],"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"source":{"kind":"plugin:messages-input-history-snapshot"},"content":[{"type":"reasoning","text":"unforwarded-empty-notice"}],"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"source":{"kind":"plugin:messages-input-history-snapshot"},"content":[{"type":"text","text":"Background subagent finished. Its closing message: Saved child answer."},{"type":"reasoning","text":"unforwarded-child-thought"},{"type":"tool-call","id":"unforwarded-child-call","name":"bash","arguments":"{}"}],"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"source":{"kind":"plugin:messages-input-history-snapshot"},"content":[{"type":"reasoning","text":"unforwarded-empty-notice"}],"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:5}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply DONE.","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/hook-cc-promptsubmit-context/session.v4.jsonl b/snapshots/session/hook-cc-promptsubmit-context/session.v4.jsonl index d0f384fd4b..8bb642279a 100644 --- a/snapshots/session/hook-cc-promptsubmit-context/session.v4.jsonl +++ b/snapshots/session/hook-cc-promptsubmit-context/session.v4.jsonl @@ -10,8 +10,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"What is my favorite color? Reply with just the color and stop. Do not use any tools."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"The user has previously stated their favorite color is teal."}],"source":{"kind":"hooks-claude-code"},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"The user has previously stated their favorite color is teal."}],"source":{"kind":"hooks-claude-code"},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"What is my favorite color?","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/hook-codex-promptsubmit-context/session.v4.jsonl b/snapshots/session/hook-codex-promptsubmit-context/session.v4.jsonl index 1d1a6ba32e..ef944a345e 100644 --- a/snapshots/session/hook-codex-promptsubmit-context/session.v4.jsonl +++ b/snapshots/session/hook-codex-promptsubmit-context/session.v4.jsonl @@ -10,8 +10,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"What is my favorite color? Reply with just the color and stop. Do not use any tools."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"The user has previously stated their favorite color is teal."}],"source":{"kind":"hooks-codex"},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"The user has previously stated their favorite color is teal."}],"source":{"kind":"hooks-codex"},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"What is my favorite color?","messageSeqs":[10],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/office-authoring-checker/session.v4.jsonl b/snapshots/session/office-authoring-checker/session.v4.jsonl index 8431a6a715..964c37875f 100644 --- a/snapshots/session/office-authoring-checker/session.v4.jsonl +++ b/snapshots/session/office-authoring-checker/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Load the Office Word, PowerPoint, and Excel authoring skills. Read their structural-check instructions and reply DONE. Do not create files."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the Office Word, PowerPoint,","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/office-progressive-native/session.v4.jsonl b/snapshots/session/office-progressive-native/session.v4.jsonl index 14ca061e74..b7bdbb4f0b 100644 --- a/snapshots/session/office-progressive-native/session.v4.jsonl +++ b/snapshots/session/office-progressive-native/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Load the office router, then the authoring and operation skills for this workflow. Reply DONE after reading them."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the office router, then","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/office-progressive-ptc/session.v4.jsonl b/snapshots/session/office-progressive-ptc/session.v4.jsonl index 9bd58408bb..5af73ae28b 100644 --- a/snapshots/session/office-progressive-ptc/session.v4.jsonl +++ b/snapshots/session/office-progressive-ptc/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Load the office router, then the authoring and operation skills for this workflow. Reply DONE after reading them."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the office router, then","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/office-render-tools-ptc/writer.expected.jsonl b/snapshots/session/office-render-tools-ptc/writer.expected.jsonl index 353adcbd17..4710113f55 100644 --- a/snapshots/session/office-render-tools-ptc/writer.expected.jsonl +++ b/snapshots/session/office-render-tools-ptc/writer.expected.jsonl @@ -8,34 +8,34 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"/office-docx Load the Office rendering tool, render page 1 of report.docx to preview, remove the rendering tool, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-docx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Word documents\n\nUse `python-docx` for DOCX creation and ordinary edits. Follow an explicit user or applicable AGENTS.md requirement for a project environment or another library. Otherwise call `load_workspace_dependencies` and execute the returned Python path with its bundled libraries. Do not install packages or discover a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.\n\nKeep source scripts, intermediate files, and final documents in the task workspace; the runtime and this skill directory are read-only resources. Use the user's requested language and preserve an existing document's design unless a redesign is requested.\n\nName Python scripts for their task, such as `edit_docx.py`; avoid module names such as `inspect.py`, `docx.py`, or `zipfile.py` that shadow imported libraries.\n\n## Create and edit\n\nFor text edits, locate the target by its text or position and inspect only its runs and formatting. A title can be an ordinary paragraph without a Title style or document-property title. Update the relevant runs; assigning paragraph `.text` destroys run formatting. Save a new file unless an in-place edit is requested. Read other structures only when the edit involves them; rebuilding a document can lose unsupported features.\n\nUse paragraph styles for headings and body text. Size tables for the section that contains them, and account for merged cells and nested tables. Chinese, Japanese, and Korean text may need an explicit `w:eastAsia` font assignment in addition to `run.font.name`; font names alone do not establish glyph availability or rendered appearance.\n\nFor a new document, use the selected Python executable:\n\n```python\nfrom docx import Document\n\ndocument = Document()\ndocument.add_heading(\"Project report\", level=0)\ndocument.add_paragraph(\"Summary\", style=\"Heading 1\")\ndocument.add_paragraph(\"The requested findings go here.\")\ndocument.save(\"report.docx\")\n```\n\npython-docx does not paginate or render documents. Do not represent ordinary replacement, colored text, or comments as tracked changes. When real revisions or unsupported OOXML features matter, preserve their package parts and verify the requested operation rather than silently discarding them. When writing package parts directly, create a new ZIP and copy each unchanged member once; appending a replacement member duplicates its name and corrupts the package.\n\n## Check and deliver\n\nReopen the saved document with python-docx and verify the requested content, related formatting, and unchanged content that must be preserved. Deliver when these checks pass. Investigate package-level details only for a concrete failure, ambiguous edit target, unsupported feature, or explicit user requirement.\n\nCreating a file or changing content with incidental basic formatting does not require additional operations. Load `office-render` for requested images or visual inspection. When styling, font color, spacing, sizing, or text alignment is the requested edit, load `office-render` and inspect the changed page even without a separate visual-check request, unless the user explicitly skips rendering. For PDF output load `office-export-pdf`.\n\nCall `present({\"files\":[{\"path\":\"report.docx\"}]})` with the actual final DOCX path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and do not present temporary QA reports unless requested. If `present` is unavailable, provide the final workspace path using the session's supported file delivery method.\n\n"}],"source":{"kind":"skill-invocation","name":"office-docx","form":"instructions"},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-docx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Word documents\n\nUse `python-docx` for DOCX creation and ordinary edits. Follow an explicit user or applicable AGENTS.md requirement for a project environment or another library. Otherwise call `load_workspace_dependencies` and execute the returned Python path with its bundled libraries. Do not install packages or discover a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.\n\nKeep source scripts, intermediate files, and final documents in the task workspace; the runtime and this skill directory are read-only resources. Use the user's requested language and preserve an existing document's design unless a redesign is requested.\n\nName Python scripts for their task, such as `edit_docx.py`; avoid module names such as `inspect.py`, `docx.py`, or `zipfile.py` that shadow imported libraries.\n\n## Create and edit\n\nFor text edits, locate the target by its text or position and inspect only its runs and formatting. A title can be an ordinary paragraph without a Title style or document-property title. Update the relevant runs; assigning paragraph `.text` destroys run formatting. Save a new file unless an in-place edit is requested. Read other structures only when the edit involves them; rebuilding a document can lose unsupported features.\n\nUse paragraph styles for headings and body text. Size tables for the section that contains them, and account for merged cells and nested tables. Chinese, Japanese, and Korean text may need an explicit `w:eastAsia` font assignment in addition to `run.font.name`; font names alone do not establish glyph availability or rendered appearance.\n\nFor a new document, use the selected Python executable:\n\n```python\nfrom docx import Document\n\ndocument = Document()\ndocument.add_heading(\"Project report\", level=0)\ndocument.add_paragraph(\"Summary\", style=\"Heading 1\")\ndocument.add_paragraph(\"The requested findings go here.\")\ndocument.save(\"report.docx\")\n```\n\npython-docx does not paginate or render documents. Do not represent ordinary replacement, colored text, or comments as tracked changes. When real revisions or unsupported OOXML features matter, preserve their package parts and verify the requested operation rather than silently discarding them. When writing package parts directly, create a new ZIP and copy each unchanged member once; appending a replacement member duplicates its name and corrupts the package.\n\n## Check and deliver\n\nReopen the saved document with python-docx and verify the requested content, related formatting, and unchanged content that must be preserved. Deliver when these checks pass. Investigate package-level details only for a concrete failure, ambiguous edit target, unsupported feature, or explicit user requirement.\n\nCreating a file or changing content with incidental basic formatting does not require additional operations. Load `office-render` for requested images or visual inspection. When styling, font color, spacing, sizing, or text alignment is the requested edit, load `office-render` and inspect the changed page even without a separate visual-check request, unless the user explicitly skips rendering. For PDF output load `office-export-pdf`.\n\nCall `present({\"files\":[{\"path\":\"report.docx\"}]})` with the actual final DOCX path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and do not present temporary QA reports unless requested. If `present` is unavailable, provide the final workspace path using the session's supported file delivery method.\n\n"}],"source":{"kind":"skill-invocation","name":"office-docx","form":"instructions"},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:5}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"/office-docx Load the Office rendering","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_skill","name":"run_code","arguments":"{\"code\":\"console.log(await tools.skill({\\\"name\\\":\\\"office-xlsx\\\"}));\",\"description\":\"Use the Office workflow\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1791559901535,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791559901535,"index":0,"dt":[],"id":"call_office_skill","name":"run_code","args":["{\"code\":\"console.log(await tools.skill({\\\"name\\\":\\\"office-xlsx\\\"}));\",\"description\":\"Use the Office workflow\"}"]},{"type":"chunk","time":1791559901535,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_skill","name":"run_code","arguments":"{\"code\":\"console.log(await tools.skill({\\\"name\\\":\\\"office-xlsx\\\"}));\",\"description\":\"Use the Office workflow\"}"}}},{"type":"chunk","time":1791559901535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_skill","name":"run_code","arguments":"{\"code\":\"console.log(await tools.skill({\\\"name\\\":\\\"office-xlsx\\\"}));\",\"description\":\"Use the Office workflow\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1791880664099,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791880664099,"index":0,"dt":[],"id":"call_office_skill","name":"run_code","args":["{\"code\":\"console.log(await tools.skill({\\\"name\\\":\\\"office-xlsx\\\"}));\",\"description\":\"Use the Office workflow\"}"]},{"type":"chunk","time":1791880664099,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_skill","name":"run_code","arguments":"{\"code\":\"console.log(await tools.skill({\\\"name\\\":\\\"office-xlsx\\\"}));\",\"description\":\"Use the Office workflow\"}"}}},{"type":"chunk","time":1791880664099,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_office_skill","name":"run_code","arguments":"{\"code\":\"console.log(await tools.skill({\\\"name\\\":\\\"office-xlsx\\\"}));\",\"description\":\"Use the Office workflow\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"call_office_skill","parentCallId":"call_office_skill","subCallId":"call_office_skill:ptc:1","name":"skill","arguments":{"name":"office-xlsx"}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"call_office_skill","parentCallId":"call_office_skill","subCallId":"call_office_skill:ptc:1","name":"skill","arguments":{"name":"office-xlsx"},"isError":false,"content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-xlsx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Excel workbooks\n\nFollow an explicit user or applicable AGENTS.md requirement for an environment or library. Otherwise call `load_workspace_dependencies` and run its Python executable with bundled `openpyxl` and `pandas`. Do not install packages or search for a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.\n\nKeep scripts, working files, and outputs in the task workspace. The runtime and skill directory are shared read-only resources. Save to a new workbook unless the user requests an in-place edit.\n\nName Python scripts for their task, such as `edit_xlsx.py`; avoid module names such as `inspect.py`, `openpyxl.py`, or `pandas.py` that shadow imported libraries.\n\n## Read and modify\n\nUse `openpyxl` for existing XLSX workbooks and targeted cell or style changes. Load with `data_only=False` when formulas must survive. Inspect sheet names, the affected cell types, formulas, styles, merged ranges, and referenced ranges before editing. Check the saved file by reopening it, including unchanged content that the request requires preserving.\n\nUse pandas for data analysis and transformations. A DataFrame is not the workbook: exporting it over an existing file can lose sheets, formulas, charts, and formatting. Write analysis results back to the intended ranges with openpyxl. `XlsxWriter` can create new workbooks, but cannot read or modify existing ones.\n\nFor a new workbook, the selected Python environment can write editable values, styles, and formulas directly:\n\n```python\nfrom openpyxl import Workbook\nfrom openpyxl.styles import Font\n\nworkbook = Workbook()\nsheet = workbook.active\nsheet.title = \"Revenue\"\nfor row in [(\"Quarter\", \"Revenue\"), (\"Q1\", 12), (\"Q2\", 18), (\"Total\", \"=SUM(B2:B3)\")]:\n sheet.append(row)\nfor cell in sheet[1]:\n cell.font = Font(bold=True)\nsheet.column_dimensions[\"A\"].width = 18\nsheet.column_dimensions[\"B\"].width = 18\nworkbook.save(\"report.xlsx\")\n```\n\nPreserve numbers, dates, booleans, and identifiers as the intended cell types; formatting is not a type conversion. For modifications, load the existing file with `openpyxl.load_workbook(\"input.xlsx\", data_only=False)`, change the requested ranges, and save a separate result. Avoid a DataFrame round trip when workbook features must survive.\n\nWriting a formula does not calculate its result. openpyxl and XlsxWriter do not evaluate formulas; `data_only=True` returns cached values that may be absent or stale. When calculated results must be refreshed, load `office-recalculate`. Do not replace requested formulas with constants or report stale values as newly calculated results.\n\nDo not rename `.xls`, `.xlsb`, encrypted files, or macro-enabled files to `.xlsx`. They need an appropriate supported operation. `keep_vba=True` can preserve VBA package content in an XLSM workflow, but does not execute or edit macros and does not guarantee every advanced workbook feature survives. Preserve the original and verify such requirements explicitly.\n\n## Check and deliver\n\nReopen the saved workbook with openpyxl and verify the requested sheet names, values, types, formulas, styles, and totals against the source data, including unchanged content that must be preserved. These checks do not calculate formulas or judge workbook appearance.\n\nLoad `office-render` for requested images or visual inspection and whenever the user's primary task targets appearance, including cell fill colors, text alignment, spacing, or sizing. These appearance changes require rendering even without a separate visual-check request, unless the user explicitly skips it. New workbooks and data or formula edits do not require rendering solely because they include incidental basic formatting. In particular, bold headers and number formats accompanying data edits do not require loading `office-render` or running its commands.\n\nLoad `office-recalculate` when refreshed calculated values are needed and `office-export-pdf` for PDF output. Deliver after the requested data checks pass and the required operations finish.\n\nCall `present({\"files\":[{\"path\":\"report.xlsx\"}]})` with the actual final workbook path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and omit intermediate scripts and reports unless requested. If `present` is unavailable, use the session's supported file delivery method.\n\n"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_skill"},"toolCallId":"call_office_skill","content":[{"type":"text","text":"{\n name: 'office-xlsx',\n provider: 'dsh-office',\n resourceBase: {\n kind: 'directory',\n path: '{{cwd}}/office-skills/office-xlsx'\n },\n content: '# Excel workbooks\\n' +\n '\\n' +\n 'Follow an explicit user or applicable AGENTS.md requirement for an environment or library. Otherwise call `load_workspace_dependencies` and run its Python executable with bundled `openpyxl` and `pandas`. Do not install packages or search for a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.\\n' +\n '\\n' +\n 'Keep scripts, working files, and outputs in the task workspace. The runtime and skill directory are shared read-only resources. Save to a new workbook unless the user requests an in-place edit.\\n' +\n '\\n' +\n 'Name Python scripts for their task, such as `edit_xlsx.py`; avoid module names such as `inspect.py`, `openpyxl.py`, or `pandas.py` that shadow imported libraries.\\n' +\n '\\n' +\n '## Read and modify\\n' +\n '\\n' +\n 'Use `openpyxl` for existing XLSX workbooks and targeted cell or style changes. Load with `data_only=False` when formulas must survive. Inspect sheet names, the affected cell types, formulas, styles, merged ranges, and referenced ranges before editing. Check the saved file by reopening it, including unchanged content that the request requires preserving.\\n' +\n '\\n' +\n 'Use pandas for data analysis and transformations. A DataFrame is not the workbook: exporting it over an existing file can lose sheets, formulas, charts, and formatting. Write analysis results back to the intended ranges with openpyxl. `XlsxWriter` can create new workbooks, but cannot read or modify existing ones.\\n' +\n '\\n' +\n 'For a new workbook, the selected Python environment can write editable values, styles, and formulas directly:\\n' +\n '\\n' +\n '```python\\n' +\n 'from openpyxl import Workbook\\n' +\n 'from openpyxl.styles import Font\\n' +\n '\\n' +\n 'workbook = Workbook()\\n' +\n 'sheet = workbook.active\\n' +\n 'sheet.title = \"Revenue\"\\n' +\n 'for row in [(\"Quarter\", \"Revenue\"), (\"Q1\", 12), (\"Q2\", 18), (\"Total\", \"=SUM(B2:B3)\")]:\\n' +\n ' sheet.append(row)\\n' +\n 'for cell in sheet[1]:\\n' +\n ' cell.font = Font(bold=True)\\n' +\n 'sheet.column_dimensions[\"A\"].width = 18\\n' +\n 'sheet.column_dimensions[\"B\"].width = 18\\n' +\n 'workbook.save(\"report.xlsx\")\\n' +\n '```\\n' +\n '\\n' +\n 'Preserve numbers, dates, booleans, and identifiers as the intended cell types; formatting is not a type conversion. For modifications, load the existing file with `openpyxl.load_workbook(\"input.xlsx\", data_only=False)`, change the requested ranges, and save a separate result. Avoid a DataFrame round trip when workbook features must survive.\\n' +\n '\\n' +\n 'Writing a formula does not calculate its result. openpyxl and XlsxWriter do not evaluate formulas; `data_only=True` returns cached values that may be absent or stale. When calculated results must be refreshed, load `office-recalculate`. Do not replace requested formulas with constants or report stale values as newly calculated results.\\n' +\n '\\n' +\n 'Do not rename `.xls`, `.xlsb`, encrypted files, or macro-enabled files to `.xlsx`. They need an appropriate supported operation. `keep_vba=True` can preserve VBA package content in an XLSM workflow, but does not execute or edit macros and does not guarantee every advanced workbook feature survives. Preserve the original and verify such requirements explicitly.\\n' +\n '\\n' +\n '## Check and deliver\\n' +\n '\\n' +\n 'Reopen the saved workbook with openpyxl and verify the requested sheet names, values, types, formulas, styles, and totals against the source data, including unchanged content that must be preserved. These checks do not calculate formulas or judge workbook appearance.\\n' +\n '\\n' +\n \"Load `office-render` for requested images or visual inspection and whenever the user's primary task targets appearance, including cell fill colors, text alignment, spacing, or sizing. These appearance changes require rendering even without a separate visual-check request, unless the user explicitly skips it. New workbooks and data or formula edits do not require rendering solely because they include incidental basic formatting. In particular, bold headers and number formats accompanying data edits do not require loading `office-render` or running its commands.\\n\" +\n '\\n' +\n 'Load `office-recalculate` when refreshed calculated values are needed and `office-export-pdf` for PDF output. Deliver after the requested data checks pass and the required operations finish.\\n' +\n '\\n' +\n 'Call `present({\"files\":[{\"path\":\"report.xlsx\"}]})` with the actual final workbook path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and omit intermediate scripts and reports unless requested. If `present` is unavailable, use the session\\'s supported file delivery method.'\n}"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_2","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"load\\\"}));\",\"description\":\"Use the Office workflow\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1791781540339,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791781540339,"index":0,"dt":[],"id":"call_office_2","name":"run_code","args":["{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"load\\\"}));\",\"description\":\"Use the Office workflow\"}"]},{"type":"chunk","time":1791781540339,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_2","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"load\\\"}));\",\"description\":\"Use the Office workflow\"}"}}},{"type":"chunk","time":1791781540339,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_2","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"load\\\"}));\",\"description\":\"Use the Office workflow\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1791880664572,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791880664572,"index":0,"dt":[],"id":"call_office_2","name":"run_code","args":["{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"load\\\"}));\",\"description\":\"Use the Office workflow\"}"]},{"type":"chunk","time":1791880664572,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_2","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"load\\\"}));\",\"description\":\"Use the Office workflow\"}"}}},{"type":"chunk","time":1791880664572,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_office_2","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"load\\\"}));\",\"description\":\"Use the Office workflow\"}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_2"},"toolCallId":"call_office_2","content":[{"type":"text","text":"Error: code run failed (exception): TypeError: tools.office_tools is not a function\nFile sandbox: danger-full-access."}],"isError":true,"id":"{{message:9}}"},"error":{"name":"CodeRunFailedError","code":"CODE_RUN_FAILED"}},"sourceEventSeqs":[23],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_3","name":"run_code","arguments":"{\"code\":\"console.log(await tools.render_document({\\\"input\\\":\\\"report.docx\\\",\\\"outputDirectory\\\":\\\"preview\\\",\\\"pages\\\":[1]}));\",\"description\":\"Use the Office workflow\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1791781540448,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791781540448,"index":0,"dt":[],"id":"call_office_3","name":"run_code","args":["{\"code\":\"console.log(await tools.render_document({\\\"input\\\":\\\"report.docx\\\",\\\"outputDirectory\\\":\\\"preview\\\",\\\"pages\\\":[1]}));\",\"description\":\"Use the Office workflow\"}"]},{"type":"chunk","time":1791781540448,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_3","name":"run_code","arguments":"{\"code\":\"console.log(await tools.render_document({\\\"input\\\":\\\"report.docx\\\",\\\"outputDirectory\\\":\\\"preview\\\",\\\"pages\\\":[1]}));\",\"description\":\"Use the Office workflow\"}"}}},{"type":"chunk","time":1791781540448,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_3","name":"run_code","arguments":"{\"code\":\"console.log(await tools.render_document({\\\"input\\\":\\\"report.docx\\\",\\\"outputDirectory\\\":\\\"preview\\\",\\\"pages\\\":[1]}));\",\"description\":\"Use the Office workflow\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1791880664650,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791880664650,"index":0,"dt":[],"id":"call_office_3","name":"run_code","args":["{\"code\":\"console.log(await tools.render_document({\\\"input\\\":\\\"report.docx\\\",\\\"outputDirectory\\\":\\\"preview\\\",\\\"pages\\\":[1]}));\",\"description\":\"Use the Office workflow\"}"]},{"type":"chunk","time":1791880664650,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_3","name":"run_code","arguments":"{\"code\":\"console.log(await tools.render_document({\\\"input\\\":\\\"report.docx\\\",\\\"outputDirectory\\\":\\\"preview\\\",\\\"pages\\\":[1]}));\",\"description\":\"Use the Office workflow\"}"}}},{"type":"chunk","time":1791880664650,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"call_office_3","name":"run_code","arguments":"{\"code\":\"console.log(await tools.render_document({\\\"input\\\":\\\"report.docx\\\",\\\"outputDirectory\\\":\\\"preview\\\",\\\"pages\\\":[1]}));\",\"description\":\"Use the Office workflow\"}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_3"},"toolCallId":"call_office_3","content":[{"type":"text","text":"Error: code run failed (exception): TypeError: tools.render_document is not a function\nFile sandbox: danger-full-access."}],"isError":true,"id":"{{message:11}}"},"error":{"name":"CodeRunFailedError","code":"CODE_RUN_FAILED"}},"sourceEventSeqs":[28],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_4","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"remove\\\"}));\",\"description\":\"Use the Office workflow\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"stream":[{"type":"chunk","time":1791781540564,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791781540564,"index":0,"dt":[],"id":"call_office_4","name":"run_code","args":["{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"remove\\\"}));\",\"description\":\"Use the Office workflow\"}"]},{"type":"chunk","time":1791781540564,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_4","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"remove\\\"}));\",\"description\":\"Use the Office workflow\"}"}}},{"type":"chunk","time":1791781540564,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_4","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"remove\\\"}));\",\"description\":\"Use the Office workflow\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"stream":[{"type":"chunk","time":1791880664729,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791880664729,"index":0,"dt":[],"id":"call_office_4","name":"run_code","args":["{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"remove\\\"}));\",\"description\":\"Use the Office workflow\"}"]},{"type":"chunk","time":1791880664729,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_4","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"remove\\\"}));\",\"description\":\"Use the Office workflow\"}"}}},{"type":"chunk","time":1791880664729,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"call_office_4","name":"run_code","arguments":"{\"code\":\"console.log(await tools.office_tools({\\\"action\\\":\\\"remove\\\"}));\",\"description\":\"Use the Office workflow\"}"}} {"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_4"},"toolCallId":"call_office_4","content":[{"type":"text","text":"Error: code run failed (exception): TypeError: tools.office_tools is not a function\nFile sandbox: danger-full-access."}],"isError":true,"id":"{{message:13}}"},"error":{"name":"CodeRunFailedError","code":"CODE_RUN_FAILED"}},"sourceEventSeqs":[33],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1791781540675,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791781540675,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1791781540676,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1791781540676,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1791781540676,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1791880664802,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791880664802,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1791880664802,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1791880664802,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1791880664802,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/office-render-tools/writer.expected.jsonl b/snapshots/session/office-render-tools/writer.expected.jsonl index 17d04ce4a4..a4a852faaf 100644 --- a/snapshots/session/office-render-tools/writer.expected.jsonl +++ b/snapshots/session/office-render-tools/writer.expected.jsonl @@ -8,32 +8,32 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"/office-docx Load the Office rendering tool, render page 1 of report.docx to preview, remove the rendering tool, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-docx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Word documents\n\nUse `python-docx` for DOCX creation and ordinary edits. Follow an explicit user or applicable AGENTS.md requirement for a project environment or another library. Otherwise call `load_workspace_dependencies` and execute the returned Python path with its bundled libraries. Do not install packages or discover a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.\n\nKeep source scripts, intermediate files, and final documents in the task workspace; the runtime and this skill directory are read-only resources. Use the user's requested language and preserve an existing document's design unless a redesign is requested.\n\nName Python scripts for their task, such as `edit_docx.py`; avoid module names such as `inspect.py`, `docx.py`, or `zipfile.py` that shadow imported libraries.\n\n## Create and edit\n\nFor text edits, locate the target by its text or position and inspect only its runs and formatting. A title can be an ordinary paragraph without a Title style or document-property title. Update the relevant runs; assigning paragraph `.text` destroys run formatting. Save a new file unless an in-place edit is requested. Read other structures only when the edit involves them; rebuilding a document can lose unsupported features.\n\nUse paragraph styles for headings and body text. Size tables for the section that contains them, and account for merged cells and nested tables. Chinese, Japanese, and Korean text may need an explicit `w:eastAsia` font assignment in addition to `run.font.name`; font names alone do not establish glyph availability or rendered appearance.\n\nFor a new document, use the selected Python executable:\n\n```python\nfrom docx import Document\n\ndocument = Document()\ndocument.add_heading(\"Project report\", level=0)\ndocument.add_paragraph(\"Summary\", style=\"Heading 1\")\ndocument.add_paragraph(\"The requested findings go here.\")\ndocument.save(\"report.docx\")\n```\n\npython-docx does not paginate or render documents. Do not represent ordinary replacement, colored text, or comments as tracked changes. When real revisions or unsupported OOXML features matter, preserve their package parts and verify the requested operation rather than silently discarding them. When writing package parts directly, create a new ZIP and copy each unchanged member once; appending a replacement member duplicates its name and corrupts the package.\n\n## Check and deliver\n\nReopen the saved document with python-docx and verify the requested content, related formatting, and unchanged content that must be preserved. Deliver when these checks pass. Investigate package-level details only for a concrete failure, ambiguous edit target, unsupported feature, or explicit user requirement.\n\nCreating a file or changing content with incidental basic formatting does not require additional operations. Load `office-render` for requested images or visual inspection. When styling, font color, spacing, sizing, or text alignment is the requested edit, load `office-render` and inspect the changed page even without a separate visual-check request, unless the user explicitly skips rendering. For PDF output load `office-export-pdf`.\n\nCall `present({\"files\":[{\"path\":\"report.docx\"}]})` with the actual final DOCX path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and do not present temporary QA reports unless requested. If `present` is unavailable, provide the final workspace path using the session's supported file delivery method.\n\n"}],"source":{"kind":"skill-invocation","name":"office-docx","form":"instructions"},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-docx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Word documents\n\nUse `python-docx` for DOCX creation and ordinary edits. Follow an explicit user or applicable AGENTS.md requirement for a project environment or another library. Otherwise call `load_workspace_dependencies` and execute the returned Python path with its bundled libraries. Do not install packages or discover a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.\n\nKeep source scripts, intermediate files, and final documents in the task workspace; the runtime and this skill directory are read-only resources. Use the user's requested language and preserve an existing document's design unless a redesign is requested.\n\nName Python scripts for their task, such as `edit_docx.py`; avoid module names such as `inspect.py`, `docx.py`, or `zipfile.py` that shadow imported libraries.\n\n## Create and edit\n\nFor text edits, locate the target by its text or position and inspect only its runs and formatting. A title can be an ordinary paragraph without a Title style or document-property title. Update the relevant runs; assigning paragraph `.text` destroys run formatting. Save a new file unless an in-place edit is requested. Read other structures only when the edit involves them; rebuilding a document can lose unsupported features.\n\nUse paragraph styles for headings and body text. Size tables for the section that contains them, and account for merged cells and nested tables. Chinese, Japanese, and Korean text may need an explicit `w:eastAsia` font assignment in addition to `run.font.name`; font names alone do not establish glyph availability or rendered appearance.\n\nFor a new document, use the selected Python executable:\n\n```python\nfrom docx import Document\n\ndocument = Document()\ndocument.add_heading(\"Project report\", level=0)\ndocument.add_paragraph(\"Summary\", style=\"Heading 1\")\ndocument.add_paragraph(\"The requested findings go here.\")\ndocument.save(\"report.docx\")\n```\n\npython-docx does not paginate or render documents. Do not represent ordinary replacement, colored text, or comments as tracked changes. When real revisions or unsupported OOXML features matter, preserve their package parts and verify the requested operation rather than silently discarding them. When writing package parts directly, create a new ZIP and copy each unchanged member once; appending a replacement member duplicates its name and corrupts the package.\n\n## Check and deliver\n\nReopen the saved document with python-docx and verify the requested content, related formatting, and unchanged content that must be preserved. Deliver when these checks pass. Investigate package-level details only for a concrete failure, ambiguous edit target, unsupported feature, or explicit user requirement.\n\nCreating a file or changing content with incidental basic formatting does not require additional operations. Load `office-render` for requested images or visual inspection. When styling, font color, spacing, sizing, or text alignment is the requested edit, load `office-render` and inspect the changed page even without a separate visual-check request, unless the user explicitly skips rendering. For PDF output load `office-export-pdf`.\n\nCall `present({\"files\":[{\"path\":\"report.docx\"}]})` with the actual final DOCX path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and do not present temporary QA reports unless requested. If `present` is unavailable, provide the final workspace path using the session's supported file delivery method.\n\n"}],"source":{"kind":"skill-invocation","name":"office-docx","form":"instructions"},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:5}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"/office-docx Load the Office rendering","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1791559900742,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791559900742,"index":0,"dt":[],"id":"call_office_skill","name":"skill","args":["{\"name\":\"office-xlsx\"}"]},{"type":"chunk","time":1791559900742,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}}},{"type":"chunk","time":1791559900742,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1791880663535,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791880663535,"index":0,"dt":[],"id":"call_office_skill","name":"skill","args":["{\"name\":\"office-xlsx\"}"]},{"type":"chunk","time":1791880663535,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}}},{"type":"chunk","time":1791880663535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_skill"},"toolCallId":"call_office_skill","content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-xlsx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Excel workbooks\n\nFollow an explicit user or applicable AGENTS.md requirement for an environment or library. Otherwise call `load_workspace_dependencies` and run its Python executable with bundled `openpyxl` and `pandas`. Do not install packages or search for a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.\n\nKeep scripts, working files, and outputs in the task workspace. The runtime and skill directory are shared read-only resources. Save to a new workbook unless the user requests an in-place edit.\n\nName Python scripts for their task, such as `edit_xlsx.py`; avoid module names such as `inspect.py`, `openpyxl.py`, or `pandas.py` that shadow imported libraries.\n\n## Read and modify\n\nUse `openpyxl` for existing XLSX workbooks and targeted cell or style changes. Load with `data_only=False` when formulas must survive. Inspect sheet names, the affected cell types, formulas, styles, merged ranges, and referenced ranges before editing. Check the saved file by reopening it, including unchanged content that the request requires preserving.\n\nUse pandas for data analysis and transformations. A DataFrame is not the workbook: exporting it over an existing file can lose sheets, formulas, charts, and formatting. Write analysis results back to the intended ranges with openpyxl. `XlsxWriter` can create new workbooks, but cannot read or modify existing ones.\n\nFor a new workbook, the selected Python environment can write editable values, styles, and formulas directly:\n\n```python\nfrom openpyxl import Workbook\nfrom openpyxl.styles import Font\n\nworkbook = Workbook()\nsheet = workbook.active\nsheet.title = \"Revenue\"\nfor row in [(\"Quarter\", \"Revenue\"), (\"Q1\", 12), (\"Q2\", 18), (\"Total\", \"=SUM(B2:B3)\")]:\n sheet.append(row)\nfor cell in sheet[1]:\n cell.font = Font(bold=True)\nsheet.column_dimensions[\"A\"].width = 18\nsheet.column_dimensions[\"B\"].width = 18\nworkbook.save(\"report.xlsx\")\n```\n\nPreserve numbers, dates, booleans, and identifiers as the intended cell types; formatting is not a type conversion. For modifications, load the existing file with `openpyxl.load_workbook(\"input.xlsx\", data_only=False)`, change the requested ranges, and save a separate result. Avoid a DataFrame round trip when workbook features must survive.\n\nWriting a formula does not calculate its result. openpyxl and XlsxWriter do not evaluate formulas; `data_only=True` returns cached values that may be absent or stale. When calculated results must be refreshed, load `office-recalculate`. Do not replace requested formulas with constants or report stale values as newly calculated results.\n\nDo not rename `.xls`, `.xlsb`, encrypted files, or macro-enabled files to `.xlsx`. They need an appropriate supported operation. `keep_vba=True` can preserve VBA package content in an XLSM workflow, but does not execute or edit macros and does not guarantee every advanced workbook feature survives. Preserve the original and verify such requirements explicitly.\n\n## Check and deliver\n\nReopen the saved workbook with openpyxl and verify the requested sheet names, values, types, formulas, styles, and totals against the source data, including unchanged content that must be preserved. These checks do not calculate formulas or judge workbook appearance.\n\nLoad `office-render` for requested images or visual inspection and whenever the user's primary task targets appearance, including cell fill colors, text alignment, spacing, or sizing. These appearance changes require rendering even without a separate visual-check request, unless the user explicitly skips it. New workbooks and data or formula edits do not require rendering solely because they include incidental basic formatting. In particular, bold headers and number formats accompanying data edits do not require loading `office-render` or running its commands.\n\nLoad `office-recalculate` when refreshed calculated values are needed and `office-export-pdf` for PDF output. Deliver after the requested data checks pass and the required operations finish.\n\nCall `present({\"files\":[{\"path\":\"report.xlsx\"}]})` with the actual final workbook path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and omit intermediate scripts and reports unless requested. If `present` is unavailable, use the session's supported file delivery method.\n\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_2","name":"office_tools","arguments":"{\"action\":\"load\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1791559900760,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791559900760,"index":0,"dt":[],"id":"call_office_2","name":"office_tools","args":["{\"action\":\"load\"}"]},{"type":"chunk","time":1791559900760,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_2","name":"office_tools","arguments":"{\"action\":\"load\"}"}}},{"type":"chunk","time":1791559900760,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_2","name":"office_tools","arguments":"{\"action\":\"load\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1791880663552,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791880663552,"index":0,"dt":[],"id":"call_office_2","name":"office_tools","args":["{\"action\":\"load\"}"]},{"type":"chunk","time":1791880663552,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_2","name":"office_tools","arguments":"{\"action\":\"load\"}"}}},{"type":"chunk","time":1791880663552,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_office_2","name":"office_tools","arguments":"{\"action\":\"load\"}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_2"},"toolCallId":"call_office_2","content":[{"type":"text","text":"Error: unknown tool \"office_tools\""}],"isError":true,"id":"{{message:9}}"},"error":{"name":"ToolNotFoundError","code":"UNKNOWN_TOOL"}},"sourceEventSeqs":[21],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_3","name":"render_document","arguments":"{\"input\":\"report.docx\",\"outputDirectory\":\"preview\",\"pages\":[1]}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1791559900776,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791559900776,"index":0,"dt":[],"id":"call_office_3","name":"render_document","args":["{\"input\":\"report.docx\",\"outputDirectory\":\"preview\",\"pages\":[1]}"]},{"type":"chunk","time":1791559900776,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_3","name":"render_document","arguments":"{\"input\":\"report.docx\",\"outputDirectory\":\"preview\",\"pages\":[1]}"}}},{"type":"chunk","time":1791559900776,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_3","name":"render_document","arguments":"{\"input\":\"report.docx\",\"outputDirectory\":\"preview\",\"pages\":[1]}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1791880663567,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791880663567,"index":0,"dt":[],"id":"call_office_3","name":"render_document","args":["{\"input\":\"report.docx\",\"outputDirectory\":\"preview\",\"pages\":[1]}"]},{"type":"chunk","time":1791880663567,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_3","name":"render_document","arguments":"{\"input\":\"report.docx\",\"outputDirectory\":\"preview\",\"pages\":[1]}"}}},{"type":"chunk","time":1791880663567,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"call_office_3","name":"render_document","arguments":"{\"input\":\"report.docx\",\"outputDirectory\":\"preview\",\"pages\":[1]}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_3"},"toolCallId":"call_office_3","content":[{"type":"text","text":"Error: unknown tool \"render_document\""}],"isError":true,"id":"{{message:11}}"},"error":{"name":"ToolNotFoundError","code":"UNKNOWN_TOOL"}},"sourceEventSeqs":[26],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_4","name":"office_tools","arguments":"{\"action\":\"remove\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"stream":[{"type":"chunk","time":1791559900792,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791559900792,"index":0,"dt":[],"id":"call_office_4","name":"office_tools","args":["{\"action\":\"remove\"}"]},{"type":"chunk","time":1791559900793,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_4","name":"office_tools","arguments":"{\"action\":\"remove\"}"}}},{"type":"chunk","time":1791559900793,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_4","name":"office_tools","arguments":"{\"action\":\"remove\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"stream":[{"type":"chunk","time":1791880663582,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791880663582,"index":0,"dt":[],"id":"call_office_4","name":"office_tools","args":["{\"action\":\"remove\"}"]},{"type":"chunk","time":1791880663582,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_4","name":"office_tools","arguments":"{\"action\":\"remove\"}"}}},{"type":"chunk","time":1791880663582,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"call_office_4","name":"office_tools","arguments":"{\"action\":\"remove\"}"}} {"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_4"},"toolCallId":"call_office_4","content":[{"type":"text","text":"Error: unknown tool \"office_tools\""}],"isError":true,"id":"{{message:13}}"},"error":{"name":"ToolNotFoundError","code":"UNKNOWN_TOOL"}},"sourceEventSeqs":[31],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1791559900807,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791559900807,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1791559900807,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1791559900807,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1791559900807,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:14}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1791880663597,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791880663597,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1791880663597,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1791880663597,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1791880663597,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/office-sidecar-instructions/session.v4.jsonl b/snapshots/session/office-sidecar-instructions/session.v4.jsonl index ada93b0337..34798cf22e 100644 --- a/snapshots/session/office-sidecar-instructions/session.v4.jsonl +++ b/snapshots/session/office-sidecar-instructions/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Load the Office rendering, PDF export, and recalculation skills, then read their shared missing-sidecar setup instructions. Do not download anything. Reply DONE after reading them."}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the Office rendering, PDF","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/office-skills-no-renderer/session.v4.jsonl b/snapshots/session/office-skills-no-renderer/session.v4.jsonl index 4e47fc6474..f39469ee0b 100644 --- a/snapshots/session/office-skills-no-renderer/session.v4.jsonl +++ b/snapshots/session/office-skills-no-renderer/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"请先加载 office-docx、office-pptx 和 office-xlsx 三个 skill,仅根据 skill 指令及当前工具清单确认工作流:在已配置好打包 Python 和 Office 库的 Desktop 环境中,缺少渲染工具是否阻止交付这三种文件?PPTX 新建和编辑分别用什么库?交付前需要哪些结构和内容检查?能否声称做了视觉检查或 Excel 公式重算?只回答工作流,不检查宿主环境,不运行命令,不创建文件,不安装依赖。"}],"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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":8192,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}} {"type":"session/title","data":{"title":"请先加载 office-docx、office-pptx","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/office-skills/session.v4.jsonl b/snapshots/session/office-skills/session.v4.jsonl index 0266c92dc8..394b68fafe 100644 --- a/snapshots/session/office-skills/session.v4.jsonl +++ b/snapshots/session/office-skills/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Load the office-pptx and office-xlsx skills with the skill tool, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-export-pdf","description":"Convert an Office document to a requested PDF with LibreOffice Kit."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-recalculate","description":"Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit."},{"name":"office-render","description":"Render requested document images or inspect visual layout with LibreOffice Kit."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the office-pptx and office-xlsx","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/skill-load/session.v4.jsonl b/snapshots/session/skill-load/session.v4.jsonl index e0cfaf54e6..f2e6c62c46 100644 --- a/snapshots/session/skill-load/session.v4.jsonl +++ b/snapshots/session/skill-load/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Load the editing-cordis-compositions skill with the skill tool, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `editing-cordis-compositions`: Use when creating, changing, or validating an agent preset or other Cordis composition for this harness, including deciding host versus preset placement and checking that an authored preset mounts.\n- `model-only-skill`: Prove user-disabled skills remain available to the model.\n- `snapshot-skill`: Exercise project skill discovery and loading in snapshot tests.\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"editing-cordis-compositions","description":"Use when creating, changing, or validating an agent preset or other Cordis composition for this harness, including deciding host versus preset placement and checking that an authored preset mounts."},{"name":"model-only-skill","description":"Prove user-disabled skills remain available to the model."},{"name":"snapshot-skill","description":"Exercise project skill discovery and loading in snapshot tests."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `editing-cordis-compositions`: Use when creating, changing, or validating an agent preset or other Cordis composition for this harness, including deciding host versus preset placement and checking that an authored preset mounts.\n- `model-only-skill`: Prove user-disabled skills remain available to the model.\n- `snapshot-skill`: Exercise project skill discovery and loading in snapshot tests.\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"editing-cordis-compositions","description":"Use when creating, changing, or validating an agent preset or other Cordis composition for this harness, including deciding host versus preset placement and checking that an authored preset mounts."},{"name":"model-only-skill","description":"Prove user-disabled skills remain available to the model."},{"name":"snapshot-skill","description":"Exercise project skill discovery and loading in snapshot tests."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the editing-cordis-compositions ski","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/session/windows-acl-skill/session.v4.jsonl b/snapshots/session/windows-acl-skill/session.v4.jsonl index 7dc806ace4..bf09a1f1a0 100644 --- a/snapshots/session/windows-acl-skill/session.v4.jsonl +++ b/snapshots/session/windows-acl-skill/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Load the diagnose-windows-sandbox-acl skill with the skill tool, then reply 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 working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"diagnose-windows-sandbox-acl","description":"Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"diagnose-windows-sandbox-acl","description":"Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the diagnose-windows-sandbox-acl sk","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/approval-composer/session.v4.jsonl b/snapshots/web/approval-composer/session.v4.jsonl index fe3d1a423a..a1a876c4cc 100644 --- a/snapshots/web/approval-composer/session.v4.jsonl +++ b/snapshots/web/approval-composer/session.v4.jsonl @@ -12,8 +12,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Write a file named notes.txt in the workspace containing exactly this text on one line: tok63z tokc7y tokibx tokofw tokujv tok10nu tok16rt tok1cvs tok1izr tok1p3q tok1v7p tok21bo tok2a4 tok8e3 tokei2 tokkm1 tokqq0 tokwtz tok12xy tok191x tok1f5w tok1l9v tok1rdu tok1xht tok23ls tok4k8 tokao7 tokgs6 tokmw5 tokt04 tokz43 tok1582 tok1bc1 tok1hg0 tok1njz tok1tny tok1zrx tokqd tok6uc tokcyb tokj2a tokp69 tokva8 tok11e7 tok17i6 tok1dm5 tok1jq4 tok1pu3 tok1vy2 tok2221 tok30h tok94g tokf8f toklce tokrgd tokxkc tok13ob tok19sa tok1fw9 tok1m08 tok1s47 tok1y86 tok24c5 tok5al tokbek tokhij toknmi toktqh tokzug tok15yf tok1c2e tok1i6d tok1oac tok1ueb tok20ia tok1gq tok7kp tokdoo tokjsn tokpwm tokw0l tok124k tok188j tok1eci tok1kgh tok1qkg tok1wof tok22se tok3qu tok9ut tokfys tokm2r toks6q tokyap tok14eo tok1ain tok1gmm tok1mql tok1suk tok1yyj tok252i tok60y tokc4x toki8w tokocv tokugu tok10kt tok16os tok1csr tok1iwq tok1p0p tok1v4o tok218n tok273 tok8b2 tokef1 tokkj0 tokqmz tokwqy tok12ux tok18yw tok1f2v tok1l6u tok1rat tok1xes tok23ir tok4h7 tokal6 tokgp5 tokmt4 toksx3 tokz12 tok1551 tok1b90 tok1hcz tok1ngy tok1tkx tok1zow toknc tok6rb tokcva tokiz9 tokp38 tokv77 tok11b6 tok17f5 tok1dj4 tok1jn3 tok1pr2 tok1vv1 tok21z0 tok2xg tok91f tokf5e tokl9d tokrdc tokxhb tok13la tok19p9 tok1ft8 tok1lx7 tok1s16 tok1y55 tok2494 tok57k tokbbj tokhfi toknjh toktng tokzrf tok15ve tok1bzd tok1i3c tok1o7b tok1uba tok20f9 tok1dp tok7ho tokdln tokjpm tokptl tokvxk tok121j tok185i tok1e9h tok1kdg tok1qhf tok1wle tok22pd tok3nt tok9rs tokfvr toklzq toks3p toky7o tok14bn tok1afm tok1gjl tok1mnk tok1srj tok1yvi tok24zh tok5xx tokc1w toki5v toko9u tokudt tok10hs tok16lr tok1cpq tok1itp tok1oxo tok1v1n tok215m tok242 tok881 tokec0 tokkfz tokqjy tokwnx. Use one bash command with the literal text inline. Then reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Write a file named notes.txt","messageSeqs":[12],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/changed-files-turn/session.v4.jsonl b/snapshots/web/changed-files-turn/session.v4.jsonl index a7b7d1848a..24479c6a34 100644 --- a/snapshots/web/changed-files-turn/session.v4.jsonl +++ b/snapshots/web/changed-files-turn/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"不用先查看目录,直接做四件事:把 intro.md 里的标题「示例项目」改成「项目说明」,新建 src/util.ts 导出一个两数相加的 add 函数,新建 app.local 写一行 mode=demo,最后用 bash 在 notes.txt 末尾追加一行 done。"}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"不用先查看目录,直接做四件","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/code-language/session.v4.jsonl b/snapshots/web/code-language/session.v4.jsonl index 4bf00d6892..a4496fbe37 100644 --- a/snapshots/web/code-language/session.v4.jsonl +++ b/snapshots/web/code-language/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use the read tool exactly once per file to read sample.pyi, deploy.ps1 and table.csv in the current directory. Use these relative paths. Do not run commands or change files. Then reply exactly: Read all three files."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Use the read tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/deepseek-messages-chat/session.v4.jsonl b/snapshots/web/deepseek-messages-chat/session.v4.jsonl index ab6d612582..66c083f594 100644 --- a/snapshots/web/deepseek-messages-chat/session.v4.jsonl +++ b/snapshots/web/deepseek-messages-chat/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"只回复 MESSAGES_WEB_READY,不调用工具。"}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-messages","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-messages","model":"deepseek-v4-flash","contextWindow":1000000}} {"type":"session/title","data":{"title":"只回复 MESSAGES_WEB_READY,不调用","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/feedback-command/session.v4.jsonl b/snapshots/web/feedback-command/session.v4.jsonl index 515cf0b681..74f8c8ec91 100644 --- a/snapshots/web/feedback-command/session.v4.jsonl +++ b/snapshots/web/feedback-command/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with the single word LIGHTHOUSE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Reply with the single word","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/file-upload-round/session.v4.jsonl b/snapshots/web/file-upload-round/session.v4.jsonl index 5d815fd354..6b253b398a 100644 --- a/snapshots/web/file-upload-round/session.v4.jsonl +++ b/snapshots/web/file-upload-round/session.v4.jsonl @@ -9,8 +9,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"file","attachment":{"attachmentId":"sha256:29a0837077f6f3cbddd98c0605897cc6f2b4e5833fb8e1ca4a8045d89b2c8c60","name":"poem.txt","bytes":16}},{"type":"image","attachment":{"attachmentId":"sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640","mediaType":"image/png","width":1,"height":1,"bytes":69,"name":"reference-1.png"}},{"type":"text","text":"Read the attached file with the read tool, reply with exactly the single word it contains, and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp","contextWindow":1000000}} {"type":"session/title","data":{"title":"Read the attached file with","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/fresh-round-trip/session.v4.jsonl b/snapshots/web/fresh-round-trip/session.v4.jsonl index ed4d0b7bfc..7718981d65 100644 --- a/snapshots/web/fresh-round-trip/session.v4.jsonl +++ b/snapshots/web/fresh-round-trip/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Use the bash tool to","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/goal-multi-turn-actions/session.v4.jsonl b/snapshots/web/goal-multi-turn-actions/session.v4.jsonl index f391b15cd3..42452767a2 100644 --- a/snapshots/web/goal-multi-turn-actions/session.v4.jsonl +++ b/snapshots/web/goal-multi-turn-actions/session.v4.jsonl @@ -11,8 +11,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"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}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user's goal is: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\" — which translates to: \"Do two turns, each turn output the file structure of a random package. Note that after you finish one turn, directly output the content and stop; our system will help you open another turn, and you just do something similar.\"\n\nSo this is round 1 of 2. I need to output the file structure of a random package. Let me check the workspace to see if there's anything relevant — maybe there are packages installed or a specific context.\n\nLet me first check the current working directory and see what's there.\n\nThe instruction says: after finishing a turn, output the content directly and stop. So for this round, I should pick a random package and output its file structure. The system will open another turn for the second one.\n\nLet me look at the workspace to understand the environment."},{"type":"tool-call","id":"call_00_IVvwEvXl7JJoIHrqvlDi1572","name":"bash","arguments":"{\"command\":\"find packages -mindepth 2 -maxdepth 2 -type d | sort\",\"description\":\"List package directories deterministically\"}"},{"type":"tool-call","id":"call_01_hlqFt1P4CYy1jb078Ke71690","name":"get_goal","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":7893,"outputTokens":297,"cacheReadTokens":0,"reasoningTokens":213},"stream":[{"type":"chunk","time":1791430277672,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1791430277673,"index":0,"dt":[],"texts":["The user's goal is: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\" — which translates to: \"Do two turns, each turn output the file structure of a random package. Note that after you finish one turn, directly output the content and stop; our system will help you open another turn, and you just do something similar.\"\n\nSo this is round 1 of 2. I need to output the file structure of a random package. Let me check the workspace to see if there's anything relevant — maybe there are packages installed or a specific context.\n\nLet me first check the current working directory and see what's there.\n\nThe instruction says: after finishing a turn, output the content directly and stop. So for this round, I should pick a random package and output its file structure. The system will open another turn for the second one.\n\nLet me look at the workspace to understand the environment."]},{"type":"chunk","time":1791430277673,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user's goal is: \"做两个turn,每个turn输出随机一个包的文件结构。注意你做完一个turn之后,直接输出内容,停止,我们的系统会帮你再开一个turn,你看着做一个类似的\" — which translates to: \"Do two turns, each turn output the file structure of a random package. Note that after you finish one turn, directly output the content and stop; our system will help you open another turn, and you just do something similar.\"\n\nSo this is round 1 of 2. I need to output the file structure of a random package. Let me check the workspace to see if there's anything relevant — maybe there are packages installed or a specific context.\n\nLet me first check the current working directory and see what's there.\n\nThe instruction says: after finishing a turn, output the content directly and stop. So for this round, I should pick a random package and output its file structure. The system will open another turn for the second one.\n\nLet me look at the workspace to understand the environment."}}},{"type":"chunk","time":1791430277673,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791430277673,"index":1,"dt":[],"id":"call_00_IVvwEvXl7JJoIHrqvlDi1572","name":"bash","args":["{\"command\":\"find packages -mindepth 2 -maxdepth 2 -type d | sort\",\"description\":\"List package directories deterministically\"}"]},{"type":"chunk","time":1791430277673,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_IVvwEvXl7JJoIHrqvlDi1572","name":"bash","arguments":"{\"command\":\"find packages -mindepth 2 -maxdepth 2 -type d | sort\",\"description\":\"List package directories deterministically\"}"}}},{"type":"chunk","time":1791430277673,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791430277673,"index":2,"dt":[],"id":"call_01_hlqFt1P4CYy1jb078Ke71690","name":"get_goal","args":["{}"]},{"type":"chunk","time":1791430277673,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_01_hlqFt1P4CYy1jb078Ke71690","name":"get_goal","arguments":"{}"}}},{"type":"chunk","time":1791430277673,"chunk":{"type":"usage","usage":{"inputTokens":7893,"outputTokens":297,"cacheReadTokens":0,"reasoningTokens":213}}},{"type":"chunk","time":1791430277673,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/web/lifecycle-chrome/session.v4.jsonl b/snapshots/web/lifecycle-chrome/session.v4.jsonl index 598027d08a..c999a8fd79 100644 --- a/snapshots/web/lifecycle-chrome/session.v4.jsonl +++ b/snapshots/web/lifecycle-chrome/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with the single word LIGHTHOUSE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Reply with the single word","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/live-interactions/session.v4.jsonl b/snapshots/web/live-interactions/session.v4.jsonl index 1980c673b0..21dc13f544 100644 --- a/snapshots/web/live-interactions/session.v4.jsonl +++ b/snapshots/web/live-interactions/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with a one-sentence description of event sourcing, then stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Reply with a one-sentence description","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/official-subagent-bundle/session.v4.jsonl b/snapshots/web/official-subagent-bundle/session.v4.jsonl index 80558e93fd..c2961e0ffd 100644 --- a/snapshots/web/official-subagent-bundle/session.v4.jsonl +++ b/snapshots/web/official-subagent-bundle/session.v4.jsonl @@ -9,8 +9,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Delegate a self-contained task to the official Claude Code subagent through its generated tools SDK in one run_code program. Ask it to reply with OFFICIAL_SUBAGENT_OK exactly, print its child ID, and wait for its completion notice before replying DONE."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Delegate a self-contained task to","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/optional-string-editor/session.v4.jsonl b/snapshots/web/optional-string-editor/session.v4.jsonl index 6d6ad99f96..07bd82aec7 100644 --- a/snapshots/web/optional-string-editor/session.v4.jsonl +++ b/snapshots/web/optional-string-editor/session.v4.jsonl @@ -9,8 +9,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use the optional string editor from the generated tools SDK in one run_code program to create edited.txt in the working directory containing exactly PTC_EDITOR_OK followed by a newline. Print the editor result, then reply DONE."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Use the optional string editor","messageSeqs":[9],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/permission-policy-context/session.v4.jsonl b/snapshots/web/permission-policy-context/session.v4.jsonl index c5068a3295..4aa8a2d830 100644 --- a/snapshots/web/permission-policy-context/session.v4.jsonl +++ b/snapshots/web/permission-policy-context/session.v4.jsonl @@ -12,8 +12,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Can you create or edit a normal file right now under the current policy? Answer directly in one sentence. Do not call a tool just to discover the policy."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Can you create or edit","messageSeqs":[12],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/plan-review/session.v4.jsonl b/snapshots/web/plan-review/session.v4.jsonl index 005952c2da..89773a2e5a 100644 --- a/snapshots/web/plan-review/session.v4.jsonl +++ b/snapshots/web/plan-review/session.v4.jsonl @@ -11,8 +11,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","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."}],"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","present","read","read_image","schedule_create","schedule_delete","schedule_list","schedule_update","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Plan a small change: add","messageSeqs":[11],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/present-svg/session.v4.jsonl b/snapshots/web/present-svg/session.v4.jsonl index 8d69a45227..0b339ce8de 100644 --- a/snapshots/web/present-svg/session.v4.jsonl +++ b/snapshots/web/present-svg/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"简单画一个 SVG 表示冯诺依曼架构, 保存为 von-neumann.svg"}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"简单画一个 SVG 表示冯诺依曼","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/present/session.v4.jsonl b/snapshots/web/present/session.v4.jsonl index 20c168cd17..d05325eb9f 100644 --- a/snapshots/web/present/session.v4.jsonl +++ b/snapshots/web/present/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use one run_code program to do the following in order. Call present for missing.txt and catch its error without creating that file. Use bash to run exactly `printf \"DELIVERED_REPORT\\n\" > report.txt; printf \"DELIVERED_NOTE\\n\" > 说明.txt`. Call present for report.txt and 说明.txt. After present succeeds, deliberately throw the string \"AFTER_PRESENT\" (not an Error object) from that same run_code program. Do not retry the program or create any other files. Finish by mentioning `report.txt` and `说明.txt` in inline code, and put PRESENT_DONE in a separate paragraph."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Use one run_code program to","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/ptc-escalation-approved/session.v4.jsonl b/snapshots/web/ptc-escalation-approved/session.v4.jsonl index 1fe54e5961..1812ef5719 100644 --- a/snapshots/web/ptc-escalation-approved/session.v4.jsonl +++ b/snapshots/web/ptc-escalation-approved/session.v4.jsonl @@ -12,8 +12,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use run_code with timeoutMs 120000 and direct Node filesystem access to create approved.txt in the working directory containing exactly \"approved\\n\". Use await import(\"node:fs/promises\") and writeFile; do not call nested tools. First attempt the write under the current read-only sandbox without escalation. In that first program, catch only filesystem errors with code EPERM, EACCES or EROFS and return exactly \"EXPECTED_SANDBOX_DENIAL\"; rethrow any other error. If the sandbox denies it, explicitly retry the program with sandbox_permissions \"workspace-write\" and justification \"Create the file requested by the user\". I will answer the approval prompt. After the file is written, reply DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Use run_code with timeoutMs 120000","messageSeqs":[12],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/ptc-round/session.v4.jsonl b/snapshots/web/ptc-round/session.v4.jsonl index 18ae5c5fa9..c489e2bb30 100644 --- a/snapshots/web/ptc-round/session.v4.jsonl +++ b/snapshots/web/ptc-round/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","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."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Using ONE run_code program: run","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/question-composer/session.v4.jsonl b/snapshots/web/question-composer/session.v4.jsonl index 8572d51fe6..315b92b892 100644 --- a/snapshots/web/question-composer/session.v4.jsonl +++ b/snapshots/web/question-composer/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","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."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Use the ask_user_question tool to","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/steering/session.v4.jsonl b/snapshots/web/steering/session.v4.jsonl index d6c62a5c3e..4fb3124ca7 100644 --- a/snapshots/web/steering/session.v4.jsonl +++ b/snapshots/web/steering/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","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."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Use the ask_user_question tool to","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/turn-tail-actions/session.v4.jsonl b/snapshots/web/turn-tail-actions/session.v4.jsonl index 4e5c1de5cc..321d908944 100644 --- a/snapshots/web/turn-tail-actions/session.v4.jsonl +++ b/snapshots/web/turn-tail-actions/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","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."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Begin your reply with the","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/web-search-round/session.v4.jsonl b/snapshots/web/web-search-round/session.v4.jsonl index 93470499fe..b77b96e14a 100644 --- a/snapshots/web/web-search-round/session.v4.jsonl +++ b/snapshots/web/web-search-round/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use web_search once with queries [\"DeepSeek Harness snapshot search\",\"DeepSeek Harness multi-query search\"]. Then reply exactly SEARCH_DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpc:1}}","clientTimeZone":"{{clientTimeZone}}"},"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Use web_search once with queries","messageSeqs":[8],"source":{"kind":"fallback"}}} From 47ea60e985ab2c4b14c02def2586d9f73ef771d2 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 13 Oct 2026 17:10:46 +0800 Subject: [PATCH 10/36] test(snapshots): align master's new scenarios with step decisions subagent-agent-preset no longer declares exit_plan_mode outside plan mode, and the seeded Web fork admits its runtime-context snapshot after the time context. --- .../tool-schemas.1.expected.json | 16 ---------------- .../tool-schemas.expected.json | 16 ---------------- .../subagent-fork-schedule/session.1.v4.jsonl | 4 ++-- .../web/subagent-fork-schedule/session.v4.jsonl | 4 ++-- 4 files changed, 4 insertions(+), 36 deletions(-) diff --git a/snapshots/session/subagent-agent-preset/tool-schemas.1.expected.json b/snapshots/session/subagent-agent-preset/tool-schemas.1.expected.json index 3e61dbecf5..137308c39b 100644 --- a/snapshots/session/subagent-agent-preset/tool-schemas.1.expected.json +++ b/snapshots/session/subagent-agent-preset/tool-schemas.1.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/subagent-agent-preset/tool-schemas.expected.json b/snapshots/session/subagent-agent-preset/tool-schemas.expected.json index e6e376230d..9eef71fa59 100644 --- a/snapshots/session/subagent-agent-preset/tool-schemas.expected.json +++ b/snapshots/session/subagent-agent-preset/tool-schemas.expected.json @@ -107,22 +107,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl index 080926a704..991f99f55a 100644 --- a/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl +++ b/snapshots/web/subagent-fork-schedule/session.1.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply PARENT_READY."}],"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Reply PARENT_READY.","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/snapshots/web/subagent-fork-schedule/session.v4.jsonl b/snapshots/web/subagent-fork-schedule/session.v4.jsonl index 710c5684d5..e498844676 100644 --- a/snapshots/web/subagent-fork-schedule/session.v4.jsonl +++ b/snapshots/web/subagent-fork-schedule/session.v4.jsonl @@ -8,8 +8,8 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply PARENT_READY."}],"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Reply PARENT_READY.","messageSeqs":[8],"source":{"kind":"fallback"}}} From e199aa1bc7a8ad15fbbd3ecdaf9ce7958a568300 Mon Sep 17 00:00:00 2001 From: Shigma Date: Wed, 14 Oct 2026 15:01:22 +0800 Subject: [PATCH 11/36] =?UTF-8?q?refactor(cordis):=20=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E8=AE=BF=E9=97=AE=E4=B8=8E=E6=B6=88=E8=B4=B9?= =?UTF-8?q?=E6=96=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/cordis-api/fiber.i18n.yaml | 21 +++-- docs/cordis-api/fiber.md | 53 ++++++++++++- docs/cordis-api/fiber.zh.md | 56 +++++++++++++- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- .../boot/app-boot/tests/config-reload.spec.ts | 4 +- .../boot/app-boot/tests/user-patches.spec.ts | 2 +- packages/boot/config-editor/src/index.ts | 5 +- packages/boot/hmr/src/index.ts | 2 +- packages/boot/hmr/tests/modules.spec.ts | 2 +- .../client/locale/tests/config.host.spec.ts | 6 +- .../tests/collection.host.spec.ts | 2 +- .../client/ui-chat/tests/config.host.spec.ts | 18 ++--- .../ui-conversation/tests/config.host.spec.ts | 4 +- .../tests/config.host.spec.ts | 2 +- .../ui-settings/tests/config.host.spec.ts | 4 +- .../client/ui-theme/tests/config.host.spec.ts | 6 +- .../experimental/translator/src/deepseek.ts | 4 +- .../translator/tests/deepseek.spec.ts | 10 +-- packages/settings/settings/src/index.ts | 2 +- .../settings/tests/configuration.spec.ts | 4 +- .../settings/settings/tests/live-config.ts | 4 +- scripts/cordis-config-access.spec.ts | 76 +++++++++++++++++++ scripts/loader-volatile-update.spec.ts | 64 ++++++++-------- vendor/README.md | 4 +- vendor/cordis/README.md | 6 ++ vendor/cordis/src/fiber.ts | 37 +++++++-- vendor/hmr/src/index.ts | 2 +- vendor/loader/src/config/entry.ts | 10 +-- 29 files changed, 314 insertions(+), 100 deletions(-) create mode 100644 scripts/cordis-config-access.spec.ts diff --git a/docs/cordis-api/fiber.i18n.yaml b/docs/cordis-api/fiber.i18n.yaml index acc84e2f3a..6c1d8987ce 100644 --- a/docs/cordis-api/fiber.i18n.yaml +++ b/docs/cordis-api/fiber.i18n.yaml @@ -50,15 +50,24 @@ /fiber/the-fiber-class/fiber-geteffects: en: 4d739a9c186fd9c2 zh: f80fd3b87e79b004 +/fiber/the-fiber-class/fiber-rawconfig: + en: 898aab51825bd8c3 + zh: b9ab6339574002df +/fiber/the-fiber-class/fiber-effectiveconfig: + en: 93ac680251e7023f + zh: 8ea7d7de5db39b8e +/fiber/the-fiber-class/fiber-resolveconfig-config: + en: d7319852e2a1c3a9 + zh: 3300fac049227006 /fiber/the-fiber-class/fiber-await: - en: 1d6258cbea61cd18 - zh: 2f10dda8918dadc5 + en: c9a6544cacdbc28e + zh: 636bf93efad95bc9 /fiber/the-fiber-class/fiber-restart: - en: 62d68dedb20b4fa9 - zh: 5a735ae0ff1266f4 + en: 6ffc1baba98d689f + zh: 7e13bc92225c7e0a /fiber/the-fiber-class/fiber-update-config-nosave: - en: b57ce0f6260c2cb8 - zh: 3bfb6c5bc252a2c2 + en: 290f7f1bf1207adc + zh: e666cfb53dea897a /fiber/effect: en: 007d5b214e8a8610 zh: d74c26fbb1b8aeb6 diff --git a/docs/cordis-api/fiber.md b/docs/cordis-api/fiber.md index 3044301eff..366c457d4f 100644 --- a/docs/cordis-api/fiber.md +++ b/docs/cordis-api/fiber.md @@ -209,6 +209,53 @@ Return metadata for currently registered effects. [Source](../../vendor/cordis/src/fiber.ts#L568) +### fiber.rawConfig + +```ts cordis-catalog +/** Raw input retained for the next activation, without evaluating expressions or validating it. */ +get rawConfig(): unknown +``` + +Raw input retained for the next activation, without evaluating expressions or validating it. + +[Source](../../vendor/cordis/src/fiber.ts#L642) + +### fiber.effectiveConfig + +```ts cordis-catalog +/** + * The config object published by the existing activation/update lifecycle, without cloning or re-parsing. + * It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`. + */ +get effectiveConfig(): unknown +``` + +The config object published by the existing activation/update lifecycle, without cloning or re-parsing. It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`. + +[Source](../../vendor/cordis/src/fiber.ts#L655) + +### fiber.resolveConfig(config) + +```ts cordis-catalog +/** + * Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema. + * Does not publish the result, replace raw input, or commit running volatile references. + * Required injections must be available when a hook uses them. + * @param config Raw candidate input. + * @returns The candidate's resolved config, retaining the schema's result identity. + * @throws {ValidationError} when the runtime schema rejects the candidate; hook errors propagate. + */ +resolveConfig(config: unknown): unknown +``` + +Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema. Does not publish the result, replace raw input, or commit running volatile references. Required injections must be available when a hook uses them. + +- `config` — Raw candidate input. + +**Returns** The candidate's resolved config, retaining the schema's result identity. + +[Source](../../vendor/cordis/src/fiber.ts#L667) + ### fiber.await() ```ts cordis-catalog @@ -225,7 +272,7 @@ Wait for current lifecycle work and rethrow startup errors. **Returns** this fiber, once it has settled into a stable state. -[Source](../../vendor/cordis/src/fiber.ts#L704) +[Source](../../vendor/cordis/src/fiber.ts#L731) ### fiber.restart() @@ -243,7 +290,7 @@ Dispose and immediately reload this plugin with its current config. **Returns** a promise resolving once the reload settled. -[Source](../../vendor/cordis/src/fiber.ts#L718) +[Source](../../vendor/cordis/src/fiber.ts#L745) ### fiber.update(config, noSave?) @@ -271,7 +318,7 @@ Runs the `internal/update` waterfall first, so update hooks (and HMR) can veto o **Returns** nothing; the restart runs behind the `internal/update` waterfall. -[Source](../../vendor/cordis/src/fiber.ts#L736) +[Source](../../vendor/cordis/src/fiber.ts#L763) ## Effect diff --git a/docs/cordis-api/fiber.zh.md b/docs/cordis-api/fiber.zh.md index bee2f523f1..05ee483bdd 100644 --- a/docs/cordis-api/fiber.zh.md +++ b/docs/cordis-api/fiber.zh.md @@ -211,6 +211,56 @@ getEffects() [源码](../../vendor/cordis/src/fiber.ts#L568) +### fiber.rawConfig + +```ts cordis-catalog +/** Raw input retained for the next activation, without evaluating expressions or validating it. */ +get rawConfig(): unknown +``` + + +保留供下次激活使用的原始输入,不执行表达式求值或验证。 + +[源码](../../vendor/cordis/src/fiber.ts#L642) + +### fiber.effectiveConfig + +```ts cordis-catalog +/** + * The config object published by the existing activation/update lifecycle, without cloning or re-parsing. + * It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`. + */ +get effectiveConfig(): unknown +``` + + +既有激活/更新生命周期发布的配置对象,不克隆或重新解析。首次解析前为 undefined,卸载后仍可读取;需要运行实例的调用方应检查 `state`。 + +[源码](../../vendor/cordis/src/fiber.ts#L655) + +### fiber.resolveConfig(config) + +```ts cordis-catalog +/** + * Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema. + * Does not publish the result, replace raw input, or commit running volatile references. + * Required injections must be available when a hook uses them. + * @param config Raw candidate input. + * @returns The candidate's resolved config, retaining the schema's result identity. + * @throws {ValidationError} when the runtime schema rejects the candidate; hook errors propagate. + */ +resolveConfig(config: unknown): unknown +``` + + +通过此 fiber 的 `internal/config` 钩子和运行时 schema 对候选值求值并验证。此操作不发布结果、不替换原始输入,也不提交运行中的 volatile 引用。钩子访问的注入服务必须已经可用。 + +- `config`:原始候选输入。 + +**返回**候选配置的解析结果,保留 schema 返回对象的身份。 + +[源码](../../vendor/cordis/src/fiber.ts#L667) + ### fiber.await() ```ts cordis-catalog @@ -227,7 +277,7 @@ async await() **返回**:进入稳定状态后的此 fiber。 -[源码](../../vendor/cordis/src/fiber.ts#L704) +[源码](../../vendor/cordis/src/fiber.ts#L731) ### fiber.restart() @@ -245,7 +295,7 @@ dispose 此插件,并立即使用其当前配置重新加载。 **返回**一个在重新加载完成后兑现的 promise。 -[源码](../../vendor/cordis/src/fiber.ts#L718) +[源码](../../vendor/cordis/src/fiber.ts#L745) ### fiber.update(config, noSave?) @@ -273,7 +323,7 @@ update(config: any, noSave = false) **返回**无返回值;重启由 `internal/update` waterfall 执行。 -[源码](../../vendor/cordis/src/fiber.ts#L736) +[源码](../../vendor/cordis/src/fiber.ts#L763) ## Effect diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d727ee4ec8..e18409d8ab 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -96,7 +96,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event string | Dispatchers | Listeners | | --- | --- | --- | -| `internal/config` | [`config-editor`](../packages/boot/config-editor) (`waterfall`) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | +| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | | `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) | | `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` | | `internal/service` | - | `gateway` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index fccfeea698..aed9a07616 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -98,7 +98,7 @@ | Event string | Dispatchers | Listeners | | --- | --- | --- | -| `internal/config` | [`config-editor`](../packages/boot/config-editor) (`waterfall`) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | +| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | | `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) | | `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` | | `internal/service` | - | `gateway` | diff --git a/packages/boot/app-boot/tests/config-reload.spec.ts b/packages/boot/app-boot/tests/config-reload.spec.ts index 4d8dae27e4..f96ddd36c6 100644 --- a/packages/boot/app-boot/tests/config-reload.spec.ts +++ b/packages/boot/app-boot/tests/config-reload.spec.ts @@ -246,13 +246,13 @@ describe('best-effort config failure recovery', () => { await ctx.loader.await() const entry = [...ctx.loader.entries()].find(candidate => candidate.options.id === 'webserver')! expect(entry.options.config).toEqual({ value: 'invalid' }) - expect(entry.fiber?.config).toEqual({ value: 1 }) + expect(entry.fiber?.effectiveConfig).toEqual({ value: 1 }) expect(ctx.get('validatedValue')).toBe(1) writeFileSync(join(dir, 'cordis.yml'), config(2)) await include.refresh() await ctx.loader.await() - expect(entry.fiber?.config).toEqual({ value: 2 }) + expect(entry.fiber?.effectiveConfig).toEqual({ value: 2 }) expect(ctx.get('validatedValue')).toBe(2) } finally { await ctx.fiber.dispose() diff --git a/packages/boot/app-boot/tests/user-patches.spec.ts b/packages/boot/app-boot/tests/user-patches.spec.ts index 09e5653c56..63e0af5ea6 100644 --- a/packages/boot/app-boot/tests/user-patches.spec.ts +++ b/packages/boot/app-boot/tests/user-patches.spec.ts @@ -451,7 +451,7 @@ describe('boot with user patches', () => { try { const noop = [...ctx.loader.entries()].find(entry => entry.options.id === 'noop') // The mounted plugin received the interpolated environment value. - expect(noop?.fiber?.config).toEqual({ value: 'user-value' }) + expect(noop?.fiber?.effectiveConfig).toEqual({ value: 'user-value' }) expect([...ctx.loader.entries()].some(entry => entry.options.id === 'user-extra')).toBe(true) } finally { await ctx.fiber.dispose() diff --git a/packages/boot/config-editor/src/index.ts b/packages/boot/config-editor/src/index.ts index ffec879f40..8fe686e478 100644 --- a/packages/boot/config-editor/src/index.ts +++ b/packages/boot/config-editor/src/index.ts @@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { isDeepStrictEqual } from 'node:util' -import { Context, FiberState, Service, resolveConfig } from '@deepseek-ai/cordis' +import { Context, FiberState, Service } from '@deepseek-ai/cordis' import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include' import yaml from 'js-yaml' import type { Entry, EntryOptions } from '@deepseek-ai/cordis-plugin-loader' @@ -100,8 +100,7 @@ export class ConfigEditor extends Service { const next = change(current, inherited) const fiber = entry.fiber if (fiber.state !== FiberState.ACTIVE) throw new Error('Configuration plugin is no longer active') - const resolved: unknown = fiber.ctx.waterfall(fiber, 'internal/config', next, () => next) - resolveConfig(fiber.runtime as NonNullable, resolved) + fiber.resolveConfig(next) let before: string try { before = await readFile(path, 'utf8') } catch (error) { diff --git a/packages/boot/hmr/src/index.ts b/packages/boot/hmr/src/index.ts index 47d71d9109..5c31921549 100644 --- a/packages/boot/hmr/src/index.ts +++ b/packages/boot/hmr/src/index.ts @@ -646,7 +646,7 @@ class Hmr extends Service { ...info, previous, fibers: [...info.runtime?.fibers ?? []].map((fiber) => { const entry = fiber.entry?.fiber?.uid === fiber.uid ? fiber.entry : undefined - const config: unknown = entry === undefined ? fiber._config : entry.options.config + const config: unknown = entry === undefined ? fiber.rawConfig : entry.options.config return { fiber, entry, config, moduleNamespace: entry?.moduleNamespace } }), })) diff --git a/packages/boot/hmr/tests/modules.spec.ts b/packages/boot/hmr/tests/modules.spec.ts index 5cf710ea07..33895a7106 100644 --- a/packages/boot/hmr/tests/modules.spec.ts +++ b/packages/boot/hmr/tests/modules.spec.ts @@ -298,7 +298,7 @@ it('leaves disposed child instances to their replacing parent', async () => { expect(seen).toContain('new:entry') expect(seen).not.toContain('new:child') expect(seen).toContain('new:independent') - expect(entry.fiber?._config).toEqual({ value: 'entry' }) + expect(entry.fiber?.rawConfig).toEqual({ value: 'entry' }) }) it.each(['v1', 'v2'] as const)('invalidates a disabled %s module without activating it', async (version) => { diff --git a/packages/client/locale/tests/config.host.spec.ts b/packages/client/locale/tests/config.host.spec.ts index 9c9d3e5462..84af262287 100644 --- a/packages/client/locale/tests/config.host.spec.ts +++ b/packages/client/locale/tests/config.host.spec.ts @@ -13,11 +13,11 @@ describe('locale host', () => { const ctx = new Context() const configuration = await liveConfig(ctx, { Config, apply }) const { fiber } = configuration - expect(plainConfig(configuration.fiber.config)).toEqual({}) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({}) await configuration.update({ preference: 'en' }) - expect(plainConfig(configuration.fiber.config)).toEqual({ preference: 'en' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ preference: 'en' }) await configuration.update({ preference: 'pt-BR' }) - expect(plainConfig(configuration.fiber.config)).toEqual({ preference: 'pt-BR' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ preference: 'pt-BR' }) await expect(configuration.update({ preference: 'bad locale' })).rejects.toThrow() await expect(configuration.update({ preference: '123' })).rejects.toThrow() await fiber.dispose() diff --git a/packages/client/product-analytics/tests/collection.host.spec.ts b/packages/client/product-analytics/tests/collection.host.spec.ts index c7878a8940..8b3cde5d2f 100644 --- a/packages/client/product-analytics/tests/collection.host.spec.ts +++ b/packages/client/product-analytics/tests/collection.host.spec.ts @@ -134,7 +134,7 @@ it('streams live policy changes and rejects intake disabled during identity look const next = iterator.next() // Loader commits the stable Config reference before publishing this notification. const { updateVolatile, createVolatile } = await import('../../../../vendor/cosmokit/src/volatile.ts') - const config = b.fiber.config as import('../src/index.ts').Config + const config = b.fiber.effectiveConfig as import('../src/index.ts').Config updateVolatile(config.enabled, createVolatile(false)) b.fiber.ctx.emit('loader/volatile-update', [['enabled']]) expect(await next).toEqual({ value: false, done: false }) diff --git a/packages/client/ui-chat/tests/config.host.spec.ts b/packages/client/ui-chat/tests/config.host.spec.ts index b3ebb9b698..cfed2e36df 100644 --- a/packages/client/ui-chat/tests/config.host.spec.ts +++ b/packages/client/ui-chat/tests/config.host.spec.ts @@ -14,22 +14,22 @@ describe('ui-chat Host settings', () => { const configuration = await liveConfig(ctx, { Config, apply }) const { fiber } = configuration - expect(plainConfig(configuration.fiber.config)).toEqual({ performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' }) await configuration.update({ transcriptView: 'normal' }) - expect(plainConfig(configuration.fiber.config)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' }) for (const mode of ['expanded', 'compact', 'standard', 'detailed', 'verbose']) { await configuration.update({ transcriptView: mode }) - expect(plainConfig(configuration.fiber.config)).toMatchObject({ transcriptView: mode }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ transcriptView: mode }) } for (const mode of ['dense', '', 42, false, {}, null, undefined]) { await configuration.update({ transcriptView: mode }) - expect(plainConfig(configuration.fiber.config)).toMatchObject({ transcriptView: mode === null ? null : undefined }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ transcriptView: mode === null ? null : undefined }) } await configuration.update({ performanceUsage: 'compact' }) - expect(plainConfig(configuration.fiber.config)).toMatchObject({ performanceUsage: 'compact' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ performanceUsage: 'compact' }) await expect(configuration.update({ performanceUsage: 'hidden' })).rejects.toThrow() await configuration.update({ linkOpening: 'new-tab' }) - expect(plainConfig(configuration.fiber.config)).toMatchObject({ linkOpening: 'new-tab' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ linkOpening: 'new-tab' }) await expect(configuration.update({ linkOpening: 'popup' })).rejects.toThrow() await fiber.dispose() @@ -38,15 +38,15 @@ describe('ui-chat Host settings', () => { it('validates collapse timing and restores its saved config independently of work details', async () => { const ctx = new Context() const configuration = await liveConfig(ctx, { Config, apply }) - expect(plainConfig(configuration.fiber.config)).toMatchObject({ collapseTiming: 'completion' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ collapseTiming: 'completion' }) await configuration.update({ transcriptView: 'compact', collapseTiming: 'next-input' }) - const saved = plainConfig(configuration.fiber.config) + const saved = plainConfig(configuration.fiber.effectiveConfig) if (typeof saved !== 'object' || saved === null) throw new Error('expected saved configuration object') expect(saved).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' }) await expect(configuration.update({ collapseTiming: 'never' })).rejects.toThrow() await configuration.fiber.dispose() const restored = await liveConfig(ctx, { Config, apply }, saved) - expect(plainConfig(restored.fiber.config)).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' }) + expect(plainConfig(restored.fiber.effectiveConfig)).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' }) await restored.fiber.dispose() }) diff --git a/packages/client/ui-conversation/tests/config.host.spec.ts b/packages/client/ui-conversation/tests/config.host.spec.ts index cb047da964..7b87d23d59 100644 --- a/packages/client/ui-conversation/tests/config.host.spec.ts +++ b/packages/client/ui-conversation/tests/config.host.spec.ts @@ -13,9 +13,9 @@ describe('ui-conversation host', () => { const ctx = new Context() const configuration = await liveConfig(ctx, { Config, apply }) const { fiber } = configuration - expect(plainConfig(configuration.fiber.config)).toEqual({ busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR }) await configuration.update({ busyEnter: 'steer' }) - expect(plainConfig(configuration.fiber.config)).toEqual({ busyEnter: 'steer' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: 'steer' }) await expect(configuration.update({ busyEnter: 'invalid' })).rejects.toThrow() await fiber.dispose() }) diff --git a/packages/client/ui-settings-general/tests/config.host.spec.ts b/packages/client/ui-settings-general/tests/config.host.spec.ts index 7bc4864b1b..cb999a2d94 100644 --- a/packages/client/ui-settings-general/tests/config.host.spec.ts +++ b/packages/client/ui-settings-general/tests/config.host.spec.ts @@ -11,7 +11,7 @@ it('validates and updates onboarding preferences without remounting', async () = onTestFinished(() => ctx.fiber.dispose()) const configuration = await liveConfig(ctx, General) await configuration.update({ welcomeNoticeVersion: 'v1' }) - expect(plainConfig(configuration.fiber.config)).toMatchObject({ welcomeNoticeVersion: 'v1' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ welcomeNoticeVersion: 'v1' }) expect(configuration.entry.fiber).toBe(configuration.fiber) }) diff --git a/packages/client/ui-settings/tests/config.host.spec.ts b/packages/client/ui-settings/tests/config.host.spec.ts index 558e6350c1..551f313633 100644 --- a/packages/client/ui-settings/tests/config.host.spec.ts +++ b/packages/client/ui-settings/tests/config.host.spec.ts @@ -9,9 +9,9 @@ it('defaults on, persists valid choices and removes its schema on disposal', asy const ctx = new Context() const configuration = await liveConfig(ctx, { Config, apply }) onTestFinished(() => ctx.fiber.dispose()) - expect(plainConfig(configuration.fiber.config)).toEqual({ enabled: true }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ enabled: true }) await configuration.update({ enabled: false }) - expect(plainConfig(configuration.fiber.config)).toEqual({ enabled: false }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ enabled: false }) await expect(configuration.update({ enabled: 'yes' })).rejects.toThrow() await configuration.fiber.dispose() }) diff --git a/packages/client/ui-theme/tests/config.host.spec.ts b/packages/client/ui-theme/tests/config.host.spec.ts index 69a10570b8..7eb60f6fb2 100644 --- a/packages/client/ui-theme/tests/config.host.spec.ts +++ b/packages/client/ui-theme/tests/config.host.spec.ts @@ -27,11 +27,11 @@ describe('ui-theme host', () => { const ctx = new Context() const configuration = await liveConfig(ctx, { Config, apply }) const { fiber } = configuration - expect(plainConfig(configuration.fiber.config)).toEqual({ preference: DEFAULT_PREFERENCE, fontSize: 14, codeFontSize: 11, terminalFontSize: 13, textFontFamily: '', codeFontFamily: '', terminalFontFamily: '' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ preference: DEFAULT_PREFERENCE, fontSize: 14, codeFontSize: 11, terminalFontSize: 13, textFontFamily: '', codeFontFamily: '', terminalFontFamily: '' }) await configuration.update({ preference: 'dark', fontSize: 10, codeFontSize: 16, codeFontFamily: '"Iosevka"' }) - expect(plainConfig(configuration.fiber.config)).toEqual({ preference: 'dark', fontSize: 10, codeFontSize: 16, terminalFontSize: 13, textFontFamily: '', codeFontFamily: '"Iosevka"', terminalFontFamily: '' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ preference: 'dark', fontSize: 10, codeFontSize: 16, terminalFontSize: 13, textFontFamily: '', codeFontFamily: '"Iosevka"', terminalFontFamily: '' }) await configuration.update({ fontSize: 22 }) - expect(plainConfig(configuration.fiber.config)).toMatchObject({ preference: 'dark', fontSize: 22 }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ preference: 'dark', fontSize: 22 }) await expect(configuration.update({ preference: 'sepia' })).rejects.toThrow() await expect(configuration.update({ fontSize: 9 })).rejects.toThrow() await expect(configuration.update({ fontSize: 23 })).rejects.toThrow() diff --git a/packages/experimental/translator/src/deepseek.ts b/packages/experimental/translator/src/deepseek.ts index a63da716a2..afdba4de20 100644 --- a/packages/experimental/translator/src/deepseek.ts +++ b/packages/experimental/translator/src/deepseek.ts @@ -72,8 +72,8 @@ function nativeOwner(ctx: Context, provider: PaidTranslationProvider): NativeOwn const entry = [...loader.entries()].find(row => row.options.id === directory.settingsNs && row.options.name === OWNER_PACKAGES[provider]) if (entry?.fiber?.state !== FiberState.ACTIVE) return undefined return provider === 'deepseek-account' - ? { llm, fiber: entry.fiber, provider, config: entry.fiber.config as AccountNativeConfig } - : { llm, fiber: entry.fiber, provider, config: entry.fiber.config as OfficialNativeConfig } + ? { llm, fiber: entry.fiber, provider, config: entry.fiber.effectiveConfig as AccountNativeConfig } + : { llm, fiber: entry.fiber, provider, config: entry.fiber.effectiveConfig as OfficialNativeConfig } } function unchanged(ctx: Context, provider: PaidTranslationProvider, previous: EligibleOwner): NativeOwner | undefined { diff --git a/packages/experimental/translator/tests/deepseek.spec.ts b/packages/experimental/translator/tests/deepseek.spec.ts index 5ce3434528..7f45aecd9f 100644 --- a/packages/experimental/translator/tests/deepseek.spec.ts +++ b/packages/experimental/translator/tests/deepseek.spec.ts @@ -179,7 +179,7 @@ describe('native Flash translation', () => { before.resolve(undefined) await continueLookup.promise const owner = [...b.ctx.loader.entries()].find(entry => entry.options.id === 'official-custom-id')! - const config = owner.fiber!.config as ReturnType + const config = owner.fiber!.effectiveConfig as ReturnType config.models = OfficialConfig({ models: [{ id: 'deepseek-v4-flash', name: 'Flash' }] }).models return models }) @@ -200,7 +200,7 @@ describe('native Flash translation', () => { vi.spyOn(b.ctx.llm, 'listConfigurableProviders').mockImplementation(() => { reads += 1 if (reads === 2) queueMicrotask(() => { - const config = owner.fiber!.config as ReturnType + const config = owner.fiber!.effectiveConfig as ReturnType config.models = OfficialConfig({ models: [{ id: 'deepseek-v4-flash' }] }).models }) return directory @@ -274,7 +274,7 @@ describe('native Flash translation', () => { await owner.fiber!.dispose() await rejected } else if (change === 'catalog') { - const config = owner.fiber!.config as ReturnType + const config = owner.fiber!.effectiveConfig as ReturnType config.models = OfficialConfig({ models: [{ id: 'deepseek-v4-flash' }] }).models } else b.setConfigured(false) release.resolve(undefined) @@ -293,7 +293,7 @@ describe('native Flash translation', () => { const rejected = expect(b.translate('deepseek-account')).rejects.toMatchObject({ code: 'TRANSLATION_UNAVAILABLE' }) await entered.promise const owner = [...b.ctx.loader.entries()].find(entry => entry.options.id === 'account-custom-id')! - const config = owner.fiber!.config as ReturnType + const config = owner.fiber!.effectiveConfig as ReturnType config.modelOverrides = AccountConfig({ modelOverrides: { 'deepseek-flash': { maxTokens: 4096 } } }).modelOverrides release.resolve(undefined) await rejected @@ -309,7 +309,7 @@ describe('native Flash translation', () => { if (pluginRecordOf(event)?.type !== 'plugin:translator/request') return if (change === 'withdrawn') withdrawal = owner.fiber!.dispose() else if (change === 'catalog') { - const config = owner.fiber!.config as ReturnType + const config = owner.fiber!.effectiveConfig as ReturnType config.models = OfficialConfig({ models: [{ id: 'deepseek-v4-flash' }] }).models } else b.setConfigured(false) }, { global: true }) diff --git a/packages/settings/settings/src/index.ts b/packages/settings/settings/src/index.ts index e0586ecb24..bd439b2301 100644 --- a/packages/settings/settings/src/index.ts +++ b/packages/settings/settings/src/index.ts @@ -316,7 +316,7 @@ export class SettingsForms extends Service { if (previous?.raw !== raw || previous.autoGenerate !== autoGenerate) { this.ownerContext.emit('settings/document-updated', entry.options.id as SettingsNamespace, revision) } - const value = projectForm(form, plainConfig(entry.fiber.config)) + const value = projectForm(form, plainConfig(entry.fiber.effectiveConfig)) const resolved: unknown = interpolate(entry.fiber.ctx, inherited) const base = projectForm(form, plainConfig(inheritedConfig(entry.fiber.runtime, resolved))) const user = projectForm(form, override) diff --git a/packages/settings/settings/tests/configuration.spec.ts b/packages/settings/settings/tests/configuration.spec.ts index 5bafea1e5b..6fd9b9fe13 100644 --- a/packages/settings/settings/tests/configuration.spec.ts +++ b/packages/settings/settings/tests/configuration.spec.ts @@ -70,9 +70,9 @@ it('preserves configuration expressions while editing a different live field', a await ctx.fiber.dispose() const restored = await start() const entry = [...restored.loader.entries()].find(row => row.options.id === 'first')! - expect((entry.fiber!.config as { ordinary: string }).ordinary).toBe('expression-value') + expect((entry.fiber!.effectiveConfig as { ordinary: string }).ordinary).toBe('expression-value') const second = [...restored.loader.entries()].find(entry => entry.options.id === 'second')! - expect((second.fiber!.config as { ordinary: string }).ordinary).toBe('untouched-expression') + expect((second.fiber!.effectiveConfig as { ordinary: string }).ordinary).toBe('untouched-expression') expect(restored.settings.describe().find(row => row.ns === 'first')!.value).toEqual({ count: 4, list: [] }) }) diff --git a/packages/settings/settings/tests/live-config.ts b/packages/settings/settings/tests/live-config.ts index 1248487f55..551ea7c107 100644 --- a/packages/settings/settings/tests/live-config.ts +++ b/packages/settings/settings/tests/live-config.ts @@ -1,5 +1,5 @@ /** Test fixtures using the same Loader updates as profile reconciliation. */ -import { Context, resolveConfig, type Fiber, type Plugin } from '@deepseek-ai/cordis' +import { Context, type Fiber, type Plugin } from '@deepseek-ai/cordis' import { expect, vi } from 'vitest' import Loader from '@deepseek-ai/cordis-plugin-loader' @@ -27,7 +27,7 @@ export async function liveConfig(ctx: Context, plugin: Plugin, initial: object = await entry.fiber!.await() const replace = async (next: Record) => { const fiber = entry.fiber! - resolveConfig(fiber.runtime!, fiber.ctx.waterfall(fiber, 'internal/config', next, () => next)) + fiber.resolveConfig(next) await entry.update({ config: next }) await entry.fiber!.await() ctx.emit('app-boot/config-reload') diff --git a/scripts/cordis-config-access.spec.ts b/scripts/cordis-config-access.spec.ts new file mode 100644 index 0000000000..16457afdec --- /dev/null +++ b/scripts/cordis-config-access.spec.ts @@ -0,0 +1,76 @@ +/** Raw retention and candidate evaluation preserve the running plugin's config identity. */ +import { Context, type Fiber } from '@deepseek-ai/cordis' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import z from '@deepseek-ai/schemastery' +import { describe, expect, it, onTestFinished, vi } from 'vitest' + +function root(): Context { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + return ctx +} + +describe('Fiber configuration access', () => { + it('keeps raw and running references unchanged while resolving valid or invalid candidates', async () => { + const ctx = root() + await ctx.plugin(Loader) + const Config = z.object({ value: z.number().min(0).volatile() }) + const applied = vi.fn() + ctx.loader.builtins.consumer = { Config, apply: applied } + const raw = { value: { __jsExpr: '1 + 1' } } + const id = await ctx.loader.create({ name: 'cordis:consumer', config: raw }) + const fiber = ctx.loader.resolve(id).fiber! + await fiber.await() + const running = applied.mock.calls[0]![1] as ReturnType + expect(fiber.rawConfig).toBe(raw) + expect(fiber.effectiveConfig).toBe(running) + const candidate = fiber.resolveConfig({ value: { __jsExpr: '2 + 2' } }) as ReturnType + expect(candidate.value.get()).toBe(4) + expect(candidate.value).not.toBe(running.value) + expect(() => fiber.resolveConfig({ value: -1 })).toThrow() + expect(fiber.rawConfig).toBe(raw) + expect(fiber.effectiveConfig).toBe(running) + expect(running.value.get()).toBe(2) + expect(applied).toHaveBeenCalledOnce() + }) + + it('uses the canonical fiber through registry wrappers and retains raw input without updating', async () => { + const ctx = root() + const initial = { value: 1 } + const apply = vi.fn() + const wrapper = ctx.plugin(apply, initial) + await wrapper + const fiber = wrapper.ctx.fiber + const hook = vi.fn(function (this: Fiber, _config: unknown, next: () => unknown) { + expect(this).toBe(fiber) + return next() + }) + fiber.ctx.on('internal/config', hook) + const raw = { value: 2 } + wrapper.rawConfig = raw + expect(fiber.rawConfig).toBe(raw) + expect(wrapper.effectiveConfig).toBe(initial) + expect(wrapper.resolveConfig(raw)).toBe(raw) + expect(hook).toHaveBeenCalledOnce() + expect(fiber.effectiveConfig).toBe(initial) + expect(apply).toHaveBeenCalledOnce() + await fiber.restart() + expect(fiber.effectiveConfig).toBe(raw) + expect(apply).toHaveBeenCalledTimes(2) + }) + + it('retains a pending raw update until its injection is available', async () => { + const ctx = root() + ctx.provide('configAccessTest') + const apply = vi.fn() + const wrapper = ctx.plugin({ inject: ['configAccessTest'], apply }, { value: 1 }) + const raw = { value: 2 } + wrapper.ctx.fiber.update(raw) + expect(wrapper.rawConfig).toBe(raw) + expect(wrapper.effectiveConfig).toBeUndefined() + ctx.set('configAccessTest', {}) + await wrapper + expect(wrapper.effectiveConfig).toBe(raw) + expect(apply).toHaveBeenCalledOnce() + }) +}) diff --git a/scripts/loader-volatile-update.spec.ts b/scripts/loader-volatile-update.spec.ts index 16d8f3b0a8..c23486cc66 100644 --- a/scripts/loader-volatile-update.spec.ts +++ b/scripts/loader-volatile-update.spec.ts @@ -47,9 +47,9 @@ describe('volatile Loader updates', () => { const fiber = await mountEntry(ctx, { Config, apply(owner: Context) { owner.on('loader/volatile-update', events) } }, { title: 'first' }) - const reference = fiber.config as ReturnType + const reference = fiber.effectiveConfig as ReturnType await update(fiber, { title: 'second' }) - expect(fiber.config).toBe(reference) + expect(fiber.effectiveConfig).toBe(reference) expect(reference.get()).toEqual({ title: 'second' }) expect(events).toHaveBeenCalledExactlyOnceWith([[]]) }) @@ -70,7 +70,7 @@ describe('volatile Loader updates', () => { await update(first, { title: 'next', nested: { count: 2 } }) await first.await() expect(mount).toHaveBeenCalledTimes(2) - expect(first.config).toBe(initial) + expect(first.effectiveConfig).toBe(initial) expect(initial.title).toBe(title) expect(configs[1]!.title.get()).toBe('hello') expect(observed).toEqual([{ paths: [['title'], ['nested', 'count']], title: 'next', count: 2 }]) @@ -117,9 +117,9 @@ describe('volatile Loader updates', () => { hooks.push(config.title.get()) }) } }, {}) - const initial = fiber.config as ReturnType + const initial = fiber.effectiveConfig as ReturnType await update(fiber, { title: 'accepted' }) - expect(fiber.config).toBe(initial) + expect(fiber.effectiveConfig).toBe(initial) expect(initial.title.get()).toBe('accepted') await update(fiber, { title: 'accepted' }) expect(hooks).toEqual([]) @@ -180,11 +180,11 @@ describe('volatile Loader updates', () => { const oldUrl = 'https://a.example/' const newUrl = 'https://b.example/' const fiber = await mountEntry(ctx, { Config: schema, apply }, { live: 'a', url: oldUrl }) - const before = fiber.config as ReturnType + const before = fiber.effectiveConfig as ReturnType await update(fiber, { live: 'b', url: newUrl }) await fiber.await() expect(apply).toHaveBeenCalledTimes(2) - expect((fiber.config as ReturnType).url.href).toBe(newUrl) + expect((fiber.effectiveConfig as ReturnType).url.href).toBe(newUrl) expect(before.live.get()).toBe('a') await update(fiber, { live: 'c', url: newUrl, data: 'first' }) await update(fiber, { live: 'd', url: newUrl, data: 'second' }) @@ -199,7 +199,7 @@ describe('volatile Loader updates', () => { owner.on('loader/volatile-update', events) } }, { values: [undefined] }) await update(fiber, { values: [null] }) - expect((fiber.config as ReturnType).values.get()).toEqual([null]) + expect((fiber.effectiveConfig as ReturnType).values.get()).toEqual([null]) expect(events).toHaveBeenCalledExactlyOnceWith([['values']]) }) }) @@ -308,7 +308,7 @@ it('updates volatile children through Group and Include custom updates and saves expect(includeEntry.fiber).toBe(originalInclude) expect(group.fiber).toBe(originalGroup) expect(consumer.fiber).toBe(originalConsumer) - expect(consumer.fiber!.config).toBe(initial) + expect(consumer.fiber!.effectiveConfig).toBe(initial) expect(configs).toHaveLength(1) expect(notifications).toHaveBeenCalledTimes(2) expect(childUpdates).not.toHaveBeenCalled() @@ -318,7 +318,7 @@ it('updates volatile children through Group and Include custom updates and saves entry.fiber!.update({ title: 'custom-update', fixed: 'ordinary' }) expect(childUpdates).toHaveBeenCalledOnce() expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' }) - expect((entry.fiber!.config as ReturnType).title.get()).toBe('hello') + expect((entry.fiber!.effectiveConfig as ReturnType).title.get()).toBe('hello') entry.fiber!.update({ title: 'ephemeral', fixed: 'ordinary' }, true) expect(childUpdates).toHaveBeenCalledTimes(2) expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' }) @@ -332,11 +332,11 @@ it('commits volatile edits in place and retains direct Fiber updates', async () const notifications = vi.fn() const apply = vi.fn(function (owner: Context) { owner.on('loader/volatile-update', notifications) }) const fiber = await mountEntry(ctx, { Config, apply }, {}) - const original = fiber.config as ReturnType + const original = fiber.effectiveConfig as ReturnType await ctx.loader.create({ name: 'cordis:disabled', disabled: true }) await update(fiber, { title: 'enabled' }) expect(apply).toHaveBeenCalledOnce() - expect(fiber.config).toBe(original) + expect(fiber.effectiveConfig).toBe(original) expect(original.title.get()).toBe('enabled') expect(notifications).toHaveBeenCalledExactlyOnceWith([['title']]) await update(fiber, { title: 'invalid', nested: { count: -1 } }) @@ -344,7 +344,7 @@ it('commits volatile edits in place and retains direct Fiber updates', async () await update(fiber, { title: 'mixed', fixed: 'changed' }) expect(apply).toHaveBeenCalledTimes(2) expect(original.title.get()).toBe('enabled') - const current = fiber.config as ReturnType + const current = fiber.effectiveConfig as ReturnType expect(current.title.get()).toBe('mixed') const hook = vi.fn((_config: unknown, _noSave: boolean, next: () => void) => { next() }) @@ -365,7 +365,7 @@ it('parses a volatile-only update through the config hook without patching the e const fiber = await mountEntry(ctx, { Config, apply(owner: Context) { owner.on('loader/volatile-update', () => { trace.push('notify') }) } }, { block: { title: 'initial' } }) - const current = fiber.config as ReturnType + const current = fiber.effectiveConfig as ReturnType const resolveHook = vi.fn((_raw: unknown, next: () => unknown) => next()) fiber.ctx.on('internal/config', resolveHook) const contextPatch = vi.fn((_entry: unknown, next: () => void) => { next() }) @@ -379,7 +379,7 @@ it('parses a volatile-only update through the config hook without patching the e expect(resolveHook).toHaveBeenCalledOnce() expect(trace).toEqual(['validate', 'notify']) expect(current.block.get()).toEqual({ title: 'changed' }) - expect(fiber._config).toBe(raw) + expect(fiber.rawConfig).toBe(raw) }) it.each([true, false])('keeps old references untouched when isolation replaces a dependency (available: %s)', async (available) => { @@ -452,7 +452,7 @@ it.each(['group', 'include'] as const)('applies profile patches to a %s subtree await reconcileProfilePatches(ctx, patch('second'), 'volatile-test') expect(parent.fiber).toBe(parentFiber) expect(entry.fiber).toBe(childFiber) - expect(entry.fiber!.config).toBe(original) + expect(entry.fiber!.effectiveConfig).toBe(original) expect(original.title).toBe(reference) expect(reference.get()).toBe('second') expect(configs).toHaveLength(1) @@ -482,7 +482,7 @@ it('logs an invalid candidate and keeps its references while other entries commi await healthy.entry!.update({ config: { title: 'healthy' } }) expect(warning).toHaveBeenCalledTimes(2) expect((invalid.config as ReturnType).title.get()).toBe('hello') - expect(invalid._config).toEqual({ title: 'invalid', nested: { count: -1 } }) + expect(invalid.rawConfig).toEqual({ title: 'invalid', nested: { count: -1 } }) expect((healthy.config as ReturnType).title.get()).toBe('healthy') expect(events).toHaveBeenCalledExactlyOnceWith([['title']]) }) @@ -500,7 +500,7 @@ it.each([false, true])('retains raw expression edits for dependency restoration await fiber.entry!.update({ config: raw }) await fiber.await() expect(values).toEqual(volatile ? ['same'] : ['same', 'same']) - expect(fiber._config).toBe(raw) + expect(fiber.rawConfig).toBe(raw) await provider.dispose() await provide('old-route', 'new-route') await fiber.await() @@ -540,10 +540,10 @@ it('compares ordinary URL transforms by value and remounts when an expression re const fixed = { __jsExpr: "ctx.get('volatile-transform-source').value" } const raw = { url: 'https://example.com/', fixed, live: 'old' } const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, raw) - const current = fiber.config as ReturnType + const current = fiber.effectiveConfig as ReturnType await update(fiber, { ...raw, live: 'new' }) expect(mount).toHaveBeenCalledOnce() - expect(fiber.config).toBe(current) + expect(fiber.effectiveConfig).toBe(current) expect(current.url.href).toBe(raw.url) expect(current.fixed).toBe('initial') expect(current.live.get()).toBe('new') @@ -554,7 +554,7 @@ it('compares ordinary URL transforms by value and remounts when an expression re expect(current.fixed).toBe('initial') expect(current.live.get()).toBe('new') expect(events).toHaveBeenCalledOnce() - const replaced = fiber.config as ReturnType + const replaced = fiber.effectiveConfig as ReturnType expect(replaced.fixed).toBe('changed') expect(replaced.live.get()).toBe('remounted') }) @@ -568,13 +568,13 @@ it('remounts when an ordinary parent expression removes a live reference path', const mount = vi.fn(function (owner: Context) { owner.on('loader/volatile-update', events) }) const raw = { block: { __jsExpr: "ctx.get('volatile-path-source').block" }, live: 'old' } const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, raw) - const current = fiber.config as ReturnType + const current = fiber.effectiveConfig as ReturnType source.block = undefined await update(fiber, { ...raw, live: 'new' }) expect(mount).toHaveBeenCalledTimes(2) expect(current.block.value.get()).toBe('old') expect(events).not.toHaveBeenCalled() - expect((fiber.config as ReturnType).block).toBeUndefined() + expect((fiber.effectiveConfig as ReturnType).block).toBeUndefined() }) it('keeps an ordinary plugin mounted when an absent object becomes its explicit default', async () => { @@ -582,13 +582,13 @@ it('keeps an ordinary plugin mounted when an absent object becomes its explicit const Config = z.object({ nested: z.object({ fixed: z.string() }).default({ fixed: 'default' }) }) const mount = vi.fn() const fiber = await mountEntry(ctx, { Config, apply: mount }, {}) - const config: unknown = fiber.config + const config: unknown = fiber.effectiveConfig await update(fiber, { nested: { fixed: 'default' } }) - expect(fiber.config).toBe(config) + expect(fiber.effectiveConfig).toBe(config) expect(mount).toHaveBeenCalledTimes(1) await update(fiber, { nested: { fixed: 'changed' } }) expect(mount).toHaveBeenCalledTimes(2) - expect(fiber.config).toEqual({ nested: { fixed: 'changed' } }) + expect(fiber.effectiveConfig).toEqual({ nested: { fixed: 'changed' } }) }) it('keeps a noSave volatile value as the pending raw config across a no-op entry update', async () => { @@ -596,11 +596,11 @@ it('keeps a noSave volatile value as the pending raw config across a no-op entry const fiber = await mountEntry(ctx, { Config, apply() {} }, { title: 'saved' }) fiber.update({ title: 'ephemeral' }, true) await fiber.await() - expect((fiber.config as ReturnType).title.get()).toBe('ephemeral') + expect((fiber.effectiveConfig as ReturnType).title.get()).toBe('ephemeral') expect(fiber.entry!.options.config).toEqual({ title: 'saved' }) await fiber.entry!.update({ config: { title: 'saved' } }) - expect(fiber._config).toEqual({ title: 'ephemeral' }) - expect((fiber.config as ReturnType).title.get()).toBe('ephemeral') + expect(fiber.rawConfig).toEqual({ title: 'ephemeral' }) + expect((fiber.effectiveConfig as ReturnType).title.get()).toBe('ephemeral') }) it('isolates a failing notification listener and dispatches with a Context receiver', async () => { @@ -613,7 +613,7 @@ it('isolates a failing notification listener and dispatches with a Context recei const warning = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) onTestFinished(() => { warning.mockRestore() }) await update(fiber, { title: 'committed' }) - expect((fiber.config as ReturnType).title.get()).toBe('committed') + expect((fiber.effectiveConfig as ReturnType).title.get()).toBe('committed') expect(receivers).toEqual([fiber]) expect(warning).toHaveBeenCalledWith(expect.objectContaining({ message: 'listener boom' })) await update(other, { title: 'unaffected' }) @@ -626,9 +626,9 @@ it('remounts instead of committing when an ordinary field parses into a fresh cl const schema = z.object({ handle: z.transform(z.string(), value => new Handle(value)), live: z.string().volatile() }) const mount = vi.fn() const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, { handle: 'h', live: 'old' }) - const before = fiber.config as ReturnType + const before = fiber.effectiveConfig as ReturnType await update(fiber, { handle: 'h', live: 'new' }) expect(mount).toHaveBeenCalledTimes(2) expect(before.live.get()).toBe('old') - expect((fiber.config as ReturnType).live.get()).toBe('new') + expect((fiber.effectiveConfig as ReturnType).live.get()).toBe('new') }) diff --git a/vendor/README.md b/vendor/README.md index 654276201d..deff0e6500 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -46,7 +46,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. 12. **`loader/src/config/entry.ts` activation observer**: the detached `Entry.init()` completion observer handles both outcomes; the fiber retains its activation error for explicit consumer audits. Covered by `packages/boot/app-boot/tests/user-patches.spec.ts`. 13. **`include/src/index.ts` `writeTask` type**: widened the optional `writeTask?: NodeJS.Timeout` property to `NodeJS.Timeout | undefined` — the debounced writer assigns `undefined` on flush, which `exactOptionalPropertyTypes` rejects on a plain optional. Type-only; no behavior change. 14. **`include/src/index.ts` durable debounced writes**: serialized and tracked config-file writes, retried transient `EACCES`/`EBUSY`/`EPERM` rename failures with a bounded backoff, observed asynchronous timer rejections, and drained writes before and after child removal during Include teardown. The first drain preserves an existing terminal write failure even if child removal schedules a later write. Missing-file initialization awaits the write and forces a fresh parse before mounting the initial entries. Windows can briefly retain a destination handle after a Loader child disposes; the upstream fire-and-forget rename escaped as an unhandled rejection and could lose the persisted `disabled` state. A terminal failure is logged by the asynchronous writer and remains on the queue so `Include.stop()` rethrows it instead of silently declaring persistence complete; Cordis's ordinary fiber teardown retains its separate error-containment contract. Covered by `packages/host/directory-picker-auto/tests/loader-composition.spec.ts` with injected transient and terminal rename failures. -15. **Lazy Loader config resolution across `cordis/src/{events,fiber}.ts`, `loader/src/{index,config/entry}.ts`, `include/src/index.ts`, and `hmr/src/index.ts`**: ports [cordiverse/cordis#41](https://github.com/cordiverse/cordis/pull/41), retaining raw fiber config and resolving it through `internal/config` only after declared injections are active. Provider replacement re-resolves the raw expression, pending updates retain it, and HMR transfers it. Resolution applies only to the entry root, so child plugins mounted by a row keep caller-owned config identity. Include declares the `EntryGroup.key` tree-carrier marker (as Group does): its config is entry and patch lists, so interpolation keeps it literal and a `!!js` expression inside a nested row's config resolves lazily in that row's own fiber (Include's own `path` therefore stays literal too). Deferred failures retain the owning row diagnostic, and tree teardown does not persist failure-driven self-disposal. Covered by `packages/boot/app-boot/tests/{app-boot,user-patches}.spec.ts`, `packages/boot/cmdline/tests/cmdline.spec.ts`, `apps/cli/tests/web-agent-presets.e2e.ts`, and the built custom-profile cases in `apps/cli/tests/built-bin.e2e.ts`. +15. **Lazy Loader config resolution across `cordis/src/{events,fiber}.ts`, `loader/src/{index,config/entry}.ts`, `include/src/index.ts`, and `hmr/src/index.ts`**: ports [cordiverse/cordis#41](https://github.com/cordiverse/cordis/pull/41), retaining raw fiber config and resolving it through `internal/config` only after declared injections are active. Provider replacement re-resolves the raw expression, pending updates retain it, and HMR transfers it. Resolution applies only to the entry root, so child plugins mounted by a row keep caller-owned config identity. Include declares the `EntryGroup.key` tree-carrier marker (as Group does): its config is entry and patch lists, so interpolation keeps it literal and a `!!js` expression inside a nested row's config resolves lazily in that row's own fiber (Include's own `path` therefore stays literal too). Deferred failures retain the owning row diagnostic, and tree teardown does not persist failure-driven self-disposal. `Fiber.rawConfig`, `Fiber.resolveConfig(candidate)` and `Fiber.effectiveConfig` centralize raw retention, candidate evaluation and reads of the lifecycle-published object. Accessors use the canonical fiber, including writes through registry wrappers; candidate resolution never publishes or commits references. Loader volatile updates, config editing, settings, translator and both HMR providers use these accessors while the existing Core config fields and event protocol remain in place. Covered by `scripts/cordis-config-access.spec.ts`, `packages/boot/app-boot/tests/{app-boot,user-patches}.spec.ts`, `packages/boot/cmdline/tests/cmdline.spec.ts`, `apps/cli/tests/web-agent-presets.e2e.ts`, and the built custom-profile cases in `apps/cli/tests/built-bin.e2e.ts`. 16. **`cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match. 17. **`@deepseek-ai` rescope**: every vendored manifest `name`, every internal dependency entry among the vendored set, and every module specifier that reaches them use the scoped names in the manifest table's `npm name` column. Directory names, version numbers, and dependency ranges are unchanged, and no upstream runtime identifier is renamed — `Symbol.for('schemastery')` and Schemastery's `vendor:` metadata field keep their upstream values. Re-apply with `pnpm run rescope-vendor --apply` after a sync; the table's two name columns are the mapping, restated for consumers in [docs/rescope.md](../docs/rescope.md). 18. **Entry `disabled` interpolation in `loader/src/config/entry.ts`**: a `disabled: !!js` expression evaluates against the loader context at every mount decision; the raw node stays in the options, so write-back keeps the `!!js` form. `disabled` is the only interpolated metadata field. Covered by `packages/boot/app-boot/tests/user-patches.spec.ts` and `apps/cli/tests/windows-shell.spec.ts`. @@ -56,7 +56,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. 21. **`cordis/src/logger.ts` exporter disposal**: each disposer retains its registration id, so removing an earlier exporter cannot delete a later console or telemetry exporter. Covered by startup collector cleanup in `packages/boot/app-boot/tests/app-boot.spec.ts` and disabled-feedback output in `packages/session/session-telemetry-otel/tests/loader-composition.e2e.ts`. -22. **Volatile config across `cosmokit`, `schemastery`, `cordis`, and `loader`**: Cosmokit supplies immutable references and framework-owned commits; `deepEqual` treats two references as equal, propagates strict comparison into arrays, compares every array slot with holes treated as undefined, handles cycles conservatively, compares URLs by normalized href, and compares other opaque objects by identity in strict mode. Schemastery adds `.volatile()`, optional/default inference, placement validation without eager lazy-schema expansion (a lazy inner is validated once when built), metadata-free serialized node compatibility, serialized metadata, reference-aware simplification, unsupported volatile values reported as `ValidationError` with their path, and `.default()` accepting the raw input type `Partial` because a volatile field makes the output type carry references. Loader's save path calls `simplify` with its schema receiver (`unparse.call`), an independent fix for the unbound-`this` call. Cordis exports consumer types without changing Fiber lifecycle. Loader compares raw options strictly in `Entry.update`; for a config-only change on an active fiber it calls the pure `equalExceptVolatile` function in `config/diff.ts`, which narrows the Standard Schema to Schemastery's `Schema` type (a new type-only `@deepseek-ai/schemastery` dependency of `loader`) and recursively skips fixed volatile paths using schema metadata without executing config hooks or validation. Missing or null object nodes compare using their declared defaults, including nodes without volatile descendants; schema backedges retain raw comparison. Entry passes its actual schema and preserves ordinary context and custom-update lifecycles. For a volatile-only change, `Entry._commitVolatile` re-parses the raw config through the fiber's `internal/config` hook and `resolveConfig`, compares ordinary effective values, commits references and emits the instance-local `loader/volatile-update` declared in `loader/src/index.ts`; a changed ordinary effective value falls back to the ordinary remount, and an invalid candidate is logged while the raw config stays retained for the next activation. Cosmokit provides reference enumeration and commits, and `simplify` is called with its schema receiver. The package READMEs document these additions; schema tests live in `scripts/volatile-config.spec.ts`, Loader runtime and real-file tests in `scripts/loader-volatile-update.spec.ts`, and code replacement tests in the HMR module suite. +22. **Volatile config across `cosmokit`, `schemastery`, `cordis`, and `loader`**: Cosmokit supplies immutable references and framework-owned commits; `deepEqual` treats two references as equal, propagates strict comparison into arrays, compares every array slot with holes treated as undefined, handles cycles conservatively, compares URLs by normalized href, and compares other opaque objects by identity in strict mode. Schemastery adds `.volatile()`, optional/default inference, placement validation without eager lazy-schema expansion (a lazy inner is validated once when built), metadata-free serialized node compatibility, serialized metadata, reference-aware simplification, unsupported volatile values reported as `ValidationError` with their path, and `.default()` accepting the raw input type `Partial` because a volatile field makes the output type carry references. Loader's save path calls `simplify` with its schema receiver (`unparse.call`), an independent fix for the unbound-`this` call. Cordis exports consumer types without changing Fiber lifecycle. Loader compares raw options strictly in `Entry.update`; for a config-only change on an active fiber it calls the pure `equalExceptVolatile` function in `config/diff.ts`, which narrows the Standard Schema to Schemastery's `Schema` type (a new type-only `@deepseek-ai/schemastery` dependency of `loader`) and recursively skips fixed volatile paths using schema metadata without executing config hooks or validation. Missing or null object nodes compare using their declared defaults, including nodes without volatile descendants; schema backedges retain raw comparison. Entry passes its actual schema and preserves ordinary context and custom-update lifecycles. For a volatile-only change, `Entry._commitVolatile` re-parses the raw config through `Fiber.resolveConfig()`, compares ordinary effective values, commits references and emits the instance-local `loader/volatile-update` declared in `loader/src/index.ts`; a changed ordinary effective value falls back to the ordinary remount, and an invalid candidate is logged while the raw config stays retained for the next activation. Cosmokit provides reference enumeration and commits, and `simplify` is called with its schema receiver. The package READMEs document these additions; schema tests live in `scripts/volatile-config.spec.ts`, Loader runtime and real-file tests in `scripts/loader-volatile-update.spec.ts`, and code replacement tests in the HMR module suite. 23. **`loader/src/config/entry.ts` module identity**: retains each entry's raw import result as `moduleNamespace`, before plugin export normalization. HMR matches that object to Node's cached module namespace and updates it after a successful reload. `EntryTree.import()` keeps its existing arguments and return value; `loader/README.md` documents the additive field. diff --git a/vendor/cordis/README.md b/vendor/cordis/README.md index d0181dbf76..2f7385dcf4 100644 --- a/vendor/cordis/README.md +++ b/vendor/cordis/README.md @@ -103,3 +103,9 @@ docs use public APIs from `cordis`; loader examples additionally use ## Volatile configuration Schemas may return `Volatile` references, whose values are read through `.get()`. Cordis exports the consumer types; Loader commits volatile-only changes into the running references without restarting and notifies the owning fiber through `loader/volatile-update`. Direct `fiber.update()` retains its existing update waterfall and default restart. + +## Configuration access + +`fiber.rawConfig` reads or retains the raw input for a later activation. Assigning it does not validate, update the running instance or trigger a restart. `fiber.resolveConfig(candidate)` evaluates the fiber’s config hooks and schema without publishing the result; any services used by those hooks must already be available. `fiber.effectiveConfig` returns the lifecycle-published object without re-parsing, preserving the identity of volatile references. It is undefined before the first resolution and stays readable after unload, so consumers that require a running instance also check the fiber state. + +Use `fiber.update()` for an ordinary config change. Loader retains raw input separately when committing only volatile values into the running object. diff --git a/vendor/cordis/src/fiber.ts b/vendor/cordis/src/fiber.ts index 6bb1caa7a5..a21f18510d 100644 --- a/vendor/cordis/src/fiber.ts +++ b/vendor/cordis/src/fiber.ts @@ -638,9 +638,36 @@ export class Fiber { }) } - private _resolveConfig(config: any) { - config = this.context.waterfall(this, 'internal/config', config, () => config) - return this.runtime ? resolveConfig(this.runtime, config) : config + /** Raw input retained for the next activation, without evaluating expressions or validating it. */ + get rawConfig(): unknown { + return this.ctx.fiber._config + } + + /** Retain raw input without changing the running config or triggering an update. */ + set rawConfig(config: unknown) { + this.ctx.fiber._config = config + } + + /** + * The config object published by the existing activation/update lifecycle, without cloning or re-parsing. + * It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`. + */ + get effectiveConfig(): unknown { + return this.ctx.fiber.config + } + + /** + * Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema. + * Does not publish the result, replace raw input, or commit running volatile references. + * Required injections must be available when a hook uses them. + * @param config Raw candidate input. + * @returns The candidate's resolved config, retaining the schema's result identity. + * @throws {ValidationError} when the runtime schema rejects the candidate; hook errors propagate. + */ + resolveConfig(config: unknown): unknown { + const fiber = this.ctx.fiber + config = fiber.context.waterfall(fiber, 'internal/config', config, () => config) + return fiber.runtime ? resolveConfig(fiber.runtime, config) : config } private async _reload() { @@ -652,7 +679,7 @@ export class Fiber { // the load. Do not run plugin code for a stale epoch; the state update // below will drain any effects collected while the fiber was PENDING. if (this._runner.epoch === oldEpoch) { - this.config = this._resolveConfig(this._config) + this.config = this.resolveConfig(this._config) await this._execute(this._runner) this._error = undefined } @@ -744,7 +771,7 @@ export class Fiber { this._refresh() return } - config = this._resolveConfig(config) + config = this.resolveConfig(config) this.context.waterfall(this, 'internal/update', config, noSave, () => { this.config = config this._error = undefined diff --git a/vendor/hmr/src/index.ts b/vendor/hmr/src/index.ts index e7aed96164..39b3461d9b 100644 --- a/vendor/hmr/src/index.ts +++ b/vendor/hmr/src/index.ts @@ -353,7 +353,7 @@ class Hmr extends Service { const reload = (plugin: any, runtime: Plugin.Runtime) => { if (!runtime) return for (const oldFiber of runtime.fibers) { - const fiber = oldFiber.parent.registry.plugin(plugin, oldFiber._config, this.getOuterStack) + const fiber = oldFiber.parent.registry.plugin(plugin, oldFiber.rawConfig, this.getOuterStack) fiber.entry = oldFiber.entry if (fiber.entry) fiber.entry.fiber = fiber } diff --git a/vendor/loader/src/config/entry.ts b/vendor/loader/src/config/entry.ts index 15b566257a..5f819367ee 100644 --- a/vendor/loader/src/config/entry.ts +++ b/vendor/loader/src/config/entry.ts @@ -1,4 +1,4 @@ -import { Context, Fiber, FiberState, Inject, resolveConfig } from '@deepseek-ai/cordis' +import { Context, Fiber, FiberState, Inject } from '@deepseek-ai/cordis' import { deepEqual, isNullable, updateVolatile, volatileEntries, type Volatile } from '@deepseek-ai/cosmokit' import { Loader } from '../index.ts' import { EntryGroup } from './group.ts' @@ -146,7 +146,7 @@ export class Entry { const volatileOnly = changes.length === 1 && changes[0] === 'config' && this.fiber.state === FiberState.ACTIVE && Object.getPrototypeOf(this.ctx) === this.parent.ctx && equalExceptVolatile(legacy.config, this.options.config, this.fiber.runtime?.Config) - if (volatileOnly) this.fiber._config = this.options.config + if (volatileOnly) this.fiber.rawConfig = this.options.config const pending = volatileOnly && this._commitVolatile() ? [] : changes if (!pending.length && !force) return this.context.emit('loader/partial-dispose', this, legacy, true) @@ -163,18 +163,18 @@ export class Entry { */ private _commitVolatile(): boolean { const fiber = this.fiber! - const refs = volatileEntries(fiber.config) + const refs = volatileEntries(fiber.effectiveConfig) if (!refs.length) return true const raw = this.options.config let candidate: unknown try { - candidate = resolveConfig(fiber.runtime!, fiber.ctx.waterfall(fiber, 'internal/config', raw, () => raw)) + candidate = fiber.resolveConfig(raw) } catch (error) { this.ctx.logger.warn('volatile config update failed for %C', this.options.id) this.ctx.logger.warn(error) return true } - if (!deepEqual(fiber.config, candidate, true)) { + if (!deepEqual(fiber.effectiveConfig, candidate, true)) { this.ctx.logger.debug('ordinary config values of %C changed with its volatile values; applying the ordinary update', this.options.id) return false } From d65835559ce01a83c99ad245d526176eab5d631a Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 15 Oct 2026 14:16:00 +0800 Subject: [PATCH 12/36] refactor(agent): commit plan selections in pre-step and drop agent/step-boundary agent/pre-step already runs before step/start, and tool resolution and prompt assembly now follow step/start, so plan-mode can keep committing pending selections after downstream pre-step listeners accept the step. Tool conditions and plan guidance still read the committed state, and a rejected proposal keeps the selection pending as on master. No agent/model listener depends on plan mode, so the separate serial event had no consumer left. The loop now claims input, runs agent/model, and then agent/pre-step. The agent/model order test replaces the boundary tests; plan-mode tests cover the rejected-proposal case again. Docs, the Agent Note, the upgrade guide, and generated catalogs follow. --- ...6-07-05-reconstructable-requests.i18n.yaml | 4 +- .../2026-07-05-reconstructable-requests.md | 2 +- .../2026-07-05-reconstructable-requests.zh.md | 2 +- ...02-system-prompt-as-surface-node.i18n.yaml | 4 +- ...026-09-02-system-prompt-as-surface-node.md | 2 +- ...-09-02-system-prompt-as-surface-node.zh.md | 2 +- ...-model-chosen-before-preparation.i18n.yaml | 16 ++--- ...12-step-model-chosen-before-preparation.md | 11 ++- ...step-model-chosen-before-preparation.zh.md | 11 ++- docs/agent-lifecycle.md | 2 - docs/agent-lifecycle.zh.md | 2 - docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 3 +- docs/architecture.zh.md | 3 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.md | 13 ++-- docs/event-producer-consumer.zh.md | 13 ++-- docs/persistence-catalog.i18n.yaml | 8 +-- docs/persistence-catalog.md | 4 +- docs/persistence-catalog.zh.md | 4 +- docs/persistence-schema.json | 2 +- docs/subsystems/core.md | 32 +-------- docs/subsystems/core.zh.md | 32 +-------- docs/subsystems/plan.i18n.yaml | 14 ++-- docs/subsystems/plan.md | 22 +++--- docs/subsystems/plan.zh.md | 22 +++--- .../conditional-tools/guide.i18n.yaml | 12 ++-- .../v0.2.1-alpha.2/conditional-tools/guide.md | 8 +-- .../conditional-tools/guide.zh.md | 8 +-- 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 | 2 - .../core/agent-loop/tests/step-model.spec.ts | 58 ++-------------- packages/core/agent/README.i18n.yaml | 8 +-- packages/core/agent/README.md | 4 +- packages/core/agent/README.zh.md | 4 +- packages/core/agent/src/runtime-types.ts | 17 +---- .../extensions/tool-cordis/src/api-catalog.ts | 16 ++--- packages/plan/plan-mode/README.i18n.yaml | 12 ++-- packages/plan/plan-mode/README.md | 6 +- packages/plan/plan-mode/README.zh.md | 6 +- packages/plan/plan-mode/src/index.ts | 69 ++++++++----------- .../plan/plan-mode/tests/plan-mode.spec.ts | 18 ++--- scripts/gen-doc-graphs.ts | 2 - 46 files changed, 173 insertions(+), 323 deletions(-) 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 84445dd681..4877b474fd 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 @@ -15,8 +15,8 @@ en: 6da15cf986d59a91 zh: 40282908b54295f9 /agent-note-every-llm-request-is-reconstructable-from-the-session-log/decision/the-mechanism: - en: ba24d551138e75ac - zh: f9288da86f510199 + en: a563e6724978e703 + zh: d1e3caeabd53b903 /agent-note-every-llm-request-is-reconstructable-from-the-session-log/decision/the-minicode-shape-adopted-with-the-event-log-as-the-source: en: e5f2ffaa3d7de0cc zh: 5ba6b36787a0e189 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 d9c1970a66..e73ca47e69 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md +++ b/.agents/notes/implemented/architecture/2026-07-05-reconstructable-requests.md @@ -24,7 +24,7 @@ Prefix-cache stability is corollary #1, not the headline: an append-only log pro `EpochHeader` records the request's non-history state: call config and tool schemas. Writers omit `tools: []` and `adapterDefaults: {}`; current acceptance rejects those fields and any `header.system`, rather than repairing them. Whitespace-only system-message content, `config.stop: []`, and nested extensions remain intact. The [V3 canonical-envelope decision](2026-09-06-v3-canonical-session-envelopes.md) owns historical conversion. The rendered system prompt is derived history — the `system/message` event at surface node 0, per the [surface-node Agent Note](2026-09-02-system-prompt-as-surface-node.md) — so a prompt change is a surface replacement rather than a header change. Adapter-supplied effort and token defaults retain their `adapterDefaults` ownership; 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, commits pending selections at `agent/step-boundary`, lets `agent/model` choose the step's provider, model, and reasoning effort as `agent.step`, and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, resolves the step's tools, assembles the system prompt and runtime context, commits a changed prompt as the `system/message` append or node-0 replacement, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. `agent/request` may replace only the frozen call config's sampling controls; the provider, model, and reasoning effort stay the step's model selection. The loop records the owed initial, resume, change, or series full snapshot, builds `GenerateOptions` from derived messages (system message first) and that header with no `system` field, and freezes it while leaving `AbortSignal` live. The [request-freeze evidence reference](../../../../packages/core/agent-loop/README.md) owns reuse of completed message freezes and per-request local header freezing. 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, lets `agent/model` choose the step's provider, model, and reasoning effort as `agent.step`, and runs `agent/pre-step`. Rejection opens no step; enter opens `step/start`, resolves the step's tools, assembles the system prompt and runtime context, commits a changed prompt as the `system/message` append or node-0 replacement, records the final message batch as `user/message` events, and may use `startsRequestSeries: true` to declare a distinct series. `agent/request` may replace only the frozen call config's sampling controls; the provider, model, and reasoning effort stay the step's model selection. The loop records the owed initial, resume, change, or series full snapshot, builds `GenerateOptions` from derived messages (system message first) and that header with no `system` field, and freezes it while leaving `AbortSignal` live. The [request-freeze evidence reference](../../../../packages/core/agent-loop/README.md) owns reuse of completed message freezes and per-request local header freezing. 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. 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 f0a84c3d44..9b1e53b6d8 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 @@ -24,7 +24,7 @@ Status: implemented `EpochHeader` 记录请求的非历史状态:调用配置和工具 schema。写入方省略 `tools: []` 与 `adapterDefaults: {}`;当前接纳拒绝这些字段以及任何 `header.system`,而不修复它们。仅含空白的系统消息内容、`config.stop: []` 与嵌套扩展保持原样。[V3 规范信封决策](2026-09-06-v3-canonical-session-envelopes.zh.md)负责历史转换。渲染后的系统提示词是派生历史——surface 第 0 号节点上的 `system/message` 事件,见[surface 节点 Agent Note](2026-09-02-system-prompt-as-surface-node.zh.md)——因此提示词变更是 surface 替换而不是 header 变更。适配器提供的推理强度与 token 默认值会保留其 `adapterDefaults` 来源信息;Web 从日志恢复模型选择时会省略适配器持有的推理强度,因此下一次解析不会把相同的有效配置重新归类为显式选择并产生虚假变更。`request/header` 始终写入完整快照:首个循环实例使用 reason `initial`,后续实例使用 `resume`,实例内变更使用 `change`,内容未变的封装显式开启消息序列或跟随表层替换时使用 `series`。如果发生变化的请求同时开启序列,`change` 快照会携带 `startsSeries: true`,无需重复 header 即可保留这两个独立事实。普通的仅追加后续 Turn、同一序列内后续的 Step 与重试沿用最新快照。`foldRequestHeader` 选择最新快照。旧的 `request/header-delta` 事件和已移除的 `fallback` reason 在追加或加载时都会被拒绝。 -每个拟议步骤先领取其 inbox 批次,在 `agent/step-boundary` 提交待生效的选择,由 `agent/model` 选定该步骤的提供方、模型与推理强度并发布为 `agent.step`,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,解析该步骤的工具并组装系统提示词与运行时上下文,把变化的提示词作为 `system/message` 追加或第 0 号节点替换提交,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。`agent/request` 只能替换冻结调用配置中的采样控制参数;提供方、模型与推理强度保持为步骤的模型选择。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息(系统消息在先)与该不含 `system` 字段的 header 构建 `GenerateOptions`,冻结请求但保持 `AbortSignal` 活跃。[请求冻结证据说明](../../../../packages/core/agent-loop/README.zh.md)拥有消息完整冻结的复用规则和每次请求的本地 header 冻结规则。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 +每个拟议步骤先领取其 inbox 批次,由 `agent/model` 选定该步骤的提供方、模型与推理强度并发布为 `agent.step`,再运行 `agent/pre-step`。reject 不打开步骤;enter 打开 `step/start`,解析该步骤的工具并组装系统提示词与运行时上下文,把变化的提示词作为 `system/message` 追加或第 0 号节点替换提交,把最终消息批次记录为 `user/message` 事件,并可使用 `startsRequestSeries: true` 声明独立序列。`agent/request` 只能替换冻结调用配置中的采样控制参数;提供方、模型与推理强度保持为步骤的模型选择。循环记录所需的 initial、resume、change 或 series 完整快照,从派生消息(系统消息在先)与该不含 `system` 字段的 header 构建 `GenerateOptions`,冻结请求但保持 `AbortSignal` 活跃。[请求冻结证据说明](../../../../packages/core/agent-loop/README.zh.md)拥有消息完整冻结的复用规则和每次请求的本地 header 冻结规则。首次调用配置从显式的 `AgentOptions` 出发,保留 fork 覆盖和恢复重配置;后续调用从折叠后的 header 出发。 **已打开步骤是重建边界。** 进入步骤的 `user/message` 批次与任何新写入的 `request/header` 都位于请求分派之前。原子领取后发生的注入加入后续请求;必须影响本次请求的监听器则通过 `agent/pre-step` 返回消息。header 重建选择该步骤的 `request/header`,或在无新 header 写入时沿用前一个快照。 diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml index e1477a5f0e..3d7df5784c 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.i18n.yaml @@ -18,8 +18,8 @@ en: a217a08932938062 zh: 4924d99d55d9c973 /agent-note-the-system-prompt-is-surface-node-0/decision/ownership-in-the-loop: - en: ca45857bcd9424eb - zh: 37247c6966423dcb + en: 6f06b79f993395ab + zh: b230ed5542a9524e /agent-note-the-system-prompt-is-surface-node-0/decision/consumers: en: 39f9f4acffcccdc6 zh: 36b23a57e7d28950 diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md index 6c61cbfcb4..ef8dc973c8 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md @@ -36,7 +36,7 @@ When the initial rendered prompt is empty, the loop reserves an empty system hea `dsh-agent-loop` owns `SystemPromptProjection` beside `RuntimeContextProjection` in `packages/core/agent-loop/src/runtime-context.ts`. It reads the surviving `system/message` nodes from the current surface on every projection, so a compaction or replacement that ran earlier in the same step is already reflected. `project(rendered, { inHistory, startsSeries })` returns `{ message, intent }` — `intent` is `{ surfaceOp: 'append' }` when no system node survives or when the [in-history rule](../feature/2026-09-02-in-history-system-prompt-replacement.md) applies, otherwise a replacement of exactly the latest surviving system node — or `undefined` when the latest node already holds the rendered text. -In `packages/core/agent-loop/src/agent.ts`, `step()` renders the prompt with `renderPrompt(assembly)` after `step/start` and projects it on each attempt after `agent/request` and `prepareCall()`, so a compaction provider's replacement inside `agent/pre-step` or retry recovery is visible to reconciliation; the `system/message` is committed before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `agent/step-boundary` → `agent/model` waterfall (published as `agent.step`) → `agent/pre-step` waterfall → `step/start` → resolve tools → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → commit `system/message` (when changed) → commit `user/message`s and a changed runtime-context snapshot → `request/header` → `request/context` → stream. +In `packages/core/agent-loop/src/agent.ts`, `step()` renders the prompt with `renderPrompt(assembly)` after `step/start` and projects it on each attempt after `agent/request` and `prepareCall()`, so a compaction provider's replacement inside `agent/pre-step` or retry recovery is visible to reconciliation; the `system/message` is committed before the step's `user/message` events, so log order is wire order. `buildRequest` sets no `system` on the request: the request is `header.config`, `session.deriveMessages()` (system message first), and `header.tools`. The loop step order is: claim inbox → `agent/model` waterfall (published as `agent.step`) → `agent/pre-step` waterfall → `step/start` → resolve tools → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → commit `system/message` (when changed) → commit `user/message`s and a changed runtime-context snapshot → `request/header` → `request/context` → stream. `dsh-token-meter` anchors usage to the priced surface immediately before the successful `assistant/message`, not to `step/start`. The loop admits the system prompt and user messages after step start, and retry recovery can replace nodes before rebuilding the request. Capturing that current surface includes every admitted input once; the embedded provider output remains separately priced so durable assistant rewrites retain their signed delta. The open step stores only turn and step for lifecycle validation, not a second node snapshot. diff --git a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md index 9bfb9df062..9e4463f21f 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md @@ -36,7 +36,7 @@ Status: implemented `dsh-agent-loop` 在 `packages/core/agent-loop/src/runtime-context.ts` 中与 `RuntimeContextProjection` 并列拥有 `SystemPromptProjection`。它在每次投影时从当前 surface 读取存活的 `system/message` 节点,因此同一步骤中更早运行的压缩或替换已经反映在内。`project(rendered, { inHistory, startsSeries })` 返回 `{ message, intent }`——没有系统节点存活或[历史内规则](../feature/2026-09-02-in-history-system-prompt-replacement.zh.md)适用时 `intent` 为 `{ surfaceOp: 'append' }`,否则是对最新存活系统节点的精确替换——最新节点已持有渲染文本时返回 `undefined`。 -在 `packages/core/agent-loop/src/agent.ts` 中,`step()` 在 `step/start` 之后用 `renderPrompt(assembly)` 渲染提示词,并在每次尝试的 `agent/request` 与 `prepareCall()` 之后投影它,因此压缩提供者在 `agent/pre-step` 内或重试恢复中做出的替换对协调可见;`system/message` 在该步骤的 `user/message` 事件之前提交,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `agent/step-boundary` → `agent/model` waterfall(发布为 `agent.step`) → `agent/pre-step` waterfall → `step/start` → 解析工具 → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → 提交 `system/message`(有变化时) → 提交各条 `user/message` 与变化后的运行时上下文快照 → `request/header` → `request/context` → 流式请求。 +在 `packages/core/agent-loop/src/agent.ts` 中,`step()` 在 `step/start` 之后用 `renderPrompt(assembly)` 渲染提示词,并在每次尝试的 `agent/request` 与 `prepareCall()` 之后投影它,因此压缩提供者在 `agent/pre-step` 内或重试恢复中做出的替换对协调可见;`system/message` 在该步骤的 `user/message` 事件之前提交,因此日志顺序即协议顺序。`buildRequest` 不在请求上设置 `system`:请求由 `header.config`、`session.deriveMessages()`(系统消息在先)和 `header.tools` 构成。循环步骤顺序为:领取收件箱 → `agent/model` waterfall(发布为 `agent.step`) → `agent/pre-step` waterfall → `step/start` → 解析工具 → `systemPrompt.assemble()` → `agent/request` waterfall → `prepareCall()` → 提交 `system/message`(有变化时) → 提交各条 `user/message` 与变化后的运行时上下文快照 → `request/header` → `request/context` → 流式请求。 `dsh-token-meter` 把用量锚定到成功的 `assistant/message` 之前的已计价 surface,而不是 `step/start`。循环在步骤开始之后接纳系统提示词与用户消息,重试恢复还可能在重建请求之前替换节点。捕获当前 surface 会让每个已接纳输入恰好计入一次;内嵌的提供方输出仍单独计价,因此持久 assistant 改写保留其带符号增量。开放步骤只保存 turn 与 step 以验证生命周期,不保存第二份节点快照。 diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml index 829d4efb0f..6536aee525 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.i18n.yaml @@ -6,17 +6,17 @@ en: f068fddb192978d2 zh: 601deb72d3d90263 /agent-note-choose-the-step-model-before-step-preparation/problem: - en: 1c3fbc5343be9e19 - zh: ee1c1c032074f2b6 + en: 76b8e8b0ba541f6d + zh: 194e32829bd3e657 /agent-note-choose-the-step-model-before-step-preparation/decision: - en: 5c62c30a1810dcf8 - zh: 5146e199e13b2dfb + en: 91a676883a36d9b1 + zh: 88f909ccf8aba339 /agent-note-choose-the-step-model-before-step-preparation/alternatives-considered: - en: e69897cbb8e51ea2 - zh: c71acdfffb7d0d60 + en: a816838268f22542 + zh: 5b455d2625372180 /agent-note-choose-the-step-model-before-step-preparation/consequences: - en: bf8a702bc7559c51 - zh: e81657ff8566e16b + en: afb5ec9f53a906d3 + zh: cb38d5d9b5736f25 /agent-note-choose-the-step-model-before-step-preparation/related: en: 00ef1147a7852c0a zh: 4bd89960e08b6eda diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md index 1c7f236cbe..41e9b59c4b 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.md @@ -6,13 +6,13 @@ English | [中文](2026-10-12-step-model-chosen-before-preparation.zh.md) ## Problem -Tool availability can depend on the route of the request that declares the tools: `web_search` must stay off routes without search credentials, and plan or team state can withhold other tools. Message preparation needs the same model: session references size snapshots by the model's context window, and model selection announces a switch. The loop assembled tools and prompt sections before `agent/pre-step` and decided the provider, model, and reasoning effort only in `agent/request` after `step/start`, so earlier consumers predicted them from model-selection state. A listener that replaced them in `agent/request`, including on a retry, made the assembled prompt and tool catalog describe another model. Plan state had the same problem: it was committed inside `agent/pre-step`, so plan guidance predicted it from the pending selection. +Tool availability can depend on the route of the request that declares the tools: `web_search` must stay off routes without search credentials, and plan or team state can withhold other tools. Message preparation needs the same model: session references size snapshots by the model's context window, and model selection announces a switch. The loop assembled tools and prompt sections before `agent/pre-step` and decided the provider, model, and reasoning effort only in `agent/request` after `step/start`, so earlier consumers predicted them from model-selection state. A listener that replaced them in `agent/request`, including on a retry, made the assembled prompt and tool catalog describe another model. Plan state had the same problem: it was committed inside `agent/pre-step` after the prompt was assembled, so plan guidance predicted it from the pending selection. ## Decision -The provider, model, and reasoning effort are a step fact, chosen together as the user chooses them before sending a message. After claiming input, the loop dispatches the serial `agent/step-boundary` event, where plugins commit selections that apply from this step, such as a pending plan-mode switch. It then dispatches `agent/model` once per proposed step. Its default comes from the agent options before this loop logs a request and from the logged header afterwards, with an effort only when one was chosen for that exact model; `installModelSelection` returns its current selection there. The loop publishes the result as `agent.step` and clears it when the step ends or its proposal is rejected, fails, or is cancelled. `agent/pre-step` listeners, tool conditions, prompt sections, and the `{{provider}}` and `{{model}}` variables read the selection from the agent. +The provider, model, and reasoning effort are a step fact, chosen together as the user chooses them before sending a message. After claiming input, the loop dispatches `agent/model` once per proposed step. Its default comes from the agent options before this loop logs a request and from the logged header afterwards, with an effort only when one was chosen for that exact model; `installModelSelection` returns its current selection there. The loop publishes the result as `agent.step` and clears it when the step ends or its proposal is rejected, fails, or is cancelled. `agent/pre-step` listeners, tool conditions, prompt sections, and the `{{provider}}` and `{{model}}` variables read the selection from the agent. -After `agent/pre-step` accepts the step and `step/start` opens it, the loop resolves conditional tools and assembles the prompt once: sections, variables, runtime context, and tool declarations. The runtime-context snapshot is admitted after the step's accepted messages. Each request attempt then runs `agent/request` and `prepareCall()` immediately before admission. `agent/request` may change sampling controls; a result with another provider, model, or reasoning effort fails the step. Retries reuse the step's model selection, tool set, and rendered assembly, and the step-owned tool set closes after the step's tool batch settles. A selection made during a step applies from the next step. +Plan mode commits a pending selection inside `agent/pre-step` after the step is accepted. After `step/start` opens the step, the loop resolves conditional tools and assembles the prompt once, so tool conditions and plan guidance read the committed plan state. The assembly contains sections, variables, runtime context, and tool declarations. The runtime-context snapshot is admitted after the step's accepted messages. Each request attempt then runs `agent/request` and `prepareCall()` immediately before admission. `agent/request` may change sampling controls; a result with another provider, model, or reasoning effort fails the step. Retries reuse the step's model selection, tool set, and rendered assembly, and the step-owned tool set closes after the step's tool batch settles. A model selection made during a step applies from the next step. ## Alternatives considered @@ -23,7 +23,7 @@ After `agent/pre-step` accepts the step and `step/start` opens it, the loop reso - **Keep the decision in `agent/request` and predict it for earlier consumers.** A prediction diverges whenever a listener other than model selection changes the model. - **Choose only the provider and model per step and leave reasoning effort to `agent/request`.** An effort is valid only for the model it was chosen for. The split required `installModelSelection` to capture the selection in one waterfall and apply its effort in another only when no other listener had replaced the model, and it let a retry change effort within a step. - **Prepare runtime context before `agent/pre-step` in a separate `system-prompt/prepare` phase.** It kept the runtime context between the claimed input and messages added by pre-step listeners, but split assembly into two hooks and made a changed runtime context alone open a step. -- **Commit pending plan selections inside `agent/pre-step`.** Phases and listeners that ran before the commit saw the previous plan state, and model choice could not depend on plan mode. +- **Commit pending plan selections in a separate step-boundary event before `agent/model`.** Model choice could then read the new plan state, but no `agent/model` listener depends on plan mode, and the event would commit selections for steps that `agent/pre-step` rejects. `agent/pre-step` already runs before tool resolution and prompt assembly. ## Consequences @@ -31,8 +31,7 @@ After `agent/pre-step` accepts the step and `step/start` opens it, the loop reso - `prepareCall()` stays adjacent to dispatch, so its adapter registration and connection snapshot cover only header logging and streaming. - A step cannot fail over to another provider or change reasoning effort on retry; a policy that needs this must run model selection, tool resolution, and assembly again for the retried attempt. - `agent.step` is undefined between steps and during `agent/model`; work that outlives its step reads it at its start. -- `agent/model` listeners can read plan state because the boundary commits it first, but model choice still cannot depend on `agent/pre-step` outcomes. -- A pending plan-mode selection is committed even when `agent/pre-step` rejects the step; its notice joins the next admitted step. +- `agent/model` runs before plan mode commits a pending selection in `agent/pre-step`, so a plan selection made during a turn reaches model choice one step after it reaches tools and guidance. Model choice cannot depend on `agent/pre-step` outcomes. - The runtime-context snapshot follows the step's accepted messages, and a changed runtime context alone does not open a step. ## Related diff --git a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md index e5ea4da203..4499a7338d 100644 --- a/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-12-step-model-chosen-before-preparation.zh.md @@ -6,13 +6,13 @@ Status: implemented ## 问题 -工具是否可用可能取决于声明这些工具的请求所用的路由:`web_search` 不得出现在没有搜索凭据的路由上,计划或团队状态也可能撤下其他工具。消息准备同样需要这一模型:会话引用按模型的上下文窗口确定快照大小,模型选择会通告模型切换。循环原先在 `agent/pre-step` 之前组装工具与提示词段落,直到 `step/start` 之后才在 `agent/request` 中决定提供方、模型与推理强度,因此更早的消费方只能依据模型选择状态预测它们。若监听器在 `agent/request` 中(包括在重试时)替换它们,已组装的提示词与工具目录就会描述另一个模型。计划状态也有同样的问题:它在 `agent/pre-step` 内提交,计划指引只能依据待提交的选择预测。 +工具是否可用可能取决于声明这些工具的请求所用的路由:`web_search` 不得出现在没有搜索凭据的路由上,计划或团队状态也可能撤下其他工具。消息准备同样需要这一模型:会话引用按模型的上下文窗口确定快照大小,模型选择会通告模型切换。循环原先在 `agent/pre-step` 之前组装工具与提示词段落,直到 `step/start` 之后才在 `agent/request` 中决定提供方、模型与推理强度,因此更早的消费方只能依据模型选择状态预测它们。若监听器在 `agent/request` 中(包括在重试时)替换它们,已组装的提示词与工具目录就会描述另一个模型。计划状态也有同样的问题:它在提示词组装之后才于 `agent/pre-step` 内提交,计划指引只能依据待提交的选择预测。 ## 决策 -提供方、模型与推理强度是步骤级事实,像用户在发送消息前那样一起选定。领取输入之后,循环派发串行事件 `agent/step-boundary`,插件在此提交从本步骤起生效的选择,例如待提交的计划模式切换。随后循环为每个拟议步骤派发一次 `agent/model`。其默认值在本循环记录请求之前取自 agent 选项,之后取自已记录的请求头,且只有为该确切模型选定过的推理强度才会保留;`installModelSelection` 在这里返回其当前选择。循环把结果发布为 `agent.step`,并在步骤结束或提案被拒绝、失败、取消时清除。`agent/pre-step` 监听器、工具条件、提示词段落以及 `{{provider}}` 与 `{{model}}` 变量都从 agent 读取该选择。 +提供方、模型与推理强度是步骤级事实,像用户在发送消息前那样一起选定。领取输入之后,循环为每个拟议步骤派发一次 `agent/model`。其默认值在本循环记录请求之前取自 agent 选项,之后取自已记录的请求头,且只有为该确切模型选定过的推理强度才会保留;`installModelSelection` 在这里返回其当前选择。循环把结果发布为 `agent.step`,并在步骤结束或提案被拒绝、失败、取消时清除。`agent/pre-step` 监听器、工具条件、提示词段落以及 `{{provider}}` 与 `{{model}}` 变量都从 agent 读取该选择。 -`agent/pre-step` 接纳步骤且 `step/start` 打开步骤之后,循环解析条件工具并一次性组装提示词:段落、变量、运行时上下文与工具声明。运行时上下文快照在该步骤已接纳的消息之后提交。之后每次请求尝试都在准入之前紧接着运行 `agent/request` 与 `prepareCall()`。`agent/request` 可以修改采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。重试复用该步骤的模型选择、工具集合与已渲染组装结果,步骤拥有的工具集合在该步骤的工具批次结束后关闭。步骤进行中做出的选择从下一个步骤开始生效。 +计划模式在 `agent/pre-step` 接纳步骤后提交待生效的选择。`step/start` 打开步骤之后,循环解析条件工具并一次性组装提示词,因此工具条件与计划指引读取的是已提交的计划状态。组装内容包括段落、变量、运行时上下文与工具声明。运行时上下文快照在该步骤已接纳的消息之后提交。之后每次请求尝试都在准入之前紧接着运行 `agent/request` 与 `prepareCall()`。`agent/request` 可以修改采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。重试复用该步骤的模型选择、工具集合与已渲染组装结果,步骤拥有的工具集合在该步骤的工具批次结束后关闭。步骤进行中做出的模型选择从下一个步骤开始生效。 ## 考虑过的替代方案 @@ -23,7 +23,7 @@ Status: implemented - **决定留在 `agent/request`,为更早的消费方预测它。** 只要模型选择之外的监听器修改模型,预测就会偏离。 - **每个步骤只选定提供方与模型,推理强度留给 `agent/request`。** 推理强度只对选定它的模型有效。拆开后,`installModelSelection` 必须在一个 waterfall 中捕获选择,再在另一个 waterfall 中、且仅当其他监听器没有替换模型时应用推理强度;重试也可以在步骤内修改推理强度。 - **在 `agent/pre-step` 之前用单独的 `system-prompt/prepare` 阶段准备运行时上下文。** 它把运行时上下文保留在已领取输入与 pre-step 监听器追加的消息之间,但把组装拆成了两个钩子,并让仅运行时上下文变化就能打开一个步骤。 -- **在 `agent/pre-step` 内提交待生效的计划选择。** 提交之前运行的阶段和监听器看到的是旧的计划状态,模型选择也无法依据计划模式。 +- **在 `agent/model` 之前用单独的步骤边界事件提交待生效的计划选择。** 这样模型选择可以读到新的计划状态,但目前没有 `agent/model` 监听器依赖计划模式,而且该事件会为被 `agent/pre-step` 拒绝的步骤提交选择。`agent/pre-step` 本身已在工具解析与提示词组装之前运行。 ## 后果 @@ -31,8 +31,7 @@ Status: implemented - `prepareCall()` 紧邻分发,因此其适配器注册与连接快照只覆盖请求头记录与流式请求。 - 步骤无法在重试时切换到其他提供方或修改推理强度;需要这种能力的策略必须为重试的尝试重新执行模型选择、工具解析与组装。 - `agent.step` 在两个步骤之间以及 `agent/model` 期间为 undefined;跨步骤运行的工作要在开始时读取它。 -- `agent/model` 监听器可以读取计划状态,因为步骤边界会先提交它;但模型选择仍不能依赖 `agent/pre-step` 的结果。 -- 即使 `agent/pre-step` 拒绝了该步骤,待生效的计划模式选择也已提交;其通告会出现在下一个被接纳的步骤中。 +- `agent/model` 在计划模式于 `agent/pre-step` 中提交待生效选择之前运行,因此轮次内做出的计划选择比工具与指引晚一个步骤才影响模型选择。模型选择不能依赖 `agent/pre-step` 的结果。 - 运行时上下文快照位于该步骤已接纳的消息之后,仅运行时上下文变化不会打开步骤。 ## 相关 diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index c91c486556..aca110adf0 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -25,7 +25,6 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/step-boundary serial commits selections pending for this step Driver->>Hooks: agent/model waterfall chooses provider, model, and effort, published as agent.step Driver->>Hooks: agent/pre-step waterfall reads agent.step Hooks-->>Driver: authoritative reject or enter(messages) @@ -75,7 +74,6 @@ sequenceDiagram opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/step-boundary serial Driver->>Hooks: agent/model waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) diff --git a/docs/agent-lifecycle.zh.md b/docs/agent-lifecycle.zh.md index 4172d114eb..07a1388e03 100644 --- a/docs/agent-lifecycle.zh.md +++ b/docs/agent-lifecycle.zh.md @@ -27,7 +27,6 @@ sequenceDiagram Note over Agent,Driver: claim pending next-step input plus one queued prompt Driver-->>SDK: agent/inbox/spliced pure deletion Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/step-boundary serial commits selections pending for this step Driver->>Hooks: agent/model waterfall chooses provider, model, and effort, published as agent.step Driver->>Hooks: agent/pre-step waterfall reads agent.step Hooks-->>Driver: authoritative reject or enter(messages) @@ -77,7 +76,6 @@ sequenceDiagram opt next-step input is pending Driver-->>Driver: claim pending next-step input Driver-->>SDK: agent/inbox/claimed { message, turn } per message - Driver->>Hooks: agent/step-boundary serial Driver->>Hooks: agent/model waterfall Driver->>Hooks: agent/pre-step waterfall Hooks-->>Driver: authoritative reject or enter(messages) diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 8091ef489e..030263c4e5 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -24,8 +24,8 @@ en: e89802f066e4955d zh: ea2fb4bef94e086d /deepseek-harness-architecture/turn-flow: - en: 0f496f867565ac9b - zh: 1c015bb06ce0a4b4 + en: c066f07d30c23310 + zh: aa9fe174dda824c9 /deepseek-harness-architecture/session-log: en: a2e35c43438fec6d zh: e27bdac8e9feff32 diff --git a/docs/architecture.md b/docs/architecture.md index f5ad4e118c..b4b1fde0ef 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -83,7 +83,6 @@ A **step** is one model request plus the tools it calls. A **turn** is zero or m ```text turn/start claim next-step input plus one queued message - agent/step-boundary -> commit pending selections agent/model -> agent.step (provider/model/effort) -> agent/pre-step reject | enter(messages, startsRequestSeries?) @@ -109,7 +108,7 @@ turn/end One inbox feeds the driver; injected context waits for a waking message. AgentLoop’s durable `inbox` projection exposes pending input without live Agents. -`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/step-boundary` commits pending selections, then `agent/model` publishes `agent.step` (provider, model, effort) before `agent/pre-step`; accepted steps resolve tools and assemble once. Each attempt's `agent/request` may change only sampling, and `prepareCall()` binds the adapter before prompt and user admission; cancellation in either commits neither. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming; retries reuse the selection, tools, and assembly. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). +`agent/pre-step` decides the accepted input. Listeners may rewrite or reject claimed messages; a rejected or empty first claim closes a durable turn without a step. An enter decision may set `startsRequestSeries`: the loop logs a fresh `request/header` (reason `series`, or `change` with `startsSeries: true` when the envelope also changed). Wrapping listeners preserve that declaration with `{ ...decision, messages }`. `agent/model` publishes `agent.step` (provider, model, effort) before `agent/pre-step`; accepted steps resolve tools and assemble once. Each attempt's `agent/request` may change only sampling, and `prepareCall()` binds the adapter before prompt and user admission; cancellation in either commits neither. Prepared call capabilities govern prompt admission, not preceding `request/context`. Each attempt refreshes runtime facts, reconciles the prompt, admits users once, restores removed context, logs headers, and freezes the request before streaming; retries reuse the selection, tools, and assembly. Surface replacements and image-offload decisions after attachment start a new request series, including during the first resumed pre-step; unchanged resume continues the series. The first admitted step reserves the system head before user messages even for an empty prompt (no wire message). The prompt travels only as `system/message` history: an empty rendering clears all active system nodes, leaving no old prompt model-visible; capable routes append non-empty updates after cached history, including supported tool updates; incapable routes and new request series consolidate non-empty prompt text at the first system node, with logged empty replacements for non-empty later system nodes ([decision](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.md); [decision rule](../packages/core/agent-loop/README.md#understand-the-implementation)). The loop sends immutable requests with live cancellation and reuses freeze evidence for frozen identities; [agent-loop](../packages/core/agent-loop/README.md) owns construction and cancellation causes. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index c66ed3b344..17998215b2 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -87,7 +87,6 @@ AgentLoop 在启动已排队工作前等待串行 `agent/created`,初始化失 ```text turn/start claim next-step input plus one queued message - agent/step-boundary -> commit pending selections agent/model -> agent.step (provider/model/effort) -> agent/pre-step reject | enter(messages, startsRequestSeries?) @@ -113,7 +112,7 @@ turn/end 输入通过同一个 inbox 到达驱动器;注入的上下文等待一条唤醒消息。AgentLoop 的持久 `inbox` 投影使待处理输入在没有活跃 Agent 时仍可读取。 -`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。`agent/step-boundary` 提交待生效的选择,随后 `agent/model` 在 `agent/pre-step` 之前发布 `agent.step`(提供方、模型、推理强度);被接纳的步骤随后解析工具并组装一次。每次尝试的 `agent/request` 只能修改采样控制参数,`prepareCall()` 在提示词与用户消息准入前绑定适配器;在任一阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求;重试复用模型选择、工具与组装结果。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 +`agent/pre-step` 决定接纳的输入。监听器可以改写或拒绝已领取消息;首次领取被拒绝或为空时,关闭不含步骤的持久轮次。enter 决策可设置 `startsRequestSeries`:循环记录新的 `request/header`(原因为 `series`,或在封装同时变化时为携带 `startsSeries: true` 的 `change`)。包装监听器通过 `{ ...decision, messages }` 保留该声明。`agent/model` 在 `agent/pre-step` 之前发布 `agent.step`(提供方、模型、推理强度);被接纳的步骤随后解析工具并组装一次。每次尝试的 `agent/request` 只能修改采样控制参数,`prepareCall()` 在提示词与用户消息准入前绑定适配器;在任一阶段取消都不会提交这两者。提示词准入依据已准备调用的能力,而非先前的 `request/context`。每次尝试刷新已注册运行时事实、协调绑定的提示词、仅接纳一次用户消息并恢复被移除的运行时上下文、按需记录 header/context,再冻结请求并通过绑定调用发起流式请求;重试复用模型选择、工具与组装结果。附接后的 surface 替换和图片省略决定开启新请求序列,包括恢复后的首次 pre-step 中发生的替换;未变化的恢复延续序列。首次接纳的步骤在用户消息之前预留系统头节点,即使提示词为空(不产生协议消息)。提示词仅通过 `system/message` 历史传递:空渲染文本清除所有生效的系统节点,模型不再看到旧提示词;具备能力的路由可在缓存前缀之后追加非空更新,包括同时发生的受支持工具更新;不具备能力的路由与新请求序列将非空提示词文本归并到首个系统节点,并为非空的后续系统节点记录空内容替换([决策](../.agents/notes/implemented/architecture/2026-09-02-system-prompt-as-surface-node.zh.md);[决策规则](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 循环发送不可变请求,同时保持取消有效,仅对完全冻结的对象复用冻结证据;[agent-loop](../packages/core/agent-loop/README.zh.md) 负责请求构建与取消原因。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index b55e7d753f..be25e67153 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2387,7 +2387,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` -- `source`: [`packages/plan/plan-mode/src/index.ts:68`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 826bf7230e..45a2537c3c 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2389,7 +2389,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` -- `source`: [`packages/plan/plan-mode/src/index.ts:68`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 18eb0fdfc5..5eaab66c78 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -10,20 +10,19 @@ 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:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:426`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:411`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:284`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:293`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:456`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../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), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:330`](../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), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../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/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:379`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:364`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:344`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:416`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:385`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:401`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:303`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/step-boundary` | `serial` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`plan-mode`](../packages/plan/plan-mode) | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:444`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../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 9d6c5c669a..2cf84822b4 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -12,20 +12,19 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:426`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:411`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:284`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`loader-smoke`](../packages/test-support/loader-smoke), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:293`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:456`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../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), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:330`](../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), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../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/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:379`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | +| `agent/model` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:364`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/experimental/webhook) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:344`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/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-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:416`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:385`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:401`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:303`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/step-boundary` | `serial` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`plan-mode`](../packages/plan/plan-mode) | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:444`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../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 7ffe6db4e7..2f2d8d8936 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -153,8 +153,8 @@ en: 4294f78d26ed985b zh: 4294f78d26ed985b /session-persistence-event-catalog/events/plan/plan-mode-log-only: - en: 862175bfe8692ef7 - zh: a8ab123bf674cf77 + en: f23bf0e5e6408adf + zh: a9442b4c5cdeef0b /session-persistence-event-catalog/events/request: en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 @@ -1389,8 +1389,8 @@ en: a74e3dfa51c987af zh: 6c3c87974d7a7260 /session-persistence-event-catalog/resolved-persistence-types/active~2: - en: a3de6a6fe9672c7a - zh: a357481e27b3b81f + en: 1bc41f689438a051 + zh: babdc92cc0ad089a /session-persistence-event-catalog/resolved-persistence-types/agentpreset: en: 1afbe8196f161601 zh: a320a36a8928817c diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 715ce47d52..641caffc22 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -735,7 +735,7 @@ Source: [`packages/interaction/permission-presets/src/index.ts:59`](../packages/ 'plan/mode': { active: boolean } ``` -Source: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +Source: [`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -5737,7 +5737,7 @@ Array of `unknown` (opaque). SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -Sources: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +Sources: [`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 7f40e2dbfe..673625214c 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -737,7 +737,7 @@ export type SessionEvent = { 'plan/mode': { active: boolean } ``` -来源:[`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -5739,7 +5739,7 @@ SHA-256: `b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7` SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -来源:[`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:51`](../packages/plan/plan-mode/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 146ca1bdfa..10a36107f4 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -22809,7 +22809,7 @@ "digest": "20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5", "names": [], "sources": [ - "packages/plan/plan-mode/src/index.ts:52" + "packages/plan/plan-mode/src/index.ts:51" ] }, { diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 6adb8ce35e..5b01a083b8 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -958,7 +958,7 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/model` — waterfall -Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, after `agent/step-boundary` and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step. +Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, after claiming its input and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step. ```ts cordis-catalog /** @@ -969,7 +969,7 @@ Choose the provider, model, and reasoning effort for one proposed step. `await n * replacement to switch; an effort belongs to its model, so a replacement * that changes the model names that model's effort or omits it for the * provider default. The loop runs this once per proposed step, after - * `agent/step-boundary` and before `agent/pre-step`, then publishes the + * claiming its input and before `agent/pre-step`, then publishes the * result as `agent.step`. Pre-step listeners, tool conditions, prompt * assembly, and every request attempt in the step use it, so a later * choice applies from the next step. Cancellation here opens no step. @@ -1099,34 +1099,6 @@ Types: [Scoped](scope.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - - -#### `agent/step-boundary` — serial - -A proposed step reached its boundary: the loop claimed its input and is about to choose its model. Listeners commit selections that take effect from this step, such as a pending plan-mode switch, so `agent/model`, `agent/pre-step`, tool conditions, and prompt assembly read one state. Runs once per proposed step; a throw fails the proposal, and cancellation opens no step. - -```ts cordis-catalog -/** - * A proposed step reached its boundary: the loop claimed its input and is - * about to choose its model. Listeners commit selections that take effect - * from this step, such as a pending plan-mode switch, so `agent/model`, - * `agent/pre-step`, tool conditions, and prompt assembly read one state. - * Runs once per proposed step; a throw fails the proposal, and - * cancellation opens no step. - * @param payload.agent - the agent proposing the step. - * @param payload.turn - the turn that will own the step. - * @param payload.step - the step proposed by the loop. - * @param payload.signal - the current turn's explicit abort signal. - * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. - * @mode serial - */ -'agent/step-boundary'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }): Promise | void -``` - -Types: [Scoped](scope.md) - -Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - #### `agent/turn-stopping` — serial diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index e090274546..72617066c9 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -970,7 +970,7 @@ Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/s #### `agent/model` — waterfall -Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, after `agent/step-boundary` and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step. +Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model's effort or omits it for the provider default. The loop runs this once per proposed step, after claiming its input and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step. ```ts cordis-catalog /** @@ -981,7 +981,7 @@ Choose the provider, model, and reasoning effort for one proposed step. `await n * replacement to switch; an effort belongs to its model, so a replacement * that changes the model names that model's effort or omits it for the * provider default. The loop runs this once per proposed step, after - * `agent/step-boundary` and before `agent/pre-step`, then publishes the + * claiming its input and before `agent/pre-step`, then publishes the * result as `agent.step`. Pre-step listeners, tool conditions, prompt * assembly, and every request attempt in the step use it, so a later * choice applies from the next step. Cancellation here opens no step. @@ -1111,34 +1111,6 @@ Types: [Scoped](scope.zh.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - - -#### `agent/step-boundary` — serial - -A proposed step reached its boundary: the loop claimed its input and is about to choose its model. Listeners commit selections that take effect from this step, such as a pending plan-mode switch, so `agent/model`, `agent/pre-step`, tool conditions, and prompt assembly read one state. Runs once per proposed step; a throw fails the proposal, and cancellation opens no step. - -```ts cordis-catalog -/** - * A proposed step reached its boundary: the loop claimed its input and is - * about to choose its model. Listeners commit selections that take effect - * from this step, such as a pending plan-mode switch, so `agent/model`, - * `agent/pre-step`, tool conditions, and prompt assembly read one state. - * Runs once per proposed step; a throw fails the proposal, and - * cancellation opens no step. - * @param payload.agent - the agent proposing the step. - * @param payload.turn - the turn that will own the step. - * @param payload.step - the step proposed by the loop. - * @param payload.signal - the current turn's explicit abort signal. - * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. - * @mode serial - */ -'agent/step-boundary'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }): Promise | void -``` - -Types: [Scoped](scope.zh.md) - -Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - #### `agent/turn-stopping` — serial diff --git a/docs/subsystems/plan.i18n.yaml b/docs/subsystems/plan.i18n.yaml index 17f616e621..9e6681b800 100644 --- a/docs/subsystems/plan.i18n.yaml +++ b/docs/subsystems/plan.i18n.yaml @@ -8,15 +8,15 @@ /plan-mode/logged-state-and-recovery: en: dd1e8ba31e6fd535 zh: a22dbccc60c73bc9 -/plan-mode/pending-selections-and-the-step-boundary-append: - en: a62c24bf1e46c0ff - zh: bbe0ff492ee1be65 +/plan-mode/pending-selections-and-the-pre-step-append: + en: 4185f7aae9fa44aa + zh: 675e8318f0fbca4b /plan-mode/configuration: en: ee04468005fae8e1 zh: 1347d554102951f2 /plan-mode/the-exit-tool-and-the-plan-command: - en: 6739f69a1b71b495 - zh: a538adbe4c85b529 + en: d5b681e65d84d0e7 + zh: 9c3d5499d34df3bc /plan-mode/the-service: - en: c798c709c5cb6454 - zh: bac179e6fd51a98f + en: f3e6d5a7fe0b67f0 + zh: 774cc97e493991fa diff --git a/docs/subsystems/plan.md b/docs/subsystems/plan.md index d37cf01a7f..088c237d63 100644 --- a/docs/subsystems/plan.md +++ b/docs/subsystems/plan.md @@ -10,11 +10,11 @@ Source: [`packages/plan/plan-mode/src/index.ts`](../../packages/plan/plan-mode/s `plan/mode` (`{ active: boolean }`) is a log-only, whole-value-replace [session event](session.md): durable and replayable, never in the model transcript. The optionally registered `plan` unit folds committed mode, command settlement, and the mode recorded at the latest request header. `ctx.planMode` reads that state through `stateOf()`; the first dependent access fails if the registry, `plan` key, or `turnBoundary` key is absent. Clients receive only `{ active, pending }`; resume, fork, and compaction recover both from the log. The complete event declaration is in the [persistence log event catalog](../persistence-catalog.md). -## Pending selections and the step-boundary append +## Pending selections and the pre-step append -Because every session event is turn-enclosed, `set(agent, active)` appends a selection immediately only between turns. During an open turn the selection remains pending until the next step boundary appends it, in whichever turn that occurs. A selection never forces continuation, so one made after a turn's final step boundary is appended in a later turn. `set` is a no-op when the target equals the logged-or-already-pending state, and `get(agent)` returns `{ active: boolean; pending?: boolean }`: the logged state used by the current step plus the selected state waiting to be appended. +Because every session event is turn-enclosed, `set(agent, active)` appends a selection immediately only between turns. During an open turn the selection remains pending until the next accepted in-turn pre-step appends it, in whichever turn that occurs. A selection never forces continuation, so one made after a turn's final accepted pre-step is appended in a later turn. `set` is a no-op when the target equals the logged-or-already-pending state, and `get(agent)` returns `{ active: boolean; pending?: boolean }`: the logged state used by the current step plus the selected state waiting to be appended. -The only append point while an agent is running is an `agent/step-boundary` listener. It runs once for every proposed step, including turn 1 step 1, after the step claims its input and before `agent/model`, so model choice, `agent/pre-step`, tool conditions, and plan guidance read the committed state; same-step request-recovery retries do not run it. An append failure fails the proposal and keeps the selection pending for a later boundary. An appended user selection also records one plugin-sourced `user/message` notice in the first admitted step, but only when the last logged request header described the other state, so the model is told exactly when its context changed and never redundantly. A selection made after a turn's final step boundary remains process-local and is lost if the process exits before another boundary ([README limitation](../../packages/plan/plan-mode/README.md#known-limitations-and-deferred-work)). +The only append point while an agent is running is an `agent/pre-step` listener. It observes every proposed step, including turn 1 step 1, calls downstream listeners first, and appends only after they accept the step; a rejected proposal keeps the selection pending, and same-step request-recovery retries do not run it. Tool conditions and plan guidance are resolved after `step/start`, so they read the committed state; `agent/model` runs before `agent/pre-step` and sees a new selection from the following step. An append failure fails the proposal and keeps the selection pending for a later accepted in-turn pre-step. An appended user selection also records one plugin-sourced `user/message` notice, but only when the last logged request header described the other state, so the model is told exactly when its context changed and never redundantly. A selection made after a turn's final accepted pre-step remains process-local and is lost if the process exits before another accepted in-turn pre-step ([README limitation](../../packages/plan/plan-mode/README.md#known-limitations-and-deferred-work)). ## Configuration @@ -30,13 +30,13 @@ A missing, blank, or non-string `section` and any unknown key fail at plugin loa ## The exit tool and the `/plan` command -[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is admitted only while the committed plan state is active, so entering or leaving plan mode changes the request tool declarations and the plan guidance together; Native and PTC execution use the same admitted set, and a call outside plan mode returns `UNKNOWN_TOOL`. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next step boundary. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. +[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is admitted only while the committed plan state is active, so entering or leaving plan mode changes the request tool declarations and the plan guidance together; Native and PTC execution use the same admitted set, and a call outside plan mode returns `UNKNOWN_TOOL`. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. When [`ctx.commands`](commands.md) is composed, the plugin registers `/plan [off|message]`: bare `/plan` selects plan mode, any other non-empty message selects it and then submits the text through `agent.steer()` so it becomes the next step's ordinary logged user message under plan guidance, and the exact argument `off` selects inactive, which also cancels a pending entry before it is appended and becomes visible to a request. ## The service -`ctx.planMode` owns the logged plan state, applies selected state at the step boundary and narrates it in the admitted step, and owns the `plan:policy` section, the `/plan` command, and the conditional exit tool; `get`/`set` signatures are in the generated [service catalog](#ctxplanmode--planmodecontroller). +`ctx.planMode` owns the logged plan state, applies and narrates selected state at step start, and owns the `plan:policy` section, the `/plan` command, and the conditional exit tool; `get`/`set` signatures are in the generated [service catalog](#ctxplanmode--planmodecontroller). @@ -55,7 +55,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ```ts cordis-catalog /** * Read the logged plan state and any selected state awaiting the next - * step boundary. + * accepted in-turn pre-step. * * @param agent The agent to read. * @returns Current logged state plus a pending selection, when present. @@ -64,17 +64,17 @@ get(agent: Agent): { active: boolean; pending?: boolean } /** * Select whether plan mode should be active. Between turns the method - * appends the change immediately because no step boundary will run until + * appends the change immediately because no in-turn pre-step will run until * another prompt starts a turn. The open-turn fold is the idle signal: * agent status stays `running` through post-turn checkpointing, when no - * further step boundary runs. During an open turn the selection remains - * pending until the next step boundary. Repeated selection of the current - * or already-pending state is a no-op. + * further in-turn pre-step runs. During an open turn the selection remains + * pending until the next accepted in-turn pre-step. Repeated selection of + * the current or already-pending state is a no-op. * * @param agent The agent to switch. * @param active Whether plan mode should be active. * @returns what happened: `committed` (logged now), `queued` (awaiting the - * next step boundary), `cancelled` (an opposite pending selection + * next accepted in-turn pre-step), `cancelled` (an opposite pending selection * was cleared; the logged state already matches), or `noop` (already in that * state). */ diff --git a/docs/subsystems/plan.zh.md b/docs/subsystems/plan.zh.md index dd97ec0a0c..d59e78ae00 100644 --- a/docs/subsystems/plan.zh.md +++ b/docs/subsystems/plan.zh.md @@ -10,11 +10,11 @@ `plan/mode`(`{ active: boolean }`)是仅记日志、整值替换的[会话事件](session.zh.md):持久且可回放,绝不进入模型 transcript(文本记录)。可选注册的 `plan` 单元折叠已提交模式、命令结算结果和最近一次请求头记录的模式。`ctx.planMode` 通过 `stateOf()` 读取该状态;注册表、`plan` key 或 `turnBoundary` key 缺失时,第一次依赖它们的访问会失败。客户端只接收 `{ active, pending }`;恢复、fork 与压缩(compaction)都能从日志恢复两者。完整事件声明见[持久化日志事件目录](../persistence-catalog.zh.md)。 -## 待生效选择与步骤边界追加 +## 待生效选择与 pre-step 追加 -由于每个会话事件都位于轮次之内,`set(agent, active)` 只在轮次之间立即追加选择。轮次进行中,选择保持待生效状态,直到下一个步骤边界追加它,无论该边界位于哪个轮次。选择不会强制续行,因此在某轮最后一个步骤边界之后作出的选择会在之后的轮次追加。目标值与已记录或已在等待的状态相同时,`set` 不做任何事;`get(agent)` 返回 `{ active: boolean; pending?: boolean }`:当前步骤使用的已记录状态,以及等待追加的已选状态。 +由于每个会话事件都位于轮次之内,`set(agent, active)` 只在轮次之间立即追加选择。轮次进行中,选择保持待生效状态,直到下一个被接受的轮内 pre-step 追加它,无论该 pre-step 位于哪个轮次。选择不会强制续行,因此在某轮最后一个被接受的 pre-step 之后作出的选择会在之后的轮次追加。目标值与已记录或已在等待的状态相同时,`set` 不做任何事;`get(agent)` 返回 `{ active: boolean; pending?: boolean }`:当前步骤使用的已记录状态,以及等待追加的已选状态。 -agent 运行时,唯一的追加点是 `agent/step-boundary` 监听器。它对每个拟议步骤运行一次(包括第 1 轮第 1 步),时机在该步骤领取输入之后、`agent/model` 之前,因此模型选择、`agent/pre-step`、工具条件与计划指引读到的都是已提交状态;同一步骤内的请求恢复重试不会运行它。追加失败会使该提案失败,选择继续等待之后的步骤边界。追加用户选择时还会在第一个被接纳的步骤中记录一条插件来源的 `user/message` 通知,但仅当最后记录的请求头描述的是另一种状态时才记录,因此模型恰好在上下文变化时收到通知,且绝不重复。在某轮最后一个步骤边界之后作出的选择只存在于进程内;如果进程在下一个步骤边界之前退出,该选择会丢失([README 限制](../../packages/plan/plan-mode/README.zh.md#known-limitations-and-deferred-work))。 +agent 运行时,唯一的追加点是 `agent/pre-step` 监听器。它观察每个拟议步骤(包括第 1 轮第 1 步),先调用下游监听器,只在下游接受该步骤后追加;被拒绝的提案让选择继续等待,同一步骤内的请求恢复重试不会运行它。工具条件与计划指引在 `step/start` 之后解析,因此读到的是已提交状态;`agent/model` 在 `agent/pre-step` 之前运行,从下一个步骤起才看到新的选择。追加失败会使该提案失败,选择继续等待之后被接受的轮内 pre-step。追加用户选择时还会记录一条插件来源的 `user/message` 通知,但仅当最后记录的请求头描述的是另一种状态时才记录,因此模型恰好在上下文变化时收到通知,且绝不重复。在某轮最后一个被接受的 pre-step 之后作出的选择只存在于进程内;如果进程在另一个被接受的轮内 pre-step 之前退出,该选择会丢失([README 限制](../../packages/plan/plan-mode/README.zh.md#known-limitations-and-deferred-work))。 ## 配置 @@ -30,13 +30,13 @@ interface PlanModeConfig { ## 退出工具与 `/plan` 命令 -[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 只在已提交的计划状态处于激活时被准入,因此进入或离开计划模式会同时改变请求的工具声明与计划指引;原生与 PTC 执行使用同一准入集合,在计划模式之外调用会返回 `UNKNOWN_TOOL`。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个步骤边界追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 +[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 只在已提交的计划状态处于激活时被准入,因此进入或离开计划模式会同时改变请求的工具声明与计划指引;原生与 PTC 执行使用同一准入集合,在计划模式之外调用会返回 `UNKNOWN_TOOL`。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 当 [`ctx.commands`](commands.zh.md) 被组合时,插件注册 `/plan [off|message]`:单独的 `/plan` 选择计划模式;任何其他非空消息先选择计划模式,再通过 `agent.steer()` 提交该文本,使其在计划指引下成为下一步骤的普通已记录用户消息;确切参数 `off` 选择未激活,这还会在待生效条目被追加并对请求可见之前将其取消。 ## 服务 -`ctx.planMode` 拥有已记录的计划状态,在步骤边界应用选中的状态并在被接纳的步骤中叙述,还拥有 `plan:policy` 段落、`/plan` 命令和按条件准入的退出工具;`get`/`set` 签名见生成的[服务目录](#ctxplanmode--planmodecontroller)。 +`ctx.planMode` 拥有已记录的计划状态,在步骤开始时应用并叙述选中的状态,还拥有 `plan:policy` 段落、`/plan` 命令和按条件准入的退出工具;`get`/`set` 签名见生成的[服务目录](#ctxplanmode--planmodecontroller)。 @@ -55,7 +55,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ```ts cordis-catalog /** * Read the logged plan state and any selected state awaiting the next - * step boundary. + * accepted in-turn pre-step. * * @param agent The agent to read. * @returns Current logged state plus a pending selection, when present. @@ -64,17 +64,17 @@ get(agent: Agent): { active: boolean; pending?: boolean } /** * Select whether plan mode should be active. Between turns the method - * appends the change immediately because no step boundary will run until + * appends the change immediately because no in-turn pre-step will run until * another prompt starts a turn. The open-turn fold is the idle signal: * agent status stays `running` through post-turn checkpointing, when no - * further step boundary runs. During an open turn the selection remains - * pending until the next step boundary. Repeated selection of the current - * or already-pending state is a no-op. + * further in-turn pre-step runs. During an open turn the selection remains + * pending until the next accepted in-turn pre-step. Repeated selection of + * the current or already-pending state is a no-op. * * @param agent The agent to switch. * @param active Whether plan mode should be active. * @returns what happened: `committed` (logged now), `queued` (awaiting the - * next step boundary), `cancelled` (an opposite pending selection + * next accepted in-turn pre-step), `cancelled` (an opposite pending selection * was cleared; the logged state already matches), or `noop` (already in that * state). */ diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml index c2b1b153ac..a69c82d9a3 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md /: - en: d8520be9ef9ace75 - zh: 7aaf5e3eff54b19d + en: 931aadab3e8321b3 + zh: 5a68ca18ad6d18e1 /update-step-model-selection-conditional-tools-and-prompt-hooks: en: 81e0b8c4355e86a3 zh: 2563f89226c11cfb /update-step-model-selection-conditional-tools-and-prompt-hooks/change: - en: be511d31b6f02e4f - zh: b25075b04ef28234 + en: 74258c18d35089bc + zh: 726a331ba0b7af0b /update-step-model-selection-conditional-tools-and-prompt-hooks/migration: - en: c849786a9f5e5100 - zh: 15aa7729b7802ed4 + en: 55ed276829aa0b38 + zh: 7cac6f3f54bfc259 diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md index ab52391610..11abb621fa 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "Each step's provider, model, and reasoning effort come from `agent/model` through `agent.step`, plan selections commit at `agent/step-boundary`, and custom tool and prompt plugins must use step-owned tool admission." +description: "Each step's provider, model, and reasoning effort come from `agent/model` through `agent.step`, and custom tool and prompt plugins must use step-owned tool admission." --- # Update step model selection, conditional tools, and prompt hooks @@ -9,11 +9,11 @@ English | [中文](guide.zh.md) ## Change -`agent/model` returns each step's `ModelSelection` (provider, model, and optional reasoning effort) after the new serial `agent/step-boundary` event and before `agent/pre-step`. The loop publishes it as `agent.step` until the step ends; `agent/pre-step` listeners, tool conditions, prompt sections, and every request attempt read it there. `agent/request` still runs for each attempt after prompt assembly and `step/start`, but it may change only sampling controls such as `maxTokens`, `temperature`, and `stop`; returning another provider, model, or reasoning effort fails the step. An agent without options provider and model must receive them from `agent/model`. Plugins that replaced the provider, model, or effort in `agent/request`, including on a retry, are affected. `installModelSelection` applies its selection through `agent/model`, and `ModelSelectionRef` no longer has `assembled`. +`agent/model` returns each step's `ModelSelection` (provider, model, and optional reasoning effort) after the loop claims the step's input and before `agent/pre-step`. The loop publishes it as `agent.step` until the step ends; `agent/pre-step` listeners, tool conditions, prompt sections, and every request attempt read it there. `agent/request` still runs for each attempt after prompt assembly and `step/start`, but it may change only sampling controls such as `maxTokens`, `temperature`, and `stop`; returning another provider, model, or reasoning effort fails the step. An agent without options provider and model must receive them from `agent/model`. Plugins that replaced the provider, model, or effort in `agent/request`, including on a retry, are affected. `installModelSelection` applies its selection through `agent/model`, and `ModelSelectionRef` no longer has `assembled`. `system-prompt/assemble` runs once per step after `step/start` and receives presentation fields without a tool array; tool declarations remain owned by registered providers. Pre-step decisions no longer contain the runtime-context message: the snapshot is admitted after the step's accepted messages, and a changed runtime context alone no longer opens a step. Conditional tools require a resolved step set for execution, including nested PTC calls. Replacing a registration does not authorize an outstanding call to run the replacement. -`exit_plan_mode` is offered only while committed plan mode is active. A plan selection made during a turn is committed at the next `agent/step-boundary`, even when `agent/pre-step` rejects that step; a failed write fails the proposal and keeps the selection pending. Existing Sessions require no format migration. +`exit_plan_mode` is offered only while committed plan mode is active. A plan selection made during a turn is still committed by the next accepted `agent/pre-step`, now before that step resolves tools and assembles its prompt; a failed write fails the proposal and keeps the selection pending. Existing Sessions require no format migration. ## Migration @@ -21,4 +21,4 @@ English | [中文](guide.zh.md) 2. Declare tool conditions with `ctx.tools.register(definition, { when })`; the condition receives `{ agent, signal }`. 3. Keep presentation changes in `system-prompt/assemble` and stop replacing its tool list. Do not look for the runtime-context message in `agent/pre-step` decisions. 4. For programmatic conditional calls, resolve `{ agent, signal }` through `ctx.tools.resolve()`, pass the resulting `toolSet` to assembly and execution, and dispose it after the batch settles. AgentLoop does this once per step for model calls. Pass `context.toolSet` when tool guidance queries `ctx.tools.get()` or `schemas()`. -5. Commit state that applies from the next step in an `agent/step-boundary` listener. Remove `assembled` from `ModelSelectionRef` objects, and set `step` on test Agents whose pre-step listeners read the model. Verify that inactive tools are absent from declarations, that a historical name returns `UNKNOWN_TOOL` without reaching the implementation, and that an `agent/request` listener changing the model or effort ends the turn with an error naming `agent/model`. +5. Remove `assembled` from `ModelSelectionRef` objects, and set `step` on test Agents whose pre-step listeners read the model. Verify that inactive tools are absent from declarations, that a historical name returns `UNKNOWN_TOOL` without reaching the implementation, and that an `agent/request` listener changing the model or effort ends the turn with an error naming `agent/model`. diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md index 4c2b6bbba4..01f879218f 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "每个步骤的提供方、模型与推理强度由 `agent/model` 决定并通过 `agent.step` 读取,计划选择在 `agent/step-boundary` 提交,自定义工具和提示词插件必须使用步骤拥有的工具准入集合。" +description: "每个步骤的提供方、模型与推理强度由 `agent/model` 决定并通过 `agent.step` 读取,自定义工具和提示词插件必须使用步骤拥有的工具准入集合。" --- # 更新步骤模型选择、条件工具与提示词钩子 @@ -9,11 +9,11 @@ description: "每个步骤的提供方、模型与推理强度由 `agent/model` ## 变更 -`agent/model` 在新增的串行事件 `agent/step-boundary` 之后、`agent/pre-step` 之前返回每个步骤的 `ModelSelection`(提供方、模型与可选的推理强度)。循环把它发布为 `agent.step`,直到步骤结束;`agent/pre-step` 监听器、工具条件、提示词段落以及每次请求尝试都从这里读取。`agent/request` 仍在提示词组装与 `step/start` 之后为每次尝试运行,但只能修改 `maxTokens`、`temperature`、`stop` 等采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。options 中没有提供方与模型的 agent 必须由 `agent/model` 提供。在 `agent/request` 中替换提供方、模型或推理强度的插件(包括在重试时替换的插件)会受到影响。`installModelSelection` 通过 `agent/model` 应用其选择,`ModelSelectionRef` 不再包含 `assembled`。 +`agent/model` 在循环领取步骤输入之后、`agent/pre-step` 之前返回每个步骤的 `ModelSelection`(提供方、模型与可选的推理强度)。循环把它发布为 `agent.step`,直到步骤结束;`agent/pre-step` 监听器、工具条件、提示词段落以及每次请求尝试都从这里读取。`agent/request` 仍在提示词组装与 `step/start` 之后为每次尝试运行,但只能修改 `maxTokens`、`temperature`、`stop` 等采样控制参数;返回其他提供方、模型或推理强度会使步骤失败。options 中没有提供方与模型的 agent 必须由 `agent/model` 提供。在 `agent/request` 中替换提供方、模型或推理强度的插件(包括在重试时替换的插件)会受到影响。`installModelSelection` 通过 `agent/model` 应用其选择,`ModelSelectionRef` 不再包含 `assembled`。 `system-prompt/assemble` 在 `step/start` 之后每个步骤运行一次,接收不含工具数组的展示字段;工具声明仍由已注册提供方持有。pre-step 决策中不再包含运行时上下文消息:快照在该步骤已接纳的消息之后提交,仅运行时上下文变化也不再打开步骤。条件工具执行需要已解析的步骤集合,包括嵌套 PTC 调用。替换注册不会授权尚未执行的旧调用使用新实现。 -`exit_plan_mode` 只在已提交的计划模式启用时提供。轮次进行中作出的计划选择在下一个 `agent/step-boundary` 提交,即使 `agent/pre-step` 拒绝了该步骤;写入失败会使该提案失败并保留待提交选择。现有 Session 无需格式迁移。 +`exit_plan_mode` 只在已提交的计划模式启用时提供。轮次进行中作出的计划选择仍由下一个被接纳的 `agent/pre-step` 提交,现在提交发生在该步骤解析工具与组装提示词之前;写入失败会使该提案失败并保留待提交选择。现有 Session 无需格式迁移。 ## 迁移 @@ -21,4 +21,4 @@ description: "每个步骤的提供方、模型与推理强度由 `agent/model` 2. 使用 `ctx.tools.register(definition, { when })` 声明工具条件;条件接收 `{ agent, signal }`。 3. 展示变更留在 `system-prompt/assemble`,停止替换它的工具列表。不要在 `agent/pre-step` 的决策中查找运行时上下文消息。 4. 程序化调用条件工具时,通过 `ctx.tools.resolve()` 解析 `{ agent, signal }`,将返回的 `toolSet` 传给组装与执行,并在批次结束后释放。AgentLoop 会为模型调用在每个步骤完成一次这些操作。工具指导查询 `ctx.tools.get()` 或 `schemas()` 时传入 `context.toolSet`。 -5. 从下一个步骤起生效的状态在 `agent/step-boundary` 监听器中提交。从 `ModelSelectionRef` 对象中删除 `assembled`;若测试中的 pre-step 监听器读取模型,为测试 Agent 设置 `step`。验证未启用工具不出现在声明中,使用历史名称调用会返回 `UNKNOWN_TOOL` 且不会进入实现,并验证修改模型或推理强度的 `agent/request` 监听器会让轮次以指向 `agent/model` 的错误结束。 +5. 从 `ModelSelectionRef` 对象中删除 `assembled`;若测试中的 pre-step 监听器读取模型,为测试 Agent 设置 `step`。验证未启用工具不出现在声明中,使用历史名称调用会返回 `UNKNOWN_TOOL` 且不会进入实现,并验证修改模型或推理强度的 `agent/request` 监听器会让轮次以指向 `agent/model` 的错误结束。 diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 43cddfd1dd..b081f9849f 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -45,8 +45,8 @@ en: 3c5721bc00a0bbf4 zh: 711f832343ffbb75 /deepseek-ai-dsh-agent-loop/understand-the-implementation/turn-and-step-flow: - en: db754159572b2c69 - zh: c9358e9df71ea589 + en: d0e6d24c8eb8403c + zh: 45a5982159b6c05e /deepseek-ai-dsh-agent-loop/understand-the-implementation/failure-and-cancellation: en: eea56903c4ff82f5 zh: c0d5abb5767780ed diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 1db9b2c0c6..1fc9e6e43b 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -117,7 +117,7 @@ The loop is the production acquisition point for session write handles. When `ct ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver dispatches `agent/step-boundary`, chooses the step's provider, model, and reasoning effort through `agent/model`, publishes them as `agent.step`, then runs `agent/pre-step`, whose fallback enters the claimed batch unchanged. A rejected decision or empty first batch opens no step; a changed runtime context alone does not open one. Cancellation at the boundary or during model selection opens no step. `agent.step` is cleared when the step ends or its proposal is rejected, fails, or is cancelled. After acceptance, `step/start` precedes asynchronous tool activation and one prompt assembly of sections, variables, runtime context, and tool declarations, both once per step. Each attempt then runs the `agent/request` waterfall and `prepareCall()` with the step's model selection; a listener that returns another provider, model, or reasoning effort fails the step, and cancellation during either async phase commits neither the pending system prompt nor accepted users. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt, then appends the runtime-context snapshot when it changed or was removed, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the step's model selection, tool set, and rendered assembly without repeating model selection, tool activation, assembly, `agent/pre-step`, or user admission. The step-owned tool set is closed after the step's tool batch settles. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. `AgentLoop` registers the standard `inbox` projection for its service lifetime, so cold reads work before any Agent exists and after all Agents unload. Its package-internal `ReactLoopInbox` uses that shared projection for structural commands and loop-only claims. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. The driver chooses the step's provider, model, and reasoning effort through `agent/model`, publishes them as `agent.step`, then runs `agent/pre-step`, whose fallback enters the claimed batch unchanged. A rejected decision or empty first batch opens no step; a changed runtime context alone does not open one. Cancellation during model selection opens no step. `agent.step` is cleared when the step ends or its proposal is rejected, fails, or is cancelled. After acceptance, `step/start` precedes asynchronous tool activation and one prompt assembly of sections, variables, runtime context, and tool declarations, both once per step. Each attempt then runs the `agent/request` waterfall and `prepareCall()` with the step's model selection; a listener that returns another provider, model, or reasoning effort fails the step, and cancellation during either async phase commits neither the pending system prompt nor accepted users. For every attempt, the loop then synchronously reconciles the rendered prompt against the surviving `system/message` nodes using the prepared call capability, refreshes registered runtime facts, appends the accepted `user/message` batch only on the first attempt, then appends the runtime-context snapshot when it changed or was removed, logs the header and context as needed, and derives and freezes the request before streaming through that bound prepared call. Retries reuse the step's model selection, tool set, and rendered assembly without repeating model selection, tool activation, assembly, `agent/pre-step`, or user admission. The step-owned tool set is closed after the step's tool batch settles. Reconciliation sees pre-step and retry compaction; a broken series consolidates the prompt at the head rather than appending an update after already-committed users. The request is `header.config`, `deriveMessages()`, and `header.tools`; it carries no `system` field. Each model attempt emits one process-local `start`, emits every `chunk` only after the matching durable assistant-frame settlement, and emits exactly one terminal `end`; final assembly or message-append failure settles it as `aborted`, while `committed` follows the durable `assistant/message`. Each successful model call appends one message anchor, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results... (line truncated to 2000 chars) Prompt admission uses the actual `prepareCall()` result, not the preceding `request/context`. With no system node, even an empty prompt is appended (reserving node 0 without a wire message). On an incapable route or at a new request series, a non-empty rendering is consolidated at the first system node: each non-empty later system node receives a logged per-node empty replacement, then the head is rewritten if needed. Dormant empty tails need no replacement and do not determine the effective text. Consolidation applies even when the latest effective text is unchanged. On a continuing `in-history` series, an unchanged effective prompt produces no event and a non-empty change appends. An empty rendering clears every non-empty later system node through a logged per-node empty replacement, then empties the head if needed, regardless of route or series state. No older instructions remain model-visible. An empty head with no active later system node means no prompt; repeated clears and resume leave it empty. A restored non-empty prompt follows the same route/series rule: a continuing capable route may append it, while an incapable route or new series refills the head. A step starts a series when the pre-step decision declares `startsRequestSeries` or `session.surface.contentGeneration` changed since attachment or the last request (a replacement or image-offload decision). Visible tool-schema changes force prompt consolidation only when the prepared route lacks `toolUpdate`. Routes supporting both tool and system-prompt updates can append a changed prompt and activate added tools without rewriting earlier messages. If another admission condition replaces a system node, the request starts a new series with current tool declarations. Resume and a provider or model swap alone continue the series; the prepared route still governs admission. Per-node empty replacements preserve intervening history without a surface delete operation. diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 03b5f3b15f..c837c10dc2 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -117,7 +117,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器派发 `agent/step-boundary`,通过 `agent/model` 选定步骤的提供方、模型与推理强度并发布为 `agent.step`,然后运行 `agent/pre-step`,其 fallback 原样接纳已领取批次。被拒绝的决定或空的首批输入不打开步骤;仅运行时上下文变化也不会打开步骤。在步骤边界或模型选择期间取消不会打开步骤。步骤结束或提案被拒绝、失败、取消时,`agent.step` 会被清除。接纳后,`step/start` 先于异步工具激活与一次提示词组装(段落、变量、运行时上下文与工具声明),两者每个步骤各执行一次。每次尝试随后按步骤的模型选择运行 `agent/request` waterfall 与 `prepareCall()`;监听器若返回其他提供方、模型或推理强度,步骤会失败,而在任一异步阶段取消都不会提交待定的系统提示词或已接纳用户消息。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次,随后在运行时上下文变化或被移除时追加其快照、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试复用该步骤的模型选择、工具集合与已渲染组装结果,不重复模型选择、工具激活、组装、`agent/pre-step` 或用户消息接纳。步骤拥有的工具集合在该步骤的工具批次结束后关闭。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。`AgentLoop` 在服务生命周期内注册标准 `inbox` 投影,因此冷读取在没有 Agent 和所有 Agent 卸载后都可用。其包内部 `ReactLoopInbox` 使用该共享投影执行结构化命令与仅供 loop 使用的领取操作。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。驱动器通过 `agent/model` 选定步骤的提供方、模型与推理强度并发布为 `agent.step`,然后运行 `agent/pre-step`,其 fallback 原样接纳已领取批次。被拒绝的决定或空的首批输入不打开步骤;仅运行时上下文变化也不会打开步骤。在模型选择期间取消不会打开步骤。步骤结束或提案被拒绝、失败、取消时,`agent.step` 会被清除。接纳后,`step/start` 先于异步工具激活与一次提示词组装(段落、变量、运行时上下文与工具声明),两者每个步骤各执行一次。每次尝试随后按步骤的模型选择运行 `agent/request` waterfall 与 `prepareCall()`;监听器若返回其他提供方、模型或推理强度,步骤会失败,而在任一异步阶段取消都不会提交待定的系统提示词或已接纳用户消息。每次尝试时,循环随后依据已准备调用的能力,同步将渲染后的提示词与存活的 `system/message` 节点协调一致、刷新已注册运行时事实、仅在首次尝试追加已接纳的 `user/message` 批次,随后在运行时上下文变化或被移除时追加其快照、按需记录 header 与 context,再派生并冻结请求,通过该绑定的已准备调用发起流式请求。重试复用该步骤的模型选择、工具集合与已渲染组装结果,不重复模型选择、工具激活、组装、`agent/pre-step` 或用户消息接纳。步骤拥有的工具集合在该步骤的工具批次结束后关闭。协调过程可见 pre-step 与重试中的压缩;序列中断时将提示词归并到头部,而非在已提交用户消息之后追加更新。请求由 `header.config`、`deriveMessages()` 与 `header.tools` 构成,不携带 `system` 字段。每次模型尝试会发出一个进程本地 `start`,仅在匹配的持久 assistant-frame 结算之后发出各个 `chunk`,并恰好发出一个终态 `end`;最终组装或消息追加失败时以 `aborted` 结算,`committed` 则出现在持久 `assistant/message` 之后。每次成功的模型调用都恰好追加一个 message 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 提示词准入依据实际的 `prepareCall()` 结果,而非先前的 `request/context`。没有系统节点时,即使提示词为空也追加(预留第 0 号节点,但不产生协议消息)。在不具备能力的路由上或新请求序列开始时,非空渲染文本归并到首个系统节点:每个非空的后续系统节点分别收到有日志记录的空内容替换,随后按需重写头节点。未生效的空尾节点无需替换,也不决定有效文本。即使最新有效文本未变,也执行归并。延续中的 `in-history` 序列在有效提示词不变时不产生事件,非空变更则追加。无论路由或序列状态如何,空渲染文本都会通过有日志记录的逐节点空内容替换清除每个非空的后续系统节点,再按需清空头节点。模型不会继续看到旧指令。空头节点且没有生效的后续系统节点表示没有提示词;重复清除与恢复会话都保持为空。重新提供的非空提示词遵循同一路由/序列规则:延续中的具备能力路由可以追加它,不具备能力的路由或新序列则重新填充头节点。以下情况开启序列:pre-step 决定声明 `startsRequestSeries`,或 `session.surface.contentGeneration` 自附接或上次请求以来发生变化(替换或图片省略决定)。仅当已准备路由未声明 `toolUpdate` 时,可见工具 schema 变化才强制归并提示词。同时支持工具和系统提示词更新的路由可以追加变更后的提示词并激活新增工具,无需改写此前消息。如果其他准入条件替换系统节点,请求会以当前工具声明开启新序列。恢复与单纯的提供方或模型切换都延续序列;准入仍由已准备的路由决定。逐节点的空内容替换保留其间历史,无需 surface 删除操作。 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 0592cdf9b6..eaa14ed3de 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -288,8 +288,6 @@ export class ReactLoopAgent implements Agent { if (this.phase.kind !== 'running') throw new Error(`agent "${this.id}": pre-step outside running phase`) const signal = this.phase.abort.signal const claimed = this.inbox.claim(target, position.turn) - await this.dispatch.serial('agent/step-boundary', { ...position, signal }) - signal.throwIfAborted() const modelSelection = await this.chooseModel(position.turn, position.step, signal) this.currentStep = Object.freeze({ modelSelection }) const decision = await this.dispatch.waterfall( diff --git a/packages/core/agent-loop/tests/step-model.spec.ts b/packages/core/agent-loop/tests/step-model.spec.ts index 97f345c280..e28dc13429 100644 --- a/packages/core/agent-loop/tests/step-model.spec.ts +++ b/packages/core/agent-loop/tests/step-model.spec.ts @@ -1,4 +1,4 @@ -/** Each proposed step commits boundary selections, then publishes its model selection as `agent.step`. */ +/** Each proposed step publishes its `agent/model` selection as `agent.step`. */ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm' @@ -48,7 +48,6 @@ describe('agent.step', () => { const ctx = await harness(adapter) const agent = await ctx.agentLoop.create(SessionId('step-visibility'), { provider: 'mock', model: 'mock' }) const seen = { - boundary: [] as (AgentStep | undefined)[], model: [] as (AgentStep | undefined)[], preStep: [] as (AgentStep | undefined)[], condition: [] as (AgentStep | undefined)[], @@ -57,7 +56,6 @@ describe('agent.step', () => { execute: [] as (AgentStep | undefined)[], stopping: [] as (AgentStep | undefined)[], } - ctx.on('agent/step-boundary', ({ agent: subject }) => { seen.boundary.push(subject.step) }) ctx.on('agent/model', async ({ agent: subject }, next) => { seen.model.push(subject.step) return next() @@ -95,7 +93,6 @@ describe('agent.step', () => { send(agent, 'go') await agent.whenIdle() - expect(seen.boundary).toEqual([undefined, undefined]) expect(seen.model).toEqual([undefined, undefined]) const [first, second] = seen.preStep expect(first).toEqual({ modelSelection: { provider: 'mock', model: 'mock' } }) @@ -139,18 +136,17 @@ describe('agent.step', () => { }) }) -describe('agent/step-boundary', () => { - it('runs after the claim and before agent/model once per proposed step', async () => { +describe('agent/model', () => { + it('runs after the claim and before agent/pre-step once per proposed step', async () => { const adapter = new MockAdapter([toolCallResponse('c1', 'noop', {}), textResponse('done')]) const ctx = await harness(adapter) - const agent = await ctx.agentLoop.create(SessionId('boundary-order'), { provider: 'mock', model: 'mock' }) + const agent = await ctx.agentLoop.create(SessionId('model-order'), { provider: 'mock', model: 'mock' }) ctx.tools.register(defineContentToolFixture({ name: 'noop', description: 'Do nothing.', parameters: {}, execute: async () => [], })) const order: string[] = [] ctx.on('agent/inbox/claimed', () => { order.push('claimed') }) - ctx.on('agent/step-boundary', ({ step }) => { order.push(`boundary:${String(step)}`) }) ctx.on('agent/model', async ({ step }, next) => { order.push(`model:${String(step)}`) return next() @@ -163,51 +159,7 @@ describe('agent/step-boundary', () => { send(agent, 'go') await agent.whenIdle() - expect(order).toEqual(['claimed', 'boundary:1', 'model:1', 'pre-step:1', 'boundary:2', 'model:2', 'pre-step:2']) - }) - - it('fails the proposal before model choice when a listener throws', async () => { - const adapter = new MockAdapter([]) - const ctx = await harness(adapter) - const agent = await ctx.agentLoop.create(SessionId('boundary-failure'), { provider: 'mock', model: 'mock' }) - let modelChosen = false - ctx.on('agent/step-boundary', () => { throw new Error('boundary commit failed') }) - ctx.on('agent/model', async (_payload, next) => { - modelChosen = true - return next() - }) - - send(agent, 'go') - await agent.whenIdle() - - expect(modelChosen).toBe(false) - const reason = lastTurnEnd(agent) - expect(reason?.kind === 'error' ? reason.error.message : undefined).toContain('boundary commit failed') - expect(eventTypes(agent)).not.toContain('step/start') - expect(adapter.requests).toEqual([]) - }) - - it('opens no step when the turn is cancelled during the boundary', async () => { - const adapter = new MockAdapter([]) - const ctx = await harness(adapter) - const agent = await ctx.agentLoop.create(SessionId('boundary-cancel'), { provider: 'mock', model: 'mock' }) - const entered = Promise.withResolvers() - const release = Promise.withResolvers() - ctx.on('agent/step-boundary', async () => { - entered.resolve(undefined) - await release.promise - }) - - send(agent, 'cancelled') - await entered.promise - agent.cancel({ kind: 'user' }) - release.resolve(undefined) - await agent.whenIdle() - - expect(lastTurnEnd(agent)?.kind).toBe('aborted') - expect(eventTypes(agent)).not.toContain('step/start') - expect(agent.step).toBeUndefined() - expect(adapter.requests).toEqual([]) + expect(order).toEqual(['claimed', 'model:1', 'pre-step:1', 'model:2', 'pre-step:2']) }) }) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index c2df453d65..e8fc692f34 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -27,8 +27,8 @@ en: 2594a1e02adea801 zh: cae8860369728efb /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: - en: f5045f7c9f1c2f7a - zh: bc6ceeb549eb0f4d + en: 244f1bd9c619b04f + zh: d7633203257b8363 /deepseek-ai-dsh-agent/understand-the-implementation: en: ce7e776e9d516bdb zh: 59d2751743db7795 @@ -36,8 +36,8 @@ en: 7c850051d2857bfa zh: 4cab817553114e15 /deepseek-ai-dsh-agent/understand-the-implementation/step-admission: - en: 0271968a215a5b72 - zh: 36e7535632a166dc + en: 3143c39974e77672 + zh: ca033c56820b088c /deepseek-ai-dsh-agent/understand-the-implementation/durable-inbox: en: f6802c7f94f623b3 zh: cc3885db80765970 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 9ac3fa06e8..c35597c9ae 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -64,7 +64,7 @@ await handle.agent.whenIdle() ### Intercept or observe work in flight -The `agent/*` events let plugins act on live work without depending on the loop package. `agent/step-boundary` commits selections that apply from the next step, such as a pending plan-mode switch; `agent/model` chooses each step's provider, model, and reasoning effort, which the agent then exposes as `agent.step`; `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). +The `agent/*` events let plugins act on live work without depending on the loop package. `agent/model` chooses each step's provider, model, and reasoning effort, which the agent then exposes as `agent.step`; `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). ----- @@ -82,7 +82,7 @@ The package is built on one separation: the public `Agent` surface and registry ### Step admission -`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. `agent/step-boundary` and `agent/model` run before `agent/pre-step`, so pre-step listeners read the step's model selection from `agent.step`. Acceptance does not commit the batch: after `step/start`, tool conditions, prompt assembly, `agent/request`, and `prepareCall()` must succeed before system and user messages are logged. Cancellation at the boundary or during model selection opens no step, and cancellation during a later async phase commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. +`PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch contains the complete identified, frozen message batch. `agent/model` runs before `agent/pre-step`, so pre-step listeners read the step's model selection from `agent.step`. Acceptance does not commit the batch: after `step/start`, tool conditions, prompt assembly, `agent/request`, and `prepareCall()` must succeed before system and user messages are logged. Cancellation during model selection opens no step, and cancellation during a later async phase commits neither message kind. `startsRequestSeries: true` declares a distinct model-message series; a wrapping listener preserves that declaration and the batch unless it intentionally replaces either one. Claiming removes offered messages from the inbox, while messages inserted after the claim remain pending for a later boundary. The step's model selection supplies or replaces the creation-time provider, model, and effort. The driver publishes it as `agent.step` after `agent/model` and clears it when the step ends or its proposal is rejected, fails, or is cancelled; `agent/pre-step`, tool conditions, prompt assembly, and every request attempt in the step read it. An `agent/request` listener that returns another provider, model, or reasoning effort fails the step. `installModelSelection` returns its current selection, effort included, when `agent/model` runs, so a selection made during a step applies from the next step. diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index 72256e0cc1..0307f5e236 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -64,7 +64,7 @@ await handle.agent.whenIdle() ### 拦截或观察进行中的工作 -`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/step-boundary` 提交从本步骤起生效的选择,例如待提交的计划模式切换;`agent/model` 选定每个步骤的提供方、模型与推理强度,agent 随后通过 `agent.step` 公开它;`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 +`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/model` 选定每个步骤的提供方、模型与推理强度,agent 随后通过 `agent.step` 公开它;`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 ----- @@ -82,7 +82,7 @@ await handle.agent.whenIdle() ### 步骤准入 -`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。`agent/step-boundary` 与 `agent/model` 在 `agent/pre-step` 之前运行,因此 pre-step 监听器从 `agent.step` 读取该步骤的模型选择。接纳不等于提交:`step/start` 之后,工具条件、提示词组装、`agent/request` 与 `prepareCall()` 都成功后,才记录系统提示词与用户批次。在步骤边界或模型选择期间取消不会打开步骤,在之后任一异步阶段取消也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 +`PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支包含完整、带标识且冻结的消息批次。`agent/model` 在 `agent/pre-step` 之前运行,因此 pre-step 监听器从 `agent.step` 读取该步骤的模型选择。接纳不等于提交:`step/start` 之后,工具条件、提示词组装、`agent/request` 与 `prepareCall()` 都成功后,才记录系统提示词与用户批次。在模型选择期间取消不会打开步骤,在之后任一异步阶段取消也不会提交这两种消息。`startsRequestSeries: true` 声明一个独立的模型消息序列;包装下游 enter 的监听器会保留该声明与批次,除非有意替换其中一项。领取会从 inbox 移除候选消息,领取后插入的消息则等待后续边界。 步骤的模型选择会补上或替换创建时的提供方、模型与推理强度。驱动在 `agent/model` 之后把它发布为 `agent.step`,并在步骤结束或提案被拒绝、失败、取消时清除;`agent/pre-step`、工具条件、提示词组装以及该步骤的每次请求尝试都读取它。`agent/request` 监听器若返回其他提供方、模型或推理强度,步骤会失败。`installModelSelection` 在 `agent/model` 运行时返回当前选择(含推理强度),因此步骤进行中做出的选择从下一个步骤开始生效。 diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 3a8111c1e8..2257a617a9 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -342,21 +342,6 @@ declare module '@deepseek-ai/cordis' { * @mode waterfall */ 'agent/pre-step'(this: Scoped, payload: { agent: Agent; messages: UserMessage[]; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise - /** - * A proposed step reached its boundary: the loop claimed its input and is - * about to choose its model. Listeners commit selections that take effect - * from this step, such as a pending plan-mode switch, so `agent/model`, - * `agent/pre-step`, tool conditions, and prompt assembly read one state. - * Runs once per proposed step; a throw fails the proposal, and - * cancellation opens no step. - * @param payload.agent - the agent proposing the step. - * @param payload.turn - the turn that will own the step. - * @param payload.step - the step proposed by the loop. - * @param payload.signal - the current turn's explicit abort signal. - * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. - * @mode serial - */ - 'agent/step-boundary'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }): Promise | void /** * Choose the provider, model, and reasoning effort for one proposed step. * `await next()` yields the selection the machine would use: agent options @@ -365,7 +350,7 @@ declare module '@deepseek-ai/cordis' { * replacement to switch; an effort belongs to its model, so a replacement * that changes the model names that model's effort or omits it for the * provider default. The loop runs this once per proposed step, after - * `agent/step-boundary` and before `agent/pre-step`, then publishes the + * claiming its input and before `agent/pre-step`, then publishes the * result as `agent.step`. Pre-step listeners, tool conditions, prompt * assembly, and every request attempt in the step use it, so a later * choice applies from the next step. Cancellation here opens no step. diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index c6eaae6b4a..bc45e1a688 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1660,15 +1660,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'get(agent: Agent): { active: boolean; pending?: boolean }', - description: 'Read the logged plan state and any selected state awaiting the next step boundary.', + description: 'Read the logged plan state and any selected state awaiting the next accepted in-turn pre-step.', parameters: [{ name: 'agent', description: 'The agent to read.' }], returns: 'Current logged state plus a pending selection, when present.', }, { signature: 'set(agent: Agent, active: boolean): \'committed\' | \'queued\' | \'cancelled\' | \'noop\'', - description: 'Select whether plan mode should be active. Between turns the method appends the change immediately because no step boundary will run until another prompt starts a turn. The open-turn fold is the idle signal: agent status stays `running` through post-turn checkpointing, when no further step boundary runs. During an open turn the selection remains pending until the next step boundary. Repeated selection of the current or already-pending state is a no-op.', + description: 'Select whether plan mode should be active. Between turns the method appends the change immediately because no in-turn pre-step will run until another prompt starts a turn. The open-turn fold is the idle signal: agent status stays `running` through post-turn checkpointing, when no further in-turn pre-step runs. During an open turn the selection remains pending until the next accepted in-turn pre-step. Repeated selection of the current or already-pending state is a no-op.', parameters: [{ name: 'agent', description: 'The agent to switch.' }, { name: 'active', description: 'Whether plan mode should be active.' }], - returns: 'what happened: `committed` (logged now), `queued` (awaiting the next step boundary), `cancelled` (an opposite pending selection was cleared; the logged state already matches), or `noop` (already in that state).', + returns: 'what happened: `committed` (logged now), `queued` (awaiting the next accepted in-turn pre-step), `cancelled` (an opposite pending selection was cleared; the logged state already matches), or `noop` (already in that state).', }, ], }, @@ -3979,7 +3979,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ mode: 'waterfall', signature: '\'agent/model\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }, next: () => Promise): Promise', summary: 'Choose the provider, model, and reasoning effort for one proposed step.', - description: 'Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model\'s effort or omits it for the provider default. The loop runs this once per proposed step, after `agent/step-boundary` and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step.', + description: 'Choose the provider, model, and reasoning effort for one proposed step. `await next()` yields the selection the machine would use: agent options before this loop logs a request, the logged header afterwards, with an effort only when one was chosen for that exact model. Return a replacement to switch; an effort belongs to its model, so a replacement that changes the model names that model\'s effort or omits it for the provider default. The loop runs this once per proposed step, after claiming its input and before `agent/pre-step`, then publishes the result as `agent.step`. Pre-step listeners, tool conditions, prompt assembly, and every request attempt in the step use it, so a later choice applies from the next step. Cancellation here opens no step.', parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, { @@ -4014,14 +4014,6 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Agent status changed (`idle` ⇄ `running`). A waking delivery enters `running` synchronously after reserving cancellation; `idle` means no driver remains scheduled or active.', parameters: [{ name: 'payload', description: '.status - the status just entered (the transition\'s destination). Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, - { - name: 'agent/step-boundary', - mode: 'serial', - signature: '\'agent/step-boundary\'(this: Scoped, payload: { agent: Agent; turn: number; step: number; signal: AbortSignal }): Promise | void', - summary: 'A proposed step reached its boundary: the loop claimed its input and is about to choose its model.', - description: 'A proposed step reached its boundary: the loop claimed its input and is about to choose its model. Listeners commit selections that take effect from this step, such as a pending plan-mode switch, so `agent/model`, `agent/pre-step`, tool conditions, and prompt assembly read one state. Runs once per proposed step; a throw fails the proposal, and cancellation opens no step.', - parameters: [{ name: 'payload', description: '.signal - the current turn\'s explicit abort signal. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], - }, { name: 'agent/turn-stopping', mode: 'serial', diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index 33b681c436..9fadebb38e 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -39,14 +39,14 @@ en: 0acc88b042a99380 zh: e4cf66b77f2fc7ae /deepseek-ai-dsh-plan-mode/understand-the-implementation/durable-state-and-step-boundary-appends: - en: 1d2abc9a8ef4a1bf - zh: e09bc45a1d94934f + en: 6d0adadc354f211e + zh: 86fa49a9f4377368 /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-plan-command: en: a7bf35c2a9da52bc zh: dea9f4b3a41f1a6d /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-exit-tool: - en: cd036af680065de1 - zh: eed170bfef995d80 + en: 86b26413acb2e835 + zh: a84d876efefa5bea /deepseek-ai-dsh-plan-mode/understand-the-implementation/session-projection-unit: en: 74cd6bdf50af51f5 zh: 67609cf7202ececb @@ -99,8 +99,8 @@ en: 9d9626fbf4cdc8de zh: 8237cbc3ca048024 /deepseek-ai-dsh-plan-mode/known-limitations-and-deferred-work: - en: 985f29a245876400 - zh: f7c9d7ed6eab1f55 + en: a87aabfede0087fd + zh: 201e9b3766980005 /deepseek-ai-dsh-plan-mode/known-limitations-and-deferred-work/dev-note: en: 7de02cd33a767bd6 zh: d9e54003f230f725 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 2c642ee0be..26b24ed4c3 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -82,7 +82,7 @@ Plan mode is a product package, not a capability seam: there is no swappable bac ### Durable state and step-boundary appends -The package persists one log-only whole-value event, `plan/mode`, and the last logged value is the state. A mode change appends immediately when no turn is open; during an open turn it stays pending until the next step boundary — the only append point while an agent runs, before the step chooses its model — and an append failure fails that proposal while retaining the pending selection. The `set`/`get` service methods and their exact return states live in [`src/index.ts`](src/index.ts) and read the registered `plan` projection; the first dependent access fails explicitly when the registry or key is absent. +The package persists one log-only whole-value event, `plan/mode`, and the last logged value is the state. A mode change appends immediately when no turn is open; during an open turn it stays pending until the next accepted in-turn pre-step — the only append point while an agent runs — and an append failure stops step admission while retaining the pending selection. The `set`/`get` service methods and their exact return states live in [`src/index.ts`](src/index.ts) and read the registered `plan` projection; the first dependent access fails explicitly when the registry or key is absent. ### The `/plan` command @@ -90,7 +90,7 @@ The command child activates only when a commands service is composed. It maps ba ### The exit tool -`exit_plan_mode` is conditionally admitted only while the committed plan state is active. Entering or leaving changes the tool declarations and plan guidance together; Native and PTC execution use the same admitted set. An approved review records a silent pending exit that the next step boundary appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. +`exit_plan_mode` is conditionally admitted only while the committed plan state is active. Entering or leaving changes the tool declarations and plan guidance together; Native and PTC execution use the same admitted set. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. ### Session projection unit @@ -182,7 +182,7 @@ Entering plan mode adds the exit tool through the route’s tool-update protocol These limits describe when plan mode does not behave as you might expect or needs extra care. They are current package constraints, not a roadmap. - **Guidance, not enforcement** — plan mode restrains through text only; deployments that need enforced restrictions configure sandbox mode and approval policy independently. -- **Pending selections are process-local** — a selection made after the turn's final step boundary is lost if the process exits before another step boundary; the UI must reapply it. +- **Pending selections are process-local** — a selection made after the turn's final accepted pre-step is lost if the process exits before another accepted in-turn pre-step; the UI must reapply it. - **No creation-time plan option** — forked agents inherit logged plan state, while newly spawned agents begin inactive. - **Live children cannot open the review** — a child owned by another live agent fails the `exit_plan_mode` call and is told to include the unresolved decision in its final result; durable fork lineage alone does not prevent a session resumed as a runtime root from opening the review. - **One specialized review renderer** — only the Web UI has a `plan-review` presentation; another interaction provider presents the same request through its generic option flow. diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index 758a5153db..3239d57803 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -82,7 +82,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 持久状态与步骤边界追加 -本包持久化一条仅记日志、整值替换的事件 `plan/mode`,最后一条已记录值即为状态。没有打开的轮次时立即记录模式变化;轮次内则等待下一个步骤边界,这是 agent 运行时唯一的写入点,位于该步骤选择模型之前。写入失败会使该提案失败,并保留待提交选择。`set`/`get` 的精确返回状态见 [`src/index.ts`](src/index.ts);它们读取已注册的 `plan` 投影,缺少注册表或投影键时在首次依赖访问处明确失败。 +本包持久化一条仅记日志、整值替换的事件 `plan/mode`,最后一条已记录值即为状态。没有打开的轮次时立即记录模式变化;轮次内则等待下一个被接纳的 pre-step。写入失败会停止步骤接纳并保留待提交选择。`set`/`get` 的精确返回状态见 [`src/index.ts`](src/index.ts);它们读取已注册的 `plan` 投影,缺少注册表或投影键时在首次依赖访问处明确失败。 ### `/plan` 命令 @@ -90,7 +90,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 退出工具 -`exit_plan_mode` 只在已提交的计划状态为 active 时准入。进入或离开会同时改变工具声明与计划指导;原生和 PTC 执行使用同一准入集合。批准评审后记录静默的待退出选择,由下一个步骤边界提交,当前工具批次的剩余调用保留计划指导。没有用户问答通道,或评审期间服务重载时,调用失败;`/plan off` 仍可手动退出。 +`exit_plan_mode` 只在已提交的计划状态为 active 时准入。进入或离开会同时改变工具声明与计划指导;原生和 PTC 执行使用同一准入集合。批准评审后记录静默的待退出选择,由下一个被接纳的轮次内 pre-step 提交,当前工具批次的剩余调用保留计划指导。没有用户问答通道,或评审期间服务重载时,调用失败;`/plan off` 仍可手动退出。 ### 会话投影单元 @@ -182,7 +182,7 @@ schema 仅在启用时按 ToolRuntime 模式计入开销;每份计划参数与 这些限制描述计划模式在哪些情况下不符合你的预期,或需要额外的注意。它们是当前包约束,不是路线图。 - **引导而非强制**——计划模式只通过文本约束;需要强制限制的部署要分别配置沙箱模式与审批策略。 -- **待生效选择只存在于进程内**——某轮最后一个步骤边界之后作出的选择,若进程在下一个步骤边界之前退出就会丢失;UI 必须重新应用它。 +- **待生效选择只存在于进程内**——某轮最后一个被接受的 pre-step 之后作出的选择,若进程在另一个被接受的轮内 pre-step 之前退出就会丢失;UI 必须重新应用它。 - **没有创建时 plan 选项**——fork 的 agent 继承已记录的计划状态,新 spawn 的 agent 则从未激活开始。 - **存活的子级无法打开评审**——由另一个存活 agent 所有的子级调用 `exit_plan_mode` 会失败,并被要求把尚未解决的决策包含进最终结果;仅有持久化 fork 谱系并不能阻止恢复为运行时根的会话打开该评审。 - **只有一个专用评审渲染器**——只有 Web UI 具备 `plan-review` 呈现;其他交互提供方通过其通用选项流程呈现同一请求。 diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 717f459661..e99f53f95a 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -7,11 +7,10 @@ * state. * * The `plan` projection folds the session log, so resume and fork restore the - * state. User selections made during a turn remain pending until the next - * step boundary. The service appends `plan/mode` from `agent/step-boundary`, - * before the step chooses its model, so `agent/model`, `agent/pre-step`, tool - * conditions, and plan guidance read the committed state. Same-step retries - * do not commit pending selections. + * state. User selections remain pending until the next accepted in-turn + * pre-step. The service appends `plan/mode` from `agent/pre-step` before + * step-time tool conditions and plan guidance read that committed state. + * Same-step retries do not commit pending selections. * * The exit tool is admitted only for requests whose committed plan state is * active. Native declarations, PTC bindings, and execution share that selection. @@ -178,40 +177,32 @@ export class PlanModeController extends Service { private readonly section: string /** - * Latest selection per session awaiting the next step boundary. + * Latest selection per session awaiting the next accepted in-turn pre-step. * `narrate` is true for user selections and false for the exit tool, whose * result already narrates the transition. */ private readonly pendingIntents = new WeakMap() - /** Sessions whose boundary-committed user switch still owes a notice in an admitted step. */ - private readonly unannounced = new WeakSet() constructor(ctx: Context, config: PlanModeConfig = { section: '' }) { super(ctx, 'planMode') this.section = resolveConfig(config).section let disposed = false - // The step boundary is outside Session.append publication, so it can append - // the log-only mode event inside an open turn without re-entering the - // session. A failed append remains pending and fails the proposal before - // model choice, guidance, or tool availability could read an uncommitted state. - ctx.on('agent/step-boundary', ({ agent }) => { - const pending = this.pendingIntents.get(agent.session) - if (pending === undefined) return - this.onBoundary(agent.session) - if (pending.narrate) this.unannounced.add(agent.session) - else this.unannounced.delete(agent.session) - }) - // The notice joins the first admitted step after the commit; a rejected - // proposal leaves it owed to the next one. + // Pre-step is outside Session.append publication, so it can append the + // log-only mode event inside an open turn without re-entering the session. + // A failed append remains pending and stops admission before guidance or + // tool availability could describe an uncommitted state. ctx.on('agent/pre-step', async ( { agent, signal }, next, ): Promise => { const decision = await next() - if (decision.kind === 'reject' || signal.aborted || !this.unannounced.has(agent.session)) return decision - this.unannounced.delete(agent.session) - const narration = this.narration(agent.session, this.loggedActive(agent.session)) - return narration === undefined ? decision : { ...decision, messages: [...decision.messages, narration] } + const pending = this.pendingIntents.get(agent.session) + if (decision.kind === 'reject' || signal.aborted || pending === undefined) return decision + const narration = this.narration(agent.session, pending.active) + this.onBoundary(agent.session) + return !pending.narrate || narration === undefined + ? decision + : { ...decision, messages: [...decision.messages, narration] } }) ctx.effect(() => () => { disposed = true }, 'dsh-plan-mode: close service lifetime') @@ -248,7 +239,7 @@ export class PlanModeController extends Service { return { kind: 'success', text: 'Plan mode entry cancelled.' } case 'noop': // Repeat the queued wording while an exit still awaits the - // next step boundary; only a truly inactive session reads + // next accepted pre-step; only a truly inactive session reads // idempotent. return this.loggedActive(agent.session) ? { kind: 'success', text: 'Leaving plan mode (applies from the next step).' } @@ -337,8 +328,8 @@ export class PlanModeController extends Service { } throw cause } - // A review may outlive this plugin fiber. Without its step-boundary - // listener, an approved selection could never be appended, so fail and keep planning. + // A review may outlive this plugin fiber. Without its pre-step listener, + // an approved selection could never be appended, so fail and keep planning. if (disposed) { throw new Error('the plan-mode service was reloaded while the plan was under review; present the plan again') } @@ -351,8 +342,8 @@ export class PlanModeController extends Service { : `The user chose to keep planning; their feedback: ${feedback}`) } // Keep plan guidance for the rest of this assistant tool batch. The - // silent selection is appended at the next step boundary, before that - // step chooses its model, tools, and prompt. + // silent selection is appended at the next accepted in-turn pre-step, + // before its tool and prompt assembly. this.pendingIntents.set(agent.session, { active: false, narrate: false }) return { approved: true } }, @@ -393,7 +384,7 @@ export class PlanModeController extends Service { /** * Read the logged plan state and any selected state awaiting the next - * step boundary. + * accepted in-turn pre-step. * * @param agent The agent to read. * @returns Current logged state plus a pending selection, when present. @@ -406,17 +397,17 @@ export class PlanModeController extends Service { /** * Select whether plan mode should be active. Between turns the method - * appends the change immediately because no step boundary will run until + * appends the change immediately because no in-turn pre-step will run until * another prompt starts a turn. The open-turn fold is the idle signal: * agent status stays `running` through post-turn checkpointing, when no - * further step boundary runs. During an open turn the selection remains - * pending until the next step boundary. Repeated selection of the current - * or already-pending state is a no-op. + * further in-turn pre-step runs. During an open turn the selection remains + * pending until the next accepted in-turn pre-step. Repeated selection of + * the current or already-pending state is a no-op. * * @param agent The agent to switch. * @param active Whether plan mode should be active. * @returns what happened: `committed` (logged now), `queued` (awaiting the - * next step boundary), `cancelled` (an opposite pending selection + * next accepted in-turn pre-step), `cancelled` (an opposite pending selection * was cleared; the logged state already matches), or `noop` (already in that * state). */ @@ -442,7 +433,7 @@ export class PlanModeController extends Service { return 'committed' } - /** Append one pending selection at a step boundary. */ + /** Append one pending selection before the next request assembly. */ private onBoundary(session: Session): void { const pending = this.pendingIntents.get(session) if (pending === undefined) return @@ -452,8 +443,8 @@ export class PlanModeController extends Service { return } session.append('plan/mode', { active: target }) - // Delete only after append succeeds so a later step boundary can retry a - // failed durable write. + // Delete only after append succeeds so a later accepted in-turn pre-step + // can retry a failed durable write. this.pendingIntents.delete(session) } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index cc9e21b61d..e1b48455eb 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -35,8 +35,8 @@ function registerQuestionAnswerer(ctx: Context, answerer: QuestionAnswerer): () * Drives the REAL plugin: mounts `dsh-plan-mode` beside real `SystemPrompt` and * `ToolRuntime` services, with fake Agents carrying real `Session`s and a * real scoped `agent.ctx` minted through `createScope`. - * Request boundaries are simulated by dispatching the real step-boundary and - * pre-step events and the following `step/start` session event used by the loop. + * Request boundaries are simulated by dispatching the real pre-step waterfall + * and the following `step/start` session event used by the loop. */ async function agentWithSession( @@ -105,7 +105,7 @@ async function setup(config: PlanModeConfig = PLAN_CONFIG): Promise { } /** - * Dispatch a step boundary, its pre-step processing, and optionally the following step-start commit. + * Dispatch pre-step processing and optionally its following step-start commit. */ async function boundary( ctx: Context, @@ -119,7 +119,6 @@ async function boundary( source: { kind: 'user' }, }) const signal = new AbortController().signal - await events.serial('agent/step-boundary', { turn: 1, step: 1, signal }) const decision = await events.waterfall( 'agent/pre-step', { messages: [message], turn: 1, step: 1, signal }, @@ -332,7 +331,7 @@ describe('the boundary flush', () => { expect(agent.session.snapshotEvents().some(event => event.type === 'plan/mode')).toBe(false) }) - it('flushes at the step boundary before the following step/start', async () => { + it('flushes from pre-step before the following step/start', async () => { const ctx = await setup() const agent = await agentWithSession(ctx) openTurn(agent.session) @@ -342,7 +341,7 @@ describe('the boundary flush', () => { expect(ctx.planMode.get(agent)).toEqual({ active: true }) }) - it('removes the boundary flush when the plugin fiber is disposed', async () => { + it('removes the pre-step flush when the plugin fiber is disposed', async () => { const ctx = new Context() await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) @@ -405,16 +404,17 @@ describe('the boundary flush', () => { expect(noticeTexts(agent.session)).toEqual(['The user switched this session back to the default mode.']) }) - it('commits at a rejected proposal and owes the notice to the next admitted step', async () => { + it('keeps the selection pending through a rejected proposal and commits it at the next accepted step', async () => { const ctx = await setup() const agent = await agentWithSession(ctx) header(agent.session) openTurn(agent.session) ctx.planMode.set(agent, true) await boundary(ctx, agent, 'pre-step', 'reject') - expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) + expect(ctx.planMode.get(agent)).toEqual({ active: false, pending: true }) expect(noticeTexts(agent.session)).toEqual([]) await boundary(ctx, agent, 'pre-step') + expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) expect(noticeTexts(agent.session)).toEqual(['The user switched this session to plan mode.']) }) @@ -457,7 +457,7 @@ describe('the boundary flush', () => { expect(ctx.planMode.get(agent).pending).toBeUndefined() }) - it('rejects a boundary append failure and keeps the intent pending', async () => { + it('rejects a pre-step append failure and keeps the intent pending', async () => { const ctx = await setup() const warn = vi.fn() ctx.logger.warn = warn as never diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 8191d85fd3..b27f69c79c 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1548,7 +1548,6 @@ function renderLifecycle(): string { ' Note over Agent,Driver: claim pending next-step input plus one queued prompt', ` Driver-->>SDK: ${mermaidCode('agent/inbox/spliced')} pure deletion`, ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, - ` Driver->>Hooks: ${mermaidCode('agent/step-boundary')} serial commits selections pending for this step`, ` Driver->>Hooks: ${mermaidCode('agent/model')} waterfall chooses provider, model, and effort, published as agent.step`, ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall reads agent.step`, ' Hooks-->>Driver: authoritative reject or enter(messages)', @@ -1598,7 +1597,6 @@ function renderLifecycle(): string { ' opt next-step input is pending', ' Driver-->>Driver: claim pending next-step input', ` Driver-->>SDK: ${mermaidCode('agent/inbox/claimed')} { message, turn } per message`, - ` Driver->>Hooks: ${mermaidCode('agent/step-boundary')} serial`, ` Driver->>Hooks: ${mermaidCode('agent/model')} waterfall`, ` Driver->>Hooks: ${mermaidCode('agent/pre-step')} waterfall`, ' Hooks-->>Driver: authoritative reject or enter(messages)', From 91f2601cc655b81125bccccf1964fcd57efa11b2 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 15 Oct 2026 14:16:07 +0800 Subject: [PATCH 13/36] test(python): admit the runtime context after the skill catalog in authoring snapshots The release-shaped authoring smoke records the first request's user blocks. The runtime-context snapshot now follows the messages that agent/pre-step admitted, so the skill catalog precedes it. CI on the previous head reported exactly this reorder for linux-x64 and win-x64; the content is unchanged. --- .../python-sdk-single-exe/authoring/model-visible.json | 2 +- .../python-sdk-single-exe/authoring/win-x64/model-visible.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/snapshots/python-sdk-single-exe/authoring/model-visible.json b/scripts/snapshots/python-sdk-single-exe/authoring/model-visible.json index f2b2dbfd29..92b4e76cf8 100644 --- a/scripts/snapshots/python-sdk-single-exe/authoring/model-visible.json +++ b/scripts/snapshots/python-sdk-single-exe/authoring/model-visible.json @@ -8,7 +8,7 @@ } }, "catalogs": [ - "Query the packaged Python environment for Office authoring.Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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`).\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n" + "Query the packaged Python environment for Office authoring.\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\nCurrent runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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`)." ], "result": { "python": "{{python}}", diff --git a/scripts/snapshots/python-sdk-single-exe/authoring/win-x64/model-visible.json b/scripts/snapshots/python-sdk-single-exe/authoring/win-x64/model-visible.json index 2b4e45627e..ff82ec7300 100644 --- a/scripts/snapshots/python-sdk-single-exe/authoring/win-x64/model-visible.json +++ b/scripts/snapshots/python-sdk-single-exe/authoring/win-x64/model-visible.json @@ -8,7 +8,7 @@ } }, "catalogs": [ - "Query the packaged Python environment for Office authoring.Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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`).\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n" + "Query the packaged Python environment for Office authoring.\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\nCurrent runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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`)." ], "result": { "python": "{{python}}", From 4eed4557fbcf6ea3c09bf3814aa46e5319062af4 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 15 Oct 2026 14:18:56 +0800 Subject: [PATCH 14/36] docs(upgrade-guide): move conditional tools to the v0.2.1-alpha.3 directory master bumped the root version to 0.2.1-alpha.3 after alpha.3 shipped without this change, so the alpha.2 directory is frozen and the guide describes the upgrade from alpha.3. --- .../conditional-tools/guide.i18n.yaml | 6 +++--- .../conditional-tools/guide.md | 0 .../conditional-tools/guide.zh.md | 0 3 files changed, 3 insertions(+), 3 deletions(-) rename docs/upgrade-guide/{v0.2.1-alpha.2 => v0.2.1-alpha.3}/conditional-tools/guide.i18n.yaml (87%) rename docs/upgrade-guide/{v0.2.1-alpha.2 => v0.2.1-alpha.3}/conditional-tools/guide.md (100%) rename docs/upgrade-guide/{v0.2.1-alpha.2 => v0.2.1-alpha.3}/conditional-tools/guide.zh.md (100%) diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.3/conditional-tools/guide.i18n.yaml similarity index 87% rename from docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml rename to docs/upgrade-guide/v0.2.1-alpha.3/conditional-tools/guide.i18n.yaml index a69c82d9a3..702105900b 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-alpha.3/conditional-tools/guide.i18n.yaml @@ -1,13 +1,13 @@ # Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.3/conditional-tools/guide.md /: en: 931aadab3e8321b3 zh: 5a68ca18ad6d18e1 /update-step-model-selection-conditional-tools-and-prompt-hooks: - en: 81e0b8c4355e86a3 - zh: 2563f89226c11cfb + en: cc28bfeb4ce0f855 + zh: 45e3bb42237e095a /update-step-model-selection-conditional-tools-and-prompt-hooks/change: en: 74258c18d35089bc zh: 726a331ba0b7af0b diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md b/docs/upgrade-guide/v0.2.1-alpha.3/conditional-tools/guide.md similarity index 100% rename from docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.md rename to docs/upgrade-guide/v0.2.1-alpha.3/conditional-tools/guide.md diff --git a/docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.3/conditional-tools/guide.zh.md similarity index 100% rename from docs/upgrade-guide/v0.2.1-alpha.2/conditional-tools/guide.zh.md rename to docs/upgrade-guide/v0.2.1-alpha.3/conditional-tools/guide.zh.md From 399f9867cd2b6d10405f538523b8bc6babfc63af Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 15 Oct 2026 14:37:15 +0800 Subject: [PATCH 15/36] test(snapshots): drop exit_plan_mode from master's cua scenarios cua-native and cua-ptc were recorded on master while exit_plan_mode stayed registered outside plan mode. With conditional admission the tool is declared only in committed plan mode, so the refreshed tool schemas and PTC prompt omit it; no other content changed. --- .../cua-native/tool-schemas.expected.json | 16 ---------------- .../session/cua-ptc/system-prompt.expected.md | 8 -------- 2 files changed, 24 deletions(-) diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 970dd64091..357bd82e9c 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -1246,22 +1246,6 @@ ] } }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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 session goal, including the id and revision that update_goal requires.", diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 64f0557897..92171689de 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -134,11 +134,6 @@ interface ToolArgsMap { /** Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request. */ justification?: string; } & Record; - /** Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. 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. */ - exit_plan_mode: { - /** The complete plan, as markdown, starting with a # heading that names it. */ - plan: string; - } & Record; /** Read the current session goal, including the id and revision that update_goal requires. */ get_goal: Record; /** Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved. */ @@ -372,9 +367,6 @@ interface ToolOutputMap { before: string; after: string; }; - exit_plan_mode: { - approved: boolean; - }; get_goal: { goal: null; } | { From 2ee53e1cceafc0132eca2dab1555fbde9288b4db Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 15 Oct 2026 16:10:22 +0800 Subject: [PATCH 16/36] test(python): admit the runtime context after the offloaded image in advanced snapshots The release-shaped sdk-snapshot smoke records an image message that a pre-step listener adds. The runtime-context snapshot now follows the messages that agent/pre-step admitted, so it moves after that image and the image/offload target seq changes from 13 to 12. The previous CI run stopped at the authoring snapshot before reaching this one. Re-recorded with --update-snapshots through apps/cli/lib/bin.js; the local result.json diff matched the linux-x64 and win-x64 CI diffs exactly. The scheduler-recovery, restart, minimal, minimal-in-history, and dynamic-tools snapshots re-record unchanged. --- .../advanced-ptc/result.json | 116 +++++++++--------- .../advanced-ptc/session.v4.jsonl | 4 +- .../advanced/result.json | 116 +++++++++--------- .../advanced/session.v4.jsonl | 4 +- 4 files changed, 120 insertions(+), 120 deletions(-) diff --git a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json index 4b8af914f2..38297aff95 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json @@ -130,6 +130,31 @@ "type": "user/message", "seq": 12, "time": 0, + "data": { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "image", + "attachment": { + "attachmentId": "sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640", + "mediaType": "image/png", + "width": 1, + "height": 1, + "bytes": 69 + } + } + ], + "source": { + "kind": "python-snapshot-image-offload" + } + }, + "surfaceOp": "append" + }, + { + "type": "user/message", + "seq": 13, + "time": 0, "data": { "content": [ { @@ -160,31 +185,6 @@ }, "surfaceOp": "append" }, - { - "type": "user/message", - "seq": 13, - "time": 0, - "data": { - "id": "{{messageId}}", - "role": "user", - "content": [ - { - "type": "image", - "attachment": { - "attachmentId": "sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640", - "mediaType": "image/png", - "width": 1, - "height": 1, - "bytes": 69 - } - } - ], - "source": { - "kind": "python-snapshot-image-offload" - } - }, - "surfaceOp": "append" - }, { "type": "request/header", "seq": 14, @@ -265,7 +265,7 @@ "data": { "targets": [ { - "seq": 13, + "seq": 12, "imageIndexes": [ 0 ] @@ -1200,6 +1200,37 @@ "type": "user/message", "seq": 12, "time": 0, + "data": { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "image", + "attachment": { + "attachmentId": "sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640", + "mediaType": "image/png", + "width": 1, + "height": 1, + "bytes": 69 + } + } + ], + "source": { + "kind": "python-snapshot-image-offload" + } + }, + "surfaceOp": "append" + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{parent}}", + "event": { + "type": "user/message", + "seq": 13, + "time": 0, "data": { "content": [ { @@ -1232,37 +1263,6 @@ } } }, - { - "method": "session.event", - "payload": { - "sessionId": "{{parent}}", - "event": { - "type": "user/message", - "seq": 13, - "time": 0, - "data": { - "id": "{{messageId}}", - "role": "user", - "content": [ - { - "type": "image", - "attachment": { - "attachmentId": "sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640", - "mediaType": "image/png", - "width": 1, - "height": 1, - "bytes": 69 - } - } - ], - "source": { - "kind": "python-snapshot-image-offload" - } - }, - "surfaceOp": "append" - } - } - }, { "method": "session.event", "payload": { @@ -1371,7 +1371,7 @@ "data": { "targets": [ { - "seq": 13, + "seq": 12, "imageIndexes": [ 0 ] diff --git a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl index 33fda38ea2..565f69ffa9 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl @@ -11,13 +11,13 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Run the advanced packaged-runtime snapshot scenario."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"image","attachment":{"attachmentId":"sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640","mediaType":"image/png","width":1,"height":1,"bytes":69}}],"source":{"kind":"python-snapshot-image-offload"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["run_code"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} {"type":"session/title","data":{"title":"Run the advanced packaged-runtime snapsh","messageSeqs":[11],"source":{"kind":"fallback"}}} {"type":"assistant/attempt","data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"code":"IMAGE_OFFLOAD_REQUIRED","message":"authored image budget failure","offloadImages":1}}}}]}} -{"type":"image/offload","data":{"targets":[{"seq":13,"imageIndexes":[0]}]}} +{"type":"image/offload","data":{"targets":[{"seq":12,"imageIndexes":[0]}]}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["run_code"]},"reason":"series"}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":4,"throughSeq":19}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Call the configured Plugin tool\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-code","name":"run_code","args":[""]},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-code","args":["{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Call the configured Plugin tool\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Call the configured Plugin tool\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/result.json b/scripts/snapshots/python-sdk-single-exe/advanced/result.json index 33e0c033e8..953717153b 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced/result.json @@ -130,6 +130,31 @@ "type": "user/message", "seq": 12, "time": 0, + "data": { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "image", + "attachment": { + "attachmentId": "sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640", + "mediaType": "image/png", + "width": 1, + "height": 1, + "bytes": 69 + } + } + ], + "source": { + "kind": "python-snapshot-image-offload" + } + }, + "surfaceOp": "append" + }, + { + "type": "user/message", + "seq": 13, + "time": 0, "data": { "content": [ { @@ -160,31 +185,6 @@ }, "surfaceOp": "append" }, - { - "type": "user/message", - "seq": 13, - "time": 0, - "data": { - "id": "{{messageId}}", - "role": "user", - "content": [ - { - "type": "image", - "attachment": { - "attachmentId": "sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640", - "mediaType": "image/png", - "width": 1, - "height": 1, - "bytes": 69 - } - } - ], - "source": { - "kind": "python-snapshot-image-offload" - } - }, - "surfaceOp": "append" - }, { "type": "request/header", "seq": 14, @@ -273,7 +273,7 @@ "data": { "targets": [ { - "seq": 13, + "seq": 12, "imageIndexes": [ 0 ] @@ -1672,6 +1672,37 @@ "type": "user/message", "seq": 12, "time": 0, + "data": { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "image", + "attachment": { + "attachmentId": "sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640", + "mediaType": "image/png", + "width": 1, + "height": 1, + "bytes": 69 + } + } + ], + "source": { + "kind": "python-snapshot-image-offload" + } + }, + "surfaceOp": "append" + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{parent}}", + "event": { + "type": "user/message", + "seq": 13, + "time": 0, "data": { "content": [ { @@ -1704,37 +1735,6 @@ } } }, - { - "method": "session.event", - "payload": { - "sessionId": "{{parent}}", - "event": { - "type": "user/message", - "seq": 13, - "time": 0, - "data": { - "id": "{{messageId}}", - "role": "user", - "content": [ - { - "type": "image", - "attachment": { - "attachmentId": "sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640", - "mediaType": "image/png", - "width": 1, - "height": 1, - "bytes": 69 - } - } - ], - "source": { - "kind": "python-snapshot-image-offload" - } - }, - "surfaceOp": "append" - } - } - }, { "method": "session.event", "payload": { @@ -1851,7 +1851,7 @@ "data": { "targets": [ { - "seq": 13, + "seq": 12, "imageIndexes": [ 0 ] diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl index dcd09c277c..f5cf4d95f8 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl @@ -11,13 +11,13 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Run the advanced packaged-runtime snapshot scenario."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"image","attachment":{"attachmentId":"sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640","mediaType":"image/png","width":1,"height":1,"bytes":69}}],"source":{"kind":"python-snapshot-image-offload"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} {"type":"session/title","data":{"title":"Run the advanced packaged-runtime snapsh","messageSeqs":[11],"source":{"kind":"fallback"}}} {"type":"assistant/attempt","data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"code":"IMAGE_OFFLOAD_REQUIRED","message":"authored image budget failure","offloadImages":1}}}}]}} -{"type":"image/offload","data":{"targets":[{"seq":13,"imageIndexes":[0]}]}} +{"type":"image/offload","data":{"targets":[{"seq":12,"imageIndexes":[0]}]}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"series"}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":4,"throughSeq":19}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-native","name":"snapshot_double","arguments":"{\"value\": 21}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-native","name":"snapshot_double","args":[""]},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-native","args":["{\"value\": 21}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-native","name":"snapshot_double","arguments":"{\"value\": 21}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"} From f2f563c681ed85586fe614a2645650a803b3f847 Mon Sep 17 00:00:00 2001 From: Shigma Date: Thu, 15 Oct 2026 16:59:58 +0800 Subject: [PATCH 17/36] fix(cordis): route wrapper updates through the canonical Fiber --- docs/cordis-api/fiber.i18n.yaml | 8 +++--- docs/cordis-api/fiber.md | 6 ++--- docs/cordis-api/fiber.zh.md | 9 +++---- packages/settings/settings/src/index.ts | 1 + scripts/cordis-config-access.spec.ts | 21 +++++++++++++-- scripts/loader-volatile-update.spec.ts | 6 ++--- vendor/README.md | 2 +- vendor/cordis/README.md | 2 +- vendor/cordis/src/fiber.ts | 36 +++++++++++++------------ 9 files changed, 54 insertions(+), 37 deletions(-) diff --git a/docs/cordis-api/fiber.i18n.yaml b/docs/cordis-api/fiber.i18n.yaml index 6c1d8987ce..042af3ba02 100644 --- a/docs/cordis-api/fiber.i18n.yaml +++ b/docs/cordis-api/fiber.i18n.yaml @@ -24,8 +24,8 @@ en: 1b527d85759324f9 zh: 54aa40db2705b95c /fiber/the-fiber-class/fiber-config: - en: ee804c03c39e7806 - zh: 4353ba7817ec61ec + en: 1efe137a7ef0e599 + zh: bb4b9818fb48f4e9 /fiber/the-fiber-class/fiber-state: en: 999ad29dfc29661b zh: 20245d11c338e3f1 @@ -66,8 +66,8 @@ en: 6ffc1baba98d689f zh: 7e13bc92225c7e0a /fiber/the-fiber-class/fiber-update-config-nosave: - en: 290f7f1bf1207adc - zh: e666cfb53dea897a + en: 5c176a6e67073e92 + zh: ee07edc8dbf7c1f3 /fiber/effect: en: 007d5b214e8a8610 zh: d74c26fbb1b8aeb6 diff --git a/docs/cordis-api/fiber.md b/docs/cordis-api/fiber.md index 366c457d4f..e85cc7b3e6 100644 --- a/docs/cordis-api/fiber.md +++ b/docs/cordis-api/fiber.md @@ -80,11 +80,11 @@ The context this fiber's plugin runs in (extends the parent context). ### fiber.config ```ts cordis-catalog -/** The validated plugin config (updated by `update()`). */ +/** The validated plugin config (updated by `update()`); read through {@link effectiveConfig}. */ public config: any ``` -The validated plugin config (updated by `update()`). +The validated plugin config (updated by `update()`); read through effectiveConfig. [Source](../../vendor/cordis/src/fiber.ts#L190) @@ -318,7 +318,7 @@ Runs the `internal/update` waterfall first, so update hooks (and HMR) can veto o **Returns** nothing; the restart runs behind the `internal/update` waterfall. -[Source](../../vendor/cordis/src/fiber.ts#L763) +[Source](../../vendor/cordis/src/fiber.ts#L764) ## Effect diff --git a/docs/cordis-api/fiber.zh.md b/docs/cordis-api/fiber.zh.md index 05ee483bdd..d529013e73 100644 --- a/docs/cordis-api/fiber.zh.md +++ b/docs/cordis-api/fiber.zh.md @@ -82,11 +82,11 @@ public readonly ctx: Context ### fiber.config ```ts cordis-catalog -/** The validated plugin config (updated by `update()`). */ +/** The validated plugin config (updated by `update()`); read through {@link effectiveConfig}. */ public config: any ``` -经过校验的插件配置(由 `update()` 更新)。 +经过校验的插件配置(由 `update()` 更新);通过 `effectiveConfig` 读取。 [源码](../../vendor/cordis/src/fiber.ts#L190) @@ -218,7 +218,6 @@ getEffects() get rawConfig(): unknown ``` - 保留供下次激活使用的原始输入,不执行表达式求值或验证。 [源码](../../vendor/cordis/src/fiber.ts#L642) @@ -233,7 +232,6 @@ get rawConfig(): unknown get effectiveConfig(): unknown ``` - 既有激活/更新生命周期发布的配置对象,不克隆或重新解析。首次解析前为 undefined,卸载后仍可读取;需要运行实例的调用方应检查 `state`。 [源码](../../vendor/cordis/src/fiber.ts#L655) @@ -252,7 +250,6 @@ get effectiveConfig(): unknown resolveConfig(config: unknown): unknown ``` - 通过此 fiber 的 `internal/config` 钩子和运行时 schema 对候选值求值并验证。此操作不发布结果、不替换原始输入,也不提交运行中的 volatile 引用。钩子访问的注入服务必须已经可用。 - `config`:原始候选输入。 @@ -323,7 +320,7 @@ update(config: any, noSave = false) **返回**无返回值;重启由 `internal/update` waterfall 执行。 -[源码](../../vendor/cordis/src/fiber.ts#L763) +[源码](../../vendor/cordis/src/fiber.ts#L764) ## Effect diff --git a/packages/settings/settings/src/index.ts b/packages/settings/settings/src/index.ts index bd439b2301..9ab841d145 100644 --- a/packages/settings/settings/src/index.ts +++ b/packages/settings/settings/src/index.ts @@ -317,6 +317,7 @@ export class SettingsForms extends Service { this.ownerContext.emit('settings/document-updated', entry.options.id as SettingsNamespace, revision) } const value = projectForm(form, plainConfig(entry.fiber.effectiveConfig)) + // Inherited layers omit profile fields, so only interpolate and validate them, without the running fiber's config hooks. const resolved: unknown = interpolate(entry.fiber.ctx, inherited) const base = projectForm(form, plainConfig(inheritedConfig(entry.fiber.runtime, resolved))) const user = projectForm(form, override) diff --git a/scripts/cordis-config-access.spec.ts b/scripts/cordis-config-access.spec.ts index 16457afdec..e70d9992f7 100644 --- a/scripts/cordis-config-access.spec.ts +++ b/scripts/cordis-config-access.spec.ts @@ -54,18 +54,35 @@ describe('Fiber configuration access', () => { expect(hook).toHaveBeenCalledOnce() expect(fiber.effectiveConfig).toBe(initial) expect(apply).toHaveBeenCalledOnce() - await fiber.restart() + await wrapper.restart() expect(fiber.effectiveConfig).toBe(raw) expect(apply).toHaveBeenCalledTimes(2) }) + it('publishes updates through registry wrappers to the canonical fiber', async () => { + const ctx = root() + const initial = { value: 1 } + const apply = vi.fn() + const wrapper = ctx.plugin(apply, initial) + await wrapper + const raw = { value: 2 } + wrapper.update(raw) + await wrapper.await() + expect(apply).toHaveBeenLastCalledWith(wrapper.ctx, raw) + expect(wrapper.rawConfig).toBe(raw) + expect(wrapper.effectiveConfig).toBe(raw) + expect(wrapper.ctx.fiber.rawConfig).toBe(raw) + expect(wrapper.ctx.fiber.effectiveConfig).toBe(raw) + expect(apply).toHaveBeenCalledTimes(2) + }) + it('retains a pending raw update until its injection is available', async () => { const ctx = root() ctx.provide('configAccessTest') const apply = vi.fn() const wrapper = ctx.plugin({ inject: ['configAccessTest'], apply }, { value: 1 }) const raw = { value: 2 } - wrapper.ctx.fiber.update(raw) + wrapper.update(raw) expect(wrapper.rawConfig).toBe(raw) expect(wrapper.effectiveConfig).toBeUndefined() ctx.set('configAccessTest', {}) diff --git a/scripts/loader-volatile-update.spec.ts b/scripts/loader-volatile-update.spec.ts index c23486cc66..f2a1c4671a 100644 --- a/scripts/loader-volatile-update.spec.ts +++ b/scripts/loader-volatile-update.spec.ts @@ -481,9 +481,9 @@ it('logs an invalid candidate and keeps its references while other entries commi await invalid.entry!.update({ config: { title: 'invalid', nested: { count: -1 } } }) await healthy.entry!.update({ config: { title: 'healthy' } }) expect(warning).toHaveBeenCalledTimes(2) - expect((invalid.config as ReturnType).title.get()).toBe('hello') + expect((invalid.effectiveConfig as ReturnType).title.get()).toBe('hello') expect(invalid.rawConfig).toEqual({ title: 'invalid', nested: { count: -1 } }) - expect((healthy.config as ReturnType).title.get()).toBe('healthy') + expect((healthy.effectiveConfig as ReturnType).title.get()).toBe('healthy') expect(events).toHaveBeenCalledExactlyOnceWith([['title']]) }) @@ -617,7 +617,7 @@ it('isolates a failing notification listener and dispatches with a Context recei expect(receivers).toEqual([fiber]) expect(warning).toHaveBeenCalledWith(expect.objectContaining({ message: 'listener boom' })) await update(other, { title: 'unaffected' }) - expect((other.config as ReturnType).title.get()).toBe('unaffected') + expect((other.effectiveConfig as ReturnType).title.get()).toBe('unaffected') }) it('remounts instead of committing when an ordinary field parses into a fresh class instance', async () => { diff --git a/vendor/README.md b/vendor/README.md index deff0e6500..207cea6847 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -46,7 +46,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. 12. **`loader/src/config/entry.ts` activation observer**: the detached `Entry.init()` completion observer handles both outcomes; the fiber retains its activation error for explicit consumer audits. Covered by `packages/boot/app-boot/tests/user-patches.spec.ts`. 13. **`include/src/index.ts` `writeTask` type**: widened the optional `writeTask?: NodeJS.Timeout` property to `NodeJS.Timeout | undefined` — the debounced writer assigns `undefined` on flush, which `exactOptionalPropertyTypes` rejects on a plain optional. Type-only; no behavior change. 14. **`include/src/index.ts` durable debounced writes**: serialized and tracked config-file writes, retried transient `EACCES`/`EBUSY`/`EPERM` rename failures with a bounded backoff, observed asynchronous timer rejections, and drained writes before and after child removal during Include teardown. The first drain preserves an existing terminal write failure even if child removal schedules a later write. Missing-file initialization awaits the write and forces a fresh parse before mounting the initial entries. Windows can briefly retain a destination handle after a Loader child disposes; the upstream fire-and-forget rename escaped as an unhandled rejection and could lose the persisted `disabled` state. A terminal failure is logged by the asynchronous writer and remains on the queue so `Include.stop()` rethrows it instead of silently declaring persistence complete; Cordis's ordinary fiber teardown retains its separate error-containment contract. Covered by `packages/host/directory-picker-auto/tests/loader-composition.spec.ts` with injected transient and terminal rename failures. -15. **Lazy Loader config resolution across `cordis/src/{events,fiber}.ts`, `loader/src/{index,config/entry}.ts`, `include/src/index.ts`, and `hmr/src/index.ts`**: ports [cordiverse/cordis#41](https://github.com/cordiverse/cordis/pull/41), retaining raw fiber config and resolving it through `internal/config` only after declared injections are active. Provider replacement re-resolves the raw expression, pending updates retain it, and HMR transfers it. Resolution applies only to the entry root, so child plugins mounted by a row keep caller-owned config identity. Include declares the `EntryGroup.key` tree-carrier marker (as Group does): its config is entry and patch lists, so interpolation keeps it literal and a `!!js` expression inside a nested row's config resolves lazily in that row's own fiber (Include's own `path` therefore stays literal too). Deferred failures retain the owning row diagnostic, and tree teardown does not persist failure-driven self-disposal. `Fiber.rawConfig`, `Fiber.resolveConfig(candidate)` and `Fiber.effectiveConfig` centralize raw retention, candidate evaluation and reads of the lifecycle-published object. Accessors use the canonical fiber, including writes through registry wrappers; candidate resolution never publishes or commits references. Loader volatile updates, config editing, settings, translator and both HMR providers use these accessors while the existing Core config fields and event protocol remain in place. Covered by `scripts/cordis-config-access.spec.ts`, `packages/boot/app-boot/tests/{app-boot,user-patches}.spec.ts`, `packages/boot/cmdline/tests/cmdline.spec.ts`, `apps/cli/tests/web-agent-presets.e2e.ts`, and the built custom-profile cases in `apps/cli/tests/built-bin.e2e.ts`. +15. **Lazy Loader config resolution across `cordis/src/{events,fiber}.ts`, `loader/src/{index,config/entry}.ts`, `include/src/index.ts`, and `hmr/src/index.ts`**: ports [cordiverse/cordis#41](https://github.com/cordiverse/cordis/pull/41), retaining raw fiber config and resolving it through `internal/config` only after declared injections are active. Provider replacement re-resolves the raw expression, pending updates retain it, and HMR transfers it. Resolution applies only to the entry root, so child plugins mounted by a row keep caller-owned config identity. Include declares the `EntryGroup.key` tree-carrier marker (as Group does): its config is entry and patch lists, so interpolation keeps it literal and a `!!js` expression inside a nested row's config resolves lazily in that row's own fiber (Include's own `path` therefore stays literal too). Deferred failures retain the owning row diagnostic, and tree teardown does not persist failure-driven self-disposal. `Fiber.rawConfig`, `Fiber.resolveConfig(candidate)` and `Fiber.effectiveConfig` centralize raw retention, candidate evaluation and reads of the lifecycle-published object. Accessors, updates and restarts use the canonical fiber, including calls through registry wrappers; candidate resolution never publishes or commits references. Loader volatile updates, config editing, settings, translator and both HMR providers use these accessors while the existing Core config fields and event protocol remain in place. Covered by `scripts/cordis-config-access.spec.ts`, `packages/boot/app-boot/tests/{app-boot,user-patches}.spec.ts`, `packages/boot/cmdline/tests/cmdline.spec.ts`, `apps/cli/tests/web-agent-presets.e2e.ts`, and the built custom-profile cases in `apps/cli/tests/built-bin.e2e.ts`. 16. **`cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match. 17. **`@deepseek-ai` rescope**: every vendored manifest `name`, every internal dependency entry among the vendored set, and every module specifier that reaches them use the scoped names in the manifest table's `npm name` column. Directory names, version numbers, and dependency ranges are unchanged, and no upstream runtime identifier is renamed — `Symbol.for('schemastery')` and Schemastery's `vendor:` metadata field keep their upstream values. Re-apply with `pnpm run rescope-vendor --apply` after a sync; the table's two name columns are the mapping, restated for consumers in [docs/rescope.md](../docs/rescope.md). 18. **Entry `disabled` interpolation in `loader/src/config/entry.ts`**: a `disabled: !!js` expression evaluates against the loader context at every mount decision; the raw node stays in the options, so write-back keeps the `!!js` form. `disabled` is the only interpolated metadata field. Covered by `packages/boot/app-boot/tests/user-patches.spec.ts` and `apps/cli/tests/windows-shell.spec.ts`. diff --git a/vendor/cordis/README.md b/vendor/cordis/README.md index 2f7385dcf4..ad3e290a54 100644 --- a/vendor/cordis/README.md +++ b/vendor/cordis/README.md @@ -106,6 +106,6 @@ Schemas may return `Volatile` references, whose values are read through `.get ## Configuration access -`fiber.rawConfig` reads or retains the raw input for a later activation. Assigning it does not validate, update the running instance or trigger a restart. `fiber.resolveConfig(candidate)` evaluates the fiber’s config hooks and schema without publishing the result; any services used by those hooks must already be available. `fiber.effectiveConfig` returns the lifecycle-published object without re-parsing, preserving the identity of volatile references. It is undefined before the first resolution and stays readable after unload, so consumers that require a running instance also check the fiber state. +`fiber.rawConfig` reads or retains the raw input for a later activation. Assigning it does not validate, update the running instance or trigger a restart. Registry wrappers route raw writes, updates and restarts through the same canonical fiber. `fiber.resolveConfig(candidate)` evaluates the fiber's config hooks and schema without publishing the result; any services used by those hooks must already be available. `fiber.effectiveConfig` returns the lifecycle-published object without re-parsing, preserving the identity of volatile references. It is undefined before the first resolution and stays readable after unload, so consumers that require a running instance also check the fiber state. Use `fiber.update()` for an ordinary config change. Loader retains raw input separately when committing only volatile values into the running object. diff --git a/vendor/cordis/src/fiber.ts b/vendor/cordis/src/fiber.ts index a21f18510d..d4aed3158f 100644 --- a/vendor/cordis/src/fiber.ts +++ b/vendor/cordis/src/fiber.ts @@ -186,9 +186,9 @@ export class Fiber { public uid: number | null /** The context this fiber's plugin runs in (extends the parent context). */ public readonly ctx: Context - /** The validated plugin config (updated by `update()`). */ + /** The validated plugin config (updated by `update()`); read through {@link effectiveConfig}. */ public config: any - /** The raw plugin config, re-resolved before each activation. */ + /** The raw plugin config, re-resolved before activation; use {@link rawConfig} to read or retain it. */ public _config: any /** Current lifecycle state; transitions emit `internal/status`. */ public state = FiberState.PENDING @@ -743,10 +743,11 @@ export class Fiber { * @throws {CordisError} `INACTIVE_EFFECT` when the fiber is already disposed. */ async restart() { - this.assertActive() - this._setEpoch(INACTIVE) - this._refresh() - await this.await() + const fiber = this.ctx.fiber + fiber.assertActive() + fiber._setEpoch(INACTIVE) + fiber._refresh() + await fiber.await() } /** @@ -761,21 +762,22 @@ export class Fiber { * @throws {ValidationError} when the new config fails validation. */ update(config: any, noSave = false) { - this.assertActive() - this._config = config - if (this.state !== FiberState.ACTIVE) { + const fiber = this.ctx.fiber + fiber.assertActive() + fiber._config = config + if (fiber.state !== FiberState.ACTIVE) { // Config resolution may access injected services, so defer it until the // fiber can activate. - this._error = undefined - this._setEpoch(INACTIVE) - this._refresh() + fiber._error = undefined + fiber._setEpoch(INACTIVE) + fiber._refresh() return } - config = this.resolveConfig(config) - this.context.waterfall(this, 'internal/update', config, noSave, () => { - this.config = config - this._error = undefined - return this.restart() + config = fiber.resolveConfig(config) + fiber.context.waterfall(fiber, 'internal/update', config, noSave, () => { + fiber.config = config + fiber._error = undefined + return fiber.restart() }) } } From 9be99a0e28521436e5ea34ebc6464b3597e519a0 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Wed, 21 Oct 2026 13:50:19 +0800 Subject: [PATCH 18/36] feat(web): upload composer images when they are added An ordinary Session's composer now uploads each image draft through the background upload queue as soon as it is added. The raw upload route stages the body as a prompt image when the request names its media type: the Host reads at most the per-image byte limit, then validates, normalizes, and stores the image as prompt admission would. The prompt cites the receipt in a file part; prompt admission resolves it to the stored image, applies the image-input check, and counts stored images toward maxImagesPerMessage. Send waits for every image receipt, and a failed image upload turns its thumbnail into a retry control. Commands and subagent continuations keep encoding images inline. --- .../2026-08-26-generic-file-upload.i18n.yaml | 8 +- .../feature/2026-08-26-generic-file-upload.md | 4 +- .../2026-08-26-generic-file-upload.zh.md | 4 +- ...-21-composer-image-upload-on-add.i18n.yaml | 25 +++ ...2026-10-21-composer-image-upload-on-add.md | 35 +++++ ...6-10-21-composer-image-upload-on-add.zh.md | 35 +++++ apps/web/tests/assembled-boot.ts | 3 + apps/web/tests/assembled-remote.ts | 31 +++- apps/web/tests/queue-image.e2e.ts | 3 + docs/event-producer-consumer.md | 10 +- docs/event-producer-consumer.zh.md | 10 +- docs/persistence-catalog.i18n.yaml | 12 +- docs/persistence-catalog.md | 6 +- docs/persistence-catalog.zh.md | 6 +- docs/persistence-schema.json | 6 +- docs/subsystems/attachment.md | 31 +++- docs/subsystems/attachment.zh.md | 31 +++- .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 2 +- packages/api/session-controller/README.zh.md | 2 +- .../api/session-controller/src/commands.ts | 22 +-- packages/api/session-controller/src/types.ts | 3 +- .../tests/commands-upload-file.host.spec.ts | 108 +++++++++++-- .../attachment/attachment/README.i18n.yaml | 4 +- packages/attachment/attachment/README.md | 2 +- packages/attachment/attachment/README.zh.md | 2 +- packages/attachment/attachment/src/index.ts | 26 +++- packages/attachment/attachment/src/types.ts | 7 +- .../attachment/tests/admission.spec.ts | 37 +++++ packages/client/file-upload/README.i18n.yaml | 12 +- packages/client/file-upload/README.md | 6 +- packages/client/file-upload/README.zh.md | 6 +- .../client/file-upload/src/client/contract.ts | 23 ++- .../client/file-upload/src/client/runtime.ts | 116 +++++++++++--- packages/client/file-upload/src/http-route.ts | 23 +-- packages/client/file-upload/src/index.ts | 111 +++++++++++--- packages/client/file-upload/src/types.ts | 15 +- .../tests/file-upload-http.host.spec.ts | 23 +++ .../tests/file-upload.client.spec.ts | 49 ++++++ .../client/ui-attachment/README.i18n.yaml | 4 +- packages/client/ui-attachment/README.md | 2 +- packages/client/ui-attachment/README.zh.md | 2 +- .../src/client/ComposerAttachments.module.css | 51 ++++++ .../src/client/ComposerAttachments.tsx | 46 ++++-- .../composer-attachments.client.spec.tsx | 26 ++++ .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../ui-conversation/src/client/apply.ts | 4 +- .../src/client/contract/slots.ts | 14 +- .../ui-conversation/src/client/service.ts | 107 +++++++------ .../src/client/skeleton/InputBar.tsx | 11 +- .../tests/input-bar.client.spec.tsx | 25 ++- .../service-orchestration.client.spec.ts | 145 +++++++++++++++--- .../src/client/slot-catalog.ts | 56 +++---- .../extensions/tool-cordis/src/api-catalog.ts | 26 +++- .../client-runtime/README.i18n.yaml | 4 +- .../test-support/client-runtime/README.md | 2 +- .../test-support/client-runtime/README.zh.md | 2 +- .../test-support/client-runtime/src/index.ts | 3 + .../tests/helpers.client.spec.tsx | 1 + scripts/gen-cordis-catalog.ts | 2 + 62 files changed, 1124 insertions(+), 280 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.md create mode 100644 .agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.zh.md diff --git a/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.i18n.yaml b/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.i18n.yaml index 496d2e8136..98789701f0 100644 --- a/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.i18n.yaml @@ -9,8 +9,8 @@ en: e7c3b5d7702714fe zh: 268f162b553b37d1 /agent-note-generic-file-upload/decision: - en: 31c7ad96c6ab82c8 - zh: 806922fc8fcd1242 + en: 1769950d73d30dca + zh: bf296b920ea9b997 /agent-note-generic-file-upload/alternatives-considered: en: 23f386b05e4e79ef zh: 0756c4fa30e8d0eb @@ -21,5 +21,5 @@ en: 3a50ac370d51cda9 zh: d490f58922f8795b /agent-note-generic-file-upload/related: - en: 7579c49eefdb8488 - zh: 68ad384fd9d2f8f9 + en: 14e8659b89dc08a8 + zh: dec5baa11f168e91 diff --git a/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.md b/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.md index f60649a083..133312a83c 100644 --- a/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.md +++ b/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.md @@ -14,7 +14,7 @@ The command plane had already established a whole-envelope rule for images: a co Files and images use separate storage schemes and one ordered message attachment list. Images keep their normalized-attachment pipeline unchanged. Other picked files enter one FIFO background-upload queue and are stored byte-for-byte with no type or size limits, then staged in-process for the same Session. Equal bytes have one canonical object under `DSH_HOME/attachments/v1/file-objects//`; each read-only model-facing path at `DSH_HOME/attachments/v1/files///` is a hard link, so different display names do not duplicate content. The configurable queue defaults to two active transfers. The independent dual-face `file-upload` Cordis package owns transfer and staging. Its Client `fileUpload` service accepts the owning Session identity together with a `Blob`, exact bytes, or a one-shot `ReadableStream`; it uses that identity to assemble the raw route request or invoke the generated Remote directly. Its Host `fileUploads` service owns the streaming route, encoded Remote fallback, command receipt resolver, and receipt tables keyed by the receiving Agent's Session object. Encoded admission and attachment-error recognition go through `ctx.attachments`, whose provider owns byte storage. Session Controller registers the resolver for cold ordinary Agents and consumes receipts during prompt admission; Session objects do not expose file transfer. Served Web pages hand each active body to a dedicated upload Worker: Blob bodies use XMLHttpRequest for total-aware byte progress, while streams transfer ownership and feed Fetch incrementally. Worker-hosted pages transfer the body through their page-owned Fetch carrier to the Host Worker, which reads bounded chunks. The page thread never reads, base64-encodes, or JSON-serializes generic file bytes. The authenticated Host route opts into Connection's streaming request mode, so the bridge dispatches before consuming the body and the local store hashes and writes bounded chunks to a private staging object. Completion atomically publishes the content-addressed object; cancellation or failure removes the staging file. Upload operations and draft state belong to the resident conversation root, so navigation to another Session does not stop the transfer; returning to the original Session shows the same card and progress. Removing the file card skips its queued transfer or aborts its active transfer. The sent message carries a structured `FileBlock` (`{ name, bytes, attachmentId }`) inside `user/message`; no new session event type exists. Request assembly in `LlmRuntime` projects every file block, including nested tool-result occurrences, to one deterministic handle naming the file and its saved read-only path. The handle tells a main agent to include that path when delegating file work and to report when the child's execution environment cannot see it. No provider receives file bytes; the model reads the stored copy with existing file tools on demand. -Default mode, active Plan Mode, and an active goal share ordinary queue, follow-up, and steer attachment admission. `/goal` create and edit and `/plan` entry accept the same ordered image and file batches; attachment-bearing control subcommands reject before changing state. Command submissions cite completed staged-file receipts, so generic file bytes are not read or copied again. Session Controller resolves every file receipt to a durable reference before `ctx.attachments.admitPromptContent()` receives the complete ordered content list; attachment admission persists images and passes file references unchanged. The Host rejects upload completion after the original Agent is disposed and deduplicates prompt retries already identified by `rpcId`. Prompt receipts remain available through failure recovery, then retire after the accepted queue or history occurrence is observed; command-only receipts remain until Session disposal. Submission echoes register through `beginSubmission` before serialization, carry mixed attachments through `pendingSubmissions`, correlate by `rpcId`, retire once after queue or history observation, and keep drafts on failure. Before submission, the composer presents the ordered batch in one non-wrapping horizontal rail: images use 64 by 64 pixel thumbnails and generic files use 240 by 64 pixel cards with a 16 pixel radius, blue document glyph, filename plus extension and size, and a hover or keyboard removal action. QueueDock uses the same order with compact thumbnails and file cards. After submission, Chat presents the ordered batch in one right-aligned wrapping attachment flow. A lone image retains the large gallery presentation; a message with multiple attachments uses 64 by 64 pixel image tiles and 240 by 64 pixel file cards, so files and images share each row until the available width forces a wrap. Trajectory keeps the user-message preview compact and adds a localized generic-file count. Paperclip, drag, and paste classify by MIME; send waits for every file upload. Continuable subagent composers disable attachment intake, and the Host rejects any file block received for a child session. +Default mode, active Plan Mode, and an active goal share ordinary queue, follow-up, and steer attachment admission. `/goal` create and edit and `/plan` entry accept the same ordered image and file batches; attachment-bearing control subcommands reject before changing state. Command submissions cite completed staged-file receipts, so generic file bytes are not read or copied again. Session Controller resolves every file receipt to a durable reference before `ctx.attachments.admitPromptContent()` receives the complete ordered content list; attachment admission persists images and passes file references unchanged. The Host rejects upload completion after the original Agent is disposed and deduplicates prompt retries already identified by `rpcId`. Prompt receipts remain available through failure recovery, then retire after the accepted queue or history occurrence is observed; command-only receipts remain until Session disposal. Submission echoes register through `beginSubmission` before serialization, carry mixed attachments through `pendingSubmissions`, correlate by `rpcId`, retire once after queue or history observation, and keep drafts on failure. Before submission, the composer presents the ordered batch in one non-wrapping horizontal rail: images use 64 by 64 pixel thumbnails and generic files use 240 by 64 pixel cards with a 16 pixel radius, blue document glyph, filename plus extension and size, and a hover or keyboard removal action. QueueDock uses the same order with compact thumbnails and file cards. After submission, Chat presents the ordered batch in one right-aligned wrapping attachment flow. A lone image retains the large gallery presentation; a message with multiple attachments uses 64 by 64 pixel image tiles and 240 by 64 pixel file cards, so files and images share each row until the available width forces a wrap. Trajectory keeps the user-message preview compact and adds a localized generic-file count. Paperclip, drag, and paste classify by MIME; send waits for every upload. Continuable subagent composers disable attachment intake, and the Host rejects any file block received for a child session. ## Alternatives considered @@ -54,3 +54,5 @@ Unit and integration coverage pins verbatim and streamed storage, name sanitizat The [Trajectory reference](../../../../packages/client/ui-trajectory/README.md) documents ledger counts and inspector attachment layouts. The [input echo admission reference](../../../../packages/api/session-controller/README.md) owns placement-specific retirement and delayed Inbox suppression for submissions with or without attachments. + +The [composer image upload on add](2026-10-21-composer-image-upload-on-add.md) note extends this background-upload queue to the images of an ordinary Session's draft. diff --git a/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.zh.md b/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.zh.md index 3d1667d181..dfc48509c5 100644 --- a/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.zh.md +++ b/.agents/notes/implemented/feature/2026-08-26-generic-file-upload.zh.md @@ -14,7 +14,7 @@ Status: implemented 文件与图片使用不同存储方案,并进入同一个有序消息附件列表。图片的规范化附件流水线保持不变。其他被选中的文件进入同一个先进先出的后台上传队列,按字节原样保存且不设类型与大小限制,再在本进程内按同一 Session 暂存。相同字节在 `DSH_HOME/attachments/v1/file-objects//` 下只有一个规范对象;每条模型可见的只读路径 `DSH_HOME/attachments/v1/files///` 都是硬链接,因此不同显示名称不会复制内容。该队列可以配置,默认同时运行两项传输。独立的双端 `file-upload` Cordis 包拥有传输与暂存。其 Client `fileUpload` 服务同时接收所属 Session 标识与 `Blob`、精确字节或只能使用一次的 `ReadableStream`;它使用该标识组装原始路由请求,或直接调用生成的 Remote。其 Host `fileUploads` 服务拥有流式路由、编码 Remote 兜底、命令凭证解析器,以及以接收方 Agent 的 Session 对象为键的凭证表。编码准入和附件错误识别通过 `ctx.attachments` 完成,字节存储由附件提供方拥有。Session Controller 注册用于休眠普通 Agent 的解析器,并在 prompt 准入时消费凭证;Session 对象不公开文件传输。普通 Web 页面把每个活动请求体交给专用上传 Worker:Blob 请求体通过 XMLHttpRequest 发送并报告包含总量的字节进度,stream 则转移所有权并增量传入 Fetch。Worker-hosted 页面通过页面自有 Fetch 载体把请求体转交给 Host Worker,后者读取有界分片。页面线程不读取通用文件字节,也不做 base64 编码或 JSON 序列化。经过认证的 Host 路由显式使用 Connection 的流式请求模式,因此 bridge 会在消费请求体前分发,本地存储则把有界分片写入私有暂存对象并同时计算摘要。接收完成后,内容寻址对象以原子方式发布;取消或失败会移除暂存文件。上传任务和草稿状态属于常驻的 conversation 根,因此切到另一条 Session 不会停止传输,返回原 Session 时仍显示同一张文件卡和当前进度。移除文件卡会跳过排队中的传输或中止正在运行的传输。发送的消息在 `user/message` 里携带结构化的 `FileBlock`(`{ name, bytes, attachmentId }`),不新增会话事件类型。`LlmRuntime` 的请求组装把每个文件块,包括嵌套工具结果中的文件块,投影成确定性 handle 文本,指出文件与其只读保存路径。handle 会要求主 agent 委派文件任务时附上该路径,并在子级执行环境看不到路径时明确报告。提供方不会收到文件字节,模型在需要时用现有文件工具读取存储副本。 -默认模式、激活的 Plan Mode 与 active goal 共用普通 queue、follow-up 和 steer 的附件准入。`/goal` create 和 edit 以及 `/plan` 进入接受同一套有序图片与文件批量;携带附件的控制子命令会在状态变更前拒绝。命令提交引用已完成暂存的文件凭证,不会再次读取或复制通用文件字节。Session Controller 先把每个文件凭证解析为持久引用,再由 `ctx.attachments.admitPromptContent()` 接收完整有序内容列表;附件准入会持久化图片,并让文件引用原样通过。原 Agent 已销毁时,Host 会拒绝发布上传完成凭证,并按 `rpcId` 去重已经存在的 prompt 重试。prompt 凭证在失败恢复期间保持可用,已接受的 queue 或历史 occurrence 被观察后才退休;只被命令使用的凭证保留到 Session 销毁。提交回显在序列化前经 `beginSubmission` 注册,通过 `pendingSubmissions` 携带混合附件,以 `rpcId` 关联,在 queue 或历史观察后只退休一次,并在失败时保留草稿。发送前,composer 把有序附件放进同一条不换行的横向附件栏:图片使用 64 乘 64 像素缩略图,通用文件使用 240 乘 64 像素卡片,带 16 像素圆角、蓝色文档图标、文件名加扩展名与大小,以及悬停或键盘操作时可用的移除按钮。QueueDock 使用相同顺序以及紧凑的缩略图和文件卡。发送后,Chat 把有序附件放进同一个右对齐、可换行的附件区域。只有一张图片时保留图片画廊的大图样式;一条消息含有多个附件时,图片使用 64 乘 64 像素缩略图,文件使用 240 乘 64 像素卡片,文件与图片在可用宽度内共用一行,空间不足时再换行。Trajectory 保持紧凑的用户消息预览,并增加本地化的通用文件数量。回形针、拖拽和粘贴按 MIME 分类;发送会等待每个文件上传完成。continuable 子代理 composer 禁用附件入口,Host 会拒绝收到的任何子会话文件块。 +默认模式、激活的 Plan Mode 与 active goal 共用普通 queue、follow-up 和 steer 的附件准入。`/goal` create 和 edit 以及 `/plan` 进入接受同一套有序图片与文件批量;携带附件的控制子命令会在状态变更前拒绝。命令提交引用已完成暂存的文件凭证,不会再次读取或复制通用文件字节。Session Controller 先把每个文件凭证解析为持久引用,再由 `ctx.attachments.admitPromptContent()` 接收完整有序内容列表;附件准入会持久化图片,并让文件引用原样通过。原 Agent 已销毁时,Host 会拒绝发布上传完成凭证,并按 `rpcId` 去重已经存在的 prompt 重试。prompt 凭证在失败恢复期间保持可用,已接受的 queue 或历史 occurrence 被观察后才退休;只被命令使用的凭证保留到 Session 销毁。提交回显在序列化前经 `beginSubmission` 注册,通过 `pendingSubmissions` 携带混合附件,以 `rpcId` 关联,在 queue 或历史观察后只退休一次,并在失败时保留草稿。发送前,composer 把有序附件放进同一条不换行的横向附件栏:图片使用 64 乘 64 像素缩略图,通用文件使用 240 乘 64 像素卡片,带 16 像素圆角、蓝色文档图标、文件名加扩展名与大小,以及悬停或键盘操作时可用的移除按钮。QueueDock 使用相同顺序以及紧凑的缩略图和文件卡。发送后,Chat 把有序附件放进同一个右对齐、可换行的附件区域。只有一张图片时保留图片画廊的大图样式;一条消息含有多个附件时,图片使用 64 乘 64 像素缩略图,文件使用 240 乘 64 像素卡片,文件与图片在可用宽度内共用一行,空间不足时再换行。Trajectory 保持紧凑的用户消息预览,并增加本地化的通用文件数量。回形针、拖拽和粘贴按 MIME 分类;发送会等待每项上传完成。continuable 子代理 composer 禁用附件入口,Host 会拒绝收到的任何子会话文件块。 ## 考虑过的替代方案 @@ -54,3 +54,5 @@ Status: implemented [Trajectory 参考](../../../../packages/client/ui-trajectory/README.zh.md)说明列表计数与详情面板附件布局。 [输入回显入档参考](../../../../packages/api/session-controller/README.zh.md)负责有无附件提交的按展示归属回收和迟到 Inbox 排除。 + +[输入框在加入时上传图片](2026-10-21-composer-image-upload-on-add.zh.md) 记录把这条后台上传队列扩展到普通 Session 草稿里的图片。 diff --git a/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.i18n.yaml b/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.i18n.yaml new file mode 100644 index 0000000000..c6eb3173f0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for 2026-10-21-composer-image-upload-on-add.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.md +/agent-note-composer-image-upload-on-add: + en: 996b39b53086b9ac + zh: c81fade50ac895ec +/agent-note-composer-image-upload-on-add/problem: + en: b184ade2bd353f50 + zh: 00b97c91df54b310 +/agent-note-composer-image-upload-on-add/decision: + en: 798706ad746c8eff + zh: 64ebebfe57abbcad +/agent-note-composer-image-upload-on-add/alternatives-considered: + en: afa82b9bce9015f6 + zh: d088b92c2cb6c622 +/agent-note-composer-image-upload-on-add/consequences: + en: 658074ab09bcdf8f + zh: 2d32fff0de0144b6 +/agent-note-composer-image-upload-on-add/testing: + en: 6ca1a9520019b074 + zh: 68a2ed83e999116f +/agent-note-composer-image-upload-on-add/related: + en: 6eac98f60c3b99f9 + zh: c1e318e74f44fbb4 diff --git a/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.md b/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.md new file mode 100644 index 0000000000..a96b6f3385 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.md @@ -0,0 +1,35 @@ +# Agent Note: Composer image upload on add + +Status: implemented + +English | [中文](2026-10-21-composer-image-upload-on-add.zh.md) + +## Problem + +The Web composer kept image drafts in the browser and base64-encoded each image into `session/prompt` at send time, so the Host received, validated, normalized, and stored image bytes inside prompt admission. Generic files already uploaded when picked ([generic file upload](2026-08-26-generic-file-upload.md)). An image message therefore carried up to the per-message image byte limit in one RPC body, and its send time grew with image size; a composer that waits for the Host to accept a message before clearing it would hold the draft for that whole transfer. + +## Decision + +An ordinary Session's composer uploads each image draft as soon as it is added, through the same FIFO background-upload queue, Worker carriers, progress, retry, and cancellation that generic files use. The raw upload route takes a `mediaType` query parameter for an image upload; the Host reads at most the deployment's per-image byte limit, then validates, normalizes, and stores the image with `ctx.attachments.saveImages` exactly as prompt admission would, and stages the normalized image under a receipt for that Session. The prompt cites the receipt in an ordinary file part, so `session/prompt` keeps its wire types; prompt admission resolves the receipt to the stored image, applies the model's image-input check to the prompt, and counts stored images toward `maxImagesPerMessage` together with encoded ones. Send waits until every image draft has a receipt, and a failed image upload turns its thumbnail into a retry control. Commands accept only file receipts, so command submissions keep encoding images inline. A continuable subagent's composer keeps inline images because the Host stages uploads only for ordinary Sessions; SDK and other wire callers may still send encoded images. + +## Alternatives considered + +- **A dedicated image-receipt prompt part.** Rejected: the receipt already names what was staged, so a second part kind would widen the `session/prompt` wire union, its generated catalogs, and every consumer that switches on parts without changing what the Host admits. +- **A separate image upload route or Remote method.** Rejected: one route with an explicit `mediaType` parameter reuses Session addressing, carrier selection, progress, and the failure envelope; the exact-bytes Remote fallback has no image caller. +- **Upload images but normalize them at send.** Rejected: normalization is the expensive part of image admission, so deferring it would keep the send-time cost this change removes. + +## Consequences + +- Sending an image message transfers only references, and the normalization cost moves to the moment the image is added. +- Per-image refusals such as an unsupported type or an oversized image surface when the image is added; the model's image-input check and the per-message image count still apply at send. +- An image added and then removed before sending is still stored under `DSH_HOME`, which never deletes attachments; on a remote Host the bytes reach the server as soon as the user adds the image. +- Staged image receipts share the generic files' in-memory lifetime: a Host restart between adding and sending surfaces `FILE_NOT_STAGED`, and the user adds the image again. +- Image drafts, like file drafts, are not restored after a page reload or after their Session's client scope is released. + +## Testing + +Host coverage pins image staging through the raw route, the per-image byte bound that stops reading, unsupported types, subagent refusal, command refusal of image receipts, receipt resolution into the admitted image, and the image-input check for an uploaded image. Attachment admission coverage pins stored-image pass-through and the combined image count. Client coverage pins image upload start, retry, cancellation, the send gate, receipt citation without re-encoding, inline images for drafts without an upload, and the rail's progress and retry states. + +## Related + +The [generic file upload](2026-08-26-generic-file-upload.md) note owns the background-upload queue, carriers, staging lifetime, and file storage that image uploads reuse. diff --git a/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.zh.md b/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.zh.md new file mode 100644 index 0000000000..50f3e18a0a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 输入框在加入时上传图片 + +Status: implemented + +[English](2026-10-21-composer-image-upload-on-add.md) | 中文 + +## 问题 + +Web 输入框把图片草稿留在浏览器里,发送时才把每张图片 base64 编码进 `session/prompt`,Host 在 prompt 准入时才接收、校验、规整并存储图片字节。通用文件早已在选中时上传([通用文件上传](2026-08-26-generic-file-upload.zh.md))。因此一条图片消息要在一个 RPC 请求体里携带最多达到单条消息图片字节上限的数据,发送耗时随图片大小增长;如果输入框要等 Host 接纳消息后才清空,草稿就要在整个传输期间一直保留。 + +## 决定 + +普通 Session 的输入框在图片草稿加入时就上传它,复用通用文件的先进先出后台上传队列、Worker 载体、进度、重试与取消。原始上传路由用 `mediaType` 查询参数表示图片上传;Host 最多读取部署配置的单张图片字节上限,然后按 prompt 准入的同样方式用 `ctx.attachments.saveImages` 校验、规整并存储图片,再以该 Session 的凭证暂存规整后的图片。prompt 在普通文件部分引用该凭证,因此 `session/prompt` 的线上类型不变;prompt 准入把凭证解析为已存储的图片,对这条 prompt 执行模型的图片输入检查,并把已存储图片与编码图片一起计入 `maxImagesPerMessage`。发送会等到每个图片草稿都取得凭证;图片上传失败时,缩略图变成重试控件。命令只接受文件凭证,所以命令提交仍以内联方式编码图片。continuable 子代理的输入框继续内联图片,因为 Host 只为普通 Session 暂存上传;SDK 和其他线上调用方仍可发送编码图片。 + +## 考虑过的替代方案 + +- **专用的图片凭证 prompt 部分。** 已否决:凭证本身已经指明暂存的内容,新增一种部分类型会扩大 `session/prompt` 线上联合类型、它的生成目录以及每个按部分类型分支的消费方,却不改变 Host 准入的内容。 +- **单独的图片上传路由或 Remote 方法。** 已否决:一条带显式 `mediaType` 参数的路由复用了 Session 寻址、载体选择、进度和失败信封;精确字节的 Remote 兜底没有图片调用方。 +- **加入时上传、发送时再规整。** 已否决:规整是图片准入中开销最大的部分,推迟它会保留这次改动要消除的发送耗时。 + +## 后果 + +- 发送图片消息只传引用,规整开销移到图片加入的时刻。 +- 不支持的类型、超过单张上限等逐张拒绝在图片加入时出现;模型的图片输入检查和单条消息图片数量仍在发送时执行。 +- 加入后在发送前又移除的图片仍会存储在 `DSH_HOME` 下,附件存储从不删除;Host 在远端时,用户一加入图片,字节就到达服务器。 +- 暂存的图片凭证与通用文件同样只存在内存里:在加入与发送之间重启 Host 会得到 `FILE_NOT_STAGED`,用户需要重新加入图片。 +- 与文件草稿一样,图片草稿在页面刷新后或其 Session 的客户端作用域释放后不会恢复。 + +## 测试 + +Host 侧覆盖经原始路由暂存图片、单张字节上限一超出即停止读取、不支持的类型、子代理拒绝、命令拒绝图片凭证、凭证解析为准入后的图片,以及已上传图片的图片输入检查。附件准入覆盖已存储图片原样通过与合并后的图片数量。客户端覆盖图片上传的开始、重试、取消、发送闸门、发送时引用凭证而不重新编码、没有上传的草稿以内联方式发送图片,以及附件栏的进度与重试状态。 + +## 相关记录 + +[通用文件上传](2026-08-26-generic-file-upload.zh.md) 记录负责图片上传所复用的后台上传队列、载体、暂存生命周期与文件存储。 diff --git a/apps/web/tests/assembled-boot.ts b/apps/web/tests/assembled-boot.ts index e58ee67be0..42f006222d 100644 --- a/apps/web/tests/assembled-boot.ts +++ b/apps/web/tests/assembled-boot.ts @@ -179,6 +179,7 @@ interface FixtureWindow extends Window { __DSH_BOOT__?: WebBootGraph __ModuleLoader__?: ClientModuleLoaderTarget __DSH_TRANSPORT__?: { readonly rpc: RemoteMock['rpc'] } + __DSH_FILE_UPLOAD__?: { readonly fetch: AssembledRemote['fileUpload'] } } class ResizeObserverStub { @@ -253,6 +254,7 @@ export function installAssembledBootEnv(): void { delete win.__DSH_BOOT__ delete win.__ModuleLoader__ delete win.__DSH_TRANSPORT__ + delete win.__DSH_FILE_UPLOAD__ document.body.innerHTML = '' document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() }) document.title = '' @@ -281,6 +283,7 @@ export function mountAssembledApp(options: AssembledBootOptions = {}): Assembled const remote = createAssembledRemote(options.remote) mountedRemote = remote.mock win.__DSH_TRANSPORT__ = { rpc: remote.mock.rpc } + win.__DSH_FILE_UPLOAD__ = { fetch: remote.fileUpload } history.replaceState(null, '', '/') const root = document.createElement('div') root.id = 'root' diff --git a/apps/web/tests/assembled-remote.ts b/apps/web/tests/assembled-remote.ts index be74dc87b6..401508bc2c 100644 --- a/apps/web/tests/assembled-remote.ts +++ b/apps/web/tests/assembled-remote.ts @@ -5,6 +5,7 @@ * Fixture Sessions have no retained Host terminals to restore. */ +import { Buffer } from 'node:buffer' import { readFileSync } from 'node:fs' import { randomUUID } from 'node:crypto' import { join } from 'node:path' @@ -106,6 +107,8 @@ export interface AssembledRemoteOptions { export interface AssembledRemote { readonly mock: RemoteMock + /** Page-owned upload carrier: stages an image upload as the Host would and answers its receipt. */ + readonly fileUpload: (input: string | URL, init: RequestInit) => Promise } const fixtureSource = readFileSync( @@ -132,6 +135,7 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass return [sessionId, next] as const })) const attachments = new Map([['fixture:image', structuredClone(fixture.attachment)]]) + const stagedImages = new Map>() const blankSessionProjections = fixture.control.value.projections['fx-gamma'] if (blankSessionProjections === undefined) { throw new Error('assembled fixture: blank Session projections missing') @@ -312,6 +316,10 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass const summary = sessions.find(candidate => candidate.sessionId === sessionId) if (summary === undefined) throw new Error(`assembled fixture: no Session ${sessionId}`) const content = recordArray(request, 'content').map((part) => { + if (isRecord(part) && part.type === 'file') { + const image = stagedImages.get(recordString(part, 'receiptId')) + return image === undefined ? part : { type: 'image', attachment: image } + } if (!isRecord(part) || part.type !== 'image') return part const attachmentId = `assembled:${randomUUID()}` const data = recordString(part, 'data') @@ -364,7 +372,28 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass }) }) - return { mock } + const fileUpload = async (input: string | URL, init: RequestInit): Promise => { + const url = new URL(String(input), 'http://assembled.test/') + const mediaType = url.searchParams.get('mediaType') + if (!url.pathname.endsWith('/api/session/uploadFileBinary') || mediaType === null || !(init.body instanceof Blob)) { + throw new Error(`assembled fixture: unexpected upload ${url.pathname}${url.search}`) + } + const bytes = new Uint8Array(await init.body.arrayBuffer()) + const name = url.searchParams.get('name') + const image = { + attachmentId: `assembled:${randomUUID()}`, + mediaType, + bytes: bytes.byteLength, + width: 160, + height: 90, + ...name === null ? {} : { name }, + } + attachments.set(image.attachmentId, ok({ attachment: image, data: Buffer.from(bytes).toString('base64') })) + const receiptId = `assembled-receipt:${randomUUID()}` + stagedImages.set(receiptId, image) + return new Response(JSON.stringify({ ok: true, value: { receiptId, image } }), { status: 200 }) + } + return { mock, fileUpload } } function eventOf( diff --git a/apps/web/tests/queue-image.e2e.ts b/apps/web/tests/queue-image.e2e.ts index 502bb0d7c9..fa6fe753a0 100644 --- a/apps/web/tests/queue-image.e2e.ts +++ b/apps/web/tests/queue-image.e2e.ts @@ -100,6 +100,9 @@ describe('web e2e: queued image submission', () => { await page.locator('[data-composer-input][contenteditable="true"]').first().waitFor({ timeout: 10_000 }) await pasteImage(page, await readFile(PNG)) await page.getByRole('img', { name: 'queued.png' }).waitFor({ timeout: 10_000 }) + // The image uploads as soon as it is added, and Send waits for its receipt. + await page.locator('button[aria-busy="false"]', { has: page.getByRole('img', { name: 'queued.png' }) }) + .waitFor({ timeout: 10_000 }) const releasePrompt = Promise.withResolvers() const releaseImage = Promise.withResolvers() let cleanupPromise: Promise | undefined diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 453e8687b9..3f7e3a9c7f 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -22,11 +22,11 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:353`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:381`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:626`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:606`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:633`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:612`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:619`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:627`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:634`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:613`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:620`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:54`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 9576e87449..209ef9de2c 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -24,11 +24,11 @@ | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:353`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:381`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:626`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:606`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:633`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:612`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:619`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:627`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:634`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:613`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:620`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:54`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index ed3dfb8f6c..6726560dfe 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1146,8 +1146,8 @@ en: 3b677f021d7dd4d3 zh: 2a875742b22879a2 /session-persistence-event-catalog/resolved-persistence-types/modelselection: - en: bf5990688bae50ac - zh: 9212bca7aa7d31e0 + en: a756bce4b580d325 + zh: 84ab7988df86487d /session-persistence-event-catalog/resolved-persistence-types/oneshotscheduledispatchchange: en: a3300babe57b6b67 zh: 4aaf06a149b399c3 @@ -1347,8 +1347,8 @@ en: 2786fef560851bb4 zh: 5d787475356b2606 /session-persistence-event-catalog/resolved-persistence-types/string: - en: 41c03b03d1bd5a44 - zh: 1b0e430af6c140b3 + en: 10d206dcc422b065 + zh: 8e65d17727283dcd /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb @@ -1833,8 +1833,8 @@ en: 809a23c25ded8497 zh: e9cd23e281f8d31f /session-persistence-event-catalog/resolved-persistence-types/kind-user: - en: 53b7abac679ee252 - zh: 63eb6a015986ef6d + en: ecd4a562cf440158 + zh: 9bd3ec23c094a14e /session-persistence-event-catalog/resolved-persistence-types/kind-user-approval: en: a52d2dfbaf844127 zh: 4c5306ca40f20873 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index da02534d25..bf13b09647 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -4337,7 +4337,7 @@ Sources: [`packages/llm/llm/src/message.ts:24`](../packages/llm/llm/src/message. SHA-256: `f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b` -Sources: [`packages/api/session-controller/src/types.ts:98`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:99`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5583,7 +5583,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:406`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:407`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -7554,7 +7554,7 @@ Sources: [`packages/core/tools/src/index.ts:35`](../packages/core/tools/src/inde SHA-256: `6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def` -Sources: [`packages/api/session-controller/src/types.ts:415`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:416`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 062a1e58b1..25831e4740 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -4339,7 +4339,7 @@ SHA-256: `719c51f67074f97034a6c94297fe1f4b5d3c8d392c57586dab732aa5398c7a91` SHA-256: `f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b` -来源:[`packages/api/session-controller/src/types.ts:98`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:99`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5585,7 +5585,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:406`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:407`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -7556,7 +7556,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` SHA-256: `6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def` -来源:[`packages/api/session-controller/src/types.ts:415`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:416`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 4d0ab002a4..8c4c432191 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -253,7 +253,7 @@ {"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:173"]}, {"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]}, {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:194"]}, - {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/agent-team/src/types.ts#TeamId","packages/experimental/agent-team/src/types.ts#TeamMessageId","packages/experimental/agent-team/src/types.ts#TeamTaskId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:406","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/agent-team/src/types.ts:21","packages/experimental/agent-team/src/types.ts:33","packages/experimental/agent-team/src/types.ts:9","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/workflow/workflow/src/types.ts:13"]}, + {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/agent-team/src/types.ts#TeamId","packages/experimental/agent-team/src/types.ts#TeamMessageId","packages/experimental/agent-team/src/types.ts#TeamTaskId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:407","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/agent-team/src/types.ts:21","packages/experimental/agent-team/src/types.ts:33","packages/experimental/agent-team/src/types.ts:9","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/workflow/workflow/src/types.ts:13"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, {"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:62","packages/web/web-search-deepseek/src/provider.ts:66"]}, @@ -335,7 +335,7 @@ {"digest":"6ccb6bc423fb3952458abf9c1b1c3284208b7e660344b612cc55da773d61afe4","names":[],"sources":[]}, {"digest":"6cda0d6d3b4336d83998fe580628426df81c2afbab5d768b8813b56d569120e8","names":[],"sources":[]}, {"digest":"6cf082d0fb6034dea61636787ff0ddf43b6e59aad71e644435a479bc9b83ad65","names":[],"sources":[]}, - {"digest":"6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def","names":[],"sources":["packages/api/session-controller/src/types.ts:415"]}, + {"digest":"6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def","names":[],"sources":["packages/api/session-controller/src/types.ts:416"]}, {"digest":"6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406","names":[],"sources":["packages/preset/agent-preset-registry/src/session.ts:31"]}, {"digest":"6ea608bdc8a7a63d3d23b84c49721325094db88d136482e43a820945295eee3e","names":[],"sources":[]}, {"digest":"6ebcc2dbec9f2dabca9f668ae6d39e877899b180740570f453409db339221df3","names":[],"sources":[]}, @@ -640,7 +640,7 @@ {"digest":"ef226a90ddac6cd8e631a3a337a3a3e27f9494be92befb7c718b404681d75e21","names":[],"sources":[]}, {"digest":"ef4f00923b9edbae15c7ef05320280bf61147ca17146cf59690359bfd5e5da45","names":[],"sources":[]}, {"digest":"f05fb85e715af4ab4de0b6ba111166dd0435bd8bb74a0fa0f32b9d174113fc7c","names":[],"sources":[]}, - {"digest":"f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b","names":["packages/api/session-controller/src/types.ts#ModelSelection"],"sources":["packages/api/session-controller/src/types.ts:98"]}, + {"digest":"f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b","names":["packages/api/session-controller/src/types.ts#ModelSelection"],"sources":["packages/api/session-controller/src/types.ts:99"]}, {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:233"]}, {"digest":"f1996af2602e6f62b5ab179ca5c4af00d8753938b74cc6ef102de09e99e74a7e","names":[],"sources":[]}, {"digest":"f19bee84bf3d20904553cdcd57465232bc1c2a194f54c4d195292ba0487223a6","names":["packages/attachment/attachment/src/types.ts#FileAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:39"]}, diff --git a/docs/subsystems/attachment.md b/docs/subsystems/attachment.md index 12ae675e3c..0adca9cef8 100644 --- a/docs/subsystems/attachment.md +++ b/docs/subsystems/attachment.md @@ -80,10 +80,15 @@ type PromptContentPart = ``` ```ts type-equiv -/** Host prompt content whose file receipts are resolved and whose image bytes await admission. */ +/** + * Host prompt content whose upload receipts are resolved. An image part + * carries encoded bytes awaiting admission, or references an image this + * service already stored for an upload the same Session staged. + */ type AttachmentAdmissionPart = | PromptContentPart | { readonly type: 'file'; readonly attachment: FileAttachmentRef } + | { readonly type: 'image'; readonly attachment: ImageAttachmentRef } ``` ```ts type-equiv @@ -200,9 +205,11 @@ abstract validateImage(input: SaveImageAttachment): Promise async saveImages(inputs: readonly SaveImageAttachment[]): Promise /** - * Admit one Host prompt and replace each uploaded image with its durable reference. - * Text and durable file references pass through unchanged. A prompt without image parts performs no storage operation. - * @param content - prompt parts in message order after file receipt resolution. + * Admit one Host prompt and replace each encoded image with its durable reference. + * Text, durable file references, and already stored images pass through unchanged. + * Every image part counts toward `maxImagesPerMessage`; the aggregate byte limit + * applies to the encoded images. A prompt without encoded images performs no storage operation. + * @param content - prompt parts in message order after upload receipt resolution. * @returns admitted prompt parts in the same order as `content`. * @throws AttachmentError when the image batch is refused. */ @@ -320,7 +327,7 @@ registerAgentResolver(resolve: AgentResolver): () => void * @param signal - caller cancellation before storage begins. * @returns the staged receipt and durable file reference. */ -@Remote('upload') upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise +@Remote('upload') async upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise /** * Persist raw chunks for one Session without aggregating the upload. @@ -329,13 +336,23 @@ registerAgentResolver(resolve: AgentResolver): () => void */ async uploadStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable readonly signal?: AbortSignal readonly name?: string }): Promise +/** + * Persist one prompt image for a Session: read at most the deployment's + * per-image byte limit, then validate, normalize, and store the image the + * way prompt admission does, so a later prompt cites it by receipt. + * @param request - Session identity, ordered bytes, the declared media type that this deployment + * must accept, cancellation, and optional display name. + * @returns the staged receipt and durable normalized image reference. + */ +async uploadImageStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable readonly mediaType: string readonly signal?: AbortSignal readonly name?: string }): Promise + /** * Resolve one staged receipt for the receiving Agent's exact Session. * @param agent - receiving Agent. * @param receiptId - opaque receipt minted for one completed upload. - * @returns durable file reference, or `undefined` for an unknown or foreign receipt. + * @returns the staged file or image, or `undefined` for an unknown or foreign receipt. */ -resolve(agent: Agent, receiptId: FileUploadReceiptId): FileAttachmentRef | undefined +resolve(agent: Agent, receiptId: FileUploadReceiptId): StagedAttachment | undefined /** * Bind receipts while one prompt enters an Agent inbox. diff --git a/docs/subsystems/attachment.zh.md b/docs/subsystems/attachment.zh.md index 06ea726f19..c7400d385f 100644 --- a/docs/subsystems/attachment.zh.md +++ b/docs/subsystems/attachment.zh.md @@ -80,10 +80,15 @@ type PromptContentPart = ``` ```ts type-equiv -/** Host prompt content whose file receipts are resolved and whose image bytes await admission. */ +/** + * Host prompt content whose upload receipts are resolved. An image part + * carries encoded bytes awaiting admission, or references an image this + * service already stored for an upload the same Session staged. + */ type AttachmentAdmissionPart = | PromptContentPart | { readonly type: 'file'; readonly attachment: FileAttachmentRef } + | { readonly type: 'image'; readonly attachment: ImageAttachmentRef } ``` ```ts type-equiv @@ -200,9 +205,11 @@ abstract validateImage(input: SaveImageAttachment): Promise async saveImages(inputs: readonly SaveImageAttachment[]): Promise /** - * Admit one Host prompt and replace each uploaded image with its durable reference. - * Text and durable file references pass through unchanged. A prompt without image parts performs no storage operation. - * @param content - prompt parts in message order after file receipt resolution. + * Admit one Host prompt and replace each encoded image with its durable reference. + * Text, durable file references, and already stored images pass through unchanged. + * Every image part counts toward `maxImagesPerMessage`; the aggregate byte limit + * applies to the encoded images. A prompt without encoded images performs no storage operation. + * @param content - prompt parts in message order after upload receipt resolution. * @returns admitted prompt parts in the same order as `content`. * @throws AttachmentError when the image batch is refused. */ @@ -320,7 +327,7 @@ registerAgentResolver(resolve: AgentResolver): () => void * @param signal - caller cancellation before storage begins. * @returns the staged receipt and durable file reference. */ -@Remote('upload') upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise +@Remote('upload') async upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise /** * Persist raw chunks for one Session without aggregating the upload. @@ -329,13 +336,23 @@ registerAgentResolver(resolve: AgentResolver): () => void */ async uploadStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable readonly signal?: AbortSignal readonly name?: string }): Promise +/** + * Persist one prompt image for a Session: read at most the deployment's + * per-image byte limit, then validate, normalize, and store the image the + * way prompt admission does, so a later prompt cites it by receipt. + * @param request - Session identity, ordered bytes, the declared media type that this deployment + * must accept, cancellation, and optional display name. + * @returns the staged receipt and durable normalized image reference. + */ +async uploadImageStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable readonly mediaType: string readonly signal?: AbortSignal readonly name?: string }): Promise + /** * Resolve one staged receipt for the receiving Agent's exact Session. * @param agent - receiving Agent. * @param receiptId - opaque receipt minted for one completed upload. - * @returns durable file reference, or `undefined` for an unknown or foreign receipt. + * @returns the staged file or image, or `undefined` for an unknown or foreign receipt. */ -resolve(agent: Agent, receiptId: FileUploadReceiptId): FileAttachmentRef | undefined +resolve(agent: Agent, receiptId: FileUploadReceiptId): StagedAttachment | undefined /** * Bind receipts while one prompt enters an Agent inbox. diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index ff8ee89c2f..6e0dfbef8f 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 8fcfa14545bd9d1c - zh: c10c2bba792699ef + en: aabd5be911e477f5 + zh: 2f7fdb44bc8777bc /session-controller/client-references: en: 41bdda1ac32df558 zh: aa5d0e325924066b diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index fbc0aeaa3b..03fddab2a9 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -33,7 +33,7 @@ History pages and follow opening snapshots carry one `{ type: 'event', event: Se The Client journal validates current Session event envelopes before publishing follow snapshots, live entries, or history pages. It reuses the browser-safe Session validators for required surface markers, exact replacement endpoints, earlier unique source seqs, embedded Assistant provider metadata, request-header omissions, and tool-error consistency. Invalid records fail without field stripping or normalization; range membership and source existence remain durable-log checks on the Host. -Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. +Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. A receipt names a staged file or a staged image, and an image receipt subjects the prompt to the same image-input check as an encoded image. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers the `session` resource kind with the default field `sessionId` through `typert.resources`. `session/page` and `session/follow` declare a `session` reader in `@Remote({ resources })` that reads `request.address.sessionId` for an ordinary Session address and `request.address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections` reads the Session resource from `request.sessionId`, so a reconnecting reader reloads only the projections of Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index d63735689f..1f33f9ec4e 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" Client journal 在发布 follow 快照、live entry 或历史页之前验证当前 Session 事件 envelope。它复用浏览器安全的 Session validator,检查必需的 surface marker、精确的 replacement endpoint、更早且唯一的 source seq、内嵌 Assistant 提供方元数据、request header 可选字段的省略规则以及工具错误一致性。无效 record 直接失败,不删除字段或归一化;范围成员与来源存在性仍由 Host 的持久日志检查。 -每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 +每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。凭证指向一个暂存文件或一张暂存图片;图片凭证与编码图片一样要经过图片输入检查。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 以默认字段 `sessionId` 登记 `session` 资源种类。`session/page` 与 `session/follow` 在 `@Remote({ resources })` 中声明 `session` 读取函数:对普通 Session 地址读 `request.address.sessionId`,对 subagent 地址读 `request.address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections` 从 `request.sessionId` 读取会话资源,因此重连的读者只会重新读取它可读的会话的 projections。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。 diff --git a/packages/api/session-controller/src/commands.ts b/packages/api/session-controller/src/commands.ts index 8dd38573c8..74455d9057 100644 --- a/packages/api/session-controller/src/commands.ts +++ b/packages/api/session-controller/src/commands.ts @@ -7,9 +7,9 @@ import { brandString } from '@deepseek-ai/dsh-brand' import type { Agent, ModelSelection as AgentModelSelection } from '@deepseek-ai/dsh-agent' import { AttachmentError } from '@deepseek-ai/dsh-attachment' import type { - AttachmentAdmissionPart, FileAttachmentRef, ImageAttachmentRef, + AttachmentAdmissionPart, ImageAttachmentRef, } from '@deepseek-ai/dsh-attachment' -import type { FileUploadReceiptId } from '@deepseek-ai/dsh-client-file-upload/types' +import type { FileUploadReceiptId, StagedAttachment } from '@deepseek-ai/dsh-client-file-upload/types' import type {} from '@deepseek-ai/dsh-client-file-upload' import { ReasoningEffortId, assistantStreamChunks, createUserMessage, freezeMessage, @@ -319,7 +319,12 @@ export class SessionCommandController { async prompt(request: SessionPromptRequest, source: MessageSource): Promise { const agent = await this.resolveAgent(request.sessionId) if (hasPromptRequest(agent, request.requestId)) return { accepted: true } - const hasImage = request.content.some(part => part.type === 'image') + const admission = resolvePromptFileReceipts( + request.content, + receiptId => this.ctx.fileUploads.resolve(agent, receiptId), + ) + // Encoded images and image upload receipts both make an image prompt. + const hasImage = admission.content.some(part => part.type === 'image') const admit = async (): Promise => { try { if (hasImage) { @@ -333,10 +338,6 @@ export class SessionCommandController { ) } } - const admission = resolvePromptFileReceipts( - request.content, - receiptId => this.ctx.fileUploads.resolve(agent, receiptId), - ) const content = await this.ctx.attachments.admitPromptContent(admission.content) const message: UserMessage = createUserMessage({ content, source }) if (this.ctx.agents.get(agent.id) !== agent) { @@ -560,14 +561,15 @@ export class SessionCommandController { } } +/** Replace each file part with the file or image its staged receipt names. */ function resolvePromptFileReceipts( content: SessionPromptRequest['content'], - stagedFile: (receiptId: FileUploadReceiptId) => FileAttachmentRef | undefined, + staged: (receiptId: FileUploadReceiptId) => StagedAttachment | undefined, ): { readonly content: AttachmentAdmissionPart[]; readonly receiptIds: readonly FileUploadReceiptId[] } { const receiptIds = new Set() const resolved = content.map((part): AttachmentAdmissionPart => { if (part.type !== 'file') return part - const attachment = stagedFile(part.receiptId) + const attachment = staged(part.receiptId) if (attachment === undefined) { throw new RemoteError( 'session/attachment-invalid', @@ -576,7 +578,7 @@ function resolvePromptFileReceipts( ) } receiptIds.add(part.receiptId) - return { type: 'file', attachment } + return attachment }) return { content: resolved, receiptIds: [...receiptIds] } } diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index f4d2daa637..7b1099754a 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -82,7 +82,8 @@ export type SessionProjectionValues = Partial /** * Browser-submitted prompt content; the Host promotes image bytes to durable * references. File parts carry the opaque receipt returned by a preceding - * `uploadFile` call on the same Session. + * upload on the same Session; the receipt of an image upload enters the + * message as that image. */ export type PromptContentPart = | { readonly type: 'text'; readonly text: string } diff --git a/packages/api/session-controller/tests/commands-upload-file.host.spec.ts b/packages/api/session-controller/tests/commands-upload-file.host.spec.ts index 48ba896f01..6ad3a71b97 100644 --- a/packages/api/session-controller/tests/commands-upload-file.host.spec.ts +++ b/packages/api/session-controller/tests/commands-upload-file.host.spec.ts @@ -5,7 +5,8 @@ import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' import type { Agent, ModelSelectionRef } from '@deepseek-ai/dsh-agent' import AttachmentStore, { AttachmentId } from '@deepseek-ai/dsh-attachment' import type { - FileAttachmentRef, ImageAttachmentRef, SaveFileAttachment, SaveFileStreamAttachment, + FileAttachmentRef, ImageAttachmentLimits, ImageAttachmentRef, SaveFileAttachment, SaveFileStreamAttachment, + SaveImageAttachment, } from '@deepseek-ai/dsh-attachment' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { MessageSource, UserMessage } from '@deepseek-ai/dsh-llm' @@ -20,6 +21,26 @@ import { SessionCommandController } from '../src/commands.ts' import type { SessionRequestId } from '../src/types.ts' const SESSION = SessionId('upload-session') +const IMAGE_LIMITS: ImageAttachmentLimits = { + maxImageBytes: 4, + maxImagesPerMessage: 2, + maxMessageImageBytes: 8, + maxImagePixels: 64, + maxImageDimension: 8, + mediaTypes: ['image/png'], +} +const STAGED_IMAGE: ImageAttachmentRef = { + attachmentId: AttachmentId(`sha256:${'12'.repeat(32)}`), + mediaType: 'image/png', + bytes: 3, + width: 1, + height: 1, + name: 'shot.png', +} + +async function* chunks(...parts: readonly number[][]): AsyncIterable { + for (const part of parts) yield Uint8Array.from(part) +} async function uploadHarness(origin?: 'subagent'): Promise<{ ctx: Context @@ -30,6 +51,7 @@ async function uploadHarness(origin?: 'subagent'): Promise<{ saveFile: ReturnType saveFileStream: ReturnType saveImages: ReturnType + resolveModelInfo: ReturnType disposeAgent: () => Promise uploadRoute: (request: Request) => Promise }> { @@ -70,10 +92,10 @@ async function uploadHarness(origin?: 'subagent'): Promise<{ bytes, } }) - const saveImages = vi.fn((): Promise => + const saveImages = vi.fn((_inputs: readonly SaveImageAttachment[]): Promise => Promise.reject(new Error('fixture did not expect image persistence'))) ctx.provide('attachments', Object.setPrototypeOf( - { saveFile, saveFileStream, saveImages }, + { saveFile, saveFileStream, saveImages, imageLimits: IMAGE_LIMITS }, AttachmentStore.prototype, ) as never) let uploadRoute: ((request: Request) => Promise) | undefined @@ -85,10 +107,16 @@ async function uploadHarness(origin?: 'subagent'): Promise<{ }, }, } as never) + const resolveModelInfo = vi.fn((): Promise<{ + readonly provider: string + readonly id: string + readonly name: string + readonly inputModalities?: readonly string[] + }> => Promise.resolve({ provider: 'fixture', id: 'fixture-model', name: 'Fixture' })) ctx.provide('llm', { listModels: async () => [{ id: 'fixture-model', name: 'Model' }], listProviders: () => [{ id: 'fixture', name: 'Fixture' }], - resolveModelInfo: () => Promise.resolve({ provider: 'fixture', id: 'fixture-model', name: 'Fixture' }), + resolveModelInfo, } as never) const selection: ModelSelectionRef = { current: { provider: 'fixture', model: 'fixture-model' }, @@ -110,6 +138,7 @@ async function uploadHarness(origin?: 'subagent'): Promise<{ saveFile, saveFileStream, saveImages, + resolveModelInfo, disposeAgent, uploadRoute, } @@ -140,7 +169,7 @@ describe('Session file uploads', () => { expect(saveFile).toHaveBeenCalledTimes(1) expect(receipt.file.name).toBe('notes.pdf') expect(receipt.file.bytes).toBe(3) - expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file) + expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file }) expect(uploads.resolve(agent, 'missing' as FileUploadReceiptId)).toBeUndefined() const commandHandler = vi.fn((_invocation: unknown) => ({ kind: 'success' as const })) ctx.commands.register({ @@ -201,6 +230,62 @@ describe('Session file uploads', () => { ]) }) + it('stages an uploaded image and admits its receipt as that image, which commands do not accept', async () => { + const { ctx, controller, uploads, agent, followup, saveImages } = await uploadHarness() + saveImages.mockResolvedValueOnce([STAGED_IMAGE]) + const receipt = await uploads.uploadImageStream({ + sessionId: SESSION, data: chunks([1, 2], [3, 4]), mediaType: 'image/png', name: 'shot.png', + }) + expect(saveImages).toHaveBeenCalledWith([{ data: Uint8Array.of(1, 2, 3, 4), mediaType: 'image/png', name: 'shot.png' }]) + expect(receipt.image).toEqual(STAGED_IMAGE) + expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'image', attachment: STAGED_IMAGE }) + const commandHandler = vi.fn((_invocation: unknown) => ({ kind: 'success' as const })) + ctx.commands.register({ + name: 'files', description: 'Use staged files', input: { hint: '', attachments: true }, + handler: commandHandler, + }) + await ctx.commands.execute( + agent, + '/files inspect', + [{ type: 'file', receiptId: receipt.receiptId }], + new AbortController().signal, + ) + expect(commandHandler).not.toHaveBeenCalled() + await controller.prompt(promptRequest([ + { type: 'file', receiptId: receipt.receiptId }, + { type: 'text', text: 'look' }, + ]), USER_SOURCE) + expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([ + { type: 'image', attachment: STAGED_IMAGE }, + { type: 'text', text: 'look' }, + ]) + expect(saveImages).toHaveBeenCalledTimes(1) + }) + + it('refuses an uploaded image for a model without image input', async () => { + const { controller, uploads, followup, saveImages, resolveModelInfo } = await uploadHarness() + saveImages.mockResolvedValueOnce([STAGED_IMAGE]) + const receipt = await uploads.uploadImageStream({ sessionId: SESSION, data: chunks([1]), mediaType: 'image/png' }) + resolveModelInfo.mockResolvedValue({ provider: 'fixture', id: 'fixture-model', name: 'Fixture', inputModalities: ['text'] }) + await expect(controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE)) + .rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' } }) + expect(followup).not.toHaveBeenCalled() + }) + + it('refuses an image past the per-image byte limit without reading further, and an unaccepted type', async () => { + const { uploads, saveImages } = await uploadHarness() + const overLimit = (async function* (): AsyncIterable { + yield Uint8Array.of(1, 2, 3) + yield Uint8Array.of(4, 5) + throw new Error('read past the limit') + })() + await expect(uploads.uploadImageStream({ sessionId: SESSION, data: overLimit, mediaType: 'image/png' })) + .rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'IMAGE_TOO_LARGE' } }) + await expect(uploads.uploadImageStream({ sessionId: SESSION, data: chunks([1]), mediaType: 'image/bmp' })) + .rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'UNSUPPORTED_IMAGE_TYPE' } }) + expect(saveImages).not.toHaveBeenCalled() + }) + it('keeps the stream name optional and maps storage failures through the same error vocabulary', async () => { const { uploads, saveFileStream } = await uploadHarness() const stream = (async function* (): AsyncIterable {})() @@ -296,6 +381,9 @@ describe('Session file uploads', () => { details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' }, }) expect(child.saveFile).not.toHaveBeenCalled() + await expect(child.uploads.uploadImageStream({ sessionId: SESSION, data: chunks([1]), mediaType: 'image/png' })) + .rejects.toMatchObject({ code: 'subagent/attachment-invalid', details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' } }) + expect(child.saveImages).not.toHaveBeenCalled() }) it('isolates receipts by Session object even when Session ids match', async () => { @@ -311,7 +399,7 @@ describe('Session file uploads', () => { expect(() => owner.uploads.bindPrompt(other.agent, [receipt.receiptId], 'other-prompt')) .toThrow(expect.objectContaining({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } })) owner.uploads.retirePrompt(other.agent, 'owner-prompt') - expect(owner.uploads.resolve(owner.agent, receipt.receiptId)).toEqual(receipt.file) + expect(owner.uploads.resolve(owner.agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file }) owner.uploads.retirePrompt(owner.agent, 'owner-prompt') expect(owner.uploads.resolve(owner.agent, receipt.receiptId)).toBeUndefined() }) @@ -321,9 +409,9 @@ describe('Session file uploads', () => { uploads.retirePrompt(agent, 'not-staged') const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal) await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE) - expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file) + expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file }) uploads.retirePrompt(agent, 'other-request') - expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file) + expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file }) uploads.retirePrompt(agent, 'req-1') expect(uploads.resolve(agent, receipt.receiptId)).toBeUndefined() }) @@ -340,7 +428,7 @@ describe('Session file uploads', () => { content: [{ type: 'text', text: 'extension event' }], source: { kind: 'user', rpcId: 1 } as never, }), { surfaceOp: 'append' }) - expect(first.uploads.resolve(first.agent, observed.receiptId)).toEqual(observed.file) + expect(first.uploads.resolve(first.agent, observed.receiptId)).toEqual({ type: 'file', attachment: observed.file }) first.agent.session.append('user/message', createUserMessage({ content: [{ type: 'text', text: 'observed' }], source: { kind: 'user', rpcId: 'req-1' as SessionRequestId }, @@ -442,7 +530,7 @@ describe('Session file uploads', () => { { type: 'file', receiptId: receipt.receiptId }, ]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/agent-busy' }) uploads.retirePrompt(agent, 'req-1') - expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file) + expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file }) }) it('retires a prompt-bound receipt when its queued occurrence is removed', async () => { diff --git a/packages/attachment/attachment/README.i18n.yaml b/packages/attachment/attachment/README.i18n.yaml index 4f941409fe..eb1d6b6f1d 100644 --- a/packages/attachment/attachment/README.i18n.yaml +++ b/packages/attachment/attachment/README.i18n.yaml @@ -39,8 +39,8 @@ en: af7deef72fd2fa93 zh: f217d52ce3971135 /deepseek-ai-dsh-attachment/understand-the-implementation/service-operations: - en: 4a35cdba790c3b8b - zh: 08d4a18bbad4b182 + en: b3d6af4425252120 + zh: ed670ebded2d20b3 /deepseek-ai-dsh-attachment/understand-the-implementation/source-map: en: 4fb4c96184c38169 zh: 015b06e4bfff4fcd diff --git a/packages/attachment/attachment/README.md b/packages/attachment/attachment/README.md index 43eb4d8ae8..9aa7eb52da 100644 --- a/packages/attachment/attachment/README.md +++ b/packages/attachment/attachment/README.md @@ -72,7 +72,7 @@ This section explains the design decisions behind the seam and the service opera ### Service operations -The service family runs one admission-and-storage flow: every entry point enforces source batch limits and canonical base64, prepares provider-independent normalized attachments before publishing any member, and commits them durably in input order without partial results. Host prompt consumers pass ordered text, encoded images, and already resolved file references to `ctx.attachments.admitPromptContent()`; the method persists images and passes file references unchanged. Encoded protocol adapters call `ctx.attachments.admitEncodedFile()`, which checks canonical base64 before delegating to `saveFile`; adapters recognize attachment failures through `ctx.attachments.isAttachmentError()`. Generic-file callers choose `saveFile` for existing bytes or `saveFileStream` for a bounded asynchronous byte source; both return the same durable reference, while `readFileStream` verifies its digest and length during a bounded read. `readImageRequest` derives deterministic route-sized variants whose identity includes the attachment id, transform version, target dimensions, byte target, and encoder settings. The pure `requestImageDimensions` and `longEdgeDimensions` exports compute aspect-preserving dimensions from a total-pixel budget or an exact long edge, so routes and request pricing share one geometry. `imageHostPath` exposes an implementation-owned host location only to trusted same-process consumers that need execution-world mapping. Callers compose ordered batches while the implementation owns compression concurrency, caching, and singleflight. Reads, streamed writes, and projections preserve caller cancellation. Failures carry stable machine-readable codes, and the caller-correctable admission subset is recognizable at runtime so each protocol adapter maps its own vocabulary; the exact per-operation contracts live in [`src/index.ts`](src/index.ts) and [`src/error.ts`](src/error.ts). +The service family runs one admission-and-storage flow: every entry point enforces source batch limits and canonical base64, prepares provider-independent normalized attachments before publishing any member, and commits them durably in input order without partial results. Host prompt consumers pass ordered text, encoded images, and already resolved file and image references to `ctx.attachments.admitPromptContent()`; the method persists the encoded images, passes references unchanged, and counts every image toward the per-message image count. Encoded protocol adapters call `ctx.attachments.admitEncodedFile()`, which checks canonical base64 before delegating to `saveFile`; adapters recognize attachment failures through `ctx.attachments.isAttachmentError()`. Generic-file callers choose `saveFile` for existing bytes or `saveFileStream` for a bounded asynchronous byte source; both return the same durable reference, while `readFileStream` verifies its digest and length during a bounded read. `readImageRequest` derives deterministic route-sized variants whose identity includes the attachment id, transform version, target dimensions, byte target, and encoder settings. The pure `requestImageDimensions` and `longEdgeDimensions` exports compute aspect-preserving dimensions from a total-pixel budget or an exact long edge, so routes and request pricing share one geometry. `imageHostPath` exposes an implementation-owned host location only to trusted same-process consumers that need execution-world mapping. Callers compose ordered batches while the implementation owns compression concurrency, caching, and singleflight. Reads, streamed writes, and projections preserve caller cancellation. Failures carry stable machine-readable codes, and the caller-correctable admission subset is recognizable at runtime so each protocol adapter maps its own vocabulary; the exact per-operation contracts live in [`src/index.ts`](src/index.ts) and [`src/error.ts`](src/error.ts). ### Source map diff --git a/packages/attachment/attachment/README.zh.md b/packages/attachment/attachment/README.zh.md index 4fa95d20f3..cdb3abf090 100644 --- a/packages/attachment/attachment/README.zh.md +++ b/packages/attachment/attachment/README.zh.md @@ -72,7 +72,7 @@ kind: "package-reference" ### 服务操作 -服务族运行同一条准入与存储流程:每个入口都强制执行源批次限制与规范 base64,在发布任何成员前准备提供方无关的规范化附件,再按输入顺序持久提交而不产生部分结果。Host 提示词消费方把有序文本、编码图片和已经解析的文件引用交给 `ctx.attachments.admitPromptContent()`;该方法持久化图片,并让文件引用原样通过。编码协议适配器调用 `ctx.attachments.admitEncodedFile()`,由该方法检查规范 base64 后委托给 `saveFile`;适配器通过 `ctx.attachments.isAttachmentError()` 识别附件错误。通用文件调用方可以用 `saveFile` 提交已有字节,或用 `saveFileStream` 提交有界异步字节源;两者返回相同的持久引用,`readFileStream` 则在有界读取过程中校验摘要与长度。`readImageRequest` 派生确定性的路由尺寸变体,其身份包含附件 id、变换版本、目标尺寸、字节目标及编码参数。纯函数导出 `requestImageDimensions` 与 `longEdgeDimensions` 按总像素预算或精确长边计算保持宽高比的尺寸,使路由与请求定价共享同一套几何计算。`imageHostPath` 只向需要把该位置映射到执行环境的受信任同进程消费方暴露实现拥有的宿主位置。调用方组合有序批次,而实现负责管理压缩并发、缓存与 singleflight。读取、流式写入和投影保留调用方的取消语义。失败带有稳定且机器可读的错误码,运行时即可识别可由调用方修正的准入子集,让每个协议适配器映射自己的词汇;各操作的确切约定见 [`src/index.ts`](src/index.ts) 与 [`src/error.ts`](src/error.ts)。 +服务族运行同一条准入与存储流程:每个入口都强制执行源批次限制与规范 base64,在发布任何成员前准备提供方无关的规范化附件,再按输入顺序持久提交而不产生部分结果。Host 提示词消费方把有序文本、编码图片和已经解析的文件与图片引用交给 `ctx.attachments.admitPromptContent()`;该方法持久化编码图片,让引用原样通过,并把每张图片计入单条消息的图片数量。编码协议适配器调用 `ctx.attachments.admitEncodedFile()`,由该方法检查规范 base64 后委托给 `saveFile`;适配器通过 `ctx.attachments.isAttachmentError()` 识别附件错误。通用文件调用方可以用 `saveFile` 提交已有字节,或用 `saveFileStream` 提交有界异步字节源;两者返回相同的持久引用,`readFileStream` 则在有界读取过程中校验摘要与长度。`readImageRequest` 派生确定性的路由尺寸变体,其身份包含附件 id、变换版本、目标尺寸、字节目标及编码参数。纯函数导出 `requestImageDimensions` 与 `longEdgeDimensions` 按总像素预算或精确长边计算保持宽高比的尺寸,使路由与请求定价共享同一套几何计算。`imageHostPath` 只向需要把该位置映射到执行环境的受信任同进程消费方暴露实现拥有的宿主位置。调用方组合有序批次,而实现负责管理压缩并发、缓存与 singleflight。读取、流式写入和投影保留调用方的取消语义。失败带有稳定且机器可读的错误码,运行时即可识别可由调用方修正的准入子集,让每个协议适配器映射自己的词汇;各操作的确切约定见 [`src/index.ts`](src/index.ts) 与 [`src/error.ts`](src/error.ts)。 ### 源码地图 diff --git a/packages/attachment/attachment/src/index.ts b/packages/attachment/attachment/src/index.ts index d5854336db..45edd7589e 100644 --- a/packages/attachment/attachment/src/index.ts +++ b/packages/attachment/attachment/src/index.ts @@ -11,6 +11,7 @@ import type { ImageAttachmentLimits, ImageAttachmentRef, ImageRequestTarget, + PromptContentPart, RequestImageAttachment, SaveFileAttachment, SaveFileStreamAttachment, @@ -49,6 +50,11 @@ declare module '@deepseek-ai/cordis' { } } +/** Whether one admission part still carries encoded image bytes. */ +function isEncodedImage(part: AttachmentAdmissionPart): part is Extract { + return part.type === 'image' && !('attachment' in part) +} + /** Immutable binary attachment service. Implementations validate bytes before publishing a reference. */ export abstract class AttachmentStore extends Service { constructor(ctx: Context) { @@ -105,25 +111,29 @@ export abstract class AttachmentStore extends Service { } /** - * Admit one Host prompt and replace each uploaded image with its durable reference. - * Text and durable file references pass through unchanged. A prompt without image parts performs no storage operation. - * @param content - prompt parts in message order after file receipt resolution. + * Admit one Host prompt and replace each encoded image with its durable reference. + * Text, durable file references, and already stored images pass through unchanged. + * Every image part counts toward `maxImagesPerMessage`; the aggregate byte limit + * applies to the encoded images. A prompt without encoded images performs no storage operation. + * @param content - prompt parts in message order after upload receipt resolution. * @returns admitted prompt parts in the same order as `content`. * @throws AttachmentError when the image batch is refused. */ async admitPromptContent( content: readonly AttachmentAdmissionPart[], ): Promise { - if (content.every(part => part.type !== 'image')) { - return content.map(part => part.type === 'text' - ? { type: 'text', text: part.text } - : { type: 'file', attachment: part.attachment }) + const encoded = content.filter(isEncodedImage) + const images = content.filter(part => part.type === 'image').length + // The encoded batch enforces its own count; stored images join it here. + if (images > encoded.length && images > this.imageLimits.maxImagesPerMessage) { + throw new AttachmentError('Image batch exceeds the configured image-count limit.', 'TOO_MANY_IMAGES') } - const refs = await admitEncodedImages(this, content.filter(part => part.type === 'image')) + const refs = encoded.length === 0 ? [] : await admitEncodedImages(this, encoded) let next = 0 return content.map((part) => { if (part.type === 'text') return { type: 'text', text: part.text } if (part.type === 'file') return { type: 'file', attachment: part.attachment } + if ('attachment' in part) return { type: 'image', attachment: part.attachment } return { type: 'image', attachment: refs[next++] as ImageAttachmentRef } }) } diff --git a/packages/attachment/attachment/src/types.ts b/packages/attachment/attachment/src/types.ts index 455d6c9de0..c0ff2bceea 100644 --- a/packages/attachment/attachment/src/types.ts +++ b/packages/attachment/attachment/src/types.ts @@ -106,10 +106,15 @@ export type PromptContentPart = readonly name?: string } -/** Host prompt content whose file receipts are resolved and whose image bytes await admission. */ +/** + * Host prompt content whose upload receipts are resolved. An image part + * carries encoded bytes awaiting admission, or references an image this + * service already stored for an upload the same Session staged. + */ export type AttachmentAdmissionPart = | PromptContentPart | { readonly type: 'file'; readonly attachment: FileAttachmentRef } + | { readonly type: 'image'; readonly attachment: ImageAttachmentRef } /** Host-admitted prompt content with every attachment represented by its durable reference. */ export type AdmittedPromptContentPart = diff --git a/packages/attachment/attachment/tests/admission.spec.ts b/packages/attachment/attachment/tests/admission.spec.ts index 71c56c0fed..7da98842d0 100644 --- a/packages/attachment/attachment/tests/admission.spec.ts +++ b/packages/attachment/attachment/tests/admission.spec.ts @@ -10,6 +10,13 @@ const FILE_REF: FileAttachmentRef = { name: 'notes.md', bytes: 12, } +const STORED_REF: ImageAttachmentRef = { + attachmentId: 'stored-1' as ImageAttachmentRef['attachmentId'], + mediaType: 'image/png', + bytes: 8, + width: 2, + height: 2, +} /** Delegation double: records the exact saveImages batch and answers ordered refs. */ function storeOf() { @@ -138,4 +145,34 @@ describe('AttachmentStore.admitPromptContent', () => { { type: 'image', attachment: { attachmentId: 'att-2', mediaType: 'image/png', bytes: 1, width: 1, height: 1 } }, ]) }) + + it('passes stored images through in part order and stores only the encoded ones', async () => { + const { store, mocks } = storeOf() + Object.defineProperty(store, 'imageLimits', { value: { maxImagesPerMessage: 2 } }) + await expect(store.admitPromptContent([ + { type: 'image', attachment: STORED_REF }, + { type: 'text', text: 'between' }, + { type: 'image', mediaType: 'image/png', data: 'AQ==' }, + ])).resolves.toEqual([ + { type: 'image', attachment: STORED_REF }, + { type: 'text', text: 'between' }, + { type: 'image', attachment: { attachmentId: 'att-1', mediaType: 'image/png', bytes: 1, width: 1, height: 1 } }, + ]) + expect(mocks.saveImages).toHaveBeenCalledTimes(1) + expect((mocks.saveImages.mock.calls[0]?.[0] as readonly SaveImageAttachment[]).length).toBe(1) + }) + + it('counts stored images toward the image-count limit before storing anything', async () => { + const { store, mocks } = storeOf() + Object.defineProperty(store, 'imageLimits', { value: { maxImagesPerMessage: 1 } }) + await expect(store.admitPromptContent([ + { type: 'image', attachment: STORED_REF }, + { type: 'image', mediaType: 'image/png', data: 'AQ==' }, + ])).rejects.toMatchObject({ code: 'TOO_MANY_IMAGES' }) + await expect(store.admitPromptContent([ + { type: 'image', attachment: STORED_REF }, + { type: 'image', attachment: { ...STORED_REF, attachmentId: 'stored-2' as ImageAttachmentRef['attachmentId'] } }, + ])).rejects.toMatchObject({ code: 'TOO_MANY_IMAGES' }) + expect(mocks.saveImages).not.toHaveBeenCalled() + }) }) diff --git a/packages/client/file-upload/README.i18n.yaml b/packages/client/file-upload/README.i18n.yaml index b8f993bd2d..287865e683 100644 --- a/packages/client/file-upload/README.i18n.yaml +++ b/packages/client/file-upload/README.i18n.yaml @@ -9,17 +9,17 @@ en: a6c9f156174554e1 zh: cd1a126905ad859b /deepseek-ai-dsh-client-file-upload/summary: - en: 430b79a11643da11 - zh: 5fbab8d425b7f15a + en: e53f2cfb8285a578 + zh: 1930ea2638e59a34 /deepseek-ai-dsh-client-file-upload/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-file-upload/use-this-package: - en: 9d5bbf52599b0d00 - zh: 7907542ce1e34549 + en: 7c19ce780c0d1357 + zh: 2d295b8b872b5f9f /deepseek-ai-dsh-client-file-upload/understand-the-implementation: - en: 77937960a540cf51 - zh: 52c478bd11200975 + en: cbfa8996ccad9e41 + zh: 0a0395d1194a1423 /deepseek-ai-dsh-client-file-upload/further-exploration: en: ac94eb9da9ecc296 zh: 25cc3362e2bea330 diff --git a/packages/client/file-upload/README.md b/packages/client/file-upload/README.md index b447226218..b2ece40ab7 100644 --- a/packages/client/file-upload/README.md +++ b/packages/client/file-upload/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This package lets browser features store a `Blob`, exact bytes, or a `ReadableStream` for one Session and receive an opaque receipt for a later prompt. Served pages send Blob and stream bodies without aggregating their bytes on the page thread; pages whose Host runs in another execution context supply a Fetch-shaped carrier before Cordis boots. Callers can observe consumed bytes and cancel an active operation. A stream body is consumed once and transfers ownership when it crosses a Worker boundary. Exact bytes use the generated Remote. +This package lets browser features store a `Blob`, exact bytes, or a `ReadableStream` for one Session and receive an opaque receipt for a later prompt. Served pages send Blob and stream bodies without aggregating their bytes on the page thread; pages whose Host runs in another execution context supply a Fetch-shaped carrier before Cordis boots. Callers can observe consumed bytes and cancel an active operation. A stream body is consumed once and transfers ownership when it crosses a Worker boundary. An image upload stages a normalized prompt image that a later prompt cites by receipt. ## Table of Contents @@ -25,7 +25,7 @@ This package lets browser features store a `Blob`, exact bytes, or a `ReadableSt ## Use this package -Mount the package before a consumer that injects `fileUpload`, then call `ctx.fileUpload.upload(sessionId, body, name, signal, onProgress)`. The Session identity addresses both the raw route and generated Remote fallback; callers do not assemble either request. +Mount the package before a consumer that injects `fileUpload`, then call `ctx.fileUpload.upload(sessionId, body, name, signal, onProgress)`, or `ctx.fileUpload.uploadImage(sessionId, blob, mediaType, name, signal, onProgress)` for a prompt image. The Session identity addresses both the raw route and generated Remote fallback; callers do not assemble either request. ```yaml - id: file-upload @@ -44,7 +44,7 @@ The package has no Cordis configuration fields. A `Blob` uses XMLHttpRequest ins The Client plugin provides `ctx.fileUpload`. Its `upload()` method receives the owning Session identity, assembles the raw route request, and invokes the generated Remote for exact bytes. The provider reads the optional pre-Cordis `__DSH_FILE_UPLOAD__` hook once. Without a hook, each Blob or stream request owns a short-lived Worker and releases it after completion, failure, or cancellation. With the hook, the service sends the body through the page-owned Fetch carrier; the Web Worker runtime transfers stream bodies through its request frame and exposes them to the Host HTTP bridge as backpressured chunks. -The Host plugin provides `ctx.fileUploads`. It owns the authenticated streaming route, encoded Remote fallback, command receipt resolver, and staged-receipt lifecycle; encoded admission, attachment-error recognition, and byte storage stay behind `ctx.attachments`. Host callers supply an Agent with its runtime-owned context; receipt tables use that Agent's exact Session object as their key. The Session Controller registers the resolver that can resume a cold ordinary Agent and consumes receipts during prompt admission. Prompt delivery holds each receipt binding in a disposable transaction: disposal restores the previous binding until successful delivery commits it, and queue or history observation then retires the committed receipt. +The Host plugin provides `ctx.fileUploads`. It owns the authenticated streaming route, encoded Remote fallback, command receipt resolver, and staged-receipt lifecycle; encoded admission, attachment-error recognition, and byte storage stay behind `ctx.attachments`. A raw upload with a `mediaType` query parameter reads at most the deployment's per-image byte limit and stores the image through `ctx.attachments.saveImages`; its receipt resolves to that image during prompt admission, and commands accept only file receipts. Host callers supply an Agent with its runtime-owned context; receipt tables use that Agent's exact Session object as their key. The Session Controller registers the resolver that can resume a cold ordinary Agent and consumes receipts during prompt admission. Prompt delivery holds each receipt binding in a disposable transaction: disposal restores the previous binding until successful delivery commits it, and queue or history observation then retires the committed receipt. | File | Role | |---|---| diff --git a/packages/client/file-upload/README.zh.md b/packages/client/file-upload/README.zh.md index 86bc9ef6f5..56a2e46aff 100644 --- a/packages/client/file-upload/README.zh.md +++ b/packages/client/file-upload/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -本包让浏览器功能为一个 Session 存储 `Blob`、精确字节或 `ReadableStream`,并取得供后续 prompt 使用的不透明凭证。普通服务页面发送 Blob 和 stream 请求体时,不会在页面线程聚合全部字节;Host 位于其他执行上下文中的页面会在 Cordis 启动前提供 Fetch 形式的载体。调用方可以观察已消费字节并取消活动操作。stream 请求体只能消费一次,跨 Worker 边界时会转移所有权。精确字节使用生成的 Remote。 +本包让浏览器功能为一个 Session 存储 `Blob`、精确字节或 `ReadableStream`,并取得供后续 prompt 使用的不透明凭证。普通服务页面发送 Blob 和 stream 请求体时,不会在页面线程聚合全部字节;Host 位于其他执行上下文中的页面会在 Cordis 启动前提供 Fetch 形式的载体。调用方可以观察已消费字节并取消活动操作。stream 请求体只能消费一次,跨 Worker 边界时会转移所有权。图片上传会暂存一张规整后的 prompt 图片,供后续 prompt 凭证引用。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在注入 `fileUpload` 的消费方之前挂载本包,再调用 `ctx.fileUpload.upload(sessionId, body, name, signal, onProgress)`。Session 标识同时用于寻址原始路由和生成的 Remote 兜底;调用方不组装这两种请求。 +在注入 `fileUpload` 的消费方之前挂载本包,再调用 `ctx.fileUpload.upload(sessionId, body, name, signal, onProgress)`;prompt 图片则调用 `ctx.fileUpload.uploadImage(sessionId, blob, mediaType, name, signal, onProgress)`。Session 标识同时用于寻址原始路由和生成的 Remote 兜底;调用方不组装这两种请求。 ```yaml - id: file-upload @@ -44,7 +44,7 @@ kind: "package-reference" Client 插件提供 `ctx.fileUpload`。其 `upload()` 方法接收所属 Session 标识,组装原始路由请求,并为精确字节调用生成的 Remote。提供方只读取一次可选的 Cordis 启动前 `__DSH_FILE_UPLOAD__` 钩子。没有该钩子时,每个 Blob 或 stream 请求拥有一个短期 Worker,并在完成、失败或取消后释放。存在该钩子时,服务通过页面自己提供的 Fetch 载体发送请求体;Web Worker runtime 会通过请求帧转移 stream 请求体,再以带背压的分片形式交给 Host HTTP bridge。 -Host 插件提供 `ctx.fileUploads`。它拥有经过认证的流式路由、编码 Remote 兜底、命令凭证解析器与暂存凭证生命周期;编码准入、附件错误识别与字节存储仍由 `ctx.attachments` 提供。Host 调用方传入具有运行时所属上下文的 Agent;凭证表以该 Agent 的准确 Session 对象为键。Session Controller 注册可恢复休眠普通 Agent 的解析器,并在 prompt 准入时消费凭证。Prompt 投递通过可释放事务持有每个凭证绑定。成功投递提交事务前,释放会恢复原绑定;提交后,队列或历史观察会退休该凭证。 +Host 插件提供 `ctx.fileUploads`。它拥有经过认证的流式路由、编码 Remote 兜底、命令凭证解析器与暂存凭证生命周期;编码准入、附件错误识别与字节存储仍由 `ctx.attachments` 提供。带 `mediaType` 查询参数的原始上传最多读取部署配置的单张图片字节上限,并通过 `ctx.attachments.saveImages` 存储图片;该凭证在 prompt 准入时解析为这张图片,命令只接受文件凭证。Host 调用方传入具有运行时所属上下文的 Agent;凭证表以该 Agent 的准确 Session 对象为键。Session Controller 注册可恢复休眠普通 Agent 的解析器,并在 prompt 准入时消费凭证。Prompt 投递通过可释放事务持有每个凭证绑定。成功投递提交事务前,释放会恢复原绑定;提交后,队列或历史观察会退休该凭证。 | 文件 | 职责 | |---|---| diff --git a/packages/client/file-upload/src/client/contract.ts b/packages/client/file-upload/src/client/contract.ts index 8bf1145193..758aaa6d81 100644 --- a/packages/client/file-upload/src/client/contract.ts +++ b/packages/client/file-upload/src/client/contract.ts @@ -1,6 +1,7 @@ +import type { ImageMediaType } from '@deepseek-ai/dsh-attachment/types' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import type { FileUploadValue } from '../types.ts' +import type { FileUploadValue, ImageUploadValue } from '../types.ts' /** Browser request body accepted by the background file-upload service. */ export type FileUploadBody = Blob | ReadableStream @@ -30,4 +31,24 @@ export interface FileUploadService { signal?: AbortSignal, onProgress?: (progress: FileUploadProgress) => void, ): Promise> + /** + * Store one prompt image for a Session through the background carrier. The + * Host validates, normalizes, and stores it as prompt admission would, and a + * later prompt cites the receipt in a file part. + * @param sessionId - Session that owns the staged receipt. + * @param data - browser image Blob. + * @param mediaType - declared image media type. + * @param name - optional display name. + * @param signal - optional cancellation for the active upload. + * @param onProgress - optional byte-progress observer. + * @returns the staged receipt and normalized image reference, or a business error. + */ + uploadImage( + sessionId: SessionId, + data: Blob, + mediaType: ImageMediaType, + name?: string, + signal?: AbortSignal, + onProgress?: (progress: FileUploadProgress) => void, + ): Promise> } diff --git a/packages/client/file-upload/src/client/runtime.ts b/packages/client/file-upload/src/client/runtime.ts index 556da15f10..46581c2873 100644 --- a/packages/client/file-upload/src/client/runtime.ts +++ b/packages/client/file-upload/src/client/runtime.ts @@ -1,13 +1,14 @@ /** Background browser upload implementation for Blob and byte-stream bodies. */ import { Service, type Context } from '@deepseek-ai/cordis' +import type { ImageMediaType } from '@deepseek-ai/dsh-attachment/types' import { bytesToBase64 } from '@deepseek-ai/dsh-util-crypto' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { FILE_UPLOAD_ROUTE } from '../protocol.ts' import type { - ClientFileUploadHooks, EncodedFileUploadRequest, FileUploadFetch, FileUploadValue, + ClientFileUploadHooks, EncodedFileUploadRequest, FileUploadFetch, FileUploadValue, ImageUploadValue, } from '../types.ts' import type { FileUploadBody, FileUploadService } from './contract.ts' @@ -198,17 +199,7 @@ export class FileUploadRuntime extends Service implements FileUploadService { if (!(data instanceof Uint8Array)) { const query = new URLSearchParams({ sessionId }) if (name !== undefined) query.set('name', name) - const response = await this.post({ - path: `${FILE_UPLOAD_ROUTE}?${query.toString()}`, - body: data, - headers: { 'content-type': 'application/octet-stream' }, - ...(signal === undefined ? {} : { signal }), - ...(onProgress === undefined ? {} : { onProgress }), - }) - if (response.status !== 200) { - throw new Error(`file upload transport failed with HTTP ${String(response.status)}`) - } - return parseFileUploadResult(response.body) + return parseUploadResult(await this.postRaw(query, data, signal, onProgress), fileUploadValue) } return (this.ctx as FileUploadRemoteContext).remote.fileUploads.upload( sessionId, @@ -219,6 +210,49 @@ export class FileUploadRuntime extends Service implements FileUploadService { signal, ) } + + /** + * Store one prompt image for a Session. + * @param sessionId - Session that owns the staged receipt. + * @param data - browser image Blob. + * @param mediaType - declared image media type. + * @param name - optional display name. + * @param signal - optional cancellation for the active upload. + * @param onProgress - optional byte-progress observer. + * @returns the staged receipt and normalized image reference, or a business error. + */ + async uploadImage( + sessionId: SessionId, + data: Blob, + mediaType: ImageMediaType, + name?: string, + signal?: AbortSignal, + onProgress?: (progress: { readonly loaded: number; readonly total?: number }) => void, + ): Promise> { + const query = new URLSearchParams({ sessionId, mediaType }) + if (name !== undefined) query.set('name', name) + return parseUploadResult(await this.postRaw(query, data, signal, onProgress), imageUploadValue) + } + + /** Post one raw body to the upload route; a non-200 status is a transport failure. */ + private async postRaw( + query: URLSearchParams, + body: FileUploadBody, + signal: AbortSignal | undefined, + onProgress: ((progress: { readonly loaded: number; readonly total?: number }) => void) | undefined, + ): Promise { + const response = await this.post({ + path: `${FILE_UPLOAD_ROUTE}?${query.toString()}`, + body, + headers: { 'content-type': 'application/octet-stream' }, + ...(signal === undefined ? {} : { signal }), + ...(onProgress === undefined ? {} : { onProgress }), + }) + if (response.status !== 200) { + throw new Error(`file upload transport failed with HTTP ${String(response.status)}`) + } + return response.body + } } function customTransport(customFetch: FileUploadFetch): FileUploadTransport { @@ -297,7 +331,7 @@ function workerTransport(): FileUploadTransport { } } -function parseFileUploadResult(body: string): RemoteResult { +function parseUploadResult(body: string, parseValue: (value: unknown) => T): RemoteResult { const value: unknown = JSON.parse(body) if (!isRecord(value) || typeof value.ok !== 'boolean') { throw new TypeError('file upload transport returned an invalid result') @@ -313,26 +347,60 @@ function parseFileUploadResult(body: string): RemoteResult { error: new RemoteError(error.code as never, error.message, error.details as never), } } - const result = value.value + return { ok: true, value: parseValue(value.value) } +} + +function fileUploadValue(result: unknown): FileUploadValue { const file = isRecord(result) ? result.file : undefined if (!isRecord(result) || typeof result.receiptId !== 'string' || !isRecord(file) - || typeof file.attachmentId !== 'string' || typeof file.name !== 'string' - || typeof file.bytes !== 'number' || !Number.isSafeInteger(file.bytes) || file.bytes < 0) { + || typeof file.attachmentId !== 'string' || typeof file.name !== 'string' || !isNonNegativeInteger(file.bytes)) { throw new TypeError('file upload transport returned an invalid receipt') } return { - ok: true, - value: { - receiptId: result.receiptId as FileUploadValue['receiptId'], - file: { - attachmentId: file.attachmentId as FileUploadValue['file']['attachmentId'], - name: file.name, - bytes: file.bytes, - }, + receiptId: result.receiptId as FileUploadValue['receiptId'], + file: { + attachmentId: file.attachmentId as FileUploadValue['file']['attachmentId'], + name: file.name, + bytes: file.bytes, }, } } +function imageUploadValue(result: unknown): ImageUploadValue { + const image = isRecord(result) ? result.image : undefined + if (!isRecord(result) || typeof result.receiptId !== 'string' || !isRecord(image) + || typeof image.attachmentId !== 'string' || !isImageMediaType(image.mediaType) + || !isNonNegativeInteger(image.bytes) || !isNonNegativeInteger(image.width) || !isNonNegativeInteger(image.height) + || (image.name !== undefined && typeof image.name !== 'string') + || (image.originalDimensions !== undefined && !isDimensions(image.originalDimensions))) { + throw new TypeError('file upload transport returned an invalid image receipt') + } + return { + receiptId: result.receiptId as ImageUploadValue['receiptId'], + image: { + attachmentId: image.attachmentId as ImageUploadValue['image']['attachmentId'], + mediaType: image.mediaType, + bytes: image.bytes, + width: image.width, + height: image.height, + ...(image.name === undefined ? {} : { name: image.name }), + ...(image.originalDimensions === undefined ? {} : { originalDimensions: image.originalDimensions }), + }, + } +} + +function isNonNegativeInteger(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 +} + +function isImageMediaType(value: unknown): value is ImageMediaType { + return value === 'image/png' || value === 'image/jpeg' || value === 'image/webp' || value === 'image/gif' +} + +function isDimensions(value: unknown): value is { width: number; height: number } { + return isRecord(value) && isNonNegativeInteger(value.width) && isNonNegativeInteger(value.height) +} + function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) } diff --git a/packages/client/file-upload/src/http-route.ts b/packages/client/file-upload/src/http-route.ts index 0f5539324e..b03c4b9562 100644 --- a/packages/client/file-upload/src/http-route.ts +++ b/packages/client/file-upload/src/http-route.ts @@ -4,17 +4,18 @@ import { brandString } from '@deepseek-ai/dsh-brand' import type { SessionId } from '@deepseek-ai/dsh-session' import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import type { FileUploads } from './index.ts' -import type { FileUploadValue } from './types.ts' +import type { FileUploadValue, ImageUploadValue } from './types.ts' type FileUploadHttpResult = - | { readonly ok: true; readonly value: FileUploadValue } + | { readonly ok: true; readonly value: FileUploadValue | ImageUploadValue } | { readonly ok: false readonly error: { readonly code: string; readonly message: string; readonly details: object } } /** - * Handle one authenticated raw-byte upload. + * Handle one authenticated raw-byte upload. A `mediaType` query parameter + * stages the body as a prompt image; without it the body is stored verbatim. * @param service - Host upload service receiving streamed bytes. * @param request - authenticated HTTP request from Connection. * @returns JSON result using HTTP status 200 after request validation. @@ -33,16 +34,20 @@ export async function handleFileUploadHttp(service: FileUploads, request: Reques return new Response('sessionId is required', { status: 400 }) } const name = url.searchParams.get('name') ?? undefined + const imageMediaType = url.searchParams.get('mediaType') ?? undefined + const upload = { + sessionId: brandString(sessionId), + data: requestBodyChunks(request.body), + signal: request.signal, + ...(name === undefined ? {} : { name }), + } let result: FileUploadHttpResult try { result = { ok: true, - value: await service.uploadStream({ - sessionId: brandString(sessionId), - data: requestBodyChunks(request.body), - signal: request.signal, - ...(name === undefined ? {} : { name }), - }), + value: imageMediaType === undefined + ? await service.uploadStream(upload) + : await service.uploadImageStream({ ...upload, mediaType: imageMediaType }), } } catch (error) { const failure = remoteErrorOf(error) diff --git a/packages/client/file-upload/src/index.ts b/packages/client/file-upload/src/index.ts index acf99f22d2..e3ee710de1 100644 --- a/packages/client/file-upload/src/index.ts +++ b/packages/client/file-upload/src/index.ts @@ -3,26 +3,28 @@ import { randomUUID } from 'node:crypto' import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' -import type { FileAttachmentRef } from '@deepseek-ai/dsh-attachment' +import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type {} from '@deepseek-ai/dsh-client-connection' import type { CommandFileReceiptResolver } from '@deepseek-ai/dsh-commands' import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session' -import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import { Remote, RemoteError, remoteErrorOf, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { handleFileUploadHttp } from './http-route.ts' import { FILE_UPLOAD_PATH } from './protocol.ts' -import type { EncodedFileUploadRequest, FileUploadReceiptId, FileUploadValue } from './types.ts' +import type { + EncodedFileUploadRequest, FileUploadReceiptId, FileUploadValue, ImageUploadValue, StagedAttachment, +} from './types.ts' export type * from './types.ts' declare module '@deepseek-ai/cordis' { interface Context { - /** Host storage and staged-receipt service for browser file uploads. */ + /** Host storage and staged-receipt service for browser file and image uploads. */ fileUploads: FileUploads } } interface StagedFileUpload { - readonly file: FileAttachmentRef + readonly attachment: StagedAttachment /** Prompt that accepted this receipt; absent until successful admission. */ requestId?: string } @@ -65,8 +67,11 @@ export class FileUploads extends TypertRemoteService { /** @param ctx - Host context carrying Agent, attachment, command, and Connection services. */ constructor(ctx: Context) { super(ctx, 'fileUploads') - const resolve: CommandFileReceiptResolver = (agent, receiptId) => - this.resolve(agent, receiptId as FileUploadReceiptId) + // Commands accept staged files only; an image receipt is unknown to them. + const resolve: CommandFileReceiptResolver = (agent, receiptId) => { + const staged = this.resolve(agent, receiptId as FileUploadReceiptId) + return staged?.type === 'file' ? staged.attachment : undefined + } ctx.effect( () => ctx.commands.registerFileReceiptResolver(resolve), 'file-upload: command file receipt resolver', @@ -105,12 +110,13 @@ export class FileUploads extends TypertRemoteService { * @returns the staged receipt and durable file reference. */ @Remote('upload') - upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise { + async upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise { signal.throwIfAborted() - return this.commit(agent, async () => this.ctx.attachments.admitEncodedFile({ + const file = await this.store(agent, async () => this.ctx.attachments.admitEncodedFile({ data: request.data, ...(request.name === undefined ? {} : { name: request.name }), })) + return { receiptId: this.stage(agent, { type: 'file', attachment: file }), file } } /** @@ -125,21 +131,60 @@ export class FileUploads extends TypertRemoteService { readonly name?: string }): Promise { const agent = await this.resolveAgent(request.sessionId) - return this.commit(agent, async () => this.ctx.attachments.saveFileStream({ + const file = await this.store(agent, async () => this.ctx.attachments.saveFileStream({ data: request.data, ...(request.signal === undefined ? {} : { signal: request.signal }), ...(request.name === undefined ? {} : { name: request.name }), })) + return { receiptId: this.stage(agent, { type: 'file', attachment: file }), file } + } + + /** + * Persist one prompt image for a Session: read at most the deployment's + * per-image byte limit, then validate, normalize, and store the image the + * way prompt admission does, so a later prompt cites it by receipt. + * @param request - Session identity, ordered bytes, the declared media type that this deployment + * must accept, cancellation, and optional display name. + * @returns the staged receipt and durable normalized image reference. + */ + async uploadImageStream(request: { + readonly sessionId: SessionId + readonly data: AsyncIterable + readonly mediaType: string + readonly signal?: AbortSignal + readonly name?: string + }): Promise { + const agent = await this.resolveAgent(request.sessionId) + const limits = this.ctx.attachments.imageLimits + const mediaType = limits.mediaTypes.find(type => type === request.mediaType) + if (mediaType === undefined) { + throw new RemoteError( + 'session/attachment-invalid' as never, + `Image type ${request.mediaType} is not accepted by this deployment.`, + { reason: 'UNSUPPORTED_IMAGE_TYPE' } as never, + ) + } + const image = await this.store(agent, async () => { + const data = await readAtMost(request.data, limits.maxImageBytes, request.signal) + const refs = await this.ctx.attachments.saveImages([{ + data, + mediaType, + ...(request.name === undefined ? {} : { name: request.name }), + }]) + // saveImages returns one reference per input, in input order. + return refs[0] as ImageAttachmentRef + }) + return { receiptId: this.stage(agent, { type: 'image', attachment: image }), image } } /** * Resolve one staged receipt for the receiving Agent's exact Session. * @param agent - receiving Agent. * @param receiptId - opaque receipt minted for one completed upload. - * @returns durable file reference, or `undefined` for an unknown or foreign receipt. + * @returns the staged file or image, or `undefined` for an unknown or foreign receipt. */ - resolve(agent: Agent, receiptId: FileUploadReceiptId): FileAttachmentRef | undefined { - return this.stagedFiles.get(agent.session)?.get(receiptId)?.file + resolve(agent: Agent, receiptId: FileUploadReceiptId): StagedAttachment | undefined { + return this.stagedFiles.get(agent.session)?.get(receiptId)?.attachment } /** @@ -179,12 +224,13 @@ export class FileUploads extends TypertRemoteService { this.retire(agent.session, requestId) } - private async commit(agent: Agent, save: () => Promise): Promise { + /** Store one upload for an ordinary Agent; storage failures become Remote failures. */ + private async store(agent: Agent, save: () => Promise): Promise { this.assertOrdinaryAgent(agent) - let file: FileAttachmentRef try { - file = await save() + return await save() } catch (error) { + if (remoteErrorOf(error) !== undefined) throw error if (this.ctx.attachments.isAttachmentError(error)) { throw new RemoteError('session/attachment-invalid' as never, error.message, { reason: error.code } as never) } @@ -195,6 +241,10 @@ export class FileUploads extends TypertRemoteService { { cause: error }, ) } + } + + /** Stage one stored upload under a new receipt for the Agent's exact Session. */ + private stage(agent: Agent, attachment: StagedAttachment): FileUploadReceiptId { if (this.ctx.agents.get(agent.id) !== agent) { throw new RemoteError( 'session/not-found', @@ -208,8 +258,8 @@ export class FileUploads extends TypertRemoteService { this.stagedFiles.set(agent.session, staged) } const receiptId = randomUUID() as FileUploadReceiptId - staged.set(receiptId, { file }) - return { receiptId, file } + staged.set(receiptId, { attachment }) + return receiptId } private async resolveAgent(sessionId: SessionId): Promise { @@ -248,6 +298,31 @@ export class FileUploads extends TypertRemoteService { } } +/** Collect one body of at most `limit` bytes, refusing it as soon as it passes the limit. */ +async function readAtMost(data: AsyncIterable, limit: number, signal?: AbortSignal): Promise { + const chunks: Uint8Array[] = [] + let length = 0 + for await (const chunk of data) { + signal?.throwIfAborted() + length += chunk.byteLength + if (length > limit) { + throw new RemoteError( + 'session/attachment-invalid' as never, + 'Image exceeds the configured byte limit.', + { reason: 'IMAGE_TOO_LARGE' } as never, + ) + } + chunks.push(chunk) + } + const bytes = new Uint8Array(length) + let offset = 0 + for (const chunk of chunks) { + bytes.set(chunk, offset) + offset += chunk.byteLength + } + return bytes +} + function fileNotStaged(): RemoteError { return new RemoteError( 'session/attachment-invalid' as never, diff --git a/packages/client/file-upload/src/types.ts b/packages/client/file-upload/src/types.ts index ff153925af..bb7565ba87 100644 --- a/packages/client/file-upload/src/types.ts +++ b/packages/client/file-upload/src/types.ts @@ -1,6 +1,6 @@ /** Browser-safe request and receipt types for staged file uploads. */ -import type { FileAttachmentRef } from '@deepseek-ai/dsh-attachment/types' +import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment/types' import type { Branded } from '@deepseek-ai/dsh-brand' /** Canonical encoded upload accepted by the Remote fallback. */ @@ -18,6 +18,19 @@ export interface FileUploadValue { readonly file: FileAttachmentRef } +/** Durable receipt for one staged image upload. */ +export interface ImageUploadValue { + /** Per-upload authority accepted only inside the receiving Agent scope. */ + readonly receiptId: FileUploadReceiptId + /** The normalized prompt image the Host stored. */ + readonly image: ImageAttachmentRef +} + +/** Durable attachment one staged receipt names: a verbatim file, or a normalized prompt image. */ +export type StagedAttachment = + | { readonly type: 'file'; readonly attachment: FileAttachmentRef } + | { readonly type: 'image'; readonly attachment: ImageAttachmentRef } + /** Host-minted authority for one staged file upload in one Agent scope. */ export type FileUploadReceiptId = Branded<'file-upload-receipt-id'> diff --git a/packages/client/file-upload/tests/file-upload-http.host.spec.ts b/packages/client/file-upload/tests/file-upload-http.host.spec.ts index cd137857ce..ed34e34d0e 100644 --- a/packages/client/file-upload/tests/file-upload-http.host.spec.ts +++ b/packages/client/file-upload/tests/file-upload-http.host.spec.ts @@ -9,12 +9,14 @@ function request(input: { method?: string sessionId?: string name?: string + mediaType?: string contentType?: string body?: Uint8Array } = {}): Request { const query = new URLSearchParams() if (input.sessionId !== undefined) query.set('sessionId', input.sessionId) if (input.name !== undefined) query.set('name', input.name) + if (input.mediaType !== undefined) query.set('mediaType', input.mediaType) const suffix = query.size === 0 ? '' : `?${query.toString()}` return new Request(`http://host/api/session/uploadFileBinary${suffix}`, { method: input.method ?? 'POST', @@ -91,6 +93,27 @@ describe('background file upload Fetch route', () => { expect(await response.json()).toEqual({ ok: true, value }) }) + it('stages the body as a prompt image when the request names its media type', async () => { + const value: Awaited> = { + receiptId: 'receipt-2' as never, + image: { attachmentId: 'image-1' as never, mediaType: 'image/png', bytes: 2, width: 1, height: 1 }, + } + const imageChunks: Uint8Array[] = [] + const uploadImageStream = vi.fn(async (input) => { + for await (const chunk of input.data) imageChunks.push(chunk) + return value + }) + const service = Object.assign(uploads(Promise.resolve({})), { uploadImageStream }) + const response = await handleFileUploadHttp(service, request({ + sessionId: 's1', name: 'shot.png', mediaType: 'image/png', + contentType: 'application/octet-stream', body: Uint8Array.of(7, 8), + })) + expect(service.uploadStream).not.toHaveBeenCalled() + expect(uploadImageStream.mock.calls[0]?.[0]).toMatchObject({ sessionId: 's1', name: 'shot.png', mediaType: 'image/png' }) + expect(imageChunks).toEqual([Uint8Array.of(7, 8)]) + expect(await response.json()).toEqual({ ok: true, value }) + }) + it('returns business and internal storage failures and keeps an absent name absent', async () => { const business = uploads(Promise.reject(new RemoteError( 'session/attachment-invalid', 'denied', { reason: 'NOPE' }, diff --git a/packages/client/file-upload/tests/file-upload.client.spec.ts b/packages/client/file-upload/tests/file-upload.client.spec.ts index 2392feed55..3a4e0b22ea 100644 --- a/packages/client/file-upload/tests/file-upload.client.spec.ts +++ b/packages/client/file-upload/tests/file-upload.client.spec.ts @@ -492,4 +492,53 @@ describe('Session-addressed file upload', () => { }) await failed.fiber.dispose() }) + + it('uploads an image with its media type and parses the stored image', async () => { + const image = { + attachmentId: 'image-1', mediaType: 'image/png', bytes: 4, width: 2, height: 2, + name: 'shot.png', originalDimensions: { width: 4, height: 4 }, + } + const fetch = vi.fn(() => Promise.resolve(new Response(JSON.stringify({ + ok: true, value: { receiptId: 'receipt-2', image }, + }), { status: 200 }))) + ;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = { fetch } + const { fiber, service } = await scopedService() + const file = new Blob(['data'], { type: 'image/png' }) + await expect(service.uploadImage(SESSION_ID, file, 'image/png', 'shot.png')).resolves.toEqual({ + ok: true, value: { receiptId: 'receipt-2', image }, + }) + expect(fetch).toHaveBeenCalledWith( + 'api/session/uploadFileBinary?sessionId=s1&mediaType=image%2Fpng&name=shot.png', + expect.objectContaining({ method: 'POST', body: file }), + ) + await fiber.dispose() + + const plain = { attachmentId: 'image-2', mediaType: 'image/webp', bytes: 1, width: 1, height: 1 } + ;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = { + fetch: () => Promise.resolve(new Response(JSON.stringify({ + ok: true, value: { receiptId: 'receipt-4', image: plain }, + }), { status: 200 })), + } + const unnamed = await scopedService() + await expect(unnamed.service.uploadImage(SESSION_ID, file, 'image/webp')).resolves.toEqual({ + ok: true, value: { receiptId: 'receipt-4', image: plain }, + }) + await unnamed.fiber.dispose() + + for (const malformed of [ + null, + { receiptId: 'receipt-3', image: { ...image, mediaType: 'image/bmp' } }, + { receiptId: 'receipt-3', image: { ...image, width: -1 } }, + { receiptId: 'receipt-3', image: { ...image, name: 3 } }, + { receiptId: 'receipt-3', image: { ...image, originalDimensions: { width: 1 } } }, + ]) { + ;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = { + fetch: () => Promise.resolve(new Response(JSON.stringify({ ok: true, value: malformed }), { status: 200 })), + } + const rejected = await scopedService() + await expect(rejected.service.uploadImage(SESSION_ID, file, 'image/png')) + .rejects.toThrow('file upload transport returned an invalid image receipt') + await rejected.fiber.dispose() + } + }) }) diff --git a/packages/client/ui-attachment/README.i18n.yaml b/packages/client/ui-attachment/README.i18n.yaml index 123b686b4e..0481d6a8c5 100644 --- a/packages/client/ui-attachment/README.i18n.yaml +++ b/packages/client/ui-attachment/README.i18n.yaml @@ -18,8 +18,8 @@ en: 15cdd9d52dcc71b8 zh: 53933fbbf5d39100 /deepseek-ai-dsh-client-ui-attachment/use-this-package/draft-attachments: - en: a77c8ec48e219aec - zh: 756d4fe881403006 + en: ce7e8e06805a6d66 + zh: de1cb8bd06e3e560 /deepseek-ai-dsh-client-ui-attachment/use-this-package/message-images-and-the-lightbox: en: 8b3d7729152d8060 zh: 815f932ccc9653f5 diff --git a/packages/client/ui-attachment/README.md b/packages/client/ui-attachment/README.md index 4fee29e123..2f28c9c2ce 100644 --- a/packages/client/ui-attachment/README.md +++ b/packages/client/ui-attachment/README.md @@ -29,7 +29,7 @@ Mount this plugin alongside [`ui-conversation`](../ui-conversation/README.md) an ### Draft attachments -Images and generic files retain pick order in one non-wrapping horizontal rail. Every item is 64px high: an image is a 64px square thumbnail, while a generic file is a 240px-wide DeepSeek Web card with a 16px radius, blue gradient document glyph, filename, and uppercase extension plus byte size. Edge arrows page hidden overflow, the scrollbar stays hidden, and a newly added item is revealed at the rail's end. Uploading replaces a file glyph with a spinner and shows byte progress when the carrier reports it, with an indeterminate bar before the first report; failure shows retry, and removal controls appear on hover or keyboard focus while remaining visible on touch devices. Clicking an image opens the original. +Images and generic files retain pick order in one non-wrapping horizontal rail. Every item is 64px high: an image is a 64px square thumbnail, while a generic file is a 240px-wide DeepSeek Web card with a 16px radius, blue gradient document glyph, filename, and uppercase extension plus byte size. Edge arrows page hidden overflow, the scrollbar stays hidden, and a newly added item is revealed at the rail's end. Uploading replaces a file glyph with a spinner and shows byte progress when the carrier reports it, with an indeterminate bar before the first report; failure shows retry, and removal controls appear on hover or keyboard focus while remaining visible on touch devices. An uploading image shows the same progress bar along its thumbnail's bottom edge, and a failed image upload turns the thumbnail into its retry control. Clicking an image opens the original. ### Message images and the lightbox diff --git a/packages/client/ui-attachment/README.zh.md b/packages/client/ui-attachment/README.zh.md index 706a6d97c7..a708581b93 100644 --- a/packages/client/ui-attachment/README.zh.md +++ b/packages/client/ui-attachment/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 草稿附件 -图片与通用文件按选择顺序进入同一条不换行的横向附件栏。所有条目均为 64px 高:图片是 64px 方形缩略图,通用文件是 240px 宽的 DeepSeek Web 卡片,带 16px 圆角、蓝色渐变文档图标、文件名,以及大写扩展名与字节大小。溢出隐藏时由边缘箭头翻页,滚动条保持隐藏,新增条目会滚动到栏尾展示。文件上传时图标位置显示 spinner,传输层报告字节时显示进度,首次报告前使用不定态进度条;失败时显示重试。移除按钮在悬停或键盘聚焦时出现,在触摸设备上保持可见。单击图片会打开原图。 +图片与通用文件按选择顺序进入同一条不换行的横向附件栏。所有条目均为 64px 高:图片是 64px 方形缩略图,通用文件是 240px 宽的 DeepSeek Web 卡片,带 16px 圆角、蓝色渐变文档图标、文件名,以及大写扩展名与字节大小。溢出隐藏时由边缘箭头翻页,滚动条保持隐藏,新增条目会滚动到栏尾展示。文件上传时图标位置显示 spinner,传输层报告字节时显示进度,首次报告前使用不定态进度条;失败时显示重试。上传中的图片在缩略图底边显示同样的进度条,上传失败的图片缩略图变成重试控件。移除按钮在悬停或键盘聚焦时出现,在触摸设备上保持可见。单击图片会打开原图。 ### 消息图片与灯箱 diff --git a/packages/client/ui-attachment/src/client/ComposerAttachments.module.css b/packages/client/ui-attachment/src/client/ComposerAttachments.module.css index adb40af60f..962148b937 100644 --- a/packages/client/ui-attachment/src/client/ComposerAttachments.module.css +++ b/packages/client/ui-attachment/src/client/ComposerAttachments.module.css @@ -30,6 +30,53 @@ object-fit: cover; } +.thumbnailFailed { + border-color: var(--dsw-alias-state-error-primary, #d54941); + cursor: pointer; +} + +.thumbnailFailed img { + opacity: 0.4; +} + +.retryGlyph { + position: absolute; + inset: 0; + display: grid; + place-items: center; + color: var(--dsw-alias-state-error-primary, #d54941); +} + +.progressTrack { + position: absolute; + right: 8px; + bottom: 6px; + left: 8px; + overflow: hidden; + height: 2px; + border-radius: 1px; + background: var(--dsw-alias-fill-tertiary, rgba(0, 0, 0, 0.08)); + pointer-events: none; +} + +.progressBar { + display: block; + width: 35%; + height: 100%; + border-radius: inherit; + background: var(--dsw-alias-brand-primary, #4d6bfe); + animation: image-upload-progress 1.2s ease-in-out infinite alternate; +} + +.progressBar[style] { + animation: none; +} + +@keyframes image-upload-progress { + from { transform: translateX(-70%); } + to { transform: translateX(220%); } +} + .remove { position: absolute; top: 4px; @@ -70,4 +117,8 @@ .remove { transition: none; } + + .progressBar { + animation: none; + } } diff --git a/packages/client/ui-attachment/src/client/ComposerAttachments.tsx b/packages/client/ui-attachment/src/client/ComposerAttachments.tsx index 0065410b9d..f8dac0c690 100644 --- a/packages/client/ui-attachment/src/client/ComposerAttachments.tsx +++ b/packages/client/ui-attachment/src/client/ComposerAttachments.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { ComposerAttachment, ComposerAttachmentsProps, ComposerImageAttachment, } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { IconCloseFillRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconCloseFillRegular, IconRefreshOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { AttachmentRail } from '../AttachmentRail.tsx' import type { AttachmentRailItem } from '../AttachmentRail.tsx' import { DropOverlay } from '../DropOverlay.tsx' @@ -71,16 +71,44 @@ export function ComposerAttachments({ /> ) } + // An uploading image shows its progress; a failed upload turns the thumbnail into its retry control. + const upload = uploads[attachment.id] return (
- + {upload?.status === 'error' + ? ( + + ) + : ( + + )} + {upload?.status === 'uploading' && ( + + + + )} + +
) - : ( - - )} + : upload?.status === 'error' + ? ( + + ) + : ( + + )} {upload?.status === 'uploading' && ( { onRemoveAttachment(attachment.id) }} > diff --git a/packages/client/ui-attachment/tests/composer-attachments.client.spec.tsx b/packages/client/ui-attachment/tests/composer-attachments.client.spec.tsx index ba5ea67ada..a419e83f3c 100644 --- a/packages/client/ui-attachment/tests/composer-attachments.client.spec.tsx +++ b/packages/client/ui-attachment/tests/composer-attachments.client.spec.tsx @@ -74,7 +74,7 @@ function fileDraft(id: string, name = `${id}.pdf`): ComposerAttachment { } } -function props(overrides: Partial = {}): ComposerAttachmentsProps { +function props(overrides: Partial = {}): Parameters[0] { return { attachments: [], canAcceptDrop: true, @@ -82,9 +82,10 @@ function props(overrides: Partial = {}): Composer onRemoveAttachment: () => {}, uploads: {}, onRetryFile: () => {}, + uploadFailureText: (reason: string) => `refused:${reason}`, t, ...overrides, - } as unknown as ComposerAttachmentsProps + } } describe('ComposerAttachments', () => { @@ -230,18 +231,18 @@ describe('ComposerAttachments', () => { }) describe('ComposerAttachments image uploads', () => { - it('shows image upload progress and turns a failed image into its retry control', () => { + it('shows image upload progress, retries a failed image, and explains one the Host refused', () => { const onRetryFile = vi.fn() const view = render() @@ -251,8 +252,23 @@ describe('ComposerAttachments image uploads', () => { expect(view.getByTitle('上传失败,点击重试')).toBeTruthy() fireEvent.click(view.getByRole('button', { name: '重试上传 failed.png' })) expect(onRetryFile).toHaveBeenCalledWith('failed') + // A refusal names its reason and offers no retry; removal stays available. + expect(view.getByRole('img', { name: 'refused:IMAGE_DIMENSION_TOO_LARGE' }).getAttribute('title')) + .toBe('refused:IMAGE_DIMENSION_TOO_LARGE') + expect(view.queryByRole('button', { name: '重试上传 refused.png' })).toBeNull() + expect(view.getByRole('button', { name: '移除图片 refused.png' })).toBeTruthy() expect(view.queryByRole('dialog', { name: '原图预览' })).toBeNull() }) + + it('names an image without a file name in its preview, retry, and remove controls', () => { + const view = render() + expect(view.getByRole('button', { name: '重试上传 待发送图片' })).toBeTruthy() + expect(view.getAllByRole('button', { name: '移除图片 待发送图片' })).toHaveLength(2) + expect(view.getByAltText('待发送图片')).toBeTruthy() + }) }) describe('ComposerAttachments file drafts', () => { diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 423b12ad0e..19576f04ed 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -368,10 +368,13 @@ export function apply(ctx: Context, config: Config = Config({})): void { const attachmentIds = from.snapshot.attachmentIds const next = inputHub.shell(nextId) if (attachmentIds.length === 0 || next.addAttachments(attachmentIds)) { - if (sessions.binding(nextId) === undefined) { + const binding = sessions.binding(nextId) + if (binding === undefined) { throw new Error(`ui-conversation: session "${nextId}" resolved no binding`) } - concreteConversation(ctx).rebindDraftFiles(nextId, attachmentIds) + // The same rule as intake: only an ordinary Session stages image uploads. + const ordinary = binding.session.getSnapshot().subagent === null + concreteConversation(ctx).rebindDraftFiles(nextId, attachmentIds, ordinary) if (draft.text !== '') { next.setDraft(draft) from.setDraft('') diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 574b368537..6f638b2371 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -53,13 +53,15 @@ export interface ComposerFileAttachment { /** * Upload lifecycle of one draft that uploads when it is added, not on send: - * every file draft, and every image draft of an ordinary Session. + * every file draft, and every image draft of an ordinary Session. A failed + * upload the Host refused keeps the attachment refusal `reason`, because + * retrying the same bytes cannot succeed. */ export type DraftFileUpload = | { readonly status: 'uploading'; readonly loaded: number; readonly total?: number } | { readonly status: 'ready'; readonly receiptId: FileUploadReceiptId; readonly file: FileAttachmentRef } - | { readonly status: 'ready'; readonly receiptId: FileUploadReceiptId; readonly image: ImageAttachmentRef } - | { readonly status: 'error'; readonly message: string } + | { readonly status: 'ready'; readonly receiptId: FileUploadReceiptId } + | { readonly status: 'error'; readonly message: string; readonly reason?: string } /** Per-draft upload states keyed by draft attachment id. */ export type DraftFileUploads = Readonly> @@ -82,6 +84,13 @@ export interface ComposerAttachmentsOwnerProps { uploads: DraftFileUploads /** Restart one failed file upload. */ onRetryFile: (id: DraftAttachmentId) => void + /** + * Explain one upload the Host refused; such a draft cannot be retried and + * stays until it is removed. + * @param reason - the refusal `reason` the failed upload carries. + * @returns localized text naming the limit or the way out. + */ + uploadFailureText: (reason: string) => string /** Display-ready limits for the drop invitation. */ dropLimits?: { readonly count: number; readonly size: string } | undefined } diff --git a/packages/client/ui-conversation/src/client/input/editor/view-binding.ts b/packages/client/ui-conversation/src/client/input/editor/view-binding.ts index dacb1796b8..524c8a37ea 100644 --- a/packages/client/ui-conversation/src/client/input/editor/view-binding.ts +++ b/packages/client/ui-conversation/src/client/input/editor/view-binding.ts @@ -2,7 +2,6 @@ import type { MouseEvent, MutableRefObject, RefObject } from 'react' import type { LexicalEditor } from 'lexical' import type { ComposerKeyboard } from '../../contract/draft-editor.ts' -import type { ComposerBarProps } from '../../contract/slots.ts' import type { BusyEnterBehavior } from '../../contract/composer-submission.ts' import { resolveSubmitMode } from '../submission-policy.ts' import { registerComposerKeymap } from './keymap.ts' @@ -16,8 +15,9 @@ interface DraftViewGate { busyEnter: BusyEnterBehavior intakeFiles: (files: readonly File[], directories?: ReadonlySet) => void uploadsPending: boolean + /** Toast text explaining why pending uploads hold the send. */ + uploadsHeldText: string showToast: (text: string) => void - t: ComposerBarProps['t'] canAcceptDrop: boolean } @@ -126,7 +126,7 @@ export function installDraftKeymap( return } if (g.uploadsPending) { - g.showToast(g.t('file.stillUploading')) + g.showToast(g.uploadsHeldText) return } keyboard.submit(resolveSubmitMode( diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index ff333a1781..41eabe4132 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -348,11 +348,14 @@ export class ConversationController extends Service implements IConversation { * Stage carried file and image drafts again for a new Session. * @param sessionId - target Agent-scope identity after a Workspace switch. * @param ids - carried draft attachment ids. + * @param uploadImages - whether the target Session stages image uploads; an image draft otherwise sends inline. */ - rebindDraftFiles(sessionId: SessionId, ids: readonly DraftAttachmentId[]): void { + rebindDraftFiles(sessionId: SessionId, ids: readonly DraftAttachmentId[], uploadImages: boolean): void { for (const id of ids) { const attachment = this.draftAttachments.get(id) - if (attachment !== undefined) this.beginFileUpload(sessionId, attachment) + if (attachment === undefined) continue + if (attachment.kind === 'image' && !uploadImages) this.dropUpload(id) + else this.beginFileUpload(sessionId, attachment) } } @@ -391,11 +394,17 @@ export class ConversationController extends Service implements IConversation { if (this.fileUploadOperations.get(attachment.id)?.controller !== controller) return this.fileUploads.update((draft) => { if (!(attachment.id in draft)) return - draft[attachment.id] = !result.ok - ? { status: 'error', message: result.error.message } - : 'image' in result.value - ? { status: 'ready', receiptId: result.value.receiptId, image: result.value.image } - : { status: 'ready', receiptId: result.value.receiptId, file: result.value.file } + if (result.ok) { + draft[attachment.id] = 'file' in result.value + ? { status: 'ready', receiptId: result.value.receiptId, file: result.value.file } + : { status: 'ready', receiptId: result.value.receiptId } + return + } + const { error } = result + // A Host refusal keeps its reason: retrying the same bytes cannot succeed. + draft[attachment.id] = error.code === 'session/attachment-invalid' || error.code === 'subagent/attachment-invalid' + ? { status: 'error', message: error.message, reason: error.details.reason } + : { status: 'error', message: error.message } }) } catch (error) { if (this.fileUploadOperations.get(attachment.id)?.controller !== controller) return @@ -446,8 +455,9 @@ export class ConversationController extends Service implements IConversation { /** * Serialize ordered draft attachments to command-submit wire payloads without - * sending or releasing them. Images are encoded; generic files cite receipts - * from their completed background uploads and never reread browser bytes. + * sending or releasing them. Images are encoded even when an upload already + * stored them, because commands accept only file receipts; generic files cite + * receipts from their completed background uploads and never reread browser bytes. * @param attachmentIds - ordered draft-local attachment ids. * @returns wire payloads in id order. */ @@ -478,12 +488,17 @@ export class ConversationController extends Service implements IConversation { releaseDraftAttachment(id: DraftAttachmentId): void { const attachment = this.draftAttachments.get(id) if (attachment === undefined) return - const operation = this.fileUploadOperations.get(id) - this.fileUploadOperations.delete(id) - operation?.controller.abort() this.draftAttachments.delete(id) if (attachment.kind === 'image') revokePreview(attachment.previewUrl) // The stored Host object stays durable; only the draft's upload state ends. + this.dropUpload(id) + } + + /** Abort one draft's active upload and drop its upload state. */ + private dropUpload(id: DraftAttachmentId): void { + const operation = this.fileUploadOperations.get(id) + this.fileUploadOperations.delete(id) + operation?.controller.abort() this.forgetUpload(id) } diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index bb303489b2..e53e666864 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -99,6 +99,11 @@ export const InputBar = memo(function InputBar({ // The deployment's image-intake limits (absent while no attachment service // is composed — the pre-check below then defers entirely to the host). const imageLimits = useProjection('imageLimits') + // Enter while uploads hold the send explains the first failed draft; a Host refusal names its reason. + const failedUpload = attachments.map(attachment => uploads[attachment.id]).find(upload => upload?.status === 'error') + const uploadsHeldText = failedUpload?.status !== 'error' + ? t('file.stillUploading') + : failedUpload.reason === undefined ? t('file.uploadFailed') : attachmentErrorText(t, failedUpload.reason, imageLimits) // Prompt failures are ordinary failures (no create/attach transaction exists // anymore): the toast announces promptError, the draft stays in the machine, // and the user resubmits. A remount over a session whose machine still holds @@ -253,11 +258,11 @@ export const InputBar = memo(function InputBar({ // registration survives re-renders without re-arming per keystroke. const gate = useRef({ locked, machineBusy, canSteerQueue, running, steeringAvailable, busyEnter, - intakeFiles, uploadsPending, showToast, t, canAcceptDrop, + intakeFiles, uploadsPending, uploadsHeldText, showToast, canAcceptDrop, }) gate.current = { locked, machineBusy, canSteerQueue, running, steeringAvailable, busyEnter, - intakeFiles, uploadsPending, showToast, t, canAcceptDrop, + intakeFiles, uploadsPending, uploadsHeldText, showToast, canAcceptDrop, } useEffect(() => { @@ -412,6 +417,7 @@ export const InputBar = memo(function InputBar({ onRemoveAttachment: (id) => { removeAttachment?.(id) }, uploads, onRetryFile: (id) => { retryFileUpload?.(id) }, + uploadFailureText: reason => attachmentErrorText(t, reason, imageLimits), dropLimits: imageLimits === undefined ? undefined : { count: imageLimits.maxImagesPerMessage, size: imageSizeText(imageLimits.maxImageBytes), diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index 48d1ef4bbb..e308d326da 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -1121,6 +1121,38 @@ describe('running and lock semantics', () => { expect(inline.button.disabled).toBe(false) }) + it('explains on Enter why uploads hold the send, naming a Host refusal', () => { + const limits = { + maxImageBytes: 1024 * 1024, + maxImagesPerMessage: 2, + maxMessageImageBytes: 2 * 1024 * 1024, + maxImagePixels: 40_000_000, + maxImageDimension: 2000, + mediaTypes: ['image/png'] as const, + } + const image = { + kind: 'image' as const, + id: 'image-1' as DraftAttachmentId, + file: new File(['x'], 'wide.png', { type: 'image/png' }), + previewUrl: 'blob:wide', + } + const enterWith = (upload: NonNullable[string]): string | null => { + const result = bench({ draft: '带图', attachments: [image], fileUploads: { [image.id]: upload }, imageLimits: limits }) + fireEvent.keyDown(result.textarea, { key: 'Enter' }) + expect(result.sink).not.toHaveBeenCalled() + const text = result.view.getByRole('alert').textContent + cleanup() + return text + } + expect(enterWith({ status: 'uploading', loaded: 0 })).toContain('文件还在上传,请等待上传完成后发送') + expect(enterWith({ status: 'error', message: 'offline' })).toContain('上传失败,点击重试') + const refusal = '图片宽高不能超过 2000px,请缩小后重试' + expect(enterWith({ status: 'error', message: 'too wide', reason: 'IMAGE_DIMENSION_TOO_LARGE' })).toContain(refusal) + // The attachments slot receives the same localized explanation for its thumbnail. + const owner = attachmentOwner(bench({ attachments: [image], imageLimits: limits }).slotCalls) + expect(owner.uploadFailureText('IMAGE_DIMENSION_TOO_LARGE')).toBe(refusal) + }) + it('idle Send keeps the plain label regardless of the busy-state preference', () => { const { button, sink } = bench({ busyEnter: 'steer', draft: '空闲发送' }) expect(button.getAttribute('aria-label')).toBe('发送消息') diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index 4d9f97cfd8..76b93bd95a 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -209,7 +209,7 @@ describe('ConversationController', () => { await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[fileDraft.id]?.status).toBe('ready') expect(b.root.fileUploads.getSnapshot()[imageDraft.id]) - .toEqual({ status: 'ready', receiptId: 'image-receipt-1', image: IMAGE_REF }) + .toEqual({ status: 'ready', receiptId: 'image-receipt-1' }) }) expect(uploadFile).toHaveBeenCalledOnce() expect(uploadFile.mock.calls[0]?.[0]).toBe(fileDraft.file) @@ -242,8 +242,10 @@ describe('ConversationController', () => { const [draft] = b.root.createDrafts(session.sessionId, [ new File([Uint8Array.of(1)], 'big.png', { type: 'image/png' }), ], UPLOAD_IMAGES) + // A Host refusal keeps its reason; retrying stays available to the service. await vi.waitFor(() => { - expect(b.root.fileUploads.getSnapshot()[draft!.id]).toEqual({ status: 'error', message: 'too big' }) + expect(b.root.fileUploads.getSnapshot()[draft!.id]) + .toEqual({ status: 'error', message: 'too big', reason: 'IMAGE_TOO_LARGE' }) }) b.root.retryFileUpload(session.sessionId, draft!.id) await vi.waitFor(() => { expect(uploadImage).toHaveBeenCalledTimes(2) }) @@ -259,6 +261,26 @@ describe('ConversationController', () => { await b.runtime.dispose() }) + it('keeps no refusal reason when an image upload fails in transport', async () => { + const b = await bench() + const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:flaky') + try { + const session = b.runtime.sessions.binding('s1')!.session + ;(session as { uploadImage?: unknown }).uploadImage = vi.fn(() => Promise.resolve({ + ok: false, error: new RemoteError('gateway/internal', 'connection reset', {}), + })) + const [draft] = b.root.createDrafts(session.sessionId, [ + new File([Uint8Array.of(1)], 'flaky.png', { type: 'image/png' }), + ], UPLOAD_IMAGES) + await vi.waitFor(() => { + expect(b.root.fileUploads.getSnapshot()[draft!.id]).toEqual({ status: 'error', message: 'connection reset' }) + }) + } finally { + created.mockRestore() + } + await b.runtime.dispose() + }) + it('serializes command files as staged receipts without reading their bytes again', async () => { const b = await bench() const session = b.runtime.sessions.binding('s1')!.session @@ -397,6 +419,38 @@ describe('ConversationController', () => { await b.runtime.dispose() }) + it('drops a carried image upload when the target Session sends images inline', async () => { + const b = await bench() + const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:carry') + try { + const source = b.runtime.sessions.binding('s1')!.session + let sourceSignal: AbortSignal | undefined + ;(source as { uploadImage?: unknown }).uploadImage = vi.fn( + (_data: Blob, _mediaType: string, _name: string | undefined, signal: AbortSignal) => { + sourceSignal = signal + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true }) + }) + }, + ) + const [image] = b.root.createDrafts(source.sessionId, [ + new File([Uint8Array.of(5)], 'carry.png', { type: 'image/png' }), + ], UPLOAD_IMAGES) + await vi.waitFor(() => { expect(sourceSignal).toBeDefined() }) + const targetUpload = vi.fn() + await b.runtime.sessions.add({ id: 's2', session: { uploadImage: targetUpload } }) + using _target = b.runtime.sessions.retain('s2' as SessionId) + await _target.ready + b.root.rebindDraftFiles(b.runtime.sessions.binding('s2')!.session.sessionId, [image!.id], INLINE_IMAGES) + expect(sourceSignal?.aborted).toBe(true) + expect(b.root.fileUploads.getSnapshot()[image!.id]).toBeUndefined() + expect(targetUpload).not.toHaveBeenCalled() + } finally { + created.mockRestore() + } + await b.runtime.dispose() + }) + it('cancels a superseded upload and stages the carried draft on the target Session', async () => { const b = await bench() const source = b.runtime.sessions.binding('s1')!.session @@ -428,7 +482,7 @@ describe('ConversationController', () => { await b.runtime.sessions.add({ id: 's2', session: target }) using _target = b.runtime.sessions.retain('s2' as SessionId) await _target.ready - b.root.rebindDraftFiles(b.runtime.sessions.binding('s2')!.session.sessionId, [attachment.id]) + b.root.rebindDraftFiles(b.runtime.sessions.binding('s2')!.session.sessionId, [attachment.id], UPLOAD_IMAGES) expect(sourceSignal?.aborted).toBe(true) await vi.waitFor(() => { 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 baf1d8f505..59f9f66f8c 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -659,7 +659,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer\', () => ctx.slots.register(\n { name: \'conversation.composer\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:270', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:279', }, { key: 'conversation.composer.bar', @@ -701,7 +701,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.bar\', () => ctx.slots.register(\n { name: \'conversation.composer.bar\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:292', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:301', }, { key: 'conversation.composer.dock', @@ -761,7 +761,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.dock\', () => ctx.slots.register(\n { name: \'conversation.composer.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:284', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:293', }, { key: 'conversation.header', @@ -799,7 +799,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.header\', () => ctx.slots.register(\n { name: \'conversation.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:220', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:229', }, { key: 'conversation.header.leading', @@ -830,7 +830,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.header.leading\', () => ctx.slots.register(\n { name: \'conversation.header.leading\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:249', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:258', }, { key: 'conversation.hero.agentPreset', @@ -870,7 +870,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.agentPreset\', () => ctx.slots.register(\n { name: \'conversation.hero.agentPreset\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:276', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:285', }, { key: 'conversation.hero.brand.mark', @@ -901,7 +901,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.brand.mark\', () => ctx.slots.register(\n { name: \'conversation.hero.brand.mark\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:274', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:283', }, { key: 'conversation.hero.options', @@ -958,7 +958,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.options\', () => ctx.slots.register(\n { name: \'conversation.hero.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:278', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:287', }, { key: 'conversation.hero.workspace', @@ -993,7 +993,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:272', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:281', }, { key: 'conversation.hero.workspace.directoryFlow', @@ -1071,7 +1071,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.activity\', () => ctx.slots.register(\n { name: \'conversation.input.activity\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:290', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:299', }, { key: 'conversation.input.attachments', @@ -1081,7 +1081,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ doc: 'Optional draft-attachment rail and drop target.', registerOptions: [], ownerProps: [ - '/** Input state handed to the optional attachment presentation plugin. */\nexport interface ComposerAttachmentsOwnerProps {\n /** Browser-owned draft attachments in input order. */\n attachments: readonly ComposerAttachment[]\n /** Whether a document-level file drop may add attachments now. */\n canAcceptDrop: boolean\n /**\n * Add one dropped batch through the composer\'s validation path.\n * @param files - dropped, pasted, or picked browser files in source order.\n * @param directories - members of `files` the drop source identified as directories.\n */\n onAddFiles: (files: readonly File[], directories?: ReadonlySet) => void\n /** Remove one draft attachment through the Conversation service. */\n onRemoveAttachment: (id: DraftAttachmentId) => void\n /** Current per-draft upload states for file-kind attachments. */\n uploads: DraftFileUploads\n /** Restart one failed file upload. */\n onRetryFile: (id: DraftAttachmentId) => void\n /** Display-ready limits for the drop invitation. */\n dropLimits?: { readonly count: number; readonly size: string } | undefined\n}', + '/** Input state handed to the optional attachment presentation plugin. */\nexport interface ComposerAttachmentsOwnerProps {\n /** Browser-owned draft attachments in input order. */\n attachments: readonly ComposerAttachment[]\n /** Whether a document-level file drop may add attachments now. */\n canAcceptDrop: boolean\n /**\n * Add one dropped batch through the composer\'s validation path.\n * @param files - dropped, pasted, or picked browser files in source order.\n * @param directories - members of `files` the drop source identified as directories.\n */\n onAddFiles: (files: readonly File[], directories?: ReadonlySet) => void\n /** Remove one draft attachment through the Conversation service. */\n onRemoveAttachment: (id: DraftAttachmentId) => void\n /** Current per-draft upload states for file-kind attachments. */\n uploads: DraftFileUploads\n /** Restart one failed file upload. */\n onRetryFile: (id: DraftAttachmentId) => void\n /**\n * Explain one upload the Host refused; such a draft cannot be retried and\n * stays until it is removed.\n * @param reason - the refusal `reason` the failed upload carries.\n * @returns localized text naming the limit or the way out.\n /* …truncated — full shape in source */', ], ownerPropsReferences: [ 'ComposerAttachment', @@ -1115,7 +1115,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.attachments\', () => ctx.slots.register(\n { name: \'conversation.input.attachments\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:294', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:303', }, { key: 'conversation.input.dock', @@ -1182,7 +1182,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.dock\', () => ctx.slots.register(\n { name: \'conversation.input.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:280', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:289', }, { key: 'conversation.input.left', @@ -1239,7 +1239,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.left\', () => ctx.slots.register(\n { name: \'conversation.input.left\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:286', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:295', }, { key: 'conversation.input.model', @@ -1281,7 +1281,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model\', () => ctx.slots.register(\n { name: \'conversation.input.model\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:308', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:317', }, { key: 'conversation.input.model.label', @@ -1387,7 +1387,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.overlay\', () => ctx.slots.register(\n { name: \'conversation.input.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:282', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:291', }, { key: 'conversation.input.permission', @@ -1429,7 +1429,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.permission\', () => ctx.slots.register(\n { name: \'conversation.input.permission\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:302', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:311', }, { key: 'conversation.input.plan', @@ -1471,7 +1471,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.plan\', () => ctx.slots.register(\n { name: \'conversation.input.plan\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:300', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:309', }, { key: 'conversation.input.right', @@ -1528,7 +1528,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.right\', () => ctx.slots.register(\n { name: \'conversation.input.right\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:288', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:297', }, { key: 'conversation.plan-review.actions', @@ -1629,7 +1629,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session\', () => ctx.slots.register(\n { name: \'conversation.session\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:214', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:223', }, { key: 'conversation.session.header', @@ -1669,7 +1669,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header\', () => ctx.slots.register(\n { name: \'conversation.session.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:222', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:231', }, { key: 'conversation.session.header.actions', @@ -1733,7 +1733,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:237', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:246', }, { key: 'conversation.session.header.corner', @@ -1775,7 +1775,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.corner\', () => ctx.slots.register(\n { name: \'conversation.session.header.corner\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:260', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:269', }, { key: 'conversation.session.header.lineage', @@ -1819,7 +1819,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.lineage\', () => ctx.slots.register(\n { name: \'conversation.session.header.lineage\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:231', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:240', }, { key: 'conversation.session.header.utilities', @@ -1882,7 +1882,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.utilities\', () => ctx.slots.register(\n { name: \'conversation.session.header.utilities\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:243', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:252', }, { key: 'conversation.session.header.views.actions', @@ -1936,7 +1936,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.views.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.views.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:266', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:275', }, { key: 'conversation.trajectory.images', @@ -2038,7 +2038,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.user.text.node\', () => ctx.slots.register(\n { name: \'conversation.user.text.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:204', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:213', }, { key: 'conversation.view', @@ -2102,7 +2102,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.view\', () => ctx.slots.register(\n { name: \'conversation.view\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:268', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:277', }, { key: 'deliverables.file.actions', @@ -2305,7 +2305,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'main.conversation\', () => ctx.slots.register(\n { name: \'main.conversation\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:212', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:221', }, { key: 'plugins.add.actions', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index acc373796e..804bde1ff1 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1163,7 +1163,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'async uploadImageStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable readonly mediaType: string readonly signal?: AbortSignal readonly name?: string }): Promise', - description: 'Persist one prompt image for a Session: read at most the deployment\'s per-image byte limit, then validate, normalize, and store the image the way prompt admission does, so a later prompt cites it by receipt. Cancellation before storage begins stores nothing; a cancelled upload never receives a receipt, although an image whose storage already began stays in the content-addressed store.', + description: 'Persist one prompt image for a Session: read at most the smaller of the deployment\'s per-image and per-message byte limits, then validate, normalize, and store the image the way prompt admission does, so a later prompt cites it by receipt. Cancellation before storage begins stores nothing; a cancelled upload never receives a receipt, although an image whose storage already began stays in the content-addressed store.', parameters: [{ name: 'request', description: 'Session identity, ordered bytes, the declared media type that this deployment must accept, cancellation, and optional display name.' }], returns: 'the staged receipt and durable normalized image reference.', }, diff --git a/scripts/no-unknown-casts.baseline.json b/scripts/no-unknown-casts.baseline.json index 9abfd131da..2cababe202 100644 --- a/scripts/no-unknown-casts.baseline.json +++ b/scripts/no-unknown-casts.baseline.json @@ -427,9 +427,6 @@ "packages/client/ui-attachment/tests/attachment-rail.client.spec.tsx": { "b42ab24a43e0f7542bf1deb8f7ac3a76698d29e098f8dc575af6c08774987c32": 1 }, - "packages/client/ui-attachment/tests/composer-attachments.client.spec.tsx": { - "ab22ebe23f59b5aa76d42502a0421f3953d1d170e8a4f900a0c442daf6f1397d": 1 - }, "packages/client/ui-chat/src/client/conversation-nodes/turn-process.ts": { "a7d8cc8d42e37ad5cc4882241492ac572ed8163c7fb8663180e893c7178e906f": 1 }, From dbb2492c010c29dc8853ba2f99a837ca5cf5e779 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Wed, 21 Oct 2026 16:48:03 +0800 Subject: [PATCH 23/36] feat(attachment): relax the default image admission limits Normalization already downscales long sides, so the default per-side limit rises from 8192px to 65,535px, the largest side a JPEG carries, and the decoded-pixel limit alone bounds admission. The default per-image limit rises from 20 MiB to 50 MiB. --- docs/config-catalog.md | 6 +++--- docs/config-catalog.zh.md | 6 +++--- .../attachment/attachment-local/README.i18n.yaml | 4 ++-- packages/attachment/attachment-local/README.md | 4 ++-- packages/attachment/attachment-local/README.zh.md | 4 ++-- packages/attachment/attachment-local/src/index.ts | 14 +++++++++----- .../attachment-local/tests/index.spec.ts | 4 ++-- 7 files changed, 23 insertions(+), 19 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 313b63aa2b..69f2b748f8 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -354,14 +354,14 @@ export interface Config { ## `@deepseek-ai/dsh-attachment-local` -- `source`: [`packages/attachment/attachment-local/src/index.ts:61`](../packages/attachment/attachment-local/src/index.ts) +- `source`: [`packages/attachment/attachment-local/src/index.ts:65`](../packages/attachment/attachment-local/src/index.ts) ```ts config-catalog /** Local attachment backend configuration. */ export interface Config { /** Explicit harness home; omitted follows `DSH_HOME`, then `~/.dsh`. */ dshHome?: string - /** Maximum encoded bytes accepted for one submitted image. Default: 20 MiB. */ + /** Maximum encoded bytes accepted for one submitted image. Default: 50 MiB. */ maxImageBytes?: number /** Maximum image count accepted in one submitted message. Default: 20. */ maxImagesPerMessage?: number @@ -369,7 +369,7 @@ export interface Config { maxMessageImageBytes?: number /** Maximum intrinsic width multiplied by height accepted for one submitted image. Default: 64,000,000. */ maxImagePixels?: number - /** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 8192px. */ + /** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 65,535px. */ maxImageDimension?: number /** Total-pixel budget of the stored provider-independent normalized image. */ normalizedImageMaxPixels?: number diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 56f50c6fe4..171587800d 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -356,14 +356,14 @@ export interface Config { ## `@deepseek-ai/dsh-attachment-local` -- `source`: [`packages/attachment/attachment-local/src/index.ts:61`](../packages/attachment/attachment-local/src/index.ts) +- `source`: [`packages/attachment/attachment-local/src/index.ts:65`](../packages/attachment/attachment-local/src/index.ts) ```ts config-catalog /** Local attachment backend configuration. */ export interface Config { /** Explicit harness home; omitted follows `DSH_HOME`, then `~/.dsh`. */ dshHome?: string - /** Maximum encoded bytes accepted for one submitted image. Default: 20 MiB. */ + /** Maximum encoded bytes accepted for one submitted image. Default: 50 MiB. */ maxImageBytes?: number /** Maximum image count accepted in one submitted message. Default: 20. */ maxImagesPerMessage?: number @@ -371,7 +371,7 @@ export interface Config { maxMessageImageBytes?: number /** Maximum intrinsic width multiplied by height accepted for one submitted image. Default: 64,000,000. */ maxImagePixels?: number - /** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 8192px. */ + /** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 65,535px. */ maxImageDimension?: number /** Total-pixel budget of the stored provider-independent normalized image. */ normalizedImageMaxPixels?: number diff --git a/packages/attachment/attachment-local/README.i18n.yaml b/packages/attachment/attachment-local/README.i18n.yaml index 520e5af483..25115adbcc 100644 --- a/packages/attachment/attachment-local/README.i18n.yaml +++ b/packages/attachment/attachment-local/README.i18n.yaml @@ -18,8 +18,8 @@ en: 912a19be4b59ff8a zh: 9c14694cf2ebbaf2 /deepseek-ai-dsh-attachment-local/use-this-package/minimal-configuration: - en: b34e09c3236f81f1 - zh: c541b5dc22c8f307 + en: 9597c3d9779cb93d + zh: 900baa94138cc7de /deepseek-ai-dsh-attachment-local/use-this-package/where-your-images-are-stored-and-how-long-they-last: en: 4ee90b8f74baa38c zh: 9c577709ec55eb82 diff --git a/packages/attachment/attachment-local/README.md b/packages/attachment/attachment-local/README.md index 4303813905..4f3bb81ba0 100644 --- a/packages/attachment/attachment-local/README.md +++ b/packages/attachment/attachment-local/README.md @@ -38,11 +38,11 @@ Mount the plugin with no required configuration. The defaults below define what | Field | Default | Meaning | |---|---|---| | `dshHome` | resolved | Explicit harness home; omitted follows `$DSH_HOME`, then `~/.dsh` | -| `maxImageBytes` | `20 MiB` | Maximum encoded source bytes accepted for one image | +| `maxImageBytes` | `50 MiB` | Maximum encoded source bytes accepted for one image | | `maxImagesPerMessage` | `20` | Maximum image count accepted in one submitted message | | `maxMessageImageBytes` | `200 MiB` | Maximum aggregate encoded source bytes in one submitted message | | `maxImagePixels` | `64,000,000` | Maximum source width multiplied by height | -| `maxImageDimension` | `8192` | Maximum source width or height | +| `maxImageDimension` | `65,535` | Maximum source width or height; the default leaves admission to `maxImagePixels`, and normalization downscales long sides | | `normalizedImageMaxPixels` | `2048 × 2048` | Total-pixel budget of the stored normalized image | | `normalizedImageMaxDimension` | `8192` | Maximum long edge after applying the total-pixel budget | | `normalizedImageMaxBytes` | `4 MiB` | Encoded-byte target; the smallest quality-ladder output is kept when none fits | diff --git a/packages/attachment/attachment-local/README.zh.md b/packages/attachment/attachment-local/README.zh.md index 4c52dab3ac..fdfc7d9161 100644 --- a/packages/attachment/attachment-local/README.zh.md +++ b/packages/attachment/attachment-local/README.zh.md @@ -38,11 +38,11 @@ kind: "package-reference" | 字段 | 默认值 | 含义 | |---|---|---| | `dshHome` | 自动解析 | 显式 harness home;省略时依次跟随 `$DSH_HOME` 与 `~/.dsh` | -| `maxImageBytes` | `20 MiB` | 单张图片接受的最大编码源字节数 | +| `maxImageBytes` | `50 MiB` | 单张图片接受的最大编码源字节数 | | `maxImagesPerMessage` | `20` | 单条提交消息接受的最大图片数量 | | `maxMessageImageBytes` | `200 MiB` | 单条提交消息接受的最大编码源图字节总数 | | `maxImagePixels` | `64,000,000` | 源图宽度与高度乘积的最大值 | -| `maxImageDimension` | `8192` | 源图接受的最大宽度或高度 | +| `maxImageDimension` | `65,535` | 源图接受的最大宽度或高度;默认值让 `maxImagePixels` 单独把关,长边由规范化缩小 | | `normalizedImageMaxPixels` | `2048 × 2048` | 已存规范化图片的总像素预算 | | `normalizedImageMaxDimension` | `8192` | 应用总像素预算后的最大长边 | | `normalizedImageMaxBytes` | `4 MiB` | 编码字节目标;没有候选满足时保留质量阶梯中的最小输出 | diff --git a/packages/attachment/attachment-local/src/index.ts b/packages/attachment/attachment-local/src/index.ts index 34959d088a..2965fef0cc 100644 --- a/packages/attachment/attachment-local/src/index.ts +++ b/packages/attachment/attachment-local/src/index.ts @@ -31,15 +31,19 @@ export type { PreparedImageFile } from './store.ts' export { readRequestImageFile, requestImageVariantId } from './request-image.ts' /** Default maximum encoded bytes for one submitted image; oversized sources are refused, not shrunk. */ -export const DEFAULT_MAX_IMAGE_BYTES = 20 * 1024 * 1024 +export const DEFAULT_MAX_IMAGE_BYTES = 50 * 1024 * 1024 /** Default maximum images in one prompt. */ export const DEFAULT_MAX_IMAGES_PER_MESSAGE = 20 /** Default maximum aggregate image bytes in one prompt. */ export const DEFAULT_MAX_MESSAGE_IMAGE_BYTES = 200 * 1024 * 1024 /** Default maximum intrinsic pixels for one submitted image. */ export const DEFAULT_MAX_IMAGE_PIXELS = 64_000_000 -/** Default per-side pixel cap for one submitted image. */ -export const DEFAULT_MAX_IMAGE_DIMENSION = 8192 +/** + * Default per-side pixel cap for one submitted image: the largest side a JPEG + * can carry. Normalization downscales a long side, so by default the + * decoded-pixel limit alone bounds admission. + */ +export const DEFAULT_MAX_IMAGE_DIMENSION = 65_535 /** * Default total-pixel budget of the stored normalized image. A larger source * is admitted and downscaled proportionally, so admission bounds what rides @@ -61,7 +65,7 @@ export const MAX_IMAGE_COMPRESSION_CONCURRENCY = 8 export interface Config { /** Explicit harness home; omitted follows `DSH_HOME`, then `~/.dsh`. */ dshHome?: string - /** Maximum encoded bytes accepted for one submitted image. Default: 20 MiB. */ + /** Maximum encoded bytes accepted for one submitted image. Default: 50 MiB. */ maxImageBytes?: number /** Maximum image count accepted in one submitted message. Default: 20. */ maxImagesPerMessage?: number @@ -69,7 +73,7 @@ export interface Config { maxMessageImageBytes?: number /** Maximum intrinsic width multiplied by height accepted for one submitted image. Default: 64,000,000. */ maxImagePixels?: number - /** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 8192px. */ + /** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 65,535px. */ maxImageDimension?: number /** Total-pixel budget of the stored provider-independent normalized image. */ normalizedImageMaxPixels?: number diff --git a/packages/attachment/attachment-local/tests/index.spec.ts b/packages/attachment/attachment-local/tests/index.spec.ts index 00a427e16e..6482190ebe 100644 --- a/packages/attachment/attachment-local/tests/index.spec.ts +++ b/packages/attachment/attachment-local/tests/index.spec.ts @@ -21,11 +21,11 @@ import LocalAttachmentStore, { describe('local attachment service', () => { it('resolves every omitted admission limit explicitly', () => { const service = new LocalAttachmentStore(new Context(), {}) - expect(DEFAULT_MAX_IMAGE_BYTES).toBe(20 * 1024 * 1024) + expect(DEFAULT_MAX_IMAGE_BYTES).toBe(50 * 1024 * 1024) expect(DEFAULT_MAX_IMAGES_PER_MESSAGE).toBe(20) expect(DEFAULT_MAX_MESSAGE_IMAGE_BYTES).toBe(200 * 1024 * 1024) expect(DEFAULT_MAX_IMAGE_PIXELS).toBe(64_000_000) - expect(DEFAULT_MAX_IMAGE_DIMENSION).toBe(8192) + expect(DEFAULT_MAX_IMAGE_DIMENSION).toBe(65_535) expect(service.imageLimits).toEqual({ maxImageBytes: DEFAULT_MAX_IMAGE_BYTES, maxImagesPerMessage: DEFAULT_MAX_IMAGES_PER_MESSAGE, From 752cc5c0c05abcd6d4a070f5a5a8570e91ad2c5a Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Wed, 21 Oct 2026 17:11:13 +0800 Subject: [PATCH 24/36] feat(plan): keep exit_plan_mode declared after the first plan-mode entry Disclose the exit tool progressively instead of following every plan-mode transition. The plan projection records whether a logged plan/mode ever activated plan mode (stateVersion 4), and the tool's condition admits it for a step whose selected state is active or once the Session has entered plan mode. Leaving plan mode now changes only the guidance section, so an addition-only route no longer drops a declaration from its cached prefix. A call while plan mode is not committed still fails as unavailable outside plan mode, and a Session that never entered plan mode does not list the tool. The Web plan-review fixtures return to master's recording because the request tool lists no longer change on exit. --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/persistence-catalog.i18n.yaml | 8 ++--- docs/persistence-catalog.md | 4 +-- docs/persistence-catalog.zh.md | 4 +-- docs/persistence-schema.json | 2 +- docs/subsystems/plan.i18n.yaml | 4 +-- docs/subsystems/plan.md | 2 +- docs/subsystems/plan.zh.md | 2 +- .../conditional-tools/guide.i18n.yaml | 12 +++---- .../v0.2.1-rc.2/conditional-tools/guide.md | 6 ++-- .../v0.2.1-rc.2/conditional-tools/guide.zh.md | 6 ++-- packages/plan/plan-mode/README.i18n.yaml | 16 ++++----- packages/plan/plan-mode/README.md | 8 ++--- packages/plan/plan-mode/README.zh.md | 8 ++--- packages/plan/plan-mode/src/index.ts | 20 ++++++----- packages/plan/plan-mode/src/types.ts | 2 ++ .../plan/plan-mode/tests/plan-mode.spec.ts | 36 ++++++++++++++----- .../plan/plan-mode/tests/projection.spec.ts | 11 ++++++ .../plan-review/approved-expanded.expected.md | 1 - snapshots/web/plan-review/session.v4.jsonl | 9 +++-- 21 files changed, 98 insertions(+), 67 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index c613b734c0..6f81d1a972 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2465,7 +2465,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` · `agents` -- `source`: [`packages/plan/plan-mode/src/index.ts:66`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c25bc8c246..21262f3f60 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2467,7 +2467,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` · `agents` -- `source`: [`packages/plan/plan-mode/src/index.ts:66`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 5b083597d0..cb8b9f7174 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -153,8 +153,8 @@ en: 4294f78d26ed985b zh: 4294f78d26ed985b /session-persistence-event-catalog/events/plan/plan-mode-log-only: - en: 862175bfe8692ef7 - zh: a8ab123bf674cf77 + en: 9ae5537eeae238de + zh: 6be761c7fd83fdce /session-persistence-event-catalog/events/request: en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 @@ -1398,8 +1398,8 @@ en: a74e3dfa51c987af zh: 6c3c87974d7a7260 /session-persistence-event-catalog/resolved-persistence-types/active~2: - en: a3de6a6fe9672c7a - zh: a357481e27b3b81f + en: c861888d6239b700 + zh: a9b2271d3c6b8737 /session-persistence-event-catalog/resolved-persistence-types/agentpreset: en: 1afbe8196f161601 zh: a320a36a8928817c diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 750ccb11e3..22ad55ab3e 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -735,7 +735,7 @@ Source: [`packages/interaction/permission-presets/src/index.ts:52`](../packages/ 'plan/mode': { active: boolean } ``` -Source: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +Source: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -5769,7 +5769,7 @@ Array of `unknown` (opaque). SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -Sources: [`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +Sources: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 7a0549676c..9899959c01 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -737,7 +737,7 @@ export type SessionEvent = { 'plan/mode': { active: boolean } ``` -来源:[`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -5771,7 +5771,7 @@ SHA-256: `b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7` SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -来源:[`packages/plan/plan-mode/src/index.ts:52`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index abaadae5b5..4e166114af 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -153,7 +153,7 @@ {"digest":"1f1385dbc3e875c021e387c7096d671d606f22daec51b25c80348735b6bbfa10","names":[],"sources":[]}, {"digest":"1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0","names":["packages/core/session/src/types.ts#TurnEndCancelCause"],"sources":["packages/core/session/src/types.ts:197"]}, {"digest":"1fdad624334d354820dfb3a26e28d0bc9fc1b62a33f87bab63f715b3f4391bfd","names":[],"sources":[]}, - {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:52"]}, + {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:53"]}, {"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]}, {"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/experimental/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/experimental/agent-team/src/types.ts:138"]}, {"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]}, diff --git a/docs/subsystems/plan.i18n.yaml b/docs/subsystems/plan.i18n.yaml index f81f88899f..5e92dac5a5 100644 --- a/docs/subsystems/plan.i18n.yaml +++ b/docs/subsystems/plan.i18n.yaml @@ -15,8 +15,8 @@ en: ee04468005fae8e1 zh: 1347d554102951f2 /plan-mode/the-exit-tool-and-the-plan-command: - en: 9f2a549447f8d374 - zh: 8f3064e31d514702 + en: 32ecfb7086dd1578 + zh: 0aaeaa69bb63f255 /plan-mode/the-service: en: f3e6d5a7fe0b67f0 zh: 774cc97e493991fa diff --git a/docs/subsystems/plan.md b/docs/subsystems/plan.md index 1979491ae7..a37207d868 100644 --- a/docs/subsystems/plan.md +++ b/docs/subsystems/plan.md @@ -30,7 +30,7 @@ A missing, blank, or non-string `section` and any unknown key fail at plugin loa ## The exit tool and the `/plan` command -[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is admitted only for steps whose selected plan state is active, so entering or leaving plan mode changes the request tool declarations and the plan guidance together; Native and PTC execution use the same admitted set, and a call outside plan mode returns `UNKNOWN_TOOL`. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. +[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so the first plan-mode entry adds it to the request tool declarations and later transitions change only the plan guidance. Native and PTC execution use the same admitted set; a call before the first entry returns `UNKNOWN_TOOL`, and a call while plan mode is not committed fails. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. When [`ctx.commands`](commands.md) is composed, the plugin registers `/plan [off|message]`: bare `/plan` selects plan mode, any other non-empty message selects it and then submits the text through `agent.steer()` so it becomes the next step's ordinary logged user message under plan guidance, and the exact argument `off` selects inactive, which also cancels a pending entry before it is appended and becomes visible to a request. diff --git a/docs/subsystems/plan.zh.md b/docs/subsystems/plan.zh.md index 0bfd84f1ba..8f45d70c5b 100644 --- a/docs/subsystems/plan.zh.md +++ b/docs/subsystems/plan.zh.md @@ -30,7 +30,7 @@ interface PlanModeConfig { ## 退出工具与 `/plan` 命令 -[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 只在已选计划状态为激活的步骤中准入,因此进入或离开计划模式会同时改变请求的工具声明与计划指引;原生与 PTC 执行使用同一准入集合,在计划模式之外调用会返回 `UNKNOWN_TOOL`。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 +[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它进入请求的工具声明,之后的切换只改变计划指引。原生与 PTC 执行使用同一准入集合;首次进入之前调用返回 `UNKNOWN_TOOL`,计划模式未提交时调用会失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 当 [`ctx.commands`](commands.zh.md) 被组合时,插件注册 `/plan [off|message]`:单独的 `/plan` 选择计划模式;任何其他非空消息先选择计划模式,再通过 `agent.steer()` 提交该文本,使其在计划指引下成为下一步骤的普通已记录用户消息;确切参数 `off` 选择未激活,这还会在待生效条目被追加并对请求可见之前将其取消。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.i18n.yaml index 7c360e83a1..20da16b12b 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md /: - en: 759962a4bf2e454f - zh: df802b222d1a46f3 + en: 1dc343c5aa10de02 + zh: 59ac1c2052255919 /declare-conditional-tools-through-step-admission: en: 4edb4c80b402de77 zh: 856160ec69c515ea /declare-conditional-tools-through-step-admission/change: - en: ba47cb460364f666 - zh: 1b5db25e4fb99ac2 + en: 71aba6399833cd1d + zh: b820e301baf72e4e /declare-conditional-tools-through-step-admission/migration: - en: 676839aab96dcd2d - zh: eae3c9a6795f8d6e + en: 943671c4348031bb + zh: 0e44d7b29eab0168 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md index f762f2a815..243816c2b8 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md +++ b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "Tool declarations come only from step-admitted registrations: `system-prompt/assemble` no longer carries tools, conditional tools need a resolved step set, and `exit_plan_mode` is declared only in plan mode." +description: "Tool declarations come only from step-admitted registrations: `system-prompt/assemble` no longer carries tools, conditional tools need a resolved step set, and `exit_plan_mode` is declared only after a Session first enters plan mode." --- # Declare conditional tools through step admission @@ -15,11 +15,11 @@ The `system-prompt/assemble` waterfall now receives sections, contexts, and vari Model tool calls run only through their step's admitted set. A call to a conditional tool without a resolved set, a call after the set is disposed, and a pending call whose registration was replaced or removed during the step return `UNKNOWN_TOOL` instead of running. -`exit_plan_mode` is declared only for steps whose selected plan state is active, so the request tool list changes when plan mode starts or ends. Existing Sessions require no format migration. +`exit_plan_mode` is declared from the first step whose selected plan state is active and stays declared for the rest of the Session, so requests of a Session that never entered plan mode no longer list it. Existing Sessions require no format migration. ## Migration 1. Replace tool filtering in `system-prompt/assemble` listeners with a `when` condition on the registration; read the step's provider, model, and reasoning effort from the condition's `modelSelection`. Keep only section, context, and variable changes in the waterfall. 2. Make tool guidance follow the same admission: section callbacks pass `context.toolSet` to `ctx.tools.get()` or `ctx.tools.schemas()`. 3. For programmatic calls of conditional tools, call `ctx.tools.resolve({ agent, modelSelection, signal })`, pass the returned `toolSet` to `assemble()` and `ctx.tools.execute()`, and dispose it after the batch settles. -4. Update expectations that listed `exit_plan_mode` outside plan mode. Verify that a disabled tool is absent from the request, that calling its name returns `UNKNOWN_TOOL` without reaching the implementation, and that a failing condition ends the turn with `TOOL_ACTIVATION_FAILED`. +4. Update expectations that listed `exit_plan_mode` before a Session entered plan mode. Verify that a disabled tool is absent from the request, that calling its name returns `UNKNOWN_TOOL` without reaching the implementation, and that a failing condition ends the turn with `TOOL_ACTIVATION_FAILED`. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.zh.md index e778c92104..6a2cfc29d9 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.zh.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: "工具声明只来自步骤准入的注册:`system-prompt/assemble` 不再携带工具,条件工具需要已解析的步骤集合,`exit_plan_mode` 只在计划模式下声明。" +description: "工具声明只来自步骤准入的注册:`system-prompt/assemble` 不再携带工具,条件工具需要已解析的步骤集合,`exit_plan_mode` 只在会话首次进入计划模式后声明。" --- # 通过步骤准入声明条件工具 @@ -15,11 +15,11 @@ description: "工具声明只来自步骤准入的注册:`system-prompt/assemb 模型的工具调用只通过所属步骤的准入集合执行。没有已解析集合的条件工具调用、集合释放之后的调用,以及注册在步骤内被替换或移除时尚未开始的调用,都会返回 `UNKNOWN_TOOL`,不会执行。 -`exit_plan_mode` 只在已选计划状态为激活的步骤中声明,因此进入或离开计划模式时请求的工具列表会变化。现有 Session 无需格式迁移。 +`exit_plan_mode` 从已选计划状态首次为激活的步骤起声明,并在会话剩余部分保持声明,因此从未进入计划模式的会话,其请求不再列出它。现有 Session 无需格式迁移。 ## 迁移 1. 把 `system-prompt/assemble` 监听器中的工具过滤改为注册时的 `when` 条件;从条件的 `modelSelection` 读取该步骤的提供方、模型与推理强度。waterfall 中只保留段落、上下文与变量的修改。 2. 让工具指引跟随同一准入:段落回调把 `context.toolSet` 传给 `ctx.tools.get()` 或 `ctx.tools.schemas()`。 3. 程序化调用条件工具时,调用 `ctx.tools.resolve({ agent, modelSelection, signal })`,把返回的 `toolSet` 传给 `assemble()` 与 `ctx.tools.execute()`,并在批次结束后释放。 -4. 更新在计划模式之外仍列出 `exit_plan_mode` 的期望。验证被禁用的工具不出现在请求中,用其名称调用会返回 `UNKNOWN_TOOL` 且不进入实现,条件失败时轮次以 `TOOL_ACTIVATION_FAILED` 结束。 +4. 更新在会话进入计划模式之前仍列出 `exit_plan_mode` 的期望。验证被禁用的工具不出现在请求中,用其名称调用会返回 `UNKNOWN_TOOL` 且不进入实现,条件失败时轮次以 `TOOL_ACTIVATION_FAILED` 结束。 diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index 321333b1a0..d2f0e3ef8d 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -45,8 +45,8 @@ en: a7bf35c2a9da52bc zh: dea9f4b3a41f1a6d /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-exit-tool: - en: ad84b4025d8ea536 - zh: 683b3f56b0b6b368 + en: 7736aea9e4934fa8 + zh: a595e477f54a199e /deepseek-ai-dsh-plan-mode/understand-the-implementation/session-projection-unit: en: 396d66816890f715 zh: fab5d67c027b33f5 @@ -90,14 +90,14 @@ en: 9622e96bdc01276d zh: 53801e68a49f3d1d /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/what-the-model-sees: - en: b0b53f72b11d634b - zh: c7bc8a10a90f7fa3 + en: 1b978a7b6eecdffe + zh: 338000d1bf8dd4a9 /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/token-effect: - en: a1a020eb7ba26e7c - zh: a99208693d331a31 + en: 5ef9db72f91e4a8c + zh: 6e96335cc3eb5976 /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/kv-cache-effect: - en: 9d9626fbf4cdc8de - zh: 8237cbc3ca048024 + en: a9eb70ad541fcfd7 + zh: 9c06d39341fc52b1 /deepseek-ai-dsh-plan-mode/known-limitations-and-deferred-work: en: a87aabfede0087fd zh: 201e9b3766980005 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 70f8c29932..4a465e68e8 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -90,7 +90,7 @@ The command child activates only when a commands service is composed. It maps ba ### The exit tool -`exit_plan_mode` is admitted only for steps whose selected plan state is active, the same state that renders plan guidance, so entering or leaving changes the tool declarations and the guidance together; Native and PTC execution use the same admitted set. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. +`exit_plan_mode` is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so entering plan mode the first time adds it together with the guidance, and later transitions change only the guidance; Native and PTC execution use the same admitted set. A call while plan mode is not committed fails. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. ### Session projection unit @@ -166,15 +166,15 @@ The user block is append-only conversation growth. Entering or leaving plan mode #### What the model sees -The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered only in plan mode; calls outside its admitted set return `UNKNOWN_TOOL`, while an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call carrying review feedback. A dismissed review returns `{ approved: false }`, renders a note that the user will reply, and concludes the turn without another model request. +The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered from the first plan-mode entry in a Session; earlier calls return `UNKNOWN_TOOL`, calls after leaving plan mode fail as unavailable outside plan mode, and an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call carrying review feedback. A dismissed review returns `{ approved: false }`, renders a note that the user will reply, and concludes the turn without another model request. #### Token effect -The schema is paid only while active, according to ToolRuntime mode, and each plan argument and review result remains in conversation history. +The schema is paid from the first entry on, according to ToolRuntime mode, and each plan argument and review result remains in conversation history. #### KV Cache effect -Entering plan mode adds the exit tool through the route’s tool-update protocol, and leaving removes it. An `in-history` route records both changes after cached history. An `addition-only` route, such as the default catalog’s `deepseek-flash`, cannot record the removal and drops the tool from later requests, so the first request after leaving can miss part of the cached prefix; a route without tool updates resends its changed declaration list after either transition. Plan arguments and review results extend the conversation normally. +The first entry into plan mode adds the exit tool through the route’s tool-update protocol; `in-history` and `addition-only` routes record the addition after cached history, while a route without tool updates resends its changed declaration list once. Later transitions leave the tool list unchanged. Plan arguments and review results extend the conversation normally. ## Known Limitations and Deferred Work diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index 25da0dd805..9e5e531d81 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -90,7 +90,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 退出工具 -`exit_plan_mode` 只在已选计划状态为激活的步骤中准入,这一状态也决定是否渲染计划指引,因此进入或离开会同时改变工具声明与指引;原生与 PTC 执行使用同一准入集合。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道,或评审等待期间服务重载,调用都会以拒绝方式失败,`/plan off` 仍是手动退路。 +`exit_plan_mode` 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它与指引一起出现,之后的切换只改变指引;原生与 PTC 执行使用同一准入集合。计划模式未提交时调用会失败。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道,或评审等待期间服务重载,调用都会以拒绝方式失败,`/plan off` 仍是手动退路。 ### 会话投影单元 @@ -166,15 +166,15 @@ You are in plan mode. Explore and design before presenting the complete plan thr #### 模型看到什么 -[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 只在计划模式中提供;不在准入集合中的调用返回 `UNKNOWN_TOOL`。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是携带评审反馈的失败调用。放弃评审返回 `{ approved: false }`,渲染一条说明用户将自行回复的文本,并结束当前轮次,不再发起模型请求。 +[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 从会话首次进入计划模式起提供;此前的调用返回 `UNKNOWN_TOOL`,离开计划模式后的调用会以计划模式之外不可用而失败。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是携带评审反馈的失败调用。放弃评审返回 `{ approved: false }`,渲染一条说明用户将自行回复的文本,并结束当前轮次,不再发起模型请求。 #### Token 影响 -schema 仅在启用时按 ToolRuntime 模式计入开销;每份计划参数与评审结果保留在对话历史中。 +schema 从首次进入计划模式起按 ToolRuntime 模式计入开销;每份计划参数与评审结果保留在对话历史中。 #### KV Cache 影响 -进入计划模式时,退出工具通过路由的工具更新协议新增,离开时则移除。`in-history` 路由会在已缓存历史之后记录这两种变化。`addition-only` 路由(例如默认目录中的 `deepseek-flash`)无法记录移除,只能在之后的请求中去掉该工具,因此离开后的首个请求可能无法命中部分已缓存前缀;不支持工具更新的路由在任一方向转换后都会重新发送变化后的声明列表。计划参数与评审结果正常扩展对话。 +首次进入计划模式时,退出工具通过路由的工具更新协议新增;`in-history` 与 `addition-only` 路由在已缓存历史之后记录这次新增,不支持工具更新的路由会重新发送一次变化后的声明列表。之后的模式切换不改变工具列表。计划参数与评审结果正常扩展对话。 ## 已知限制与延期工作 diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 7dfe31ca23..88bfc0ea7d 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -12,9 +12,10 @@ * assembly, then appends `plan/mode` from `agent/pre-step` only when the step * is accepted. Same-step request retries reuse their assembly. * - * The exit tool is admitted only for steps whose selected state is active, - * the same state that renders the guidance section. Native declarations, PTC - * bindings, and execution share that admission. + * The exit tool is disclosed progressively: it is admitted from the first step + * whose selected state is active and stays admitted for the rest of the + * Session, so leaving plan mode changes only the guidance section. Native + * declarations, PTC bindings, and execution share that admission. * * See packages/plan/plan-mode/README.md. * @@ -59,7 +60,7 @@ declare module '@deepseek-ai/cordis' { } } -/** The model-facing exit tool's name, admitted only for steps in plan mode. */ +/** The model-facing exit tool's name, admitted once the Session enters plan mode. */ export const EXIT_PLAN_MODE = 'exit_plan_mode' /** Deployment-owned plan guidance. */ @@ -121,6 +122,7 @@ const planUnitStateSchema: ZodType = zod.object({ wanted: zod.boolean(), }).strict().nullable(), activeAtLastHeader: zod.boolean().nullable(), + entered: zod.boolean(), }).strict() /** Wire payload schema of the `plan` projection. */ @@ -132,9 +134,9 @@ const planProjectionSchema: ZodType = zod.object({ /** Projection of logged plan selections and committed mode. */ export const planProjectionDefinition = { key: 'plan', - stateVersion: 3, + stateVersion: 4, stateSchema: planUnitStateSchema, - init: () => ({ active: false, wanted: null, running: null, activeAtLastHeader: null }), + init: () => ({ active: false, wanted: null, running: null, activeAtLastHeader: null, entered: false }), apply: (state, event) => { if (event.type === 'command/run' && event.data.name === 'plan') { if (event.data.args === undefined) return state @@ -148,7 +150,7 @@ export const planProjectionDefinition = { return { ...state, wanted, running: null } } if (event.type === 'plan/mode') { - return { ...state, active: event.data.active, wanted: null } + return { ...state, active: event.data.active, wanted: null, entered: state.entered || event.data.active } } if (event.type === 'request/header') { return { ...state, activeAtLastHeader: state.active } @@ -299,7 +301,7 @@ export class PlanModeController extends Service { execute: async (args, exec) => { // oxlint-disable-next-line typescript/no-non-null-assertion -- conditional admission requires the step's Agent const agent = exec.agent! - // Admission follows the selected state; a failed pre-step append can leave it uncommitted. + // Admission outlives plan mode and follows the selected state, so check the committed state. if (!this.loggedActive(agent.session)) { throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`) } @@ -371,7 +373,7 @@ export class PlanModeController extends Service { title: 'Plan review', content: result.content, }), - }), { when: ({ agent }) => this.selectedActive(agent.session) }) + }), { when: ({ agent }) => this.selectedActive(agent.session) || this.planState(agent.session).entered }) } private loggedActive(session: Session): boolean { diff --git a/packages/plan/plan-mode/src/types.ts b/packages/plan/plan-mode/src/types.ts index 79fbaa3617..b8f3257ba5 100644 --- a/packages/plan/plan-mode/src/types.ts +++ b/packages/plan/plan-mode/src/types.ts @@ -33,6 +33,8 @@ export interface PlanUnitState { running: { commandId: CommandId; wanted: boolean } | null /** Active state recorded by the latest `request/header`, or null. */ activeAtLastHeader: boolean | null + /** Whether a logged `plan/mode` has ever activated plan mode in this Session. */ + entered: boolean } declare module '@deepseek-ai/dsh-session-projection/types' { diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 32d2d6f3f4..b6ce911835 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -438,7 +438,7 @@ describe('the boundary flush', () => { }) describe('the soft layer', () => { - it('adds the exit schema together with plan guidance', async () => { + it('adds the exit schema with the first plan guidance and keeps it after leaving plan mode', async () => { const ctx = await setup() registerNamedTools(ctx, ['read', 'write']) const agent = await agentWithSession(ctx) @@ -450,6 +450,11 @@ describe('the soft layer', () => { const planAssembly = await assembleFor(ctx, agent) expect(planAssembly.tools.map(tool => tool.name)).toEqual([EXIT_PLAN_MODE, 'read', 'write']) expect(planAssembly.sections.find(section => section.name === 'plan:policy')?.text).toBe(TEST_PLAN_SECTION) + + agent.session.append('plan/mode', { active: false }) + const leftAssembly = await assembleFor(ctx, agent) + expect(leftAssembly.tools).toEqual(planAssembly.tools) + expect(leftAssembly.sections.find(section => section.name === 'plan:policy')?.text).toBe('') }) it('leaves an agent-less assembly untouched', async () => { @@ -506,7 +511,7 @@ describe('the soft layer', () => { expectPlanPtcSdkBindings(sdk) }) - it('includes the PTC exit binding only while plan mode is active', async () => { + it('includes the PTC exit binding from the first plan-mode entry', async () => { class FakeRuntime extends PtcRuntime { resolve(request: import('@deepseek-ai/dsh-ptc-runtime').PtcRunRequest): import('@deepseek-ai/dsh-ptc-runtime').PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } @@ -527,6 +532,9 @@ describe('the soft layer', () => { agent.session.append('plan/mode', { active: true }) const planSdk = (await assembleFor(withPlanMode, agent)).sections.find(section => section.name === 'tools:sdk')?.text ?? '' expectPlanPtcSdkBindings(planSdk) + agent.session.append('plan/mode', { active: false }) + const leftSdk = (await assembleFor(withPlanMode, agent)).sections.find(section => section.name === 'tools:sdk')?.text ?? '' + expect(leftSdk).toBe(planSdk) const bare = new Context() await bare.plugin(SystemPrompt) @@ -804,7 +812,7 @@ describe('exit_plan_mode', () => { expect(result.content).toEqual([{ type: 'text', text: 'Error: unknown tool "exit_plan_mode"' }]) }) - it('omits and rejects the exit tool outside plan mode', async () => { + it('omits and rejects the exit tool before the Session enters plan mode', async () => { const ctx = await setup() const agent = await agentWithSession(ctx) expect((await assembleFor(ctx, agent)).tools.map(tool => tool.name)).not.toContain(EXIT_PLAN_MODE) @@ -813,6 +821,16 @@ describe('exit_plan_mode', () => { expect(result.content).toEqual([{ type: 'text', text: 'Error: unknown tool "exit_plan_mode"' }]) }) + it('keeps the exit tool after leaving plan mode and rejects a call outside it', async () => { + const ctx = await setup() + const agent = await agentWithSession(ctx, 'left-plan', { active: true }) + agent.session.append('plan/mode', { active: false }) + expect((await assembleFor(ctx, agent)).tools.map(tool => tool.name)).toContain(EXIT_PLAN_MODE) + const result = await callExit(ctx, agent) + expect(result.isError).toBe(true) + expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }]) + }) + it('admits the exit tool for a selected entry but rejects a call before the entry is logged', async () => { const ctx = await setup() const agent = await agentWithSession(ctx) @@ -944,22 +962,22 @@ describe('exit_plan_mode', () => { expect(ctx.planMode.get(agent)).toEqual({ active: true, pending: false }) }) - it('an approved exit removes the tool and guidance from the next proposed assembly', async () => { + it('an approved exit removes the guidance from the next proposed assembly and keeps the tool', async () => { const { ctx, agent } = await setupWithReview({ selected: ['Approve'] }) const approved = await callExit(ctx, agent) expect(approved.isError).toBe(false) // Calls of the SAME assistant response were requested under the existing - // plan-shaped header. Pending state shapes the proposed next assembly, - // tool declarations included; the accepted boundary then commits the - // matching durable fold. + // plan-shaped header. Pending state shapes the proposed next assembly; + // the accepted boundary then commits the matching durable fold. The tool + // stays declared because the Session has entered plan mode. expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) const assembly = await assembleFor(ctx, agent) - expect(assembly.tools.some(tool => tool.name === EXIT_PLAN_MODE)).toBe(false) + expect(assembly.tools.some(tool => tool.name === EXIT_PLAN_MODE)).toBe(true) expect(assembly.sections.find(section => section.name === 'plan:policy')?.text).toBe('') await boundary(ctx, agent, 'step-start') expect(foldPlanMode(agent.session.snapshotEvents())).toBe(false) const afterExit = await assembleFor(ctx, agent) - expect(afterExit.tools.some(tool => tool.name === EXIT_PLAN_MODE)).toBe(false) + expect(afterExit.tools).toEqual(assembly.tools) expect(afterExit.sections.find(section => section.name === 'plan:policy')?.text).toBe('') }) diff --git a/packages/plan/plan-mode/tests/projection.spec.ts b/packages/plan/plan-mode/tests/projection.spec.ts index 8809293a5d..bb0f486929 100644 --- a/packages/plan/plan-mode/tests/projection.spec.ts +++ b/packages/plan/plan-mode/tests/projection.spec.ts @@ -114,6 +114,17 @@ describe('plan projection unit', () => { expect(bench.values().plan).toEqual({ active: false, pending: true }) }) + it('records that plan mode was entered and keeps the record after leaving', async () => { + const bench = await harness(true) + expect(bench.ctx.sessionProjections.checkpoint(bench.session).plan?.val).toMatchObject({ entered: false }) + commitPlanMode(bench.session, false, 0) + expect(bench.ctx.sessionProjections.checkpoint(bench.session).plan?.val).toMatchObject({ entered: false }) + commitPlanMode(bench.session, true, 1) + expect(bench.ctx.sessionProjections.checkpoint(bench.session).plan?.val).toMatchObject({ active: true, entered: true }) + commitPlanMode(bench.session, false, 2) + expect(bench.ctx.sessionProjections.checkpoint(bench.session).plan?.val).toMatchObject({ active: false, entered: true }) + }) + it('freezes the active state across a request/header into activeAtLastHeader', async () => { const bench = await harness(true) commitPlanMode(bench.session, true, 0) diff --git a/snapshots/web/plan-review/approved-expanded.expected.md b/snapshots/web/plan-review/approved-expanded.expected.md index f58d3ce0f6..e1664c9688 100644 --- a/snapshots/web/plan-review/approved-expanded.expected.md +++ b/snapshots/web/plan-review/approved-expanded.expected.md @@ -18,7 +18,6 @@ - text: . - button "Called tools" [expanded] - 'button "Tool call exit_plan_mode · # Add `--greeting` flag to CLI"' -- text: "Tool removed: exit_plan_mode" - '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."' - paragraph: DONE - 'button "Open plan: Add `--greeting` flag to CLI"': "Add `--greeting` flag to CLI Plan · Markdown Open" diff --git a/snapshots/web/plan-review/session.v4.jsonl b/snapshots/web/plan-review/session.v4.jsonl index d9a9046773..ce244393f1 100644 --- a/snapshots/web/plan-review/session.v4.jsonl +++ b/snapshots/web/plan-review/session.v4.jsonl @@ -13,18 +13,17 @@ {"type":"user/message","data":{"content":[{"type":"text","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."}],"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 working directory: \"{{cwd}}\".\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.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"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."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","read","read_image","schedule_create","schedule_delete","schedule_list","schedule_update","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"Plan a small change: add","messageSeqs":[11],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."},{"type":"text","text":"Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with `exit_plan_mode`."},{"type":"tool-call","id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":4529,"outputTokens":303,"cacheReadTokens":640,"reasoningTokens":52},"stream":[{"type":"chunk","time":1792565774238,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1792565774255,"index":0,"dt":[15,16,15,16,17,15,15,17,16,15,17,15,17,15,17,15,16,15,16,15,16,17,15,15,17,15,17,15,17,16,15,16,17,16,17,16,17,16,16,16,16,15,17,15,15,16,15,16,16,16,16],"texts":["The"," user"," wants"," me"," to"," plan"," a"," small"," change"," to"," add"," a"," `","--","gre","eting","`"," flag"," to"," a"," CLI","."," They"," explicitly"," told"," me"," not"," to"," read"," or"," write"," any"," files",","," and"," to"," call"," exit","_","plan","_mode"," with"," a"," short"," plan","."," Let"," me"," do"," that"," directly","."]},{"type":"chunk","time":1792565775080,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1792565775097,"index":1,"dt":[16,15,16,16,16,16,16,16,15,17,16,16,17,16,15,16,16,17,16,16,15,16,84,16,16,17,16,16,16,17],"texts":["Since"," the"," user"," has"," explicitly"," asked"," me"," not"," to"," read"," or"," write"," any"," files"," and"," to"," go"," straight"," to"," planning",","," I","'ll"," proceed"," with"," `","exit","_","plan","_mode","`."]},{"type":"chunk","time":1792565775661,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792565775678,"index":2,"dt":[16,17,15,17,15,16,15,15,16,16,15,17,16,15,16,16,16,16,17,15,17,16,16,16,16,15,16,16,16,16,17,16,16,15,16,16,16,16,15,16,16,16,16,16,16,17,16,16,16,15,15,17,17,14,16,17,16,16,17,16,15,16,16,17,16,16,16,16,15,15,17,17,15,16,16,15,17,16,15,17,16,16,15,17,16,15,17,16,16,16,16,16,16,15,17,16,16,15,17,16,15,17,15,16,16,16,16,16,17,16,15,16,16,15,17,16,14,16,16,16,16,15,17,15,16,17,15,16,17,15,16,17,16,16,14,17,16,16,15,17,16,15,17,15,16,17,15,15,16,16,16,17,16,16,16,16,16,15,17,16,16,17,15,15,16,15,16,17,16,16,17,16,16,16,16,15,16,17,16,15,17,16,16,16,16],"id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","args":["","{","\"","plan","\"",": ","\"","#"," Add"," `","--","gre","eting","`"," flag"," to"," CLI","\\n\\n","-"," **","Loc","ate"," the"," CLI"," entry"," point","**"," (","e",".g",".,"," `","cli",".py","`,"," `","main",".go","`,"," `","index",".js","`"," etc",".)"," and"," find"," the"," argument"," parser"," definition"," (","arg","parse",","," click",","," cob","ra",","," y","args",","," or"," similar",").\\n","-"," **","Register"," a"," new"," optional"," string"," argument","**"," named"," `","--","gre","eting","`"," with"," a"," short"," alias"," (`","-","g","`"," if"," available",")"," and"," a"," sensible"," default"," value"," (","e",".g",".,"," `","\\\"","Hello","\\\"","`",").\\n","-"," **","Thread"," the"," parsed"," value","**"," through"," the"," main"," handler"," function"," so"," it"," is"," passed"," where"," the"," greeting"," string"," is"," used"," (","e",".g",".,"," the"," welcome","/","response"," message",").\\n","-"," **","Update"," the"," help"," text","**"," so"," `","--","help","`"," or"," `","-","h","`"," shows"," the"," new"," flag"," with"," its"," description",".\\n","-"," **","No"," tests"," or"," config"," changes","**"," unless"," they"," already"," exist"," and"," directly"," validate"," the"," flag","'s"," presence",".","\"","}"]},{"type":"chunk","time":1792565778646,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."}}},{"type":"chunk","time":1792565778662,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with `exit_plan_mode`."}}},{"type":"chunk","time":1792565778678,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}}},{"type":"chunk","time":1792565778695,"chunk":{"type":"usage","usage":{"inputTokens":4529,"outputTokens":303,"cacheReadTokens":640,"reasoningTokens":52}}},{"type":"chunk","time":1792565778710,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."},{"type":"text","text":"Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with `exit_plan_mode`."},{"type":"tool-call","id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":4529,"outputTokens":303,"cacheReadTokens":640,"reasoningTokens":52},"stream":[{"type":"chunk","time":1790389349382,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790389349399,"index":0,"dt":[17,15,17,17,17,16,17,16,16,16,16,16,16,15,17,18,14,17,17,15,16,17,16,16,17,16,16,17,14,16,16,16,17,16,16,16,16,16,17,98,16,17,17,16,16,17,17,16,15,16,18],"texts":["The"," user"," wants"," me"," to"," plan"," a"," small"," change"," to"," add"," a"," `","--","gre","eting","`"," flag"," to"," a"," CLI","."," They"," explicitly"," told"," me"," not"," to"," read"," or"," write"," any"," files",","," and"," to"," call"," exit","_","plan","_mode"," with"," a"," short"," plan","."," Let"," me"," do"," that"," directly","."]},{"type":"chunk","time":1790389350326,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1790389350341,"index":1,"dt":[16,16,16,15,17,16,16,16,17,16,17,16,16,16,17,15,17,17,15,17,15,15,16,16,16,17,16,16,15,16],"texts":["Since"," the"," user"," has"," explicitly"," asked"," me"," not"," to"," read"," or"," write"," any"," files"," and"," to"," go"," straight"," to"," planning",","," I","'ll"," proceed"," with"," `","exit","_","plan","_mode","`."]},{"type":"chunk","time":1790389350839,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790389350855,"index":2,"dt":[17,17,15,16,15,17,16,16,17,17,15,16,16,17,17,16,16,17,16,15,16,17,17,16,16,17,16,16,16,15,16,16,17,16,17,16,16,15,16,16,17,16,15,16,16,16,17,16,16,16,17,15,16,16,16,17,16,16,17,17,17,15,17,17,17,16,17,16,17,15,16,16,14,16,16,17,16,16,17,15,16,16,16,16,16,16,15,17,15,16,16,16,16,16,17,17,15,17,16,17,16,16,14,15,16,16,15,17,16,16,16,16,16,16,15,16,16,16,15,16,16,16,16,15,15,17,16,16,16,17,15,17,16,15,16,16,17,15,17,16,17,17,15,17,15,17,14,17,16,16,17,17,15,16,16,17,16,16,16,17,15,16,17,15,17,16,16,16,16,16,17,16,16,16,16,15,17,15,16,16,17,17,16,16,17],"id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","args":["","{","\"","plan","\"",": ","\"","#"," Add"," `","--","gre","eting","`"," flag"," to"," CLI","\\n\\n","-"," **","Loc","ate"," the"," CLI"," entry"," point","**"," (","e",".g",".,"," `","cli",".py","`,"," `","main",".go","`,"," `","index",".js","`"," etc",".)"," and"," find"," the"," argument"," parser"," definition"," (","arg","parse",","," click",","," cob","ra",","," y","args",","," or"," similar",").\\n","-"," **","Register"," a"," new"," optional"," string"," argument","**"," named"," `","--","gre","eting","`"," with"," a"," short"," alias"," (`","-","g","`"," if"," available",")"," and"," a"," sensible"," default"," value"," (","e",".g",".,"," `","\\\"","Hello","\\\"","`",").\\n","-"," **","Thread"," the"," parsed"," value","**"," through"," the"," main"," handler"," function"," so"," it"," is"," passed"," where"," the"," greeting"," string"," is"," used"," (","e",".g",".,"," the"," welcome","/","response"," message",").\\n","-"," **","Update"," the"," help"," text","**"," so"," `","--","help","`"," or"," `","-","h","`"," shows"," the"," new"," flag"," with"," its"," description",".\\n","-"," **","No"," tests"," or"," config"," changes","**"," unless"," they"," already"," exist"," and"," directly"," validate"," the"," flag","'s"," presence",".","\"","}"]},{"type":"chunk","time":1790389353849,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to plan a small change to add a `--greeting` flag to a CLI. They explicitly told me not to read or write any files, and to call exit_plan_mode with a short plan. Let me do that directly."}}},{"type":"chunk","time":1790389353865,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"Since the user has explicitly asked me not to read or write any files and to go straight to planning, I'll proceed with `exit_plan_mode`."}}},{"type":"chunk","time":1790389353881,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}}},{"type":"chunk","time":1790389353898,"chunk":{"type":"usage","usage":{"inputTokens":4529,"outputTokens":303,"cacheReadTokens":640,"reasoningTokens":52}}},{"type":"chunk","time":1790389353915,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_TPh5fH8x5kRezK115kgx8155","name":"exit_plan_mode","arguments":"{\"plan\": \"# Add `--greeting` flag to CLI\\n\\n- **Locate the CLI entry point** (e.g., `cli.py`, `main.go`, `index.js` etc.) and find the argument parser definition (argparse, click, cobra, yargs, or similar).\\n- **Register a new optional string argument** named `--greeting` with a short alias (`-g` if available) and a sensible default value (e.g., `\\\"Hello\\\"`).\\n- **Thread the parsed value** through the main handler function so it is passed where the greeting string is used (e.g., the welcome/response message).\\n- **Update the help text** so `--help` or `-h` shows the new flag with its description.\\n- **No tests or config changes** unless they already exist and directly validate the flag's presence.\"}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_TPh5fH8x5kRezK115kgx8155"},"toolCallId":"call_00_TPh5fH8x5kRezK115kgx8155","content":[{"type":"text","text":"Plan approved — plan mode exited; carry out the plan starting with your next step."}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[18],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"plan/mode","data":{"active":false}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:7}}"}},"sourceEventSeqs":[10],"surfaceOp":{"op":"replace","startSeq":10,"endSeq":10}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["ask_user_question","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","read","read_image","schedule_create","schedule_delete","schedule_list","schedule_update","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} -{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"exit_plan_mode"}],"role":"developer","id":"{{message:8}}"}},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"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."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"usage":{"inputTokens":441,"outputTokens":43,"cacheReadTokens":4608,"reasoningTokens":40},"stream":[{"type":"chunk","time":1792565779968,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1792565779984,"index":0,"dt":[16,17,16,16,16,15,17,16,16,16,16,16,16,17,16,17,16,16,16,17,16,16,15,17,16,17,16,16,16,17,16,16,16,16,15,16,16,16,16],"texts":["The"," plan"," was"," approved","."," The"," user","'s"," last"," instruction"," says",":"," \"","Once"," the"," plan"," is"," approved",","," reply"," with"," the"," single"," word"," D","ONE"," and"," stop",".\""," So"," I"," should"," just"," reply"," with"," D","ONE"," and"," stop","."]},{"type":"chunk","time":1792565780629,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1792565780646,"index":1,"dt":[16],"texts":["D","ONE"]},{"type":"chunk","time":1792565780678,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"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."}}},{"type":"chunk","time":1792565780694,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1792565780710,"chunk":{"type":"usage","usage":{"inputTokens":441,"outputTokens":43,"cacheReadTokens":4608,"reasoningTokens":40}}},{"type":"chunk","time":1792565780726,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"series"}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"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."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":441,"outputTokens":43,"cacheReadTokens":4608,"reasoningTokens":40},"stream":[{"type":"chunk","time":1790389355144,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1790389355159,"index":0,"dt":[16,16,17,16,17,16,16,16,16,17,15,17,15,16,17,17,16,14,16,16,17,16,16,16,17,15,16,16,19,16,16,17,15,16,16,16,16,16,15],"texts":["The"," plan"," was"," approved","."," The"," user","'s"," last"," instruction"," says",":"," \"","Once"," the"," plan"," is"," approved",","," reply"," with"," the"," single"," word"," D","ONE"," and"," stop",".\""," So"," I"," should"," just"," reply"," with"," D","ONE"," and"," stop","."]},{"type":"chunk","time":1790389355805,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1790389355821,"index":1,"dt":[16],"texts":["D","ONE"]},{"type":"chunk","time":1790389355854,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"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."}}},{"type":"chunk","time":1790389355870,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790389355887,"chunk":{"type":"usage","usage":{"inputTokens":441,"outputTokens":43,"cacheReadTokens":4608,"reasoningTokens":40}}},{"type":"chunk","time":1790389355904,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} From 85181cad37abd32e82e6012f276dc84fd6db5ae3 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Wed, 21 Oct 2026 17:25:57 +0800 Subject: [PATCH 25/36] fix(web): show image upload failures in a tooltip A refused image thumbnail named its reason only through a native title, which browsers show late or not at all, so hovering it showed nothing. The refused and the failed image thumbnails now use the shared tooltip: the Host's refusal opens on hover or keyboard focus and a tap or click pins it, and the retry hint of a failed upload opens on hover or focus. --- .../client/ui-attachment/README.i18n.yaml | 4 +- packages/client/ui-attachment/README.md | 2 +- packages/client/ui-attachment/README.zh.md | 2 +- .../src/client/ComposerAttachments.module.css | 1 - .../src/client/ComposerAttachments.tsx | 45 ++++++++++--------- .../composer-attachments.client.spec.tsx | 40 ++++++++++++++--- 6 files changed, 63 insertions(+), 31 deletions(-) diff --git a/packages/client/ui-attachment/README.i18n.yaml b/packages/client/ui-attachment/README.i18n.yaml index c5d89995d3..ae497ad6ce 100644 --- a/packages/client/ui-attachment/README.i18n.yaml +++ b/packages/client/ui-attachment/README.i18n.yaml @@ -18,8 +18,8 @@ en: 15cdd9d52dcc71b8 zh: 53933fbbf5d39100 /deepseek-ai-dsh-client-ui-attachment/use-this-package/draft-attachments: - en: c7535c34db5d782c - zh: 4fc4caccac84261f + en: 8246cb3c470e3fc5 + zh: 7028cf466a832b99 /deepseek-ai-dsh-client-ui-attachment/use-this-package/message-images-and-the-lightbox: en: 8b3d7729152d8060 zh: 815f932ccc9653f5 diff --git a/packages/client/ui-attachment/README.md b/packages/client/ui-attachment/README.md index 5d3faadf45..0805928455 100644 --- a/packages/client/ui-attachment/README.md +++ b/packages/client/ui-attachment/README.md @@ -29,7 +29,7 @@ Mount this plugin alongside [`ui-conversation`](../ui-conversation/README.md) an ### Draft attachments -Images and generic files retain pick order in one non-wrapping horizontal rail. Every item is 64px high: an image is a 64px square thumbnail, while a generic file is a 240px-wide DeepSeek Web card with a 16px radius, blue gradient document glyph, filename, and uppercase extension plus byte size. Edge arrows page hidden overflow, the scrollbar stays hidden, and a newly added item is revealed at the rail's end. Uploading replaces a file glyph with a spinner and shows byte progress when the carrier reports it, with an indeterminate bar before the first report; failure shows retry, and removal controls appear on hover or keyboard focus while remaining visible on touch devices. An uploading image shows the same progress bar along its thumbnail's bottom edge, and a failed image upload turns the thumbnail into its retry control, except an image the Host refused, whose thumbnail names the refusal and leaves removal as the way out. Clicking an image opens the original. +Images and generic files retain pick order in one non-wrapping horizontal rail. Every item is 64px high: an image is a 64px square thumbnail, while a generic file is a 240px-wide DeepSeek Web card with a 16px radius, blue gradient document glyph, filename, and uppercase extension plus byte size. Edge arrows page hidden overflow, the scrollbar stays hidden, and a newly added item is revealed at the rail's end. Uploading replaces a file glyph with a spinner and shows byte progress when the carrier reports it, with an indeterminate bar before the first report; failure shows retry, and removal controls appear on hover or keyboard focus while remaining visible on touch devices. An uploading image shows the same progress bar along its thumbnail's bottom edge, and a failed image upload turns the thumbnail into its retry control, except an image the Host refused, whose thumbnail explains the refusal in a tooltip that a tap or click also pins and leaves removal as the way out. Clicking an image opens the original. ### Message images and the lightbox diff --git a/packages/client/ui-attachment/README.zh.md b/packages/client/ui-attachment/README.zh.md index 64ac2dcfe5..c17f914b4d 100644 --- a/packages/client/ui-attachment/README.zh.md +++ b/packages/client/ui-attachment/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 草稿附件 -图片与通用文件按选择顺序进入同一条不换行的横向附件栏。所有条目均为 64px 高:图片是 64px 方形缩略图,通用文件是 240px 宽的 DeepSeek Web 卡片,带 16px 圆角、蓝色渐变文档图标、文件名,以及大写扩展名与字节大小。溢出隐藏时由边缘箭头翻页,滚动条保持隐藏,新增条目会滚动到栏尾展示。文件上传时图标位置显示 spinner,传输层报告字节时显示进度,首次报告前使用不定态进度条;失败时显示重试。上传中的图片在缩略图底边显示同样的进度条,上传失败的图片缩略图变成重试控件;Host 拒绝的图片则在缩略图上说明原因,只能移除。移除按钮在悬停或键盘聚焦时出现,在触摸设备上保持可见。单击图片会打开原图。 +图片与通用文件按选择顺序进入同一条不换行的横向附件栏。所有条目均为 64px 高:图片是 64px 方形缩略图,通用文件是 240px 宽的 DeepSeek Web 卡片,带 16px 圆角、蓝色渐变文档图标、文件名,以及大写扩展名与字节大小。溢出隐藏时由边缘箭头翻页,滚动条保持隐藏,新增条目会滚动到栏尾展示。文件上传时图标位置显示 spinner,传输层报告字节时显示进度,首次报告前使用不定态进度条;失败时显示重试。上传中的图片在缩略图底边显示同样的进度条,上传失败的图片缩略图变成重试控件;Host 拒绝的图片则用缩略图的提示说明原因,点按也能固定该提示,只能移除。移除按钮在悬停或键盘聚焦时出现,在触摸设备上保持可见。单击图片会打开原图。 ### 消息图片与灯箱 diff --git a/packages/client/ui-attachment/src/client/ComposerAttachments.module.css b/packages/client/ui-attachment/src/client/ComposerAttachments.module.css index 1befbc9dce..2d2dc878f6 100644 --- a/packages/client/ui-attachment/src/client/ComposerAttachments.module.css +++ b/packages/client/ui-attachment/src/client/ComposerAttachments.module.css @@ -40,7 +40,6 @@ } .thumbnailRefused { - box-sizing: border-box; cursor: default; } diff --git a/packages/client/ui-attachment/src/client/ComposerAttachments.tsx b/packages/client/ui-attachment/src/client/ComposerAttachments.tsx index 7738662eeb..8035470f69 100644 --- a/packages/client/ui-attachment/src/client/ComposerAttachments.tsx +++ b/packages/client/ui-attachment/src/client/ComposerAttachments.tsx @@ -3,7 +3,7 @@ import type { ComposerAttachment, ComposerAttachmentsProps, ComposerImageAttachment, } from '@deepseek-ai/dsh-client-ui-conversation/client' import { - IconCloseFillRegular, IconRefreshOutlineRegular, IconWarningOutlineRegular, + IconCloseFillRegular, IconRefreshOutlineRegular, IconWarningOutlineRegular, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import { AttachmentRail } from '../AttachmentRail.tsx' import type { AttachmentRailItem } from '../AttachmentRail.tsx' @@ -79,7 +79,8 @@ export function ComposerAttachments({ ) } // An uploading image shows its progress; a failed upload turns the thumbnail into its retry - // control, except one the Host refused, which shows why and leaves removal as the way out. + // control, except one the Host refused, which explains why and leaves removal as the way out. + // The refusal is the only explanation of its warning, so a tap or click also pins it. const upload = uploads[attachment.id] const name = attachment.file.name || t('image.pending') const refusal = upload?.status === 'error' && upload.reason !== undefined @@ -89,28 +90,30 @@ export function ComposerAttachments({
{refusal !== undefined ? ( -
- - -
+ + + ) : upload?.status === 'error' ? ( - + + + ) : ( @@ -393,16 +347,17 @@ export function ModelListEditor(props: ModelListEditorProps): ReactNode {
{models.length === 0 ?

{t('modelsEmpty')}

: null}
- {models.map((model, index) => ( + {rowState.rows.map(({ model, key, expanded, order }, index) => ( { patch(index, { [field]: value }) }} onChange={(next) => { onChange(models.map((row, at) => at === index ? next : row)) }} - onToggle={() => { toggleExpanded(index) }} + onToggle={() => { rowState.toggle(index) }} onRemove={() => { onChange(models.filter((_model, at) => at !== index)) - forgetRows(new Set([index])) + rowState.forget(new Set([index])) }} /> ))} diff --git a/packages/client/ui-settings-models/src/client/ModelRow.tsx b/packages/client/ui-settings-models/src/client/ModelRow.tsx index 22a1177a40..af567b65fe 100644 --- a/packages/client/ui-settings-models/src/client/ModelRow.tsx +++ b/packages/client/ui-settings-models/src/client/ModelRow.tsx @@ -2,12 +2,14 @@ import type { ReactNode } from 'react' import { - IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconTrashOutlineRegular, + IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconChevronsUpDownOutlineRegular, + IconTrashOutlineRegular, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { DeepSeekModelDraft } from './DeepSeekModelsEditor.tsx' import type { ModelsKey } from './locales.ts' import { ModelInputTypes } from './ModelInputTypes.tsx' import { ModelReasoningEfforts } from './ModelReasoningEfforts.tsx' +import type { ModelRowOrder } from './useModelRows.ts' import styles from './ModelsSection.module.css' /** A capacity's editable text and adapter-specific inherited hint. */ @@ -22,6 +24,7 @@ interface CapacityInput { interface ModelRowProps { model: DeepSeekModelDraft position: number + order: ModelRowOrder inputField: 'inputModalities' | 'input' inputFallback?: readonly string[] | undefined inputLoading?: boolean @@ -47,8 +50,48 @@ interface ModelRowProps { export function ModelRow(props: ModelRowProps): ReactNode { const { model, position, t, disabled } = props return ( -
+
{ + if (!props.order.canDrop) return + event.preventDefault() + event.dataTransfer.dropEffect = 'move' + props.order.onOver() + }} + onDrop={(event) => { + if (!props.order.canDrop) return + event.preventDefault() + props.order.onDrop() + }} + >
+ + + {(['id', 'name'] as const).map(field => ( +} + +/** Drag state and actions for one model row within its editor. */ +export interface ModelRowOrder { + dragging: boolean + target: boolean + canDrop: boolean + onStart: () => void + onEnd: () => void + onOver: () => void + onDrop: () => void + onMove: (offset: -1 | 1) => void +} + +interface ModelRows { + rows: (RowState & { model: DeepSeekModelDraft; order: ModelRowOrder })[] + toggle: (index: number) => void + edit: (index: number, field: CapacityField, text: string | undefined) => void + forget: (removed: ReadonlySet) => void + reset: () => void +} + +/** One editor-local identity; editing a model ID never replaces its controls. */ +function createRow(key: number): RowState { + return { key, expanded: false, editing: new Map() } +} + +/** + * Keep row state with its model through draft moves and removals. + * @param models - current draft array, owned by the provider card. + * @param onChange - replaces only that card's draft array. + * @param disabled - prevents reordering while the card cannot be edited. + * @returns row state and local editing and ordering actions. + */ +export function useModelRows( + models: readonly DeepSeekModelDraft[], onChange: (models: DeepSeekModelDraft[]) => void, disabled: boolean, +): ModelRows { + const nextKey = useRef(0) + const [stored, setRows] = useState(() => models.map(() => createRow(nextKey.current++))) + const [dragged, setDragged] = useState() + const [target, setTarget] = useState() + const entries = models.map((model, index) => ({ model, state: stored[index] ?? createRow(nextKey.current++) })) + const rows = entries.map(entry => entry.state) + if (stored.length !== models.length) setRows(rows) + + const endDrag = (): void => { setDragged(undefined); setTarget(undefined) } + const move = (from: number, to: number): void => { + if (disabled || from === to || from < 0 || to < 0 || to >= models.length) return + const order = [...entries] + const moved = order.splice(from, 1) + order.splice(to, 0, ...moved) + setRows(order.map(entry => entry.state)) + onChange(order.map(entry => entry.model)) + } + + return { + rows: entries.map(({ model, state }, index) => ({ + ...state, + model, + order: { + dragging: dragged === state.key, + target: target === state.key, + canDrop: !disabled && dragged !== undefined, + onStart: (): void => { setDragged(state.key) }, + onEnd: endDrag, + onOver: (): void => { setTarget(state.key) }, + onDrop: (): void => { move(rows.findIndex(row => row.key === dragged), index); endDrag() }, + onMove: (offset: -1 | 1): void => { move(index, index + offset) }, + }, + })), + toggle: (index: number): void => { + setRows(rows.map((row, at) => at === index ? { ...row, expanded: !row.expanded } : row)) + }, + edit: (index: number, field: CapacityField, text: string | undefined): void => { + setRows(rows.map((row, at) => { + if (at !== index) return row + const editing = new Map(row.editing) + if (text === undefined) editing.delete(field) + else editing.set(field, text) + return { ...row, editing } + })) + }, + forget: (removed: ReadonlySet): void => { + setRows(rows.filter((_row, index) => !removed.has(index))) + endDrag() + }, + reset: (): void => { setRows(models.map(() => createRow(nextKey.current++))); endDrag() }, + } +} diff --git a/packages/client/ui-settings-models/tests/model-order.client.spec.tsx b/packages/client/ui-settings-models/tests/model-order.client.spec.tsx new file mode 100644 index 0000000000..1dfd141951 --- /dev/null +++ b/packages/client/ui-settings-models/tests/model-order.client.spec.tsx @@ -0,0 +1,166 @@ +// @vitest-environment jsdom +/** Provider-local ordering preserves row instances and unfinished model edits. */ +import { useState } from 'react' +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { DeepSeekModelsEditor } from '../src/client/DeepSeekModelsEditor.tsx' +import type { DeepSeekModelDraft } from '../src/client/DeepSeekModelsEditor.tsx' +import { ModelListEditor } from '../src/client/ModelListEditor.tsx' +import { en } from '../src/client/locales.ts' + +afterEach(cleanup) + +function Editor(props: { + family: 'deepseek' | 'pi-ai' + initial: DeepSeekModelDraft[] + changed: (models: DeepSeekModelDraft[]) => void + disabled?: boolean +}) { + const [models, setModels] = useState(props.initial) + const shared = { + models, disabled: props.disabled === true, overridden: true, + t: (key: keyof typeof en) => en[key], + onChange: (next: DeepSeekModelDraft[]): void => { props.changed(next); setModels(next) }, + onReset: (): void => { setModels(props.initial) }, + } + return props.family === 'deepseek' + ? + : {}} + operations={{ discoverModels: vi.fn(), storeCredential: vi.fn(), removeCredential: vi.fn(), writeSettings: vi.fn() }} + /> +} + +function handle(position: number): HTMLButtonElement { + return screen.getByRole('button', { name: `${en.reorderModel} ${String(position)}` }) +} + +function row(button: HTMLButtonElement): HTMLElement { + const entry = button.closest('[data-model-row]') + if (!(entry instanceof HTMLElement)) throw new Error('Model row is missing') + return entry +} + +function transfer() { + return { setData: vi.fn(), setDragImage: vi.fn(), effectAllowed: '', dropEffect: '' } +} + +describe.each(['deepseek', 'pi-ai'] as const)('%s model ordering', (family) => { + it('moves a complete model and its expanded capacity draft to the drop position', () => { + const first = { id: 'first', name: 'First', contextWindow: 4096, input: ['image'], hidden: { preserved: true } } + const second = { id: 'second', maxTokens: 1024 } + const third = { id: 'third' } + const changed = vi.fn() + render() + const identity = screen.getByLabelText(`${en.modelId} 1`) + const source = handle(1) + const destination = row(handle(3)) + fireEvent.click(screen.getByRole('button', { name: `${en.modelAdvanced} 1` })) + fireEvent.change(screen.getByLabelText(`${en.contextWindow} 1`), { target: { value: 'unfinished' } }) + fireEvent.change(screen.getByLabelText(`${en.maxTokens} 1`), { target: { value: '2000' } }) + changed.mockClear() + + const dataTransfer = transfer() + fireEvent.dragStart(source, { dataTransfer }) + fireEvent.dragOver(destination, { dataTransfer }) + expect(changed).not.toHaveBeenCalled() + fireEvent.drop(destination, { dataTransfer }) + fireEvent.dragEnd(source) + + expect(changed).toHaveBeenCalledExactlyOnceWith([ + second, third, { ...first, contextWindow: Number.NaN, maxTokens: 2000 }, + ]) + expect(screen.getByLabelText(`${en.modelId} 3`)).toBe(identity) + expect(screen.getByLabelText(`${en.contextWindow} 3`).value).toBe('unfinished') + expect(screen.getByLabelText(`${en.maxTokens} 3`).value).toBe('2000') + expect(screen.queryByLabelText(`${en.contextWindow} 1`)).toBeNull() + expect(first.contextWindow).toBe(4096) + }) + + it('moves with arrow keys, retains focus, and ignores moves past either end', () => { + const changed = vi.fn() + render() + const source = handle(1) + source.focus() + fireEvent.keyDown(source, { key: 'ArrowUp' }) + fireEvent.keyDown(source, { key: 'Enter' }) + expect(changed).not.toHaveBeenCalled() + fireEvent.keyDown(source, { key: 'ArrowDown' }) + expect(handle(2)).toBe(source) + expect(document.activeElement).toBe(source) + fireEvent.keyDown(source, { key: 'ArrowDown' }) + expect(changed).toHaveBeenCalledExactlyOnceWith([{ id: 'second' }, { id: 'first' }]) + fireEvent.keyDown(source, { key: 'ArrowUp' }) + expect(changed).toHaveBeenLastCalledWith([{ id: 'first' }, { id: 'second' }]) + }) + + it('keeps canceled, same-row, foreign, and disabled drops from changing the draft', () => { + const changed = vi.fn() + const initial = [{ id: 'first' }, { id: 'second' }] + const view = render() + const source = handle(1) + const destination = row(handle(2)) + const dataTransfer = transfer() + fireEvent.drop(destination, { dataTransfer }) + fireEvent.dragStart(source, { dataTransfer }) + fireEvent.drop(row(source), { dataTransfer }) + fireEvent.dragStart(source, { dataTransfer }) + fireEvent.dragOver(destination, { dataTransfer }) + fireEvent.dragEnd(source) + fireEvent.drop(destination, { dataTransfer }) + expect(changed).not.toHaveBeenCalled() + + view.rerender() + expect(source.disabled).toBe(true) + expect(source.draggable).toBe(false) + fireEvent.keyDown(source, { key: 'ArrowDown' }) + fireEvent.drop(destination, { dataTransfer }) + expect(changed).not.toHaveBeenCalled() + }) + + it('keeps blank rows distinct through editing, moves, removal, and addition', () => { + render() + const first = screen.getByLabelText(`${en.modelId} 1`) + const second = screen.getByLabelText(`${en.modelId} 2`) + first.focus() + fireEvent.change(first, { target: { value: 'renamed' } }) + expect(document.activeElement).toBe(first) + fireEvent.keyDown(handle(1), { key: 'ArrowDown' }) + expect(screen.getByLabelText(`${en.modelId} 2`)).toBe(first) + expect(screen.getByLabelText(`${en.modelId} 1`)).toBe(second) + fireEvent.click(screen.getByRole('button', { name: `${en.removeModel} 1` })) + expect(screen.getByLabelText(`${en.modelId} 1`)).toBe(first) + fireEvent.click(screen.getByRole('button', { name: en.addModel })) + expect(screen.getByLabelText(`${en.modelId} 2`)).not.toBe(second) + fireEvent.keyDown(handle(2), { key: 'ArrowUp' }) + expect(screen.getByLabelText(`${en.modelId} 2`)).toBe(first) + }) + + it('restores inherited order and clears row drafts when defaults are restored', () => { + render() + fireEvent.click(screen.getByRole('button', { name: `${en.modelAdvanced} 1` })) + fireEvent.change(screen.getByLabelText(`${en.contextWindow} 1`), { target: { value: 'bad' } }) + fireEvent.keyDown(handle(1), { key: 'ArrowDown' }) + fireEvent.click(screen.getByRole('button', { name: en.resetModels })) + expect(screen.getByLabelText(`${en.modelId} 1`).value).toBe('first') + expect(screen.queryByLabelText(`${en.contextWindow} 1`)).toBeNull() + fireEvent.click(screen.getByRole('button', { name: `${en.modelAdvanced} 1` })) + expect(screen.getByLabelText(`${en.contextWindow} 1`).value).toBe('') + }) +}) + +it('does not accept another provider editor\'s dragged model', () => { + const firstChanged = vi.fn() + const secondChanged = vi.fn() + const first = render() + const second = render() + const source = within(first.container).getByRole('button', { name: `${en.reorderModel} 1` }) + const destination = within(second.container).getByRole('button', { name: `${en.reorderModel} 2` }) + const dataTransfer = transfer() + fireEvent.dragStart(source, { dataTransfer }) + fireEvent.dragOver(row(destination), { dataTransfer }) + fireEvent.drop(row(destination), { dataTransfer }) + fireEvent.dragEnd(source) + expect(firstChanged).not.toHaveBeenCalled() + expect(secondChanged).not.toHaveBeenCalled() +}) From dae4bfa413e44751926ba9e72cd991b79beb99df Mon Sep 17 00:00:00 2001 From: Magolor Date: Wed, 21 Oct 2026 20:11:39 +0800 Subject: [PATCH 29/36] feat(settings): use a three-line model reorder handle --- .../models-settings/reordered.expected.md | 72 ------------------- apps/web/tests/models-settings.e2e.ts | 8 +-- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../client/ui-primitives/src/icons/index.tsx | 17 +++++ .../ui-primitives/tests/icons.client.spec.tsx | 4 +- .../src/client/ModelRow.tsx | 4 +- .../tests/model-order.client.spec.tsx | 2 +- 9 files changed, 30 insertions(+), 85 deletions(-) delete mode 100644 apps/web/tests/expected/models-settings/reordered.expected.md diff --git a/apps/web/tests/expected/models-settings/reordered.expected.md b/apps/web/tests/expected/models-settings/reordered.expected.md deleted file mode 100644 index 130de2d25a..0000000000 --- a/apps/web/tests/expected/models-settings/reordered.expected.md +++ /dev/null @@ -1,72 +0,0 @@ -- dialog "设置": - - text: 设置 - - navigation: - - button "通用设置" - - button "模型" - - button "内置插件" - - button "Agent 预设" - - button "打开配置文件" - - button "关闭" - - heading "模型" [level=2] - - paragraph: 填入各提供商的 API 密钥即可使用其模型。 - - list: - - listitem: - - text: minimax-cn - - img "API 密钥已配置" - - button "编辑 minimax-cn": 编辑 - - button "删除 minimax-cn": 删除 - - listitem: - - text: Acme 网关 自定义 - - button "编辑 Acme 网关 (acme-gateway)": 编辑 - - button "删除 Acme 网关 (acme-gateway)": 删除 - - text: Acme 网关 acme-gateway API 密钥 - - textbox "API 密钥": - - /placeholder: 输入 API 密钥 - - group: - - text: 自定义设置 显示名称 - - textbox "显示名称": - - /placeholder: acme-gateway - - text: Acme 网关 - - text: API 地址 - - textbox "API 地址": - - /placeholder: https://gateway.acme.example/v1 - - text: https://gateway.acme.example/v1 - - text: API 协议 - - combobox "API 协议": - - option "OpenAI Chat Completions" - - option "OpenAI Responses" - - option "Anthropic Messages" [selected] - - region "模型目录": - - text: 模型目录 已自定义模型目录 - - button "恢复默认模型" - - button "获取可用模型" - - button "调整模型顺序 1" - - textbox "模型 ID 1": - - /placeholder: 模型 ID - - text: order-second - - textbox "显示名称 1": - - /placeholder: 显示名称 - - text: order-second - - button "模型选项 1" - - button "删除模型 1" - - button "调整模型顺序 2" - - textbox "模型 ID 2": - - /placeholder: 模型 ID - - text: order-third - - textbox "显示名称 2": - - /placeholder: 显示名称 - - text: order-third - - button "模型选项 2" - - button "删除模型 2" - - button "调整模型顺序 3" - - textbox "模型 ID 3": - - /placeholder: 模型 ID - - text: acme-large - - textbox "显示名称 3": - - /placeholder: 显示名称 - - button "模型选项 3" - - button "删除模型 3" - - button "添加模型" - - button "取消" - - button "保存" - - button "添加模型提供商" diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index b4cec75da7..568a0f0803 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -586,9 +586,9 @@ describe('web e2e: Models settings page configures a dormant provider', () => { } }) await edit.click() await dialog.getByText('自定义设置').click() - expect(await dialog.getByLabel('模型 ID 1', { exact: true }).inputValue()).toBe('order-second') - await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'reordered.expected.md'), - await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), MODE) + expect(await Promise.all([1, 2, 3].map(position => + dialog.getByLabel(`模型 ID ${String(position)}`, { exact: true }).inputValue(), + ))).toEqual(['order-second', 'order-third', 'acme-large']) const viewport = page.viewportSize() if (viewport === null) throw new Error('Model ordering checks require an explicit viewport') try { @@ -645,7 +645,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { 'configured.expected.md', 'declared-edit.expected.md', 'declared.expected.md', 'delete.expected.md', 'empty.expected.md', 'model-picker.expected.md', 'native-delete.expected.md', 'native-keyless.expected.md', 'catalog-inputs.expected.md', - 'refreshing.expected.md', 'image-only.expected.md', 'reordered.expected.md', + 'refreshing.expected.md', 'image-only.expected.md', ]) }) }) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 9a13d1d0a6..a709ad8518 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,8 +18,8 @@ en: d2f5701274be5110 zh: d60e2617136a6f26 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: cb874a0ca53a6747 - zh: 31179193dd1d6e12 + en: a3d646d5179348aa + zh: 592a0abe6788541f /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: en: fff68b60f4abdc7e zh: 5cf5952ec78f7f91 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index ecd3fd4e29..56c2db14d8 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -70,7 +70,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `UserTextRun`, `ReferenceChip` | Uninterpreted inline text and business-resolved reference labels or activation buttons. | | `CommandText` | Selectable command or argument text; only horizontal overflow adds a named keyboard focus target. | | `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, `WebBlock` | The agent-output card matching each tool-result intent. | -| `icons/*`, `FishLogo`, `BrandWordmark`, `ReferenceIconRegular`/`ReferenceIconMedium`, `LinkIconRegular`/`LinkIconMedium` | Glyphs and brand marks. The thinking glyph keeps an inset orbit within its 16px view box. `IconAppsAddOutlineRegular`/`Medium`, the More launcher glyph, take `compact` to draw their tiles closer together at card size. Use `LinkIconMedium` for 14px clickable-link categories and known-site marks. | +| `icons/*`, `FishLogo`, `BrandWordmark`, `ReferenceIconRegular`/`ReferenceIconMedium`, `LinkIconRegular`/`LinkIconMedium` | Glyphs and brand marks. `IconDragHandleOutlineRegular`/`Medium` draw a three-line grip for reordering. The thinking glyph keeps an inset orbit within its 16px view box. `IconAppsAddOutlineRegular`/`Medium`, the More launcher glyph, take `compact` to draw their tiles closer together at card size. Use `LinkIconMedium` for 14px clickable-link categories and known-site marks. | | `PermissionIconReadOnlyRegular`/`Medium`, `PermissionIconWorkspaceWriteRegular`/`Medium`, `PermissionIconFullAccessRegular`/`Medium`, `PermissionIconAutoReviewRegular`/`Medium` | Permission-mode glyphs for read-only, workspace-write, full-access, and auto-review choices. | | `PluginArtworkTerminal`/`Loop`/`Subagent`/`Search`/`Default` | Fixed-palette 36×36 plugin artwork; `Terminal` supplies the light-blue prompt in plugin cards and sidebar guide entries. `Default` marks plugins without artwork of their own. Def ids are per-instance, so the same artwork repeats safely on one page. | | `GuideArtworkBrowser`/`Files` | Fixed-palette 36×36 browser and folder artwork for sidebar guide entries. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 3de121ab2c..f6bfaaf7a5 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -70,7 +70,7 @@ kind: "package-library" | `UserTextRun`、`ReferenceChip` | 不做解析的行内文本,以及业务已解析的引用标签或激活按钮。 | | `CommandText` | 可选中的命令或参数文本;仅横向溢出时添加具名的键盘聚焦目标。 | | `TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock`、`WebBlock` | 与各类工具结果意图对应的 agent 输出卡片。 | -| `icons/*`、`FishLogo`、`BrandWordmark`、`ReferenceIconRegular`/`ReferenceIconMedium`、`LinkIconRegular`/`LinkIconMedium` | 字形与品牌标识。思考图标的轨道在 16px 视口内保留内边距。“更多”入口使用的 `IconAppsAddOutlineRegular`/`Medium` 接受 `compact`,在卡片尺寸下让方块更靠近。`LinkIconMedium` 用于 14px 的可点击链接分类及已知站点标记。 | +| `icons/*`、`FishLogo`、`BrandWordmark`、`ReferenceIconRegular`/`ReferenceIconMedium`、`LinkIconRegular`/`LinkIconMedium` | 字形与品牌标识。`IconDragHandleOutlineRegular`/`Medium` 以三条横线表示可拖动的排序手柄。思考图标的轨道在 16px 视口内保留内边距。“更多”入口使用的 `IconAppsAddOutlineRegular`/`Medium` 接受 `compact`,在卡片尺寸下让方块更靠近。`LinkIconMedium` 用于 14px 的可点击链接分类及已知站点标记。 | | `PermissionIconReadOnlyRegular`/`Medium`、`PermissionIconWorkspaceWriteRegular`/`Medium`、`PermissionIconFullAccessRegular`/`Medium`、`PermissionIconAutoReviewRegular`/`Medium` | 只读、工作区写入、完全访问与自动审查选项使用的权限模式图形。 | | `PluginArtworkTerminal`/`Loop`/`Subagent`/`Search`/`Default` | 固定配色的 36×36 插件插画;`Terminal` 为插件卡片和侧边栏开始页入口提供浅蓝色提示符。`Default` 用于没有自有插画的插件。def id 按实例生成,同一插画可在一页中安全重复。 | | `GuideArtworkBrowser`/`Files` | 固定配色的 36×36 浏览器与文件夹插画,用于侧栏引导入口。 | diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index cdfb4faf5e..1674d03b5c 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -1571,6 +1571,23 @@ export const IconChevronsUpDownOutlineMedium = (props: IconProps) => ( ) +const IconDragHandleOutlineArtwork = ({ size = 16, className, strokeWidth }: WeightedIconProps) => ( + +) + +/** Regular one-pixel IconDragHandleOutline artwork. */ +export const IconDragHandleOutlineRegular = (props: IconProps) => ( + +) + +/** Medium IconDragHandleOutline artwork with a 1.3px stroke. */ +export const IconDragHandleOutlineMedium = (props: IconProps) => ( + +) + const IconArchiveOffOutlineArtwork = ({ size = 16, className, strokeWidth }: WeightedIconProps) => { // The mask carves whitespace along the slash out of the box strokes, so the // id must stay unique per rendered instance. diff --git a/packages/client/ui-primitives/tests/icons.client.spec.tsx b/packages/client/ui-primitives/tests/icons.client.spec.tsx index b79e3d4856..97bc3cc02c 100644 --- a/packages/client/ui-primitives/tests/icons.client.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.client.spec.tsx @@ -17,8 +17,8 @@ const icons = Object.fromEntries( const iconNames = Object.keys(icons) describe('product icon set', () => { - it('exports regular and medium variants for all 95 public glyphs', () => { - expect(iconNames.length).toBe(190) + it('exports regular and medium variants for all 96 public glyphs', () => { + expect(iconNames.length).toBe(192) expect(iconNames.some(name => /\d+$/.test(name))).toBe(false) const regular = iconNames.filter(name => name.endsWith('Regular')).map(name => name.slice(0, -'Regular'.length)) const medium = iconNames.filter(name => name.endsWith('Medium')).map(name => name.slice(0, -'Medium'.length)) diff --git a/packages/client/ui-settings-models/src/client/ModelRow.tsx b/packages/client/ui-settings-models/src/client/ModelRow.tsx index af567b65fe..b0252635c0 100644 --- a/packages/client/ui-settings-models/src/client/ModelRow.tsx +++ b/packages/client/ui-settings-models/src/client/ModelRow.tsx @@ -2,7 +2,7 @@ import type { ReactNode } from 'react' import { - IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconChevronsUpDownOutlineRegular, + IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconDragHandleOutlineRegular, IconTrashOutlineRegular, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { DeepSeekModelDraft } from './DeepSeekModelsEditor.tsx' @@ -89,7 +89,7 @@ export function ModelRow(props: ModelRowProps): ReactNode { props.order.onMove(event.key === 'ArrowUp' ? -1 : 1) }} > - + {(['id', 'name'] as const).map(field => ( diff --git a/packages/client/ui-settings-models/tests/model-order.client.spec.tsx b/packages/client/ui-settings-models/tests/model-order.client.spec.tsx index 1dfd141951..f108a95531 100644 --- a/packages/client/ui-settings-models/tests/model-order.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/model-order.client.spec.tsx @@ -42,7 +42,7 @@ function row(button: HTMLButtonElement): HTMLElement { } function transfer() { - return { setData: vi.fn(), setDragImage: vi.fn(), effectAllowed: '', dropEffect: '' } + return { setData: vi.fn(), effectAllowed: '', dropEffect: '' } } describe.each(['deepseek', 'pi-ai'] as const)('%s model ordering', (family) => { From 5d3ea87d28627921910ed732c5ae9ca422922ffc Mon Sep 17 00:00:00 2001 From: Magolor Date: Wed, 21 Oct 2026 20:45:12 +0800 Subject: [PATCH 30/36] refactor(web): share workspace drag behavior with model lists --- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 + packages/client/ui-primitives/README.zh.md | 2 + .../src}/AnimatedRows.module.css | 0 .../src}/AnimatedRows.tsx | 18 ++--- .../src/RowDragPreview.module.css | 12 ++++ packages/client/ui-primitives/src/index.ts | 3 + .../src}/useRowDragPreview.ts | 21 +++--- .../ui-settings-models/README.i18n.yaml | 4 +- packages/client/ui-settings-models/README.md | 2 +- .../client/ui-settings-models/README.zh.md | 2 +- .../src/client/DeepSeekModelsEditor.tsx | 7 +- .../src/client/ModelListEditor.tsx | 7 +- .../src/client/ModelRow.tsx | 22 ++++-- .../src/client/ModelsSection.module.css | 41 ++++++++++- .../src/client/useModelRows.ts | 21 ++++-- .../tests/model-order.client.spec.tsx | 70 +++++++++++++++++-- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 4 +- packages/client/ui-workspace/README.zh.md | 4 +- .../src/client/rows/Rows.module.css | 11 --- .../ui-workspace/src/client/rows/Rows.tsx | 7 +- .../src/client/rows/WorkspaceBrowser.tsx | 5 +- .../tests/animated-rows.client.spec.tsx | 3 +- .../ui-workspace/tests/rows.client.spec.tsx | 4 +- 25 files changed, 204 insertions(+), 76 deletions(-) rename packages/client/{ui-workspace/src/client/rows => ui-primitives/src}/AnimatedRows.module.css (100%) rename packages/client/{ui-workspace/src/client/rows => ui-primitives/src}/AnimatedRows.tsx (92%) create mode 100644 packages/client/ui-primitives/src/RowDragPreview.module.css rename packages/client/{ui-workspace/src/client/rows => ui-primitives/src}/useRowDragPreview.ts (76%) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index a709ad8518..c49fb07d10 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,8 +18,8 @@ en: d2f5701274be5110 zh: d60e2617136a6f26 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: a3d646d5179348aa - zh: 592a0abe6788541f + en: ab9409aa3bef94c3 + zh: 2907d18bd144c294 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: en: fff68b60f4abdc7e zh: 5cf5952ec78f7f91 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 56c2db14d8..a41b8201d1 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -55,6 +55,8 @@ Check this table before writing a control in a feature package. A plugin cannot | `StateDot` | Solid green `done`, amber `warning`, red `error`, and neutral-grey `idle` marks in a 10px slot, plus a tertiary-grey 14px rotating `ongoing` loader whose animations pin to document time zero on mount and on every animation restart, such as a list reorder, so every visible loader rotates in phase. `aria-hidden`, so the render site owns the name. `appearance="step"` shows a filled check for completion and a hollow pending circle. | | `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. | | `DisclosureRow` | 24px compact disclosure that lays title and content side by side. The header supplies tertiary at rest and secondary on hover; text and icons inherit it regardless of expandability or open state unless the caller supplies a feature-specific override. Semantic status colors remain explicit. Collapsed rows preview a down chevron on hover, and expanded rows keep an up chevron visible. `headerAccessory` places an independent action outside the disclosure target and shimmer; with an accessory, the title row shrinks to its content width. Memoized with shallow prop comparison; keep callbacks and React-node props stable when their content is unchanged. | +| `AnimatedRows` | Keyed list movement with 200 ms glides and 100 ms entry/exit fades. Starts after local pointer or keyboard input, honors reduced motion, and settles loading or view replacement. Mark rows with `data-row-key`, supply matching `rowKeys`, and position the parent for the inert exit overlay; `role` and `label` belong to the caller. | +| `useRowDragPreview` | Native drag preview using an inert offscreen row copy. Supply a class for the surface background and, for a child drag handle, pass the row to `start`; `clear` and unmount remove the copy. | | `TextShimmer` | One left-to-right highlight across a row’s title, separators, summary, and suffix, with a 300ms initial delay, a one-second sweep and a 500ms rest. The mask spans the content width, capped by the visible row and tilts 15° from vertical, with a flat peak and soft edges. The moving decoration stays clipped to the row without enlarging its scrollable area. Base text inherits the caller’s color, including hover changes; the theme supplies the translucent highlight. Place icons and chevrons outside `TextShimmer` so only text and separators receive the highlight. A string child uses the same retained text interface; nested `TextShimmer` instances share the outer animation. Composite children render twice while active and must have no effects or element ids. Mark separators with `data-shimmer-decoration` so their fill receives the highlight. `DisclosureRow` forwards `contentClassName` for the text area and `contentLayoutClassName` for its inner layout. The inert decorative copy is excluded from interaction, selection, and accessibility; text updates retain the animation, and reduced-motion mode keeps the static base. | | `Modal` | Centered dialog over a page mask. A nested dialog can intercept keys with `onKeyDownCapture` before document Escape handlers. The tint and dialog fade in while backdrop blur stays fully applied, honoring reduced motion. Set `backdropBlur={false}` when the caller already blurs the source page. | | `RiskConfirmation` | Sensitive action gated behind an explicit checkbox. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index f6bfaaf7a5..2cee4f9eb5 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -55,6 +55,8 @@ kind: "package-library" | `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading,其动画在挂载时以及每次动画重启(如列表重排)时固定到文档时间零点,所以所有可见 loading 同相旋转。它是 `aria-hidden` 的,名称由渲染点提供。 `appearance="step"` 以实心勾表示完成、空心圆表示等待。 | | `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 | | `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。标题行默认使用 tertiary,悬停时使用 secondary;文字与图标继承该颜色,不受能否展开及开合状态影响,调用方可提供功能专属覆盖。语义状态色保持显式指定。收起时悬停预览向下箭头,展开后持续显示向上箭头。`headerAccessory` 将独立操作放在折叠触发区域和流光之外;有此操作时,标题行收窄到内容宽度。使用浅层 prop 比较进行 memo;内容未变时,保持回调与 React 节点 prop 的引用稳定。 | +| `AnimatedRows` | 带键列表的位移动画:移动为 200 ms,进出淡变为 100 ms。列表内发生指针或键盘输入后才启用,遵循减少动态效果设置,加载或替换视图时直接完成。为行标记 `data-row-key` 并传入对应的 `rowKeys`,为父容器设置定位以承载不可交互的退出层;`role` 和 `label` 由调用方提供。 | +| `useRowDragPreview` | 使用不可交互的离屏行副本生成原生拖拽预览。传入设置表面底色的类名;拖拽来自子级手柄时,将行元素传给 `start`;`clear` 和卸载会移除副本。 | | `TextShimmer` | 同一道高光从左到右扫过一行的标题、分隔符、摘要与后缀:首次等待 300ms,扫动一秒,再静止 500ms。遮罩覆盖内容宽度,并限制在可见行宽内,相对垂直方向倾斜 15°,峰值区域平坦,两侧柔和渐隐。移动的装饰层始终裁剪在行内,不会扩大可滚动区域。底色继承调用方的颜色,包括悬停变化;主题提供半透明高光。图标和箭头放在 `TextShimmer` 外,只有文字和分隔符参与扫光。字符串子节点沿用稳定的文字接口;嵌套的 `TextShimmer` 共用外层动画。活动期间组合子节点渲染两次,因此不得带副作用或元素 id。分隔符标记 `data-shimmer-decoration`,让填色参与扫光。`DisclosureRow` 将 `contentClassName` 传给文字区域,将 `contentLayoutClassName` 传给内部布局。惰性装饰副本不参与交互、选区和无障碍访问;文字更新保留动画,减少动态效果模式保留静态底色。 | | `Modal` | 页面遮罩之上的居中对话框。嵌套对话框可通过 `onKeyDownCapture` 在文档级 Escape 处理器之前拦截按键。 色层与弹窗淡入,背景模糊始终完整生效,并遵循减少动态效果偏好。调用方已模糊源页面时设置 `backdropBlur={false}`。 | | `RiskConfirmation` | 以显式复选框把关的敏感操作确认。 | diff --git a/packages/client/ui-workspace/src/client/rows/AnimatedRows.module.css b/packages/client/ui-primitives/src/AnimatedRows.module.css similarity index 100% rename from packages/client/ui-workspace/src/client/rows/AnimatedRows.module.css rename to packages/client/ui-primitives/src/AnimatedRows.module.css diff --git a/packages/client/ui-workspace/src/client/rows/AnimatedRows.tsx b/packages/client/ui-primitives/src/AnimatedRows.tsx similarity index 92% rename from packages/client/ui-workspace/src/client/rows/AnimatedRows.tsx rename to packages/client/ui-primitives/src/AnimatedRows.tsx index 12030ab6f2..fb4a8fac68 100644 --- a/packages/client/ui-workspace/src/client/rows/AnimatedRows.tsx +++ b/packages/client/ui-primitives/src/AnimatedRows.tsx @@ -1,14 +1,16 @@ -/** React-commit-driven movement and entry/exit fades for the sidebar's keyed rows. */ -import { Component, createRef, type ReactNode } from 'react' +/** React-commit-driven movement and entry/exit fades for keyed rows. */ +import { Component, createRef, type AriaRole, type ReactNode } from 'react' import css from './AnimatedRows.module.css' const ROW_FADE_MS = 100 const ROW_GLIDE_MS = 200 -interface AnimatedRowsProps { +/** Keyed row content, list semantics, and animation readiness. */ +export interface AnimatedRowsProps { children: ReactNode className: string - label: string + role?: AriaRole + label?: string /** Unique DOM-order keys matching the rendered data-row-key attributes. */ rowKeys: readonly string[] ready: boolean @@ -38,7 +40,7 @@ function intersects(row: DOMRect, viewport: DOMRect): boolean { } /** - * Animates keyed sidebar rows only when their rendered membership or order changes. + * Animates keyed rows only when their rendered membership or order changes. * Motion starts after the first pointer or keyboard input inside the mounted list. * The parent supplies a positioned container for the inert exit overlay. */ @@ -65,9 +67,7 @@ export class AnimatedRows extends Component { const clone = row.element.cloneNode(true) as HTMLElement clone.removeAttribute('data-row-key') clone.inert = true - clone.style.setProperty( - '--dsh-workspace-indent', getComputedStyle(row.element).getPropertyValue('--dsh-workspace-indent'), - ) + clone.style.paddingInlineStart = getComputedStyle(row.element).paddingInlineStart removed.set(key, { ...row, element: clone }) } return { positions, removed } @@ -170,7 +170,7 @@ export class AnimatedRows extends Component {
{ this.armed = true }} onKeyDownCapture={() => { this.armed = true }} diff --git a/packages/client/ui-primitives/src/RowDragPreview.module.css b/packages/client/ui-primitives/src/RowDragPreview.module.css new file mode 100644 index 0000000000..f16dfc1d07 --- /dev/null +++ b/packages/client/ui-primitives/src/RowDragPreview.module.css @@ -0,0 +1,12 @@ +.preview { + position: fixed; + top: 0; + pointer-events: none; +} + +.preview > :first-child { + box-sizing: border-box; + margin: 0; + width: 100%; + height: 100%; +} diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 8b09ee19cb..8ba17514ed 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -7,6 +7,9 @@ export { StateDot } from './StateDot.tsx' export type { StateDotState } from './StateDot.tsx' export { DisclosureRow } from './DisclosureRow.tsx' export type { DisclosureRowProps } from './DisclosureRow.tsx' +export { AnimatedRows } from './AnimatedRows.tsx' +export type { AnimatedRowsProps } from './AnimatedRows.tsx' +export { useRowDragPreview } from './useRowDragPreview.ts' export { TextShimmer } from './TextShimmer.tsx' export type { TextShimmerProps } from './TextShimmer.tsx' export { Button } from './Button.tsx' diff --git a/packages/client/ui-workspace/src/client/rows/useRowDragPreview.ts b/packages/client/ui-primitives/src/useRowDragPreview.ts similarity index 76% rename from packages/client/ui-workspace/src/client/rows/useRowDragPreview.ts rename to packages/client/ui-primitives/src/useRowDragPreview.ts index bf84a9e1f4..f60e4bdc93 100644 --- a/packages/client/ui-workspace/src/client/rows/useRowDragPreview.ts +++ b/packages/client/ui-primitives/src/useRowDragPreview.ts @@ -1,18 +1,22 @@ -/** Offscreen snapshots for native Workspace and Session row dragging. */ +/** Offscreen row snapshots for native browser dragging. */ import { useEffect, useMemo, useRef } from 'react' import type { DragEvent } from 'react' -import css from './Rows.module.css' +import clsx from 'clsx' +import css from './RowDragPreview.module.css' /** * Own a row's inert drag preview until drag end, replacement, or unmount. * The offscreen copy keeps WebKit snapshots separate from overlapping panels. * Its cloned slot DOM remains in document.body for that lifetime; query live rows * within their list to exclude duplicate text and element IDs. + * @param className - preview background matching the row's surface; WebKit fills + * transparent snapshot pixels white, including rounded corners. * @returns preview callbacks; cleanup reports whether this row started a drag, * even when its preview failed or the row became non-draggable before drag end. + * Start accepts the source row when a child handle owns the drag event. */ -export function useRowDragPreview(): { - start: (event: DragEvent) => void +export function useRowDragPreview(className: string): { + start: (event: DragEvent, row?: HTMLElement) => void clear: () => boolean } { const current = useRef(null) @@ -27,10 +31,9 @@ export function useRowDragPreview(): { } return { clear, - start: (event: DragEvent): void => { + start: (event: DragEvent, row = event.currentTarget): void => { clear() dragging.current = true - const row = event.currentTarget const rect = row.getBoundingClientRect() const style = getComputedStyle(row) const copy = row.cloneNode(true) as HTMLElement @@ -40,15 +43,15 @@ export function useRowDragPreview(): { 'button, a[href], input, select, textarea, [tabindex], [contenteditable]', )) control.tabIndex = -1 copy.style.color = style.color + copy.style.paddingInlineStart = style.paddingInlineStart const image = row.ownerDocument.createElement('div') - image.className = css.dragPreview as string + image.className = clsx(css.preview, className) image.inert = true image.setAttribute('aria-hidden', 'true') Object.assign(image.style, { left: `${String(-rect.width)}px`, width: `${String(rect.width)}px`, height: `${String(rect.height)}px`, font: style.font, }) - image.style.setProperty('--dsh-workspace-indent', style.getPropertyValue('--dsh-workspace-indent')) image.append(copy) row.ownerDocument.body.append(image) current.current = image @@ -61,7 +64,7 @@ export function useRowDragPreview(): { } }, } - }, []) + }, [className]) useEffect(() => () => { preview.clear() }, [preview]) return preview } diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index fdca1da3d1..53f1ab1e77 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -21,8 +21,8 @@ en: f4817eb2e3537ed9 zh: e589c193fa85473f /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: 53ce9a4847e106fe - zh: 197e020b7f137442 + en: a4ac56de00a7e59b + zh: 9b3f914dc43393c7 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: c0b04b2b11af60d3 zh: d195eec281e445cb diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index de068178b3..0a65e5a7d2 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -57,7 +57,7 @@ The collapsed 自定义设置 fold carries the curated extras: `baseURL` for bot The DeepSeek card edits the `llm-deepseek` endpoint, credentials, and model catalog. It uses Messages, with the default endpoint placeholder `https://api.deepseek.com/anthropic`. -Drag a model’s reorder handle to change its position within the provider, or focus the handle and use the up and down arrow keys. Apply saves the order; Cancel discards it. Each model keeps its settings, expanded options, and unfinished capacity text when moved. +Drag a model’s reorder handle to change its position within the provider, or focus the handle and use the up and down arrow keys. Apply saves the order; Cancel discards it. Each model keeps its settings, expanded options, and unfinished capacity text when moved. The full-row drag preview and reduced-motion-aware row animations share primitives with workspace reordering; before/after insertion markers follow the same style. Expand **Customized settings → Model options** to edit each model. Both provider families share the same row layout, labels, and icons: context window and max output tokens occupy two columns, and **Input types** occupies a separate row with **Text** and **Image** checkboxes. A row without an input declaration displays the installed model’s input types, then the provider default, then Text. Known pi-ai providers load their installed catalog without endpoint I/O; opening a row does not write an override. Explicit input selections take precedence, including text-only overrides of vision models. Checkbox edits save the selected types, with at least one type required. DeepSeek writes `inputModalities`; pi-ai writes `input`. Unchecking Image for DeepSeek also removes `imagePixelBudget` and `imageMaxBytes`, because the adapter rejects those limits without image input. Clearing the input field in `cordis.patch.yml` restores adapter inheritance; **Restore default models** resets the entire catalog override. Declare only input types the upstream model can actually process. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 3b66d8404c..a99154c6db 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -57,7 +57,7 @@ API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求 `llm-deepseek` 的 DeepSeek 卡片编辑端点、凭据和模型目录。它使用 Messages,默认端点占位符为 `https://api.deepseek.com/anthropic`。 -拖动模型的排序手柄可调整它在当前提供商内的位置,也可以聚焦手柄后使用上下方向键。保存会保留顺序,取消会放弃修改。移动时,每个模型的参数、已展开选项和未完成的容量输入都会随模型保留。 +拖动模型的排序手柄可调整它在当前提供商内的位置,也可以聚焦手柄后使用上下方向键。保存会保留顺序,取消会放弃修改。移动时,每个模型的参数、已展开选项和未完成的容量输入都会随模型保留。整行拖拽预览及遵循减少动态效果设置的行动画,与工作区排序共用基础组件;前后插入标记沿用相同样式。 展开**自定义设置 → 模型选项**编辑模型。两个提供商家族共用相同的模型行布局、标签和图标:上下文窗口与最大输出 token 数分为两列,**输入类型**独占下一行,提供**文本**和**图片**复选框。未声明输入类型的模型行优先显示已安装模型的输入类型,其次是提供商默认值,最后回退为文本。已知 pi-ai 提供商会加载已安装目录,不向端点发送请求;打开模型行不会写入覆盖值。显式输入选择具有优先权,包括为视觉模型设置的仅文本覆盖。修改复选框会保存所选类型,且至少保留一种。DeepSeek 写入 `inputModalities`,pi-ai 写入 `input`。DeepSeek 取消勾选图片时,还会移除 `imagePixelBudget` 和 `imageMaxBytes`,因为适配器在没有图片输入时拒绝这些限制。在 `cordis.patch.yml` 中清除输入字段可恢复适配器继承;**恢复默认模型**会重置整个模型目录覆盖。仅声明上游模型实际能够处理的输入类型。 diff --git a/packages/client/ui-settings-models/src/client/DeepSeekModelsEditor.tsx b/packages/client/ui-settings-models/src/client/DeepSeekModelsEditor.tsx index abe9f91499..2d9caefa01 100644 --- a/packages/client/ui-settings-models/src/client/DeepSeekModelsEditor.tsx +++ b/packages/client/ui-settings-models/src/client/DeepSeekModelsEditor.tsx @@ -6,7 +6,7 @@ */ import type { ReactNode } from 'react' -import { IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { AnimatedRows, IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { en } from './locales.ts' import { ModelRow } from './ModelRow.tsx' import { useModelRows } from './useModelRows.ts' @@ -221,10 +221,11 @@ export function DeepSeekModelsEditor(props: DeepSeekModelsEditorProps): ReactNod {props.models.length === 0 ?

{props.t('modelsEmpty')}

: ( -
+ String(row.key))} ready resetKey=""> {rowState.rows.map(({ model, key, expanded, order }, index) => ( { remove(index) }} /> ))} -
+ )}
{models.length === 0 ?

{t('modelsEmpty')}

: null} -
+ String(row.key))} ready resetKey=""> {rowState.rows.map(({ model, key, expanded, order }, index) => ( ))} -
+ + +
+} + +function fixture(handle: boolean) { + const view = render() + const button = screen.getByRole('button') + const row = button.parentElement as HTMLElement + vi.spyOn(row, 'getBoundingClientRect').mockReturnValue(new DOMRect(5, 10, 200, 40)) + const source = handle ? button : row + const dataTransfer = { setDragImage: vi.fn<(element: HTMLElement, x: number, y: number) => void>() } + const start = () => { + const event = createEvent.dragStart(source, { dataTransfer }) + Object.defineProperties(event, { clientX: { value: 20 }, clientY: { value: 30 } }) + fireEvent(source, event) + return dataTransfer.setDragImage.mock.calls.at(-1)![0] + } + return { ...view, row, source, dataTransfer, start } +} + +describe('row drag preview', () => { + it.each([false, true])('copies the whole row with handle=%s and removes replaced, ended, or unmounted previews', (handle) => { + const { row, source, dataTransfer, start, unmount } = fixture(handle) + const originalStyle = row.getAttribute('style') + const first = start() + expect(dataTransfer.setDragImage).toHaveBeenLastCalledWith(first, 15, 20) + expect(first.inert).toBe(true) + expect(first.getAttribute('aria-hidden')).toBe('true') + expect(first.className).toContain('surface') + expect(first.style.width).toBe('200px') + expect(first.style.height).toBe('40px') + expect(first.style.left).toBe('-200px') + expect(first.querySelector('[data-row-key]')).toBeNull() + expect((first.firstElementChild as HTMLElement).style.paddingInlineStart).toBe('32px') + expect(first.querySelector('input')?.value).toBe('Draft') + expect([...first.querySelectorAll('button, input')].every(control => (control as HTMLElement).tabIndex === -1)).toBe(true) + expect(row.getAttribute('style')).toBe(originalStyle) + const second = start() + expect(first.isConnected).toBe(false) + fireEvent.dragEnd(source) + expect(second.isConnected).toBe(false) + const third = start() + unmount() + expect(third.isConnected).toBe(false) + }) + + it('removes a rejected custom preview while allowing native drag cleanup', () => { + const { source, dataTransfer, start } = fixture(true) + dataTransfer.setDragImage.mockImplementation(() => { throw new DOMException('Unavailable') }) + const image = start() + expect(image.isConnected).toBe(false) + fireEvent.dragEnd(source) + }) +}) diff --git a/packages/client/ui-settings-models/src/client/DeepSeekModelsEditor.tsx b/packages/client/ui-settings-models/src/client/DeepSeekModelsEditor.tsx index 2d9caefa01..d2b98d894e 100644 --- a/packages/client/ui-settings-models/src/client/DeepSeekModelsEditor.tsx +++ b/packages/client/ui-settings-models/src/client/DeepSeekModelsEditor.tsx @@ -10,6 +10,7 @@ import { AnimatedRows, IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui import type { en } from './locales.ts' import { ModelRow } from './ModelRow.tsx' import { useModelRows } from './useModelRows.ts' +import type { CapacityField } from './useModelRows.ts' import styles from './ModelsSection.module.css' /** One catalog entry kept structurally open so hidden or future fields survive an edit. */ @@ -18,9 +19,6 @@ export type DeepSeekModelDraft = Record /** The catalog fields this editor writes. */ type CatalogField = 'id' | 'name' | 'contextWindow' | 'maxTokens' -/** The two token counts edited as K/M-suffixed text behind a row's disclosure. */ -type CapacityField = 'contextWindow' | 'maxTokens' - /** Accepted capacity spellings: a decimal count with an optional K/M suffix. */ const CAPACITY_PATTERN = /^(\d+(?:\.\d+)?)([km])?$/i @@ -218,35 +216,32 @@ export function DeepSeekModelsEditor(props: DeepSeekModelsEditorProps): ReactNod ) : null}
- {props.models.length === 0 - ?

{props.t('modelsEmpty')}

- : ( - String(row.key))} ready resetKey=""> - {rowState.rows.map(({ model, key, expanded, order }, index) => ( - { update(index, field, value) }} - onIdBlur={(value) => { - const trimmed = value.trim() - if (trimmed !== value) update(index, 'id', trimmed) - }} - onChange={(next) => { props.onChange(props.models.map((row, at) => at === index ? next : row)) }} - onToggle={() => { rowState.toggle(index) }} - onRemove={() => { remove(index) }} - /> - ))} - - )} + String(row.key))} ready resetKey=""> + {props.models.length === 0 ?

{props.t('modelsEmpty')}

: null} + {rowState.rows.map(({ model, key, expanded, order }, index) => ( + { update(index, field, value) }} + onIdBlur={(value) => { + const trimmed = value.trim() + if (trimmed !== value) update(index, 'id', trimmed) + }} + onChange={(next) => { props.onChange(props.models.map((row, at) => at === index ? next : row)) }} + onToggle={() => { rowState.toggle(index) }} + onRemove={() => { remove(index) }} + /> + ))} +
)} - {showBubble &&
+ {showBubble && {renderFactorySlot('conversation.user.text', { text, facts, interactive, ellipsis })} {extraBlocks.map((block, index) => ( ))} -
} + } {referenceLabels.length > 0 && (
{t('message.referenceSummary', { labels: referenceLabels.join(t('message.referenceSeparator')) })} diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 9a13d1d0a6..563aaa4111 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,8 +18,8 @@ en: d2f5701274be5110 zh: d60e2617136a6f26 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: cb874a0ca53a6747 - zh: 31179193dd1d6e12 + en: f6a957182c4756c1 + zh: 0c49c47b4dc3daa8 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: en: fff68b60f4abdc7e zh: 5cf5952ec78f7f91 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index ecd3fd4e29..66dadbe369 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -67,6 +67,8 @@ Check this table before writing a control in a feature package. A plugin cannot | `JsonTree`, `JsonBlock` | Read-only JSON inspection. | | `MarkdownText`, `MarkdownDelegateProvider`, `CodeBlock` | Untrusted GFM with TeX math, owner-delegated HTTP(S) navigation, and highlighted code. `CodeBlock` accepts opt-in `lineNumbers`; copied source excludes the gutter, and `contentRef` exposes its stable source wrapper to an owner that uses it as a scrollport. Set `showHeader={false}` when the owner supplies its own language and copy toolbar. | | `DetailDocument`, `detailDocumentState`, `useDetailDocumentLabels` | Section without a heading of its own for a long Markdown description, such as a plugin's detail document: three skeleton lines while loading, the document, the owner's failure message with a retry, or nothing when there is no document. A document taller than `min(560px, 60vh)` scrolls inside a keyboard-focusable region that the owner's title names. Raw HTML in the document is omitted. Relative links stay text and only images the owner's `images` resolver accepts, or absolute HTTP(S) images, load. `detailDocumentState` maps an owner's read to the shown state, and `useDetailDocumentLabels` builds reference-stable labels from translated strings. | +| `useClipboardCopy` | Copies the current text with one-second success feedback, prevents overlapping or success-window repeats, and cancels its reset timer on unmount; late write completion cannot update an unmounted control. | +| `UserMessageBubble` | User-message background, radius, content inset, typography, and plain-text wrapping. Accepts native div props; callers own row alignment, width, content, and actions. | | `UserTextRun`, `ReferenceChip` | Uninterpreted inline text and business-resolved reference labels or activation buttons. | | `CommandText` | Selectable command or argument text; only horizontal overflow adds a named keyboard focus target. | | `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, `WebBlock` | The agent-output card matching each tool-result intent. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 3de121ab2c..5737246b45 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -67,6 +67,8 @@ kind: "package-library" | `JsonTree`、`JsonBlock` | 只读 JSON 查看。 | | `MarkdownText`、`MarkdownDelegateProvider`、`CodeBlock` | 不可信 GFM 与 TeX 数学、owner 委托的 HTTP(S) 导航,以及高亮代码。`CodeBlock` 可通过 `lineNumbers` 开启行号;复制的源码不含行号栏,`contentRef` 则向需要把稳定源码包装节点用作滚动区的 owner 提供该节点。调用方提供自己的语言与复制工具栏时,设置 `showHeader={false}`。 | | `DetailDocument`、`detailDocumentState`、`useDetailDocumentLabels` | 用于较长 Markdown 描述(例如插件的详细介绍文档)的区块,本身不带标题:加载期间显示三行骨架屏,随后显示文档、owner 提供的失败消息和重试,或在没有文档时不显示任何内容。文档高度超过 `min(560px, 60vh)` 时,在可通过键盘聚焦、由 owner 的标题命名的区域内滚动。文档中的原始 HTML 会被省略。相对链接保持为文本,只加载 owner 的 `images` 解析器接受的图片或绝对 HTTP(S) 地址的图片。`detailDocumentState` 把 owner 的读取结果映射为显示状态,`useDetailDocumentLabels` 根据翻译后的字符串构建引用稳定的标签。 | +| `useClipboardCopy` | 复制当前文本并显示一秒成功反馈,阻止写入期间及成功反馈期间的重复操作,卸载时清除重置计时器;迟到的写入结果不会更新已卸载控件。 | +| `UserMessageBubble` | 用户消息的背景、圆角、内容内边距、字体与纯文本换行规则。接收原生 div props;行对齐、宽度、内容和操作由调用方拥有。 | | `UserTextRun`、`ReferenceChip` | 不做解析的行内文本,以及业务已解析的引用标签或激活按钮。 | | `CommandText` | 可选中的命令或参数文本;仅横向溢出时添加具名的键盘聚焦目标。 | | `TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock`、`WebBlock` | 与各类工具结果意图对应的 agent 输出卡片。 | diff --git a/packages/client/ui-primitives/src/SearchBlock.tsx b/packages/client/ui-primitives/src/SearchBlock.tsx index c2328d6a9d..a8a02a651f 100644 --- a/packages/client/ui-primitives/src/SearchBlock.tsx +++ b/packages/client/ui-primitives/src/SearchBlock.tsx @@ -1,7 +1,7 @@ import { useCallback, useState, type ReactNode } from 'react' import clsx from 'clsx' import { headTailCap } from './head-tail-cap.ts' -import { useCopyFeedback } from './use-copy-feedback.ts' +import { useClipboardCopy } from './use-clipboard-copy.ts' import css from './SearchBlock.module.css' /** @@ -184,7 +184,7 @@ export function SearchBlock(props: SearchBlockProps) { const rows = toRows(props, collapsed) const shown = shownCount(props) const empty = rows.length === 0 - const { copied, onCopy } = useCopyFeedback(copyText(props)) + const { copied, onCopy } = useClipboardCopy(copyText(props)) const onToggle = useCallback(() => { setExpanded(value => !value) }, []) diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx index 19c5c3296e..15f5ed1781 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.tsx +++ b/packages/client/ui-primitives/src/TerminalBlock.tsx @@ -2,7 +2,7 @@ import { useCallback, useMemo, useState } from 'react' import clsx from 'clsx' import { parseAnsiLines, type AnsiLine } from './ansi.ts' import { headTailCap } from './head-tail-cap.ts' -import { useCopyFeedback } from './use-copy-feedback.ts' +import { useClipboardCopy } from './use-clipboard-copy.ts' import { Pill } from './Pill.tsx' import { StateDot, type StateDotState } from './StateDot.tsx' import css from './TerminalBlock.module.css' @@ -204,7 +204,7 @@ export function TerminalBlock({ const [expanded, setExpanded] = useState(false) // The raw output (or the caller's override), never the rendered tree: the // prompt line and the status pill are chrome the user did not run. - const { copied, onCopy } = useCopyFeedback(copyText ?? text) + const { copied, onCopy } = useClipboardCopy(copyText ?? text) const onToggle = useCallback(() => { setExpanded(value => !value) }, []) diff --git a/packages/client/ui-primitives/src/UserMessageBubble.module.css b/packages/client/ui-primitives/src/UserMessageBubble.module.css new file mode 100644 index 0000000000..b004e22374 --- /dev/null +++ b/packages/client/ui-primitives/src/UserMessageBubble.module.css @@ -0,0 +1,11 @@ +.bubble { + max-width: 100%; + background: var(--dsw-specific-bubble); + border-radius: var(--dsw-radius-xl); + padding: 10px 16px; + font-size: var(--dsh-content-font-size, 14px); + line-height: calc(22px + var(--dsh-content-font-delta, 0px)); + color: var(--dsw-alias-label-primary); + white-space: pre-wrap; + word-break: break-word; +} diff --git a/packages/client/ui-primitives/src/UserMessageBubble.tsx b/packages/client/ui-primitives/src/UserMessageBubble.tsx new file mode 100644 index 0000000000..dc9f89bf88 --- /dev/null +++ b/packages/client/ui-primitives/src/UserMessageBubble.tsx @@ -0,0 +1,16 @@ +/** Shared user-message background, typography, and content inset. */ +import type { ComponentPropsWithoutRef } from 'react' +import clsx from 'clsx' +import css from './UserMessageBubble.module.css' + +/** Native div attributes for user-authored message content. */ +export type UserMessageBubbleProps = ComponentPropsWithoutRef<'div'> + +/** + * Render user-style message content without row placement or actions. + * @param props - Native div attributes and the caller-owned content. + * @returns A theme-aware message surface that wraps its content. + */ +export function UserMessageBubble({ className, ...props }: UserMessageBubbleProps) { + return
+} diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 8b09ee19cb..8a93f5e747 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -3,6 +3,8 @@ */ export type { CodeToolbarLabels } from './CodeToolbar.tsx' +export { UserMessageBubble } from './UserMessageBubble.tsx' +export type { UserMessageBubbleProps } from './UserMessageBubble.tsx' export { StateDot } from './StateDot.tsx' export type { StateDotState } from './StateDot.tsx' export { DisclosureRow } from './DisclosureRow.tsx' @@ -67,6 +69,8 @@ export { pointerModality } from './input-modality.ts' export { Toast } from './Toast.tsx' export { fileSizeText } from './file-size.ts' export { writeClipboard } from './clipboard.ts' +export { useClipboardCopy } from './use-clipboard-copy.ts' +export type { ClipboardCopyState } from './use-clipboard-copy.ts' export { SettingsForm } from './settings-form/SettingsForm.tsx' export type { SettingsFormLabels, SettingsFormProps } from './settings-form/SettingsForm.tsx' export { SettingsSecretField, SettingsValueField } from './settings-form/fields.tsx' diff --git a/packages/client/ui-primitives/src/use-clipboard-copy.ts b/packages/client/ui-primitives/src/use-clipboard-copy.ts new file mode 100644 index 0000000000..8dc2f8331d --- /dev/null +++ b/packages/client/ui-primitives/src/use-clipboard-copy.ts @@ -0,0 +1,44 @@ +/** Clipboard writes with component-owned success feedback and cleanup. */ +import { useCallback, useEffect, useRef, useState } from 'react' +import { writeClipboard } from './clipboard.ts' + +/** Clipboard action and its temporary success state. */ +export interface ClipboardCopyState { + /** True for one second after an accepted clipboard write. */ + readonly copied: boolean + /** Write the current text unless a write or success indication is already active. */ + readonly onCopy: () => void +} + +/** + * Keep clipboard feedback local to the mounted control and release its reset timer on unmount. + * @param text - Exact text to copy when the action is invoked. + * @returns Success feedback and a callback stable while text and feedback are unchanged. + */ +export function useClipboardCopy(text: string): ClipboardCopyState { + const [copied, setCopied] = useState(false) + const copyPending = useRef(false) + const copyTimer = useRef | null>(null) + const copyEpoch = useRef(0) + useEffect(() => () => { + copyEpoch.current += 1 + copyPending.current = false + if (copyTimer.current !== null) clearTimeout(copyTimer.current) + }, []) + const onCopy = useCallback(() => { + if (copied || copyPending.current) return + const epoch = copyEpoch.current + copyPending.current = true + void writeClipboard(text).then((ok) => { + if (epoch !== copyEpoch.current) return + copyPending.current = false + if (!ok) return + setCopied(true) + copyTimer.current = window.setTimeout(() => { + copyTimer.current = null + setCopied(false) + }, 1000) + }) + }, [copied, text]) + return { copied, onCopy } +} diff --git a/packages/client/ui-primitives/src/use-copy-feedback.ts b/packages/client/ui-primitives/src/use-copy-feedback.ts deleted file mode 100644 index 73c8581206..0000000000 --- a/packages/client/ui-primitives/src/use-copy-feedback.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { useCallback, useState } from 'react' -import { writeClipboard } from './clipboard.ts' - -/** How long the `copied` flag stays true after a successful write, in ms. */ -const COPIED_FEEDBACK_MS = 1000 - -/** The copy-feedback hook's return: the transient flag and the copy handler. */ -export interface CopyFeedback { - /** True for {@link COPIED_FEEDBACK_MS} after a successful write; render the success label off it. */ - copied: boolean - /** Copy the hook's text; no-op while `copied` is still true, silent on a refused write. */ - onCopy: () => void -} - -/** - * Copy `text` to the clipboard with one-second success feedback. - * @param text - the text to write on copy. - * @returns the `copied` flag and the `onCopy` handler. - */ -export function useCopyFeedback(text: string): CopyFeedback { - const [copied, setCopied] = useState(false) - const onCopy = useCallback(() => { - if (copied) return - void writeClipboard(text).then((ok) => { - if (!ok) return - setCopied(true) - window.setTimeout(() => { setCopied(false) }, COPIED_FEEDBACK_MS) - }) - }, [copied, text]) - return { copied, onCopy } -} diff --git a/packages/client/ui-primitives/tests/UserMessageBubble.client.spec.tsx b/packages/client/ui-primitives/tests/UserMessageBubble.client.spec.tsx new file mode 100644 index 0000000000..496dec28b3 --- /dev/null +++ b/packages/client/ui-primitives/tests/UserMessageBubble.client.spec.tsx @@ -0,0 +1,24 @@ +// @vitest-environment jsdom +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it } from 'vitest' +import { UserMessageBubble } from '../src/UserMessageBubble.tsx' + +afterEach(cleanup) + +describe('UserMessageBubble', () => { + it('preserves caller content, attributes, and layout class', () => { + render( +
Which color?
Blue
+
) + const surface = screen.getByRole('group', { name: 'answer' }) + expect(surface.classList.contains('owner-layout')).toBe(true) + expect(screen.getByText('Which color?').tagName).toBe('DT') + expect(screen.getByText('Blue').tagName).toBe('DD') + }) + + it('renders a plain surface without additional interaction', () => { + render(Plain user text) + expect(screen.getByText('Plain user text').tagName).toBe('DIV') + expect(screen.queryByRole('button')).toBeNull() + }) +}) diff --git a/packages/client/ui-primitives/tests/useClipboardCopy.client.spec.tsx b/packages/client/ui-primitives/tests/useClipboardCopy.client.spec.tsx new file mode 100644 index 0000000000..470ca1342e --- /dev/null +++ b/packages/client/ui-primitives/tests/useClipboardCopy.client.spec.tsx @@ -0,0 +1,80 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useClipboardCopy } from '../src/use-clipboard-copy.ts' + +const originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard') +const writeText = vi.fn<(text: string) => Promise>() +beforeEach(() => { + vi.useFakeTimers() + writeText.mockReset().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) +}) +afterEach(() => { + cleanup() + vi.useRealTimers() + if (originalClipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard') + else Object.defineProperty(navigator, 'clipboard', originalClipboard) +}) + +/** Complete the clipboard promise and its success feedback callback. */ +async function settleCopy(): Promise { + await act(async () => { await Promise.resolve(); await Promise.resolve() }) +} + +describe('useClipboardCopy', () => { + it('copies current text, blocks success-window repeats, and resets after one second', async () => { + const { result, rerender } = renderHook(({ text }) => useClipboardCopy(text), { initialProps: { text: 'first' } }) + const callback = result.current.onCopy + rerender({ text: 'first' }) + expect(result.current.onCopy).toBe(callback) + act(() => { result.current.onCopy() }) + expect(writeText).toHaveBeenCalledWith('first') + await settleCopy() + expect(result.current.copied).toBe(true) + act(() => { result.current.onCopy() }) + expect(writeText).toHaveBeenCalledTimes(1) + act(() => { vi.advanceTimersByTime(1000) }) + expect(result.current.copied).toBe(false) + expect(vi.getTimerCount()).toBe(0) + rerender({ text: 'second' }) + act(() => { result.current.onCopy() }) + expect(writeText).toHaveBeenLastCalledWith('second') + await settleCopy() + }) + + it('blocks overlapping writes and ignores completion after unmount', async () => { + let finish: (() => void) | undefined + writeText.mockImplementation(() => new Promise((resolve) => { finish = resolve })) + const { result, unmount } = renderHook(() => useClipboardCopy('pending')) + act(() => { result.current.onCopy(); result.current.onCopy() }) + expect(writeText).toHaveBeenCalledTimes(1) + expect(result.current.copied).toBe(false) + unmount() + finish!() + await settleCopy() + expect(vi.getTimerCount()).toBe(0) + }) + + it('keeps failure unconfirmed and allows another attempt', async () => { + writeText.mockRejectedValueOnce(new Error('denied')) + const { result } = renderHook(() => useClipboardCopy('retry')) + act(() => { result.current.onCopy() }) + await settleCopy() + expect(result.current.copied).toBe(false) + expect(vi.getTimerCount()).toBe(0) + act(() => { result.current.onCopy() }) + await settleCopy() + expect(writeText).toHaveBeenCalledTimes(2) + expect(result.current.copied).toBe(true) + }) + + it('releases its success reset timer on unmount', async () => { + const { result, unmount } = renderHook(() => useClipboardCopy('done')) + act(() => { result.current.onCopy() }) + await settleCopy() + expect(vi.getTimerCount()).toBe(1) + unmount() + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/packages/client/ui-user-questions/README.i18n.yaml b/packages/client/ui-user-questions/README.i18n.yaml index a307a1361c..ae89cb24b4 100644 --- a/packages/client/ui-user-questions/README.i18n.yaml +++ b/packages/client/ui-user-questions/README.i18n.yaml @@ -21,14 +21,14 @@ en: 8900fbf9cbd72083 zh: 67a951d58a029a58 /deepseek-ai-dsh-client-ui-user-questions/use-this-package/reading-a-settled-question-back: - en: 10975f68ff9c6fcc - zh: 92246aadc363f0eb + en: d51f61aec8981c28 + zh: 9973db6ce3fe6b72 /deepseek-ai-dsh-client-ui-user-questions/use-this-package/the-plan-review-card: en: 6b12f1362c614a39 zh: 27d9cf54d4cbd5d2 /deepseek-ai-dsh-client-ui-user-questions/use-this-package/failure-and-recovery: - en: 3ad0e0fd224aabfc - zh: db15f400e6f2bfd7 + en: d4f1dee7e7ff1d15 + zh: 6fb56ad50ca6851c /deepseek-ai-dsh-client-ui-user-questions/understand-the-implementation: en: 77e1b2585acdf67b zh: d433ec185c6b8f57 diff --git a/packages/client/ui-user-questions/README.md b/packages/client/ui-user-questions/README.md index a637ac1251..205b8732b4 100644 --- a/packages/client/ui-user-questions/README.md +++ b/packages/client/ui-user-questions/README.md @@ -35,7 +35,7 @@ Fixed approval questions use the same pending-question and answer channel. A fea ### Reading a settled question back -Each late reply is shown once, including when it opens a new Turn. Replies follow normal Chat process grouping and whole-Turn folding. Expand the containing Turn and work group to read a reply that has been folded away. +Each answered batch appears once in a right-aligned user-style bubble after its answer is recorded, for native and PTC blocking questions and late replies. The bubble shows every question above its selected choices and custom answer, uses lighter question text, and stays visible when process groups or the containing Turn are folded. A blocking-question answer bubble does not prevent completed work steps from collapsing. Late replies admitted after the opening step are interleaved Turn inputs and keep that Turn open. Each bubble separates the process runs before and after its recorded answer. Unanswered questions remain in the question card and tool row. A question that already settled opens as a read-only card: the same pager over the recorded answers, marked `Answered`. Every option and text field is disabled, Skip and the submit action are gone, a question the user skipped says so in place of its empty answer, and a free-text field appears only where the recorded answer used one. Closing it removes the card, and the tool call row builds another from the same record. @@ -57,7 +57,7 @@ Each Session and pending request has an independent draft in browser storage. A A browser that reconnects while the tool call is open receives the pending request again and can still complete it with the remaining time. A Session reopened after the agent or process ended shows the card as continued; submitting resumes the Session's root agent and enters the answer as a new user turn. -Settled question replies remain compact in chat history. A caret marks the bubble as a disclosure; clicking it reopens the read-only question and answer details, and never reopens the settled tool call for a second submission. Its copy action writes each question with the answer the user gave, the same text whether the bubble is open or closed. +The settled bubble is fully visible and has no disclosure control. Question and answer text renders as plain text; question detail and unselected options are omitted. Its copy action writes each question with the answer the user gave, without reopening the tool call or submitting another answer. ----- diff --git a/packages/client/ui-user-questions/README.zh.md b/packages/client/ui-user-questions/README.zh.md index 85a4cc8902..122b6e9c26 100644 --- a/packages/client/ui-user-questions/README.zh.md +++ b/packages/client/ui-user-questions/README.zh.md @@ -35,7 +35,7 @@ Web 客户端在聊天输入框旁显示 agent(智能体)的提问。用户 ### 回看已结束的问题 -每条迟到回复只显示一次,包括由它开启新轮次的情况。回复遵循 Chat 原有的过程分组与整轮折叠规则。回复被收起时,展开所属轮次和工作分组即可查看。 +原生工具调用、PTC 子调用的阻塞提问和迟到回复都会在回答记录后,将每批问答显示为一个右对齐的用户样式气泡,且只显示一次。气泡逐题显示问题及其已选选项、自定义回答,问题文字使用较浅颜色;过程分组或所属轮次收起后,气泡仍保持可见。普通阻塞提问的回答气泡不阻止已完成的工作步骤收起。首个步骤之后获准进入的迟到回复属于轮次中的交错输入,会使该轮次保持展开。每个气泡会分隔回答记录前后的过程分组。未回答的问题仍由提问卡片和工具调用行承载。 已经结束的问题以只读卡片打开:同一个翻页器走过已记录的回答,并标注「已回答」。所有选项与文本框都被禁用,跳过与提交动作消失,用户当时跳过的问题会在空回答处说明这一点,自由文本框只出现在当时确实用过它的回答上。关闭它会移除该卡片,工具调用行会用同一份记录再建一个。 @@ -57,7 +57,7 @@ Web 客户端在聊天输入框旁显示 agent(智能体)的提问。用户 工具调用开放期间重新连接的浏览器会再次收到挂起请求,仍可用剩余时间完成它。在 agent 或进程结束后重新打开的会话把卡片显示为已继续;提交时先恢复会话的根 agent,再把回答作为新的用户轮次送入。 -已结算的问题回复在聊天历史中保持紧凑。气泡以三角标记指示可以展开;点击它会展开只读的问题与回答详情,且不会重新打开已经结算的工具调用,也不会产生第二次提交。它的复制动作写出每个问题与用户当时给出的回答,无论气泡展开还是收起都是同一份文本。 +已结算的气泡完整显示内容,不提供展开控件。问题和回答以纯文本呈现,不显示问题说明及未选选项。复制操作写出每个问题与用户当时给出的回答,不会重新打开工具调用,也不会再次提交回答。 ----- diff --git a/packages/client/ui-user-questions/package.json b/packages/client/ui-user-questions/package.json index 6f9c2bf77b..977b1544e2 100644 --- a/packages/client/ui-user-questions/package.json +++ b/packages/client/ui-user-questions/package.json @@ -72,7 +72,8 @@ "clsx": "^2.0.0", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", - "@deepseek-ai/dsh-client-ui-tool": "workspace:*" + "@deepseek-ai/dsh-client-ui-tool": "workspace:*", + "@deepseek-ai/dsh-tool-executor-ptc": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-user-questions/src/client/QuestionReplyView.module.css b/packages/client/ui-user-questions/src/client/QuestionReplyView.module.css index f29c727c62..5abe124469 100644 --- a/packages/client/ui-user-questions/src/client/QuestionReplyView.module.css +++ b/packages/client/ui-user-questions/src/client/QuestionReplyView.module.css @@ -1,128 +1,41 @@ .row { display: flex; flex-direction: column; - justify-content: flex-end; align-items: flex-end; gap: 6px; - padding: 4px 0; +} + +.bubbleWidth { + max-width: min(calc(var(--dsh-chat-content-width, 748px) * 0.702), 82%); + min-width: 0; } .bubble { - max-width: 72%; - padding: 10px 16px; - border-radius: var(--dsw-radius-xl); - background: var(--dsw-specific-bubble); - color: var(--dsw-alias-label-primary); - cursor: pointer; - font-size: var(--dsh-content-font-size, 14px); - line-height: calc(22px + var(--dsh-content-font-delta, 0px)); text-align: left; overflow-wrap: anywhere; - white-space: pre-wrap; -} - -.toggle { - width: 100%; - padding: 0; - border: 0; - background: transparent; - color: inherit; - cursor: pointer; - font: inherit; - text-align: left; -} - -.toggle:focus-visible { - outline: 2px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - outline-offset: 2px; -} - -.bubble:has(.toggle:focus-visible) { - box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); -} - -.labelRow { - display: flex; - align-items: center; - gap: 3px; -} - -.caret { - display: inline-flex; - color: var(--dsw-alias-label-secondary); -} - -.caret svg { - width: 12px; - height: 12px; -} - -.label { - color: var(--dsw-alias-label-secondary); - display: block; - font-size: var(--dsh-content-font-size-secondary, 13px); - line-height: calc(18px + var(--dsh-content-font-delta-secondary, 0px)); -} - -.summary { - display: block; - margin-top: 3px; - color: var(--dsw-alias-label-primary); - font-size: var(--dsh-content-font-size, 14px); -} - -.text { - margin: 8px 0 0; } +.text, .details { - margin: 8px 0 0; - padding-top: 8px; - border-top: 1px solid color-mix(in srgb, var(--dsw-alias-label-secondary) 24%, transparent); + margin: 0; } .details > div + div { margin-top: 12px; } -.details dt { - color: var(--dsw-alias-label-secondary); - font-size: 12px; -} - .question { display: grid; gap: 3px; -} - -.header, -.detail, -.options { color: var(--dsw-alias-label-secondary); - font-size: 11px; } -.questionText { - color: var(--dsw-alias-label-primary); -} - -.options { - margin: 0; - padding-left: 16px; -} - -.details dd { - margin: 4px 0 0; +.header { + font-size: var(--dsh-content-font-size-secondary, 13px); } .answer { - font-size: 14px; -} - -.answerLabel { - margin-right: 4px; - color: var(--dsw-alias-label-secondary); - font-size: 12px; + margin: 4px 0 0; } .actions { diff --git a/packages/client/ui-user-questions/src/client/QuestionReplyView.tsx b/packages/client/ui-user-questions/src/client/QuestionReplyView.tsx index 8cd59f5b4d..9c1680cb83 100644 --- a/packages/client/ui-user-questions/src/client/QuestionReplyView.tsx +++ b/packages/client/ui-user-questions/src/client/QuestionReplyView.tsx @@ -1,9 +1,9 @@ -import { memo, useCallback, useState } from 'react' +/** Settled question batches rendered with the shared user-message surface. */ +import { memo } from 'react' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import { - IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, - IconCopyOutlineRegular, Tooltip, writeClipboard, + IconCheckOutlineRegular, IconCopyOutlineRegular, Tooltip, UserMessageBubble, useClipboardCopy, } from '@deepseek-ai/dsh-client-ui-primitives' import type { QuestionReplyData } from './question-reply.ts' import { replyAnswerValues, replyClipboardText } from './question-reply.ts' @@ -13,82 +13,39 @@ type QuestionReplyViewProps = PropsRuntime<'conversation.chat.node', 'question-reply'> & PropsLocale<'question'> -/** - * Right-aligned late-reply bubble: a label naming the earlier pending - * questions, then one question and answer pair per question. A payload the - * Client cannot read falls back to the model-facing text. - */ +/** Render recorded questions and answers without an expandable process row. */ export const QuestionReplyView = memo(function QuestionReplyView({ node, t }: QuestionReplyViewProps) { return }) /** - * Render one settled question reply as a compact transcript bubble. + * Render one answered batch with questions above their corresponding answers. * @param props - Reply data and the question locale translator. - * @returns The expandable reply bubble. + * @returns The right-aligned, fully visible question-and-answer bubble. */ export function QuestionReplyBubble({ data, t }: { data: QuestionReplyData; t: PropsLocale<'question'>['t'] }) { - const label = t('reply.label') - const [open, setOpen] = useState(false) - const toggleLabel = t(open ? 'reply.close' : 'reply.open') - const summary = data.questions.map(question => replyAnswerValues(data, question.id)).flat().join(', ') const copyText = replyClipboardText(data, t) - const [copied, setCopied] = useState(false) - const onCopy = useCallback(() => { - if (copied) return - void writeClipboard(copyText).then((ok) => { - if (!ok) return - setCopied(true) - window.setTimeout(() => { setCopied(false) }, 1000) - }) - }, [copied, copyText]) + const { copied, onCopy } = useClipboardCopy(copyText) return ( -
-
- - {open && (data.questions.length === 0 - ?

{data.text}

- : ( -
+
+
+ + {data.questions.length === 0 + ?

{data.text}

+ :
{data.questions.map((question) => { const values = replyAnswerValues(data, question.id) - return ( -
-
- {question.header && question.header !== question.question && {question.header}} - {question.question} - {question.detail && {question.detail}} - {question.options && question.options.length > 0 && ( -
    - {question.options.map(option =>
  • {option.label}{option.description && ` — ${option.description}`}
  • )} -
- )} -
-
- {t('reply.answerLabel')} - {values.length === 0 ? t('reply.skipped') : values.join(', ')} -
-
- ) + return
+
+ {question.header && question.header !== question.question && {question.header}} + {question.question} +
+
{values.length === 0 ? t('reply.skipped') : values.join(', ')}
+
})} -
- ))} +
} +
diff --git a/packages/client/ui-user-questions/src/client/index.ts b/packages/client/ui-user-questions/src/client/index.ts index 2d04df1b4b..618cb599af 100644 --- a/packages/client/ui-user-questions/src/client/index.ts +++ b/packages/client/ui-user-questions/src/client/index.ts @@ -28,7 +28,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import { createWaterfallRequest, PendingQuestion, type QuestionRpcChannel } from './contract/slots.ts' import { createQuestionDraftStore } from './draft-store.ts' import { QuestionComposer } from './QuestionComposer.tsx' -import { questionReplyDefinition } from './question-reply.ts' +import { answeredQuestionDefinition, questionReplyDefinition } from './question-reply.ts' import { QuestionReplyView } from './QuestionReplyView.tsx' import { en, ja, zh, type QuestionKey } from './locales.ts' @@ -392,6 +392,7 @@ export function apply(ctx: ClientContext): void { QuestionComposer, )) ctx.uiConversation.events.register(questionReplyDefinition) + ctx.uiConversation.events.register(answeredQuestionDefinition) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({ name: 'conversation.chat.node', key: 'question-reply', diff --git a/packages/client/ui-user-questions/src/client/locales.ts b/packages/client/ui-user-questions/src/client/locales.ts index 83ec122186..719e4ecd0b 100644 --- a/packages/client/ui-user-questions/src/client/locales.ts +++ b/packages/client/ui-user-questions/src/client/locales.ts @@ -14,9 +14,7 @@ export const zh = { 'wait.continued': '已继续工作,仍可回答', 'review.status': '已回答', 'review.skipped': '这道问题当时被跳过。', - 'reply.label': '回答先前等待中的问题', - 'reply.open': '展开问题详情', - 'reply.close': '收起问题详情', + 'reply.label': '问题与回答', 'reply.answerLabel': '回答:', 'reply.skipped': '已跳过', 'nav.prev': '上一题', @@ -54,9 +52,7 @@ export const en = { 'wait.continued': 'Work continued — you can still answer', 'review.status': 'Answered', 'review.skipped': 'This question was skipped.', - 'reply.label': 'Reply to earlier pending questions', - 'reply.open': 'Open question details', - 'reply.close': 'Close question details', + 'reply.label': 'Questions and answers', 'reply.answerLabel': 'Answer: ', 'reply.skipped': 'Skipped', 'nav.prev': 'Previous question', @@ -91,9 +87,7 @@ export const ja = { 'wait.continued': '作業は続行されました — まだ回答できます', 'review.status': '回答済み', 'review.skipped': 'この質問はスキップされました。', - 'reply.label': '以前の保留中の質問に返信', - 'reply.open': '質問の詳細を開く', - 'reply.close': '質問の詳細を閉じる', + 'reply.label': '質問と回答', 'reply.answerLabel': '回答: ', 'reply.skipped': 'スキップ済み', 'nav.prev': '前の質問', diff --git a/packages/client/ui-user-questions/src/client/question-reply.ts b/packages/client/ui-user-questions/src/client/question-reply.ts index 68973b32df..8af46e8036 100644 --- a/packages/client/ui-user-questions/src/client/question-reply.ts +++ b/packages/client/ui-user-questions/src/client/question-reply.ts @@ -1,19 +1,17 @@ -/** Late-reply conversation node: the steered `user-question-reply` message projected as question and answer pairs. */ +/** Answered-question Chat data from in-time tool results and late human replies. */ import type {} from '@deepseek-ai/dsh-client-ui-chat/client' -import type { ConversationNodeDefinition } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { ConversationLocation, ConversationNodeDefinition } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import { isAppendSurfaceEvent } from '@deepseek-ai/dsh-session/surface' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-user-questions/types' +import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types' /** One asked question as echoed in the reply payload. */ export interface QuestionReplyQuestion { readonly id: string readonly question: string - readonly detail?: string readonly header?: string - readonly options?: readonly { readonly label: string; readonly description?: string }[] - readonly multiSelect?: boolean } /** One structured answer as echoed in the reply payload. */ @@ -23,10 +21,10 @@ export interface QuestionReplyAnswer { readonly custom?: string } -/** Presentation data of one late reply. */ +/** Presentation data of one submitted answer batch. */ export interface QuestionReplyData { readonly callId: string - /** A late answer to the pending questions. */ + /** A submitted answer batch, including individually skipped questions. */ readonly outcome: 'answered' readonly questions: readonly QuestionReplyQuestion[] readonly answers: readonly QuestionReplyAnswer[] @@ -37,7 +35,7 @@ export interface QuestionReplyData { declare module '@deepseek-ai/dsh-client-ui-chat/client' { interface ChatNodeDataMap { - /** Late answer to a continued question. */ + /** One answered question batch, regardless of foreground wait timing. */ 'question-reply': QuestionReplyData } } @@ -73,15 +71,7 @@ export function replyPairsOf(text: string): Pick { - if (!isRecord(option) || typeof option.label !== 'string') return [] - return [{ label: option.label, ...(typeof option.description === 'string' ? { description: option.description } : {}) }] - }) } - : {}), - ...(typeof question.multiSelect === 'boolean' ? { multiSelect: question.multiSelect } : {}), }) } const answers: QuestionReplyAnswer[] = [] @@ -110,9 +100,8 @@ export function replyAnswerValues(data: QuestionReplyData, id: string): string[] } /** - * Clipboard text of one late reply: every question with the answer the user - * gave, in the layout the open bubble shows, without the options nobody chose. - * The text does not depend on whether the bubble is open. + * Clipboard text of one answer batch: every question with the answer the user + * gave, without question details or unselected options. * @param data - Projected reply to copy. * @param t - Bound `question` namespace translator owning the answer labels. * @returns One block per question, or the model-facing text when the payload was unreadable. @@ -142,6 +131,115 @@ function replySource( : null } +/** Reply data retained until a matching tool result records a complete answer batch. */ +interface AnsweredQuestionState { + readonly questions: readonly QuestionReplyQuestion[] | null + readonly reply: QuestionReplyState | undefined +} + +function jsonRecord(text: string): Record | null { + try { + const value: unknown = JSON.parse(text) + return isRecord(value) ? value : null + } catch (error) { + // Malformed tool JSON remains visible through the generic Tool node. + void error + return null + } +} + +function callQuestions(value: unknown): readonly QuestionReplyQuestion[] | null { + if (!isRecord(value) || !Array.isArray(value.questions) || value.questions.length === 0) return null + const ids = new Set() + const questions: QuestionReplyQuestion[] = [] + for (const question of value.questions) { + if (!isRecord(question) || typeof question.id !== 'string' || typeof question.question !== 'string' + || ids.has(question.id) || (isRecord(question.intent) && question.intent.kind === 'plan-review')) return null + ids.add(question.id) + questions.push({ + id: question.id, + question: question.question, + ...(typeof question.header === 'string' ? { header: question.header } : {}), + }) + } + return questions +} + +function resultReply( + questions: readonly QuestionReplyQuestion[], + event: SessionEvent<'tool/result' | 'tool/ptc-dispatch'>, +): QuestionReplyState | undefined { + const result = event.type === 'tool/result' ? event.data.message : event.data + if (result.isError === true) return undefined + const content = result.content + if (content.length !== 1 || content[0]?.type !== 'text') return undefined + const text = content[0].text + const value = jsonRecord(text) + if (value === null || value.pending === true || !Array.isArray(value.answers) + || value.answers.length !== questions.length) return undefined + const ids = new Set(questions.map(question => question.id)) + const answers: QuestionReplyAnswer[] = [] + for (const answer of value.answers) { + if (!isRecord(answer) || typeof answer.id !== 'string' || !ids.delete(answer.id) + || !Array.isArray(answer.selected) || !answer.selected.every(item => typeof item === 'string') + || (answer.custom !== undefined && typeof answer.custom !== 'string')) return undefined + answers.push({ id: answer.id, selected: answer.selected, + ...(answer.custom === undefined ? {} : { custom: answer.custom }) }) + } + return { seq: event.seq, time: event.time, callId: String(event.type === 'tool/result' ? event.data.message.source.callId : event.data.subCallId), + outcome: 'answered', questions, answers, text } +} + +/** + * In-time ask-user answers paired by native callId or PTC subCallId. Pending, failed, and + * malformed results retain their generic Tool presentation; late answers are + * owned by questionReplyDefinition. Work is bounded by this call's answer batch. + */ +export const answeredQuestionDefinition: ConversationNodeDefinition = { + kind: 'answered-user-question', + target: 'chat', + match: (event) => { + if (event.type === 'tool/call' && event.data.name === 'ask_user_question') { + return { id: String(event.data.callId), role: 'start' } + } + if (event.type === 'tool/ptc-dispatch-start' && event.data.name === 'ask_user_question') { + return { id: String(event.data.subCallId), role: 'start' } + } + if (event.type === 'tool/ptc-dispatch' && event.data.name === 'ask_user_question') { + return { id: String(event.data.subCallId), role: 'update' } + } + // Native results omit the tool name; retain update-only matches for history prepends. + if (event.type === 'tool/result' && isAppendSurfaceEvent(event)) { + return { id: String(event.data.message.source.callId), role: 'update' } + } + return null + }, + start: (_context, match) => { + const event = match.event + if (event.type !== 'tool/call' && event.type !== 'tool/ptc-dispatch-start') { + throw new Error('answered-user-question requires tool/call or tool/ptc-dispatch-start') + } + return { questions: callQuestions(event.type === 'tool/call' ? jsonRecord(event.data.arguments) : event.data.arguments), reply: undefined } + }, + update: (context, match) => { + if ((match.event.type !== 'tool/result' && match.event.type !== 'tool/ptc-dispatch') || context.state.questions === null) return context.state + return { ...context.state, reply: resultReply(context.state.questions, match.event) } + }, + buildViewNode: (context) => { + const reply = context.state?.reply + if (reply === undefined) { + const current = context.current.get('chat') + return current == null ? null : { ...current, visibility: 'hidden' } + } + const { seq, ...data } = reply + return { + key: context.key, id: context.id, kind: 'question-reply', target: 'chat', + anchorSeq: seq, location: context.start?.location ?? { kind: 'unresolved' }, + groupTree: 'turn', visibility: 'visible', data, + } + }, +} + /** * Late-reply projection owned by the questions UI. It claims the reply message * on the Chat target, so the generic message Definition never presents it. @@ -173,13 +271,15 @@ export const questionReplyDefinition: ConversationNodeDefinition { if (context.state === undefined) return null const { seq, ...data } = context.state + const location: ConversationLocation = context.start?.location ?? { kind: 'unresolved' } return { key: context.key, kind: 'question-reply', id: context.id, target: 'chat', anchorSeq: seq, - location: context.start?.location ?? { kind: 'unresolved' }, + location, + groupTree: location.kind === 'step' && location.step.step === 1 ? 'exchange' : 'input', visibility: 'visible', data, } diff --git a/packages/client/ui-user-questions/tests/QuestionReplyView.client.spec.tsx b/packages/client/ui-user-questions/tests/QuestionReplyView.client.spec.tsx index dddc3c5bc9..ea2625a912 100644 --- a/packages/client/ui-user-questions/tests/QuestionReplyView.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/QuestionReplyView.client.spec.tsx @@ -4,11 +4,16 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { useDisclosure } from '@deepseek-ai/dsh-client-ui-chat/src/client/chat/use-disclosure.ts' -import { zh } from '../src/client/locales.ts' +import { ja, zh } from '../src/client/locales.ts' import { QuestionReplyBubble, QuestionReplyView } from '../src/client/QuestionReplyView.tsx' import type { QuestionReplyData } from '../src/client/question-reply.ts' -afterEach(cleanup) +const originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard') +afterEach(() => { + cleanup() + if (originalClipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard') + else Object.defineProperty(navigator, 'clipboard', originalClipboard) +}) /** Render the keyed Chat renderer itself; the framework props it never reads are stubbed. */ function renderView(data: QuestionReplyData) { @@ -34,32 +39,28 @@ const data = { callId: 'call-reply', outcome: 'answered', questions: [{ - id: 'goal', question: 'What should we build?', header: 'What should we build?', detail: 'Choose the first milestone.', - options: [{ label: 'A dashboard', description: 'A focused web surface.' }, { label: 'A CLI' }], + id: 'goal', question: 'What should we build?', header: 'What should we build?', }], answers: [{ id: 'goal', selected: ['A dashboard'] }], text: '{"questions":[],"answers":[]}', time: 1, } satisfies QuestionReplyData describe('QuestionReplyView', () => { - it('reopens the settled question details from the history bubble', () => { - render() + it('names answered batches in Japanese', () => { + render() + expect(screen.getByRole('group', { name: '質問と回答' })).toBeTruthy() + }) - const bubble = screen.getByRole('button', { name: /展开问题详情/ }) - expect(bubble.getAttribute('aria-expanded')).toBe('false') + it('shows paired questions and answers immediately without auxiliary option content', () => { + render() + expect(screen.getAllByText('What should we build?')).toHaveLength(1) expect(screen.getAllByText('A dashboard')).toHaveLength(1) + expect(screen.queryByText('Choose the first milestone.')).toBeNull() + expect(screen.queryByText('A focused web surface.')).toBeNull() + expect(screen.queryByText('A CLI')).toBeNull() + expect(screen.queryByRole('button', { name: /展开问题详情/ })).toBeNull() expect(screen.getByRole('button', { name: 'copy' })).toBeTruthy() expect(screen.getByText(/\d{2}:\d{2}/)).toBeTruthy() - expect(screen.queryByText('What should we build?')).toBeNull() - - fireEvent.click(bubble) - - expect(screen.getByRole('button', { name: /收起问题详情/ }).getAttribute('aria-expanded')).toBe('true') - expect(screen.getByText('What should we build?')).toBeTruthy() - expect(screen.getAllByText('What should we build?')).toHaveLength(1) - expect(screen.getByText('A dashboard — A focused web surface.')).toBeTruthy() - expect(screen.getByText('回答:')).toBeTruthy() - expect(screen.getAllByText('A dashboard')).toHaveLength(1) }) it('copies the question with its answer, then confirms the write', async () => { @@ -81,7 +82,7 @@ describe('QuestionReplyView', () => { it('renders through the conversation.chat.node slot with the same bubble', () => { renderView(data) - expect(screen.getByRole('group', { name: '回答先前等待中的问题' }).getAttribute('data-question-reply')).toBe('call-reply') + expect(screen.getByRole('group', { name: '问题与回答' }).getAttribute('data-question-reply')).toBe('call-reply') }) it('shows a distinct header, marks an unanswered question skipped, and falls back to the raw text', () => { @@ -90,20 +91,18 @@ describe('QuestionReplyView', () => { ...data, questions: [ { id: 'goal', question: 'What should we build?', header: 'Goal' }, - { id: 'notes', question: 'Any notes?', options: [{ label: 'None' }] }, + { id: 'notes', question: 'Any notes?' }, ], answers: [{ id: 'goal', selected: [], custom: ' ' }], }} t={t} />) - fireEvent.click(screen.getByRole('button', { name: /展开问题详情/ })) expect(screen.getByText('Goal')).toBeTruthy() - expect(screen.getByText('None')).toBeTruthy() + expect(screen.queryByText('None')).toBeNull() expect(screen.getAllByText('已跳过')).toHaveLength(2) cleanup() render() - fireEvent.click(screen.getByRole('button', { name: /展开问题详情/ })) expect(screen.getByText('raw reply text')).toBeTruthy() }) @@ -136,12 +135,46 @@ describe('QuestionReplyView', () => { } }) - it('copies the same text once the bubble is open', () => { + it('ignores repeated pending copies and does not schedule feedback after unmount', async () => { + vi.useFakeTimers() + try { + let finish!: () => void + const writeText = vi.fn(() => new Promise((resolve) => { finish = resolve })) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const view = render() + fireEvent.click(screen.getByRole('button', { name: 'copy' })) + fireEvent.click(screen.getByRole('button', { name: 'copy' })) + expect(writeText).toHaveBeenCalledTimes(1) + view.unmount() + await act(async () => { finish(); await Promise.resolve() }) + expect(vi.getTimerCount()).toBe(0) + } finally { + vi.useRealTimers() + } + }) + + it('clears the confirmation timer when the bubble unmounts', async () => { + vi.useFakeTimers() + try { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, value: { writeText: vi.fn().mockResolvedValue(undefined) }, + }) + const view = render() + fireEvent.click(screen.getByRole('button', { name: 'copy' })) + await act(async () => { await Promise.resolve(); await Promise.resolve() }) + expect(screen.getByRole('button', { name: 'copied' })).toBeTruthy() + view.unmount() + expect(vi.getTimerCount()).toBe(0) + } finally { + vi.useRealTimers() + } + }) + + it('copies the complete visible question and answer', () => { const writeText = vi.fn().mockResolvedValue(undefined) Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) render() - fireEvent.click(screen.getByRole('button', { name: /展开问题详情/ })) fireEvent.click(screen.getByRole('button', { name: 'copy' })) expect(writeText).toHaveBeenCalledWith('What should we build?\n回答:A dashboard') }) diff --git a/packages/client/ui-user-questions/tests/browser-plugin.client.spec.ts b/packages/client/ui-user-questions/tests/browser-plugin.client.spec.ts index 3fa48a81b6..07a4479c9c 100644 --- a/packages/client/ui-user-questions/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-user-questions/tests/browser-plugin.client.spec.ts @@ -336,8 +336,9 @@ describe('apply', () => { it('registers the late-reply conversation node with the conversation runtime', async () => { const b = await bench() - expect(b.registerNode).toHaveBeenCalledOnce() + expect(b.registerNode).toHaveBeenCalledTimes(2) expect(b.registerNode.mock.calls[0]![0]).toMatchObject({ kind: 'user-question-reply', target: 'chat' }) + expect(b.registerNode.mock.calls[1]![0]).toMatchObject({ kind: 'answered-user-question', target: 'chat' }) expect(b.slots.entries('conversation.chat.node').map(entry => entry.options.key)).toEqual(['question-reply']) }) diff --git a/packages/client/ui-user-questions/tests/question-reply.client.spec.ts b/packages/client/ui-user-questions/tests/question-reply.client.spec.ts index 789371b623..d9001258bf 100644 --- a/packages/client/ui-user-questions/tests/question-reply.client.spec.ts +++ b/packages/client/ui-user-questions/tests/question-reply.client.spec.ts @@ -2,12 +2,19 @@ import { describe, expect, it } from 'vitest' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { SessionSeq } from '@deepseek-ai/dsh-session' +import type { ChatConversationViewNode } from '../../ui-chat/src/client/contract/chat-nodes.ts' +import type { ChatSnapshot } from '../../ui-chat/src/client/contract/snapshot.ts' +import { chatViewDefinition } from '../../ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts' +import { assistantDefinition } from '../../ui-chat/src/client/conversation-nodes/assistant.ts' +import { toolDefinition } from '../../ui-chat/src/client/conversation-nodes/tool.ts' +import { turnProcessDefinition } from '../../ui-chat/src/client/conversation-nodes/turn-process.ts' +import { isAtOrOutside } from '../../ui-chat/src/client/contract/group-tree.ts' import type { ConversationViewNode } from '@deepseek-ai/dsh-client-ui-conversation/client' import { messageDefinition } from '../../ui-chat/src/client/conversation-nodes/message.ts' import { ConversationNodeAssembler } from '../../ui-conversation/src/client/conversation/assembler.ts' import { en } from '../src/client/locales.ts' import type { QuestionReplyData } from '../src/client/question-reply.ts' -import { questionReplyDefinition, replyAnswerValues, replyClipboardText, replyPairsOf } from '../src/client/question-reply.ts' +import { answeredQuestionDefinition, questionReplyDefinition, replyAnswerValues, replyClipboardText, replyPairsOf } from '../src/client/question-reply.ts' const answered = JSON.stringify({ kind: 'answer_to_pending_question', @@ -21,10 +28,10 @@ const answered = JSON.stringify({ }) const noAnswers = JSON.stringify({ questions: [{ id: 'scope', question: 'Which scope?' }] }) -function message(source: Record, text: string, surfaceOp: string | null = 'append') { +function message(source: Record, text: string, surfaceOp: string | null = 'append', seq = 7) { return { type: 'user/message', - seq: SessionSeq(7), + seq: SessionSeq(seq), time: 7_000, ...(surfaceOp === null ? {} : { surfaceOp }), data: { id: 'msg-1', role: 'user', source, content: [{ type: 'text', text }] }, @@ -37,20 +44,19 @@ describe('replyPairsOf', () => { it('reads question and answer pairs, tolerating a payload without answers', () => { expect(replyPairsOf(answered)).toEqual({ questions: [{ - id: 'scope', question: 'Which scope?', header: 'Scope', detail: 'Choose the smallest useful surface.', - options: [{ label: 'Tool only', description: 'Keep the change narrow.' }], multiSelect: false, + id: 'scope', question: 'Which scope?', header: 'Scope', }, { id: 'notes', question: 'Any notes?' }], answers: [{ id: 'scope', selected: ['Tool only'], custom: 'note' }, { id: 'notes', selected: [] }], }) expect(replyPairsOf(noAnswers)).toEqual({ questions: [{ id: 'scope', question: 'Which scope?' }], answers: [] }) }) - it('keeps only the well-formed options of a question and drops the rest', () => { + it('omits options from the projected question', () => { const text = JSON.stringify({ questions: [{ id: 'scope', question: 'Which scope?', options: [{ label: 'Tool only', description: 1 }, 'nope', { description: 'no label' }] }], answers: [], }) - expect(replyPairsOf(text).questions).toEqual([{ id: 'scope', question: 'Which scope?', options: [{ label: 'Tool only' }] }]) + expect(replyPairsOf(text).questions).toEqual([{ id: 'scope', question: 'Which scope?' }]) }) it('renders nothing structured for text it cannot read', () => { @@ -60,13 +66,233 @@ describe('replyPairsOf', () => { }) }) +function toolCall(argumentsText = JSON.stringify({ questions: [{ + id: 'scope', question: 'Which scope?', header: 'Scope', detail: 'Hidden detail', options: [{ label: 'Tool only' }], +}, { id: 'notes', question: 'Any notes?' }] }), name = 'ask_user_question') { + return { type: 'tool/call', seq: SessionSeq(5), time: 5_000, + data: { turn: 1, step: 1, callId: 'call-1', name, arguments: argumentsText } } as never +} + +function toolResult(text = JSON.stringify({ answers: [ + { id: 'notes', selected: [] }, { id: 'scope', selected: ['Tool only'], custom: 'note' }, +] }), isError = false, surfaceOp = 'append') { + return { type: 'tool/result', seq: SessionSeq(6), time: 6_000, surfaceOp, + data: { turn: 1, step: 1, message: { role: 'tool', isError, + source: { kind: 'tool', callId: 'call-1' }, content: [{ type: 'text', text }] } } } as never +} + +function ptcCall(argumentsValue: unknown = { questions: [{ id: 'scope', question: 'Which scope?', header: 'Scope' }, { id: 'notes', question: 'Any notes?' }] }, name = 'ask_user_question') { + return { type: 'tool/ptc-dispatch-start', seq: SessionSeq(5), time: 5_000, + data: { rootCallId: 'root', parentCallId: 'root', subCallId: 'call-1', name, arguments: argumentsValue } } as never +} + +function ptcResult(text = JSON.stringify({ answers: [{ id: 'notes', selected: [] }, { id: 'scope', selected: ['Tool only'], custom: 'note' }] }), isError = false, name = 'ask_user_question') { + return { type: 'tool/ptc-dispatch', seq: SessionSeq(6), time: 6_000, + data: { rootCallId: 'root', parentCallId: 'root', subCallId: 'call-1', name, arguments: {}, isError, + content: [{ type: 'text', text }] } } as never +} + +function answerAssembler() { + let nodes: readonly ConversationViewNode[] = [] + const assembler = new ConversationNodeAssembler( + { entries: () => [answeredQuestionDefinition, questionReplyDefinition, messageDefinition], fallbackEntry: () => undefined }, + { entries: () => [{ target: 'chat', create: () => ({ + empty: nodes, + replace: input => (nodes = input.nodes), + apply: (input) => { + const changed = new Map(nodes.map(node => [node.key, node])) + for (const node of input.upserts) changed.set(node.key, node) + return (nodes = [...changed.values()]) + }, + }) }] }, + ) + assembler.activateTarget('chat') + return { assembler, nodes: () => nodes as readonly ChatConversationViewNode[] } +} + +describe('answeredQuestionDefinition', () => { + it.each(['native', 'ptc'].flatMap(transport => ['replay', 'live', 'prepend'].flatMap(mode => [false, true].map(late => ({ mode, late, transport })))))('projects ordinary and late answer folding independently ($transport, $mode, late=$late)', ({ mode, late, transport }) => { + const call = transport === 'native' ? toolCall() : ptcCall() + const result = transport === 'native' ? toolResult : ptcResult + const entries = [ + { type: 'event' as const, event: { type: 'turn/start', seq: SessionSeq(1), time: 1000, data: { turn: 1 } } as never }, + { type: 'event' as const, event: { type: 'step/start', seq: SessionSeq(2), time: 2000, data: { turn: 1, step: 1 } } as never }, + { type: 'event' as const, event: message({ kind: 'user' }, 'Ask me about scope', 'append', 3) }, + { type: 'event' as const, event: call }, + { type: 'event' as const, event: late ? result('{"pending":true,"callId":"call-1"}') : result() }, + { type: 'event' as const, event: { type: 'step/end', seq: SessionSeq(7), time: 7000, data: { turn: 1, step: 1 } } as never }, + { type: 'event' as const, event: { type: 'step/start', seq: SessionSeq(8), time: 8000, data: { turn: 1, step: 2 } } as never }, + { type: 'event' as const, event: { type: 'assistant/message', seq: SessionSeq(10), time: 10000, surfaceOp: 'append', + data: { turn: 1, step: 2, stream: [], message: { id: 'final', role: 'assistant', source: { kind: 'model', provider: 'fake', model: 'fake' }, content: [{ type: 'text', text: 'Done' }] } } } as never }, + { type: 'event' as const, event: { type: 'step/end', seq: SessionSeq(11), time: 11000, data: { turn: 1, step: 2 } } as never }, + { type: 'event' as const, event: { type: 'turn/end', seq: SessionSeq(12), time: 12000, data: { turn: 1, reason: { kind: 'completed' } } } as never }, + ] + if (late) entries.splice(7, 0, { type: 'event' as const, event: message(replySource('answered'), answered, 'append', 9) }) + if (transport === 'ptc') entries.splice(3, 0, { type: 'event' as const, event: { + type: 'tool/call', seq: SessionSeq(4), time: 4000, + data: { turn: 1, step: 1, callId: 'root', name: 'run_code', arguments: '{}' }, + } as never }) + const run = new ConversationNodeAssembler( + { + entries: () => [answeredQuestionDefinition, questionReplyDefinition, messageDefinition, + assistantDefinition, toolDefinition, turnProcessDefinition], + fallbackEntry: () => undefined, + }, + { entries: () => [chatViewDefinition] }, + ) + if (mode === 'live') { + run.replaceWindow([], false) + run.activateTarget('chat') + for (const entry of entries) { run.append(entry); run.flush() } + } else if (mode === 'prepend') { + run.replaceWindow(entries.slice(4), true) + run.activateTarget('chat') + run.prepend(entries.slice(0, 4), false) + run.flush() + } else { + run.replaceWindow(entries, false) + run.activateTarget('chat') + } + const view = run.snapshot('chat') as ChatSnapshot + const batch = view.nodes.values().find(node => node.kind === 'question-reply')! + const presentation = view.nodes.processSource(batch.key).getSnapshot() + expect(presentation).toMatchObject({ turnClosed: true, hasExternalProcess: true, hasInterleavedInput: late }) + expect(batch).toMatchObject({ groupTree: late ? 'input' : 'turn', visibility: 'visible' }) + expect(isAtOrOutside(batch, 'turn')).toBe(true) + expect(isAtOrOutside(batch, 'input')).toBe(late) + }) + + it('does not present a question until its answer arrives, then pairs one batch at the result position', () => { + const run = answerAssembler() + run.assembler.replaceWindow([{ type: 'event', event: toolCall() }], false) + run.assembler.flush() + expect(run.nodes()).toEqual([]) + run.assembler.append({ type: 'event', event: toolResult() }) + run.assembler.flush() + expect(run.nodes()).toHaveLength(1) + expect(run.nodes()[0]).toMatchObject({ kind: 'question-reply', anchorSeq: 6, groupTree: 'turn', visibility: 'visible', + data: { callId: 'call-1', time: 6_000, outcome: 'answered', + questions: [{ id: 'scope', question: 'Which scope?', header: 'Scope' }, { id: 'notes', question: 'Any notes?' }], + answers: [{ id: 'notes', selected: [] }, { id: 'scope', selected: ['Tool only'], custom: 'note' }] } }) + expect(run.nodes()[0]?.data).not.toHaveProperty('seq') + const replay = answerAssembler() + replay.assembler.replaceWindow([{ type: 'event', event: toolCall() }, { type: 'event', event: toolResult() }], false) + replay.assembler.flush() + expect(replay.nodes().map(({ location: _location, ...node }) => node)) + .toEqual(run.nodes().map(({ location: _location, ...node }) => node)) + expect(replay.nodes()[0]?.location.kind).toBe(run.nodes()[0]?.location.kind) + }) + + it('keeps an update-only tail pending and derives the batch when its call is prepended', () => { + const run = answerAssembler() + run.assembler.replaceWindow([{ type: 'event', event: toolResult() }], false) + run.assembler.flush() + expect(run.nodes()).toEqual([]) + run.assembler.prepend([{ type: 'event', event: toolCall() }], false) + run.assembler.flush() + expect(run.nodes()).toHaveLength(1) + expect(run.nodes()[0]).toMatchObject({ kind: 'question-reply', anchorSeq: 6 }) + }) + + it('leaves pending results without a bubble and presents the eventual late answer exactly once', () => { + const run = answerAssembler() + run.assembler.replaceWindow([{ type: 'event', event: toolCall() }, + { type: 'event', event: toolResult('{"pending":true,"callId":"call-1"}') }, + { type: 'event', event: message(replySource('answered'), answered) }], false) + run.assembler.flush() + expect(run.nodes()).toHaveLength(1) + expect(run.nodes()[0]).toMatchObject({ kind: 'question-reply', anchorSeq: 7, groupTree: 'exchange' }) + }) + + it.each([ + 'null', '[]', 'not json', '{"answers":"wrong"}', '{"answers":[]}', + '{"answers":[{"id":"scope","selected":[]},{"id":"scope","selected":[]}]}', + '{"answers":[{"id":"scope","selected":[1]},{"id":"notes","selected":[]}]}', + '{"answers":[{"id":"scope","selected":[],"custom":1},{"id":"notes","selected":[]}]}', + '{"answers":[{"id":"wrong","selected":[]},{"id":"notes","selected":[]}]}', + ])('retains the generic fallback instead of fabricating answers from %s', (text) => { + const run = answerAssembler() + run.assembler.replaceWindow([{ type: 'event', event: toolCall() }, { type: 'event', event: toolResult(text) }], false) + run.assembler.flush() + expect(run.nodes()).toEqual([]) + }) + + it.each(['not json', '{"questions":[]}', '{"questions":[{"id":1}]}', + '{"questions":[{"id":"scope","question":"A"},{"id":"scope","question":"B"}]}', + '{"questions":[{"id":"scope","question":"Approve?","intent":{"kind":"plan-review"}}]}', + ])('does not pair unsafe or plan-review call arguments %s', (args) => { + const run = answerAssembler() + run.assembler.replaceWindow([{ type: 'event', event: toolCall(args) }, { type: 'event', event: toolResult() }], false) + run.assembler.flush() + expect(run.nodes()).toEqual([]) + }) + + it.each([{ content: [] }, { content: [{ type: 'image', source: { kind: 'inline', data: '', mediaType: 'image/png' } }] }, + { content: [{ type: 'text', text: '{}' }, { type: 'text', text: '{}' }] }, + ])('leaves unsupported result content in the generic Tool presentation', ({ content }) => { + const run = answerAssembler() + const result = { type: 'tool/result', seq: SessionSeq(6), time: 6_000, surfaceOp: 'append', + data: { turn: 1, step: 1, message: { role: 'tool', source: { kind: 'tool', callId: 'call-1' }, content } } } as never + run.assembler.replaceWindow([{ type: 'event', event: toolCall() }, { type: 'event', event: result }], false) + run.assembler.flush() + expect(run.nodes()).toEqual([]) + }) + + it('retains a published node key while replay withdraws its answer evidence', () => { + const event = toolCall() + const state = answeredQuestionDefinition.start({} as never, { event, id: 'call-1', role: 'start' } as never, {} as never) + const answeredState = answeredQuestionDefinition.update({ state } as never, + { event: toolResult(), id: 'call-1', role: 'update' } as never) + const current = new Map() + const node = answeredQuestionDefinition.buildViewNode!({ state: answeredState, current, + key: 'answered:1', id: 'call-1', start: undefined } as never) as ChatConversationViewNode + expect(node.location).toEqual({ kind: 'unresolved' }) + expect(node.visibility).toBe('visible') + current.set('chat', node) + const hidden = answeredQuestionDefinition.buildViewNode!({ state, current, + key: 'answered:1', id: 'call-1', start: undefined } as never) + expect(hidden).toMatchObject({ key: 'answered:1', visibility: 'hidden' }) + expect(answeredQuestionDefinition.buildViewNode!({ state: undefined, current: new Map() } as never)).toBeNull() + }) + + it('ignores unrelated PTC calls and retains malformed or failed dispatches in the generic tool view', () => { + expect(answeredQuestionDefinition.match(ptcCall(undefined, 'bash'))).toBeNull() + expect(answeredQuestionDefinition.match(ptcResult(undefined, false, 'bash'))).toBeNull() + for (const [call, result] of [ + [ptcCall(), ptcResult(undefined, true)], + [ptcCall(), ptcResult('not json')], + [ptcCall({ questions: [] }), ptcResult()], + [ptcCall({ questions: [{ id: 'plan', question: 'Approve?', intent: { kind: 'plan-review' } }] }), ptcResult()], + ]) { + const run = answerAssembler() + run.assembler.replaceWindow([{ type: 'event', event: call! }, { type: 'event', event: result! }], false) + run.assembler.flush() + expect(run.nodes()).toEqual([]) + } + }) + + it('requires tool/call as its starting evidence', () => { + expect(() => answeredQuestionDefinition.start({} as never, + { event: toolResult(), id: 'call-1', role: 'start' } as never, {} as never)).toThrow(/requires tool\/call/) + }) + + it('excludes other tools, plan approval, failed results, and non-appended results', () => { + expect(answeredQuestionDefinition.match(toolCall(undefined, 'exit_plan_mode'))).toBeNull() + expect(answeredQuestionDefinition.match(toolCall(undefined, 'bash'))).toBeNull() + expect(answeredQuestionDefinition.match(toolResult(undefined, false, 'replace'))).toBeNull() + const run = answerAssembler() + run.assembler.replaceWindow([{ type: 'event', event: toolCall() }, { type: 'event', event: toolResult(undefined, true) }], false) + run.assembler.flush() + expect(run.nodes()).toEqual([]) + }) +}) + const t = makeTranslate(en) const replyData = (overrides: Partial = {}): QuestionReplyData => ({ callId: 'call-1', outcome: 'answered', questions: [{ id: 'scope', question: 'Which scope?', header: 'Scope', - options: [{ label: 'Tool only', description: 'Keep the change narrow.' }, { label: 'Whole package' }], }, { id: 'notes', question: 'Any notes?' }], answers: [{ id: 'scope', selected: ['Tool only'], custom: 'note' }, { id: 'notes', selected: [] }], text: answered, @@ -156,6 +382,17 @@ describe('questionReplyDefinition', () => { expect(questionReplyDefinition.buildViewNode!({ state: undefined } as never)).toBeNull() }) + it('opens an exchange only for a reply admitted into Step 1', () => { + const event = message(replySource('answered'), answered) + const state = questionReplyDefinition.start({} as never, { event, id: 'msg-1', role: 'start' } as never, {} as never) + for (const step of [1, 2]) { + const node = questionReplyDefinition.buildViewNode!({ + state, key: 'reply:1', id: 'msg-1', start: { location: { kind: 'step', step: { step } } }, + } as never) + expect((node as ChatConversationViewNode | null)?.groupTree).toBe(step === 1 ? 'exchange' : 'input') + } + }) + it('starts an empty record for a reply without text', () => { const untyped = { type: 'user/message', seq: SessionSeq(8), time: 8_000, surfaceOp: 'append', diff --git a/packages/client/ui-user-questions/tsconfig.json b/packages/client/ui-user-questions/tsconfig.json index 8368699f96..0be6a8fb64 100644 --- a/packages/client/ui-user-questions/tsconfig.json +++ b/packages/client/ui-user-questions/tsconfig.json @@ -58,6 +58,9 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../core/tool-executor-ptc" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 52192df9e3..2feeec4672 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6655,6 +6655,9 @@ importers: '@deepseek-ai/dsh-tool-executor-native': specifier: workspace:* version: link:../../core/tool-executor-native + '@deepseek-ai/dsh-tool-executor-ptc': + specifier: workspace:* + version: link:../../core/tool-executor-ptc '@deepseek-ai/dsh-tools': specifier: workspace:* version: link:../../core/tools diff --git a/snapshots/web/question-composer/answered-expanded.expected.md b/snapshots/web/question-composer/answered-expanded.expected.md index 3788023355..ad16ac9371 100644 --- a/snapshots/web/question-composer/answered-expanded.expected.md +++ b/snapshots/web/question-composer/answered-expanded.expected.md @@ -17,6 +17,12 @@ - term: Which color do you prefer? - definition: Blue Include accessibility notes - button "Inspect" +- group "Questions and answers": + - term: Pick one Which color do you prefer? + - definition: Blue, Include accessibility notes + - text: {{clock}} + - button "Copy" +- button "Analysis completed" [expanded] - button "Think The user answered \"Blue\". I should now reply with the single word DONE and stop." - paragraph: DONE - button "Copy" diff --git a/snapshots/web/question-composer/answered.expected.md b/snapshots/web/question-composer/answered.expected.md index 532d4d15fa..5030acee5b 100644 --- a/snapshots/web/question-composer/answered.expected.md +++ b/snapshots/web/question-composer/answered.expected.md @@ -11,6 +11,11 @@ - button "Copy" - status: Completed - button "Completed in {{duration}}" +- group "Questions and answers": + - term: Pick one Which color do you prefer? + - definition: Blue, Include accessibility notes + - text: {{clock}} + - button "Copy" - paragraph: DONE - button "Copy" - button "Good response" diff --git a/snapshots/web/question-composer/late-answered.expected.md b/snapshots/web/question-composer/late-answered.expected.md index 91f1ca73c2..043646677f 100644 --- a/snapshots/web/question-composer/late-answered.expected.md +++ b/snapshots/web/question-composer/late-answered.expected.md @@ -21,13 +21,13 @@ - term: Which color do you prefer? - definition: Green Answered after the timeout - button "Inspect" -- status: Completed -- button "Completed in {{duration}}" [expanded] -- button "Analysis completed" [expanded] -- group "Reply to earlier pending questions": - - button "Reply to earlier pending questions · Open question details": Reply to earlier pending questions Green, Answered after the timeout +- group "Questions and answers": + - term: Pick one Which color do you prefer? + - definition: Green, Answered after the timeout - text: {{clock}} - button "Copy" +- status: Completed +- button "Completed in {{duration}}" [disabled] - region "Which color do you prefer?": - text: Pick one Answered - button "Collapse the question card" [expanded] diff --git a/snapshots/web/steering/settled-expanded.expected.md b/snapshots/web/steering/settled-expanded.expected.md index 53f8b29d3e..0107f21a63 100644 --- a/snapshots/web/steering/settled-expanded.expected.md +++ b/snapshots/web/steering/settled-expanded.expected.md @@ -13,6 +13,11 @@ - button "Completed in {{duration}}" [disabled] - button "Asked questions" [expanded] - button "Ask question 1/1 answered" +- group "Questions and answers": + - term: Checkpoint Ready to continue? + - definition: "Yes" + - text: {{clock}} + - button "Copy" - text: "Interjection: include the word BANANA in your final reply. {{clock}}" - button "Copy" - paragraph: Great, let's move forward. BANANA! diff --git a/snapshots/web/steering/settled.expected.md b/snapshots/web/steering/settled.expected.md index 740662fd9d..a463df9054 100644 --- a/snapshots/web/steering/settled.expected.md +++ b/snapshots/web/steering/settled.expected.md @@ -12,6 +12,11 @@ - status: Completed - button "Completed in {{duration}}" [disabled] - button "Asked questions" +- group "Questions and answers": + - term: Checkpoint Ready to continue? + - definition: "Yes" + - text: {{clock}} + - button "Copy" - text: "Interjection: include the word BANANA in your final reply. {{clock}}" - button "Copy" - paragraph: Great, let's move forward. BANANA! diff --git a/tsconfig.host.json b/tsconfig.host.json index d3feb855de..825b1e662e 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -57,6 +57,7 @@ "apps/web/tests/subagent-fork-schedule.snapshot.ts", "apps/web/tests/live-interactions.e2e.ts", "apps/web/tests/question-composer.e2e.ts", + "apps/web/tests/question-ptc.e2e.ts", "apps/web/tests/approval-composer.e2e.ts", "apps/web/tests/plan-control-row.e2e.ts", "apps/web/tests/plan-review.e2e.ts", From 47b6867566b371426a0a88968f33d544b245dde1 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Wed, 21 Oct 2026 23:51:22 +0800 Subject: [PATCH 36/36] fix(tools): settle cancelled admitted calls through cancellation A step's tool set no longer empties when the step is cancelled. The shared pipeline already settles unstarted calls as cancelled; keeping admission lets those calls keep their finalizers, and a wrapper result completed at cancellation now reports cancellation instead of UNKNOWN_TOOL. exit_plan_mode checks for a missing Agent explicitly instead of asserting it. Document the activation types on the tools subsystem page, the turn/end code for a failed tool condition, the replacement and no-set consequences in the upgrade guide, and the admission rule in the parallel tool-call note. --- ...-10-parallel-tool-call-execution.i18n.yaml | 12 +- ...2026-07-10-parallel-tool-call-execution.md | 6 +- ...6-07-10-parallel-tool-call-execution.zh.md | 6 +- docs/persistence-catalog.i18n.yaml | 148 +++++++++--------- docs/persistence-catalog.md | 74 ++++----- docs/persistence-catalog.zh.md | 74 ++++----- docs/persistence-schema.json | 44 +++--- docs/subsystems/session.md | 5 +- docs/subsystems/session.zh.md | 5 +- docs/subsystems/tools.i18n.yaml | 3 + docs/subsystems/tools.md | 44 ++++++ docs/subsystems/tools.zh.md | 44 ++++++ .../conditional-tools/guide.i18n.yaml | 8 +- .../v0.2.1-rc.2/conditional-tools/guide.md | 6 +- .../v0.2.1-rc.2/conditional-tools/guide.zh.md | 6 +- packages/core/session/src/types.ts | 5 +- packages/core/tools/README.i18n.yaml | 4 +- packages/core/tools/README.md | 2 +- packages/core/tools/README.zh.md | 2 +- packages/core/tools/src/index.ts | 2 +- packages/core/tools/tests/activation.spec.ts | 24 ++- packages/plan/plan-mode/src/index.ts | 5 +- .../plan/plan-mode/tests/plan-mode.spec.ts | 13 ++ scripts/gen-cordis-catalog.ts | 6 +- scripts/type-equiv.manifest.json | 15 ++ 25 files changed, 353 insertions(+), 210 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml index 639381d125..ca48f70356 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml @@ -12,8 +12,8 @@ en: 532bb7268d9b93ce zh: ad47162233222ab0 /agent-note-parallel-tool-call-execution-by-per-call-safety/scheduling-and-ordering: - en: 4e85280cc5eb8697 - zh: 8e6b09b1527784fa + en: 47010d626ab15117 + zh: a5b77385d7a3e781 /agent-note-parallel-tool-call-execution-by-per-call-safety/safety-contract: en: 16c4ee08b65ead23 zh: df80d6e49982615b @@ -21,11 +21,11 @@ en: e112957ed8a48039 zh: 37d63f9ea4968fb2 /agent-note-parallel-tool-call-execution-by-per-call-safety/verification: - en: eb5a6aa84980f0ab - zh: eed2680a160e8ed2 + en: 224b6838130c113f + zh: f3d7eb68ab5932fb /agent-note-parallel-tool-call-execution-by-per-call-safety/alternatives-considered: en: 17becc038bb7df7c zh: 673d9a9bdfa39edf /agent-note-parallel-tool-call-execution-by-per-call-safety/consequences: - en: a5508057bc03f4f6 - zh: 96b46c59402474c3 + en: 20a3e29931e01aa0 + zh: acbfc61dd710d960 diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md index 40adc9f9aa..4eb497b1ff 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md @@ -26,7 +26,7 @@ A tagged mode, rather than a public boolean scheduler API, keeps resource-aware ## Scheduling and ordering -The loop waits for the complete assistant message, parses every call once, creates a distinct `ToolExecution` for each call, and scans them in model order. Consecutive parallel calls form one group; every exclusive call forms a singleton group and an ordering barrier. Groups execute sequentially. Classification is lazy: the scheduler resolves the next call after each barrier and reclassifies every later call before replenishing a parallel pool. If a registry mutation makes that call exclusive, the current pool drains before the call starts as the next barrier. +The loop waits for the complete assistant message, parses every call once, creates a distinct `ToolExecution` for each call, and scans them in model order. Consecutive parallel calls form one group; every exclusive call forms a singleton group and an ordering barrier. Groups execute sequentially. Classification is lazy: the scheduler resolves the next call after each barrier and reclassifies every later call before replenishing a parallel pool. Calls resolve through the step's admitted tool set, so replacing or removing a call's registration makes that unstarted call fail as `UNKNOWN_TOOL`; the scheduler classifies it as exclusive, and the current pool drains before it settles as the next barrier. For example: @@ -66,7 +66,7 @@ Filesystem read relies on a narrow recorder exception: its synchronous observati ## Verification -Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, live reclassification after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration. +Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration. Snapshot coverage pins the visible multi-call transcript: pending calls may overlap while completed results remain model-ordered. PTC mode coverage pins its serial boundary. No provider-backed e2e is required because scheduling is deterministic loop behavior. @@ -102,6 +102,6 @@ Ordered commits may hold a fast result behind a slow earlier sibling. This prese Concurrent external calls can compete for quota or process capacity. Providers own their capacity controls; the loop cap only limits calls from one agent step. -Tool registration is a scheduling boundary. Registry mutations affect not-yet-started calls because the scheduler reclassifies after each barrier and before every pool replenishment. Already-started calls retain the scheduling decision under which they entered the pool. +Tool registration is a scheduling boundary. Registry mutations affect not-yet-started calls because the scheduler reclassifies after each barrier and before every pool replenishment. A call runs only the registration its step declared ([conditional tools](../../../../packages/core/tools/README.md)), so a hot reload, MCP reconnect, or skill reload that re-registers a tool mid-step fails that step's unstarted calls of it; the next step declares and runs the new registration. Already-started calls retain the scheduling decision under which they entered the pool. A terminal scheduler failure reaches step recovery only after live dispatches settle. Recovery reports uncommitted outcomes as unknown, preserving quiescence and the original failure while keeping later model history usable. diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md index 536541370b..dbfa7cd684 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md @@ -26,7 +26,7 @@ Status: implemented ## 调度与顺序 -循环会等待完整的 assistant 消息,对每个调用只解析一次,为每个调用创建独立的 `ToolExecution`,再按模型顺序扫描。连续的并行调用组成一组;每个独占调用单独组成一组,并构成顺序屏障。各组按顺序执行。分类采用惰性方式:每经过一个屏障,调度器都会解析下一个调用;补充并行池之前,还会重新分类每个后续调用。如果注册表变更使该调用变为独占,当前池会先完全排空,然后该调用才作为下一个屏障启动。 +循环会等待完整的 assistant 消息,对每个调用只解析一次,为每个调用创建独立的 `ToolExecution`,再按模型顺序扫描。连续的并行调用组成一组;每个独占调用单独组成一组,并构成顺序屏障。各组按顺序执行。分类采用惰性方式:每经过一个屏障,调度器都会解析下一个调用;补充并行池之前,还会重新分类每个后续调用。调用通过本步骤的准入工具集合解析,因此替换或移除某个调用的注册后,该尚未开始的调用会以 `UNKNOWN_TOOL` 失败;调度器把它分类为独占,当前池会先完全排空,然后它才作为下一个屏障结束。 例如: @@ -66,7 +66,7 @@ Status: implemented ## 验证 -单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后的运行时重新分类、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明。 +单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明。 快照测试固定了可见的多调用 transcript(文本记录):待处理调用可以重叠执行,已完成结果仍按模型顺序排列。PTC mode 测试固定了其串行边界。此调度属于确定性循环行为,因此无需依赖提供方的 e2e 测试。 @@ -102,6 +102,6 @@ Status: implemented 并发外部调用可能会争用配额或进程容量。提供方负责自身容量控制;循环上限只限制一个 agent 步骤中的调用数量。 -工具注册是调度边界。调度器会在每个屏障之后以及每次补充池之前重新分类,因此注册表变更会影响尚未启动的调用。已启动的调用保留它们进入池时所依据的调度决策。 +工具注册是调度边界。调度器会在每个屏障之后以及每次补充池之前重新分类,因此注册表变更会影响尚未启动的调用。调用只执行其步骤所声明的注册([条件工具](../../../../packages/core/tools/README.zh.md)),因此在步骤中途重新注册工具的热重载、MCP 重连或 skill 重载会让该步骤里这个工具尚未开始的调用失败;下一个步骤声明并执行新的注册。已启动的调用保留它们进入池时所依据的调度决策。 终态调度器故障只有在运行中的派发结算后才会进入步骤恢复。恢复将未提交的执行结果报告为未知,保留完全停稳与原始失败,同时让后续模型历史保持可用。 diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index f71193cb9f..55fa452e81 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -12,8 +12,8 @@ en: bcff48893d904af8 zh: f82e75c91c39adb1 /session-persistence-event-catalog/event-envelope: - en: 689f781d95689e20 - zh: 602f6a7f0835d698 + en: 981db6b1928eda50 + zh: d77bc66cf678099d /session-persistence-event-catalog/events: en: f4776ba3d0fd53ce zh: e86769f50a69055a @@ -45,11 +45,11 @@ en: 44426b6cd0dc01cf zh: 44426b6cd0dc01cf /session-persistence-event-catalog/events/assistant/assistant-attempt-log-only: - en: 5b002a8dcefbfc71 - zh: e44f53ed4bf1f929 + en: 4e684124f71bd73b + zh: 445ad50a3a4fb635 /session-persistence-event-catalog/events/assistant/assistant-message-surface: - en: a0f8289f97125e4f - zh: 1ff54770086eb016 + en: 87d9bb62e2aea4b9 + zh: 68ef3b05d4aad7d3 /session-persistence-event-catalog/events/command: en: 2cecb5b0ee955732 zh: 2cecb5b0ee955732 @@ -84,8 +84,8 @@ en: 3344204b1858edb1 zh: 3344204b1858edb1 /session-persistence-event-catalog/events/developer/developer-message-surface: - en: cd036bde54c62690 - zh: 5a21179b33551ed5 + en: 927f25c5dbd69c82 + zh: 9c0331f6e61d7e2b /session-persistence-event-catalog/events/feedback: en: f50dbac6867fa64d zh: f50dbac6867fa64d @@ -159,11 +159,11 @@ en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 /session-persistence-event-catalog/events/request/request-context-log-only: - en: 799784e7cd019889 - zh: db6c59d673b4acff + en: 9167d83823675b3e + zh: dfe9095419cf76f4 /session-persistence-event-catalog/events/request/request-header-log-only: - en: fb095eddad22b5f5 - zh: 49f1a3ac0a9ec57c + en: 6d9e26081d1e3aec + zh: 36d30d0bff197d1e /session-persistence-event-catalog/events/sandbox: en: ec841ab8439335b0 zh: ec841ab8439335b0 @@ -180,8 +180,8 @@ en: a1ac8f2660a4f61e zh: a1ac8f2660a4f61e /session-persistence-event-catalog/events/session/session-end-seed-log-only: - en: 70c3c0d6614f2d30 - zh: bb4dd52f5bcf351c + en: f285c670d1bf0e71 + zh: 14ec5689a5943156 /session-persistence-event-catalog/events/session/session-title-log-only: en: 6c6a27578dff5828 zh: 9a5add2bc0df2d0a @@ -198,11 +198,11 @@ en: bd0dcbbc352b771a zh: bd0dcbbc352b771a /session-persistence-event-catalog/events/step/step-end-log-only: - en: 2de61d81867d485c - zh: 21025a396ef7c88f + en: 24bc99ca25809609 + zh: 420384e753feba64 /session-persistence-event-catalog/events/step/step-start-log-only: - en: cb8f05bf3b59adef - zh: 686b33b689c4a841 + en: 269a493d00348184 + zh: 80feab63a0431c60 /session-persistence-event-catalog/events/subagent: en: 9630752e97ddbfbc zh: 9630752e97ddbfbc @@ -219,8 +219,8 @@ en: 8cac41d2fb575975 zh: 8cac41d2fb575975 /session-persistence-event-catalog/events/system/system-message-surface: - en: 92b1f61ac638da71 - zh: 2d60ba9d38abda05 + en: 23aedcadb0c95a51 + zh: f58e5195075ddb21 /session-persistence-event-catalog/events/team: en: a640800a38b3c874 zh: a640800a38b3c874 @@ -246,8 +246,8 @@ en: 28a24430609494b2 zh: 28a24430609494b2 /session-persistence-event-catalog/events/tool/tool-call-log-only: - en: 03f36237cbf9e267 - zh: 83fe2e69bbbfd3c1 + en: b5dfd3b4c54281c3 + zh: 3ac01ceab4a36d06 /session-persistence-event-catalog/events/tool/tool-ptc-dispatch-log-only: en: a62b38c00afed655 zh: 793bef93e856eafa @@ -255,8 +255,8 @@ en: da841b1ed3b22c87 zh: 4c9a4d4bc5bd76b6 /session-persistence-event-catalog/events/tool/tool-result-surface: - en: 283e3cf1fdd57f05 - zh: 0bc3a15ae4f47aaf + en: 722a3bf051b384eb + zh: 01e1258be37a82ce /session-persistence-event-catalog/events/tool-workflow: en: 1eac7deac6af15f3 zh: 1eac7deac6af15f3 @@ -276,17 +276,17 @@ en: d7e8c999a0851a0c zh: d7e8c999a0851a0c /session-persistence-event-catalog/events/turn/turn-end-log-only: - en: ce5ef6916c95ea16 - zh: 9652c8d40b5dfb6d + en: 38d2280f449d3112 + zh: 0f7f05475ea514a3 /session-persistence-event-catalog/events/turn/turn-start-log-only: - en: 999ffb7ad4e600aa - zh: a8720bf8578431ae + en: 853b7f23d092c48a + zh: 53e312793b609198 /session-persistence-event-catalog/events/user: en: d864a88c03e8971c zh: d864a88c03e8971c /session-persistence-event-catalog/events/user/user-message-surface: - en: 55128b5458eae10f - zh: 4198ea89093484f6 + en: ba681b5ec685d6e8 + zh: e4b14b585d2b5804 /session-persistence-event-catalog/events/web: en: d278748103cf1640 zh: d278748103cf1640 @@ -1011,8 +1011,8 @@ en: 997b5db27df00446 zh: 07e5197ddd7bd59b /session-persistence-event-catalog/resolved-persistence-types/epochheader: - en: 3786becd1ca9c697 - zh: ea8e6fd4f6590567 + en: c804cb9e2e31c5ec + zh: 3ed7ac59cd1441b7 /session-persistence-event-catalog/resolved-persistence-types/everyscheduledispatchchange: en: 54c487394ce0db1d zh: 48d7c9affbe841cb @@ -1179,11 +1179,11 @@ en: 488050ba0b6438b4 zh: 2bf607b5ad51e39d /session-persistence-event-catalog/resolved-persistence-types/requestcontext: - en: b1ade5ed2c42b1ad - zh: f1a6126bec25657b + en: 00058b6c2220cdcb + zh: a3426a8c69123e2e /session-persistence-event-catalog/resolved-persistence-types/requestheaderreason: - en: 0db3aa2b122a4454 - zh: 15b6cfd8896935b8 + en: 8e563a11c123255f + zh: ebf891f6a3cb93d3 /session-persistence-event-catalog/resolved-persistence-types/sandboxmode: en: c9fa5343ea99733b zh: d6de41351c57a73f @@ -1236,8 +1236,8 @@ en: d34acab659e74957 zh: 25cabc6c9fb44a7e /session-persistence-event-catalog/resolved-persistence-types/surfaceop: - en: 95f8ef2fb8a7c154 - zh: 04cdad161fb88cc3 + en: a62be7c2cb8a4af7 + zh: 616fd1ac4bd3995a /session-persistence-event-catalog/resolved-persistence-types/systemmessage: en: 94876079d6696df9 zh: d25c7ad9f5054eb7 @@ -1314,8 +1314,8 @@ en: 4dc89c072fe5d0d1 zh: 4ed2c9e9e8b4f7e2 /session-persistence-event-catalog/resolved-persistence-types/turnendreason: - en: eec92deb07c000fa - zh: 666682b6f3efcfa3 + en: 344a7207a4199a32 + zh: d500af39e83289cf /session-persistence-event-catalog/resolved-persistence-types/usermessage: en: bd3aedd570ded4d2 zh: f020d0816d3a6c1a @@ -1410,8 +1410,8 @@ en: a117573a5d58cb3c zh: d5ad59e17a3a815d /session-persistence-event-catalog/resolved-persistence-types/arguments-callid-name-step: - en: 99e67b046fa9cf40 - zh: 88060ee577d02d20 + en: 036101ee99efbf72 + zh: a324d7f9f671bab0 /session-persistence-event-catalog/resolved-persistence-types/callid-files-turn: en: 5f4d3f66ed86a14d zh: 7c729360fa1279e6 @@ -1443,8 +1443,8 @@ en: a1f188c9058cf621 zh: eb43c0f045fb9afb /session-persistence-event-catalog/resolved-persistence-types/code-name-reason: - en: 39c67256532a22f9 - zh: 59f823e98630c5e2 + en: 17649d71411cb827 + zh: abb3138d38c76459 /session-persistence-event-catalog/resolved-persistence-types/commandid-kind-sourceeventseq-text: en: 87b03e1c73d2a326 zh: d7b9f06863cad891 @@ -1485,14 +1485,14 @@ en: 4b7a8793663d3fef zh: 249459c825d330c3 /session-persistence-event-catalog/resolved-persistence-types/endseq-op-startseq: - en: 318404925fed44c8 - zh: 6cc8b0fcd8d11540 + en: 1a533265eb56a8b8 + zh: 57480f4b53713570 /session-persistence-event-catalog/resolved-persistence-types/error-kind-error: - en: 72572b3d4f2f0c01 - zh: 4c4234325c1713fc + en: 8d0448ef77e0da08 + zh: 25770329c9db129a /session-persistence-event-catalog/resolved-persistence-types/error-message-meta-step: - en: 8cc3e4d05fa25012 - zh: 2c2d1c1936dd99ce + en: 9ffa836bf88fd7b4 + zh: 7ca8bc7ebefeadb8 /session-persistence-event-catalog/resolved-persistence-types/failure-kind-aborted: en: 349cd90f2598fd12 zh: 1eda02d520ad5d76 @@ -1500,11 +1500,11 @@ en: 51af619ed8532a43 zh: a5ad878c63d0e046 /session-persistence-event-catalog/resolved-persistence-types/header-reason-startsseries: - en: fe0f6163c5202da6 - zh: 98feea5f03b725e1 + en: 0b1ca5c765d716d1 + zh: dd939095c250c4eb /session-persistence-event-catalog/resolved-persistence-types/headerseq-message-step-turn: - en: 05903e55f510fd79 - zh: 90a17b10f682abcb + en: 3d16abb7b9581429 + zh: dc959157864261d8 /session-persistence-event-catalog/resolved-persistence-types/height-width: en: a5df50710083ac25 zh: aad3ccf6f6de70e4 @@ -1521,14 +1521,14 @@ en: 41f73c58a77dfa28 zh: af77f4aee3cb4a40 /session-persistence-event-catalog/resolved-persistence-types/inherited: - en: 8a9199b1784c70f5 - zh: 76c98bc74686fda0 + en: 6ce6ddac6d815805 + zh: f7196176e902c965 /session-persistence-event-catalog/resolved-persistence-types/inserted-outcome-removedcount-start: en: 346d884a7a74e48d zh: 646ac1021f9ca920 /session-persistence-event-catalog/resolved-persistence-types/interrupted-message-step-stream: - en: ec10cd8e9c202a81 - zh: e08f859bcb13f0d4 + en: 89fb3f919d181c86 + zh: 4380624236500687 /session-persistence-event-catalog/resolved-persistence-types/kind-aborted-reason: en: 48424cbed3fbc269 zh: 2ce88c04ad002104 @@ -1569,8 +1569,8 @@ en: 78e34e6d0d70339e zh: 072127e40cfb9686 /session-persistence-event-catalog/resolved-persistence-types/kind-forked: - en: dc750041126fe853 - zh: 736505cd1e57db62 + en: e2588043ee1a8d50 + zh: d87a5bff12b9190f /session-persistence-event-catalog/resolved-persistence-types/kind-hook: en: 78278a869370695f zh: 6cdc47f1876f3b23 @@ -1617,14 +1617,14 @@ en: a8a338be3b91008f zh: c7632c42c869c2f6 /session-persistence-event-catalog/resolved-persistence-types/kind-interrupted: - en: b2dea1e08facaa40 - zh: 71c9b8d4e3d1d2b8 + en: 452b4a96d072a9b9 + zh: d63c8ab84bd37dbb /session-persistence-event-catalog/resolved-persistence-types/kind-legacy: en: c6f68741f8631d4f zh: 090b58f2b86c02d0 /session-persistence-event-catalog/resolved-persistence-types/kind-max-tokens: - en: 4746f91df74cc1dd - zh: d0427e9191359299 + en: f85b7a64a6a5f1f7 + zh: 3f4ad5183e1020fd /session-persistence-event-catalog/resolved-persistence-types/kind-model-selection: en: a5165486dca91116 zh: b7051ca8167806ef @@ -1872,8 +1872,8 @@ en: 82b0989dad6bbfc0 zh: 0789b63f1d59b2ed /session-persistence-event-catalog/resolved-persistence-types/message-step-turn: - en: dcaa676f106cfdfd - zh: e3941fea97c943fb + en: 762219ab10a2d9b1 + zh: ce31f3b385595b96 /session-persistence-event-catalog/resolved-persistence-types/message-teamid-version: en: f778769acb264dd5 zh: eba9b81d04e9f57b @@ -1890,8 +1890,8 @@ en: 8ebd37343b638773 zh: bf7ffa9a60ca42a8 /session-persistence-event-catalog/resolved-persistence-types/reason-turn: - en: a4ba4d0ee1396381 - zh: b6f595f8a696d512 + en: 2d45d5c5e3959d12 + zh: df4d0d7fca4e26bc /session-persistence-event-catalog/resolved-persistence-types/role-user: en: 04b34b8ffe7e7764 zh: a792d5371516fd9d @@ -1902,11 +1902,11 @@ en: 7a2ab7b62244f43b zh: 1084e3f8876feebc /session-persistence-event-catalog/resolved-persistence-types/step-stream-turn: - en: 84004f9b9c6bf24c - zh: ce1abe27b0bc43e2 + en: d911fd8591d66386 + zh: cba2966a909b9293 /session-persistence-event-catalog/resolved-persistence-types/step-turn: - en: 989fad01cdd866ba - zh: 4f08dafda68f0c77 + en: 4bbf63488cce88c9 + zh: 46b40433a749c133 /session-persistence-event-catalog/resolved-persistence-types/targets: en: 5360af614fe753e3 zh: 96427c489cc71de6 @@ -1917,8 +1917,8 @@ en: 8ab873d30e062fd5 zh: a138832c6e299ebb /session-persistence-event-catalog/resolved-persistence-types/turn: - en: c58b89cec274f956 - zh: 056a29ed1ada9690 + en: ea32b4165dbfb182 + zh: 57f48af06cfa201c /session-persistence-event-catalog/resolved-persistence-types/type-agent-preset-selected: en: c8c731ee23bed85a zh: f4ffc80f7828701d diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 86e2167aa2..4710ea562d 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -160,7 +160,7 @@ export type SessionEvent = { }[T] ``` -Sources: [`packages/core/session/src/types.ts:432`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:440`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:463`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:494`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:433`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:441`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:495`](../packages/core/session/src/types.ts) ## Events @@ -290,7 +290,7 @@ Source: [`packages/interaction/user-approval/src/index.ts:40`](../packages/inter 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] } ``` -Source: [`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) @@ -320,7 +320,7 @@ Source: [`packages/core/session/src/types.ts:356`](../packages/core/session/src/ Types: [TokenUsage](subsystems/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:342`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) ### `command/*` @@ -508,7 +508,7 @@ Source: [`packages/deliverables/tool-present/src/types.ts:15`](../packages/deliv } ``` -Source: [`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) ### `feedback/*` @@ -753,7 +753,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:403`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:404`](../packages/core/session/src/types.ts) @@ -772,7 +772,7 @@ Source: [`packages/core/session/src/types.ts:403`](../packages/core/session/src/ } ``` -Source: [`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:392`](../packages/core/session/src/types.ts) ### `sandbox/*` @@ -849,7 +849,7 @@ Source: [`packages/schedule/schedule/src/types.ts:365`](../packages/schedule/sch 'session/end-seed': { inherited?: true } ``` -Source: [`packages/core/session/src/types.ts:428`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:429`](../packages/core/session/src/types.ts) @@ -911,7 +911,7 @@ Source: [`packages/session/session-log-deepseek/src/types.ts:81`](../packages/se 'step/end': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) @@ -922,7 +922,7 @@ Source: [`packages/core/session/src/types.ts:302`](../packages/core/session/src/ 'step/start': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:300`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) ### `subagent/*` @@ -998,7 +998,7 @@ Source: [`packages/subagent/tool-subagent/src/model-selection-state.ts:17`](../p 'system/message': { turn: number; step: number; message: SystemMessage } ``` -Source: [`packages/core/session/src/types.ts:331`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:332`](../packages/core/session/src/types.ts) ### `team/*` @@ -1091,7 +1091,7 @@ Source: [`packages/todo/tool-todo/src/types.ts:33`](../packages/todo/tool-todo/s Types: [ToolCallId](subsystems/core.md) -Source: [`packages/core/session/src/types.ts:362`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) @@ -1172,7 +1172,7 @@ Source: [`packages/core/tool-executor-ptc/src/types.ts:45`](../packages/core/too } ``` -Source: [`packages/core/session/src/types.ts:376`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:377`](../packages/core/session/src/types.ts) ### `tool-workflow/*` @@ -1252,7 +1252,7 @@ Source: [`packages/workflow/tool-workflow/src/types.ts:47`](../packages/workflow Types: [TurnEndReason](subsystems/session.md) -Source: [`packages/core/session/src/types.ts:298`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) @@ -1268,7 +1268,7 @@ Source: [`packages/core/session/src/types.ts:298`](../packages/core/session/src/ 'turn/start': { turn: number } ``` -Source: [`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) ### `user/*` @@ -1287,7 +1287,7 @@ Source: [`packages/core/session/src/types.ts:289`](../packages/core/session/src/ 'user/message': UserMessage ``` -Source: [`packages/core/session/src/types.ts:310`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) ### `web/*` @@ -3398,7 +3398,7 @@ Attribution-only additions: `tmux-context`, `user-question-reply`, `working-dire SHA-256: `9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7` -Sources: [`packages/core/session/src/types.ts:241`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:242`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4528,7 +4528,7 @@ Sources: [`packages/llm/llm/src/types.ts:448`](../packages/llm/llm/src/types.ts) SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` -Sources: [`packages/core/session/src/types.ts:255`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:256`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4547,7 +4547,7 @@ Sources: [`packages/core/session/src/types.ts:255`](../packages/core/session/src SHA-256: `530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6` -Sources: [`packages/core/session/src/types.ts:274`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:275`](../packages/core/session/src/types.ts) One of: @@ -4885,7 +4885,7 @@ Sources: [`packages/subagent/subagent/src/continuation-messages.ts:29`](../packa SHA-256: `335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5` -Sources: [`packages/core/session/src/types.ts:463`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) One of: @@ -5350,7 +5350,7 @@ Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` -Sources: [`packages/core/session/src/types.ts:233`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:234`](../packages/core/session/src/types.ts) | kind | Form property | Other required fields | Full definition | |---|---|---|---| @@ -5820,7 +5820,7 @@ Sources: [`packages/interaction/commands/src/types.ts:105`](../packages/interact SHA-256: `e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1` -Sources: [`packages/core/session/src/types.ts:362`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5979,7 +5979,7 @@ SHA-256: `cbbe8377ee744964537dbafd83607219e58ba79a13f6db0d0645c7ad3d5e8a09` SHA-256: `a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735` -Sources: [`packages/core/session/src/types.ts:384`](../packages/core/session/src/types.ts) · [`packages/core/tool-executor-ptc/src/types.ts:27`](../packages/core/tool-executor-ptc/src/types.ts) +Sources: [`packages/core/session/src/types.ts:385`](../packages/core/session/src/types.ts) · [`packages/core/tool-executor-ptc/src/types.ts:27`](../packages/core/tool-executor-ptc/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6199,7 +6199,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:38`](../packages/compacti SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` -Sources: [`packages/core/session/src/types.ts:465`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:466`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6213,7 +6213,7 @@ Sources: [`packages/core/session/src/types.ts:465`](../packages/core/session/src SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` -Sources: [`packages/core/session/src/types.ts:213`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:214`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6226,7 +6226,7 @@ Sources: [`packages/core/session/src/types.ts:213`](../packages/core/session/src SHA-256: `5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777` -Sources: [`packages/core/session/src/types.ts:376`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:377`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6268,7 +6268,7 @@ Sources: [`packages/llm/llm/src/types.ts:161`](../packages/llm/llm/src/types.ts) SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` -Sources: [`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:392`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6282,7 +6282,7 @@ Sources: [`packages/core/session/src/types.ts:391`](../packages/core/session/src SHA-256: `f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb` -Sources: [`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6365,7 +6365,7 @@ SHA-256: `e3e77b26f0148755a505f5b8ea843a3be117827d4703bb5754d9dc8ddbef521f` SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` -Sources: [`packages/core/session/src/types.ts:428`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:429`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6393,7 +6393,7 @@ Sources: [`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/typ SHA-256: `1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d` -Sources: [`packages/core/session/src/types.ts:342`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6561,7 +6561,7 @@ Sources: [`packages/session/session-title/src/types.ts:29`](../packages/session/ SHA-256: `ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7` -Sources: [`packages/core/session/src/types.ts:229`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:230`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6742,7 +6742,7 @@ SHA-256: `88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa` SHA-256: `56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23` -Sources: [`packages/core/session/src/types.ts:222`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:223`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -6766,7 +6766,7 @@ Sources: [`packages/core/session/src/types.ts:197`](../packages/core/session/src SHA-256: `ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7` -Sources: [`packages/core/session/src/types.ts:215`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) +Sources: [`packages/core/session/src/types.ts:216`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7721,7 +7721,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:230`](../packages/exper SHA-256: `6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5` -Sources: [`packages/core/session/src/types.ts:331`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:332`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7802,7 +7802,7 @@ Sources: [`packages/interaction/permission-presets/src/index.ts:53`](../packages SHA-256: `e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654` -Sources: [`packages/core/session/src/types.ts:298`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7856,7 +7856,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:82`](../packages/compacti SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` -Sources: [`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7870,7 +7870,7 @@ Sources: [`packages/core/session/src/types.ts:356`](../packages/core/session/src SHA-256: `ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545` -Sources: [`packages/core/session/src/types.ts:300`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7921,7 +7921,7 @@ Sources: [`packages/todo/tool-todo/src/types.ts:33`](../packages/todo/tool-todo/ SHA-256: `f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d` -Sources: [`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) +Sources: [`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 50d6f7efbc..059dcad706 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -162,7 +162,7 @@ export type SessionEvent = { }[T] ``` -来源:[`packages/core/session/src/types.ts:432`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:440`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:463`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:494`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:433`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:441`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:495`](../packages/core/session/src/types.ts) ## 事件 @@ -292,7 +292,7 @@ export type SessionEvent = { 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] } ``` -来源:[`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) @@ -322,7 +322,7 @@ export type SessionEvent = { 类型:[TokenUsage](subsystems/llm-streaming.zh.md) -来源:[`packages/core/session/src/types.ts:342`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) ### `command/*` @@ -510,7 +510,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) ### `feedback/*` @@ -755,7 +755,7 @@ export type SessionEvent = { 'request/context': RequestContext ``` -来源:[`packages/core/session/src/types.ts:403`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:404`](../packages/core/session/src/types.ts) @@ -774,7 +774,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:392`](../packages/core/session/src/types.ts) ### `sandbox/*` @@ -851,7 +851,7 @@ export type SessionEvent = { 'session/end-seed': { inherited?: true } ``` -来源:[`packages/core/session/src/types.ts:428`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:429`](../packages/core/session/src/types.ts) @@ -913,7 +913,7 @@ export type SessionEvent = { 'step/end': { turn: number; step: number } ``` -来源:[`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) @@ -924,7 +924,7 @@ export type SessionEvent = { 'step/start': { turn: number; step: number } ``` -来源:[`packages/core/session/src/types.ts:300`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) ### `subagent/*` @@ -1000,7 +1000,7 @@ export type SessionEvent = { 'system/message': { turn: number; step: number; message: SystemMessage } ``` -来源:[`packages/core/session/src/types.ts:331`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:332`](../packages/core/session/src/types.ts) ### `team/*` @@ -1093,7 +1093,7 @@ export type SessionEvent = { 类型:[ToolCallId](subsystems/core.zh.md) -来源:[`packages/core/session/src/types.ts:362`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) @@ -1174,7 +1174,7 @@ export type SessionEvent = { } ``` -来源:[`packages/core/session/src/types.ts:376`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:377`](../packages/core/session/src/types.ts) ### `tool-workflow/*` @@ -1254,7 +1254,7 @@ export type SessionEvent = { 类型:[TurnEndReason](subsystems/session.zh.md) -来源:[`packages/core/session/src/types.ts:298`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) @@ -1270,7 +1270,7 @@ export type SessionEvent = { 'turn/start': { turn: number } ``` -来源:[`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) ### `user/*` @@ -1289,7 +1289,7 @@ export type SessionEvent = { 'user/message': UserMessage ``` -来源:[`packages/core/session/src/types.ts:310`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) ### `web/*` @@ -3400,7 +3400,7 @@ SHA-256: `0f6265188dae7ba6faa26830a180bb4deb0760561f97ee0c9d399ccf6c9cf1f7` SHA-256: `9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7` -来源:[`packages/core/session/src/types.ts:241`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:242`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4530,7 +4530,7 @@ SHA-256: `0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555` SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` -来源:[`packages/core/session/src/types.ts:255`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:256`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4549,7 +4549,7 @@ SHA-256: `b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081` SHA-256: `530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6` -来源:[`packages/core/session/src/types.ts:274`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:275`](../packages/core/session/src/types.ts) 以下类型之一: @@ -4887,7 +4887,7 @@ SHA-256: `4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a` SHA-256: `335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5` -来源:[`packages/core/session/src/types.ts:463`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:464`](../packages/core/session/src/types.ts) 以下类型之一: @@ -5352,7 +5352,7 @@ SHA-256: `1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0` SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` -来源:[`packages/core/session/src/types.ts:233`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:234`](../packages/core/session/src/types.ts) | kind | form 属性 | 其他必需字段 | 完整定义 | |---|---|---|---| @@ -5822,7 +5822,7 @@ SHA-256: `a853902cfab417b8f08aa51ad6855fea46f34ed4588a74e47403035111d0fb86` SHA-256: `e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1` -来源:[`packages/core/session/src/types.ts:362`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:363`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5981,7 +5981,7 @@ SHA-256: `cbbe8377ee744964537dbafd83607219e58ba79a13f6db0d0645c7ad3d5e8a09` SHA-256: `a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735` -来源:[`packages/core/session/src/types.ts:384`](../packages/core/session/src/types.ts) · [`packages/core/tool-executor-ptc/src/types.ts:27`](../packages/core/tool-executor-ptc/src/types.ts) +来源:[`packages/core/session/src/types.ts:385`](../packages/core/session/src/types.ts) · [`packages/core/tool-executor-ptc/src/types.ts:27`](../packages/core/tool-executor-ptc/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6201,7 +6201,7 @@ SHA-256: `9e41386b3a0c9572b0d63078492ebb3997da7d3a830d44e0259418bd02f4bcb2` SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` -来源:[`packages/core/session/src/types.ts:465`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:466`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6215,7 +6215,7 @@ SHA-256: `bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825` SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` -来源:[`packages/core/session/src/types.ts:213`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:214`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6228,7 +6228,7 @@ SHA-256: `79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985` SHA-256: `5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777` -来源:[`packages/core/session/src/types.ts:376`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:377`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6270,7 +6270,7 @@ SHA-256: `693f4952fb5565da96c06bace8924b098ac2fbc915fde0ff8019701183abc057` SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` -来源:[`packages/core/session/src/types.ts:391`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:392`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6284,7 +6284,7 @@ SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` SHA-256: `f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb` -来源:[`packages/core/session/src/types.ts:312`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6367,7 +6367,7 @@ SHA-256: `e3e77b26f0148755a505f5b8ea843a3be117827d4703bb5754d9dc8ddbef521f` SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` -来源:[`packages/core/session/src/types.ts:428`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:429`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6395,7 +6395,7 @@ SHA-256: `fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42` SHA-256: `1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d` -来源:[`packages/core/session/src/types.ts:342`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6563,7 +6563,7 @@ SHA-256: `1b5649238876e28811e80f10ec67a00c197ad3babd4ecc61a22b09064b88c597` SHA-256: `ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7` -来源:[`packages/core/session/src/types.ts:229`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:230`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6744,7 +6744,7 @@ SHA-256: `88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa` SHA-256: `56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23` -来源:[`packages/core/session/src/types.ts:222`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:223`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6768,7 +6768,7 @@ SHA-256: `eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c` SHA-256: `ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7` -来源:[`packages/core/session/src/types.ts:215`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) +来源:[`packages/core/session/src/types.ts:216`](../packages/core/session/src/types.ts) · [`packages/llm/llm/src/types.ts:159`](../packages/llm/llm/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7723,7 +7723,7 @@ SHA-256: `b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1` SHA-256: `6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5` -来源:[`packages/core/session/src/types.ts:331`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:332`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7804,7 +7804,7 @@ SHA-256: `8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad` SHA-256: `e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654` -来源:[`packages/core/session/src/types.ts:298`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:299`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7858,7 +7858,7 @@ SHA-256: `5dd766ccd1702a1142ad8b4bd44f2242f8e8a6752669ad3de0a5d224329b1438` SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` -来源:[`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:357`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7872,7 +7872,7 @@ SHA-256: `54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0` SHA-256: `ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545` -来源:[`packages/core/session/src/types.ts:300`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:301`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:303`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7923,7 +7923,7 @@ SHA-256: `79ddc907312f97cf9553d4841e8b3fc937097bd8d97900a790efad3c05255e99` SHA-256: `f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d` -来源:[`packages/core/session/src/types.ts:289`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) +来源:[`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) · [`packages/deliverables/workspace-changes/src/types.ts:106`](../packages/deliverables/workspace-changes/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 095946eff0..559babc96f 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -123,7 +123,7 @@ {"digest":"15d5dfdd822aa35e115afd74a8982825a493880457774e6850bc1520b50875e4","names":[],"sources":[]}, {"digest":"16d0507cb94b4cfc84a87446b1ba7652d6ec1d65ee1684789e747e30d542800e","names":[],"sources":[]}, {"digest":"17aae616ef020b8b9f011ec398ec935450fb06d3e2a0722c456f63aeaf5ff728","names":[],"sources":[]}, - {"digest":"17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3","names":[],"sources":["packages/core/session/src/types.ts:428"]}, + {"digest":"17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3","names":[],"sources":["packages/core/session/src/types.ts:429"]}, {"digest":"18dc21f12bbac8ade8377e6fbb54179e20c3d955d73fba3244c57fb6bf001df0","names":["packages/schedule/schedule/src/types.ts#ScheduleDeleteChange"],"sources":["packages/schedule/schedule/src/types.ts:230"]}, {"digest":"18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f","names":["packages/session/session-persistence-jsonl/src/format.ts#HeaderLine"],"sources":["packages/session/session-persistence-jsonl/src/format.ts:83"]}, {"digest":"18fcdd273a2f2f9d813a3be5e71df5903a963a5c88e46b90b14de6e2db890da0","names":[],"sources":[]}, @@ -138,7 +138,7 @@ {"digest":"1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5","names":[],"sources":[]}, {"digest":"1c2686c0682e7bc51d61117b2652bd4a80707e331aa276d6ef915ae32534a330","names":[],"sources":[]}, {"digest":"1c5a58f4599bd4a9711712551ffe2442a5e5fcd0758bafe630cc4ead850bdaa7","names":[],"sources":[]}, - {"digest":"1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d","names":[],"sources":["packages/core/session/src/types.ts:342"]}, + {"digest":"1ccb56061942f5ccb0d30c9e4f2883b9d115ff906560029de637b61d3cde896d","names":[],"sources":["packages/core/session/src/types.ts:343"]}, {"digest":"1cde1bedde79c5e8a56aee9c05c8e0a579cf5bc611deb85b93fa331a16ca978f","names":["packages/compaction/compaction-image-offload/src/projection.ts#ImageOffloadTarget"],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:9"]}, {"digest":"1d5f04a03ea75fc8eeece544129eba0f49f0c82046e9c404461920390135c7b2","names":[],"sources":[]}, {"digest":"1d76406cbb2ddadb0dbbb51e9d8bc6cf678fed455cf8eb512f36f7c86d37a62f","names":[],"sources":["packages/llm/llm/src/types.ts:157"]}, @@ -197,7 +197,7 @@ {"digest":"326a9bfda27dda5882fb3cbe6e715df41dae2298fdae3d66437457268a665693","names":["packages/llm/llm/src/call-config.ts#LlmCallConfigAdapterDefaults"],"sources":["packages/llm/llm/src/call-config.ts:54"]}, {"digest":"3305a4bb6b6c29b482ba91d59c60b47e8f98282d3dacc8c29e4a4c2712209bdd","names":[],"sources":[]}, {"digest":"33341aac09312300de5a178e6cc6f6544a4876f7f710cfea55eda473c8d329ef","names":["packages/llm/llm/src/assistant-stream.ts#AssistantStreamRecord"],"sources":["packages/llm/llm/src/assistant-stream.ts:20"]}, - {"digest":"335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5","names":["packages/core/session/src/types.ts#SurfaceOp"],"sources":["packages/core/session/src/types.ts:463"]}, + {"digest":"335e242de1fcc17b6ca920fc420d71bec2d76e53e37955c00948b65ab77f05c5","names":["packages/core/session/src/types.ts#SurfaceOp"],"sources":["packages/core/session/src/types.ts:464"]}, {"digest":"347de3380f2da308d0c74e08821f9e85559f55af4c5010795b110d00f7fc9dbd","names":[],"sources":[]}, {"digest":"34d1ab5c5df378186d6054b1a1beea9a41e41965d6f336f0bc0025c441a82e66","names":[],"sources":[]}, {"digest":"35203ba7ad5ef6f97d556b85df20ae98f04f09c65748cecdf8eefdb8b6405ffc","names":[],"sources":[]}, @@ -269,14 +269,14 @@ {"digest":"525254db03b1d1e6b74cf55aced52817568331ac1f96c0818728910b6692e336","names":[],"sources":[]}, {"digest":"529e0ccd0e34079ab4ff21ed87f810cee0388246263bf22e8aba5986b56fae05","names":[],"sources":["packages/util/values/src/index.ts:4"]}, {"digest":"52c6113cb0e53f345324bf84f01928bea5d5df57ee80bc0dd65407b8bc5a3734","names":[],"sources":[]}, - {"digest":"5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777","names":[],"sources":["packages/core/session/src/types.ts:376"]}, - {"digest":"530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6","names":["packages/core/session/src/types.ts#RequestHeaderReason"],"sources":["packages/core/session/src/types.ts:274"]}, + {"digest":"5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777","names":[],"sources":["packages/core/session/src/types.ts:377"]}, + {"digest":"530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6","names":["packages/core/session/src/types.ts#RequestHeaderReason"],"sources":["packages/core/session/src/types.ts:275"]}, {"digest":"53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac","names":[],"sources":[]}, {"digest":"53cf1704ae0709c7678bcf070c83c619fc48ca1b5c173b74cfa8702f22a8e492","names":[],"sources":[]}, - {"digest":"54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0","names":[],"sources":["packages/core/session/src/types.ts:356"]}, + {"digest":"54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0","names":[],"sources":["packages/core/session/src/types.ts:357"]}, {"digest":"557e148d30b79ee48645850832b30c717d7c3b64641deb5d6133b8b4e91ee0b8","names":[],"sources":[]}, {"digest":"5654685d7557ec747e74887237065e626a5bdfa426ca43f7fbb0b6fee9b0916c","names":[],"sources":[]}, - {"digest":"56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23","names":[],"sources":["packages/core/session/src/types.ts:222"]}, + {"digest":"56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23","names":[],"sources":["packages/core/session/src/types.ts:223"]}, {"digest":"570e85022434613394418ad33e77e9f1f7a05699b33d0b62eae0677a638c3833","names":[],"sources":[]}, {"digest":"576a2de8355eb09850963ff5953420b172e274d9283666eb7d889097db120796","names":[],"sources":[]}, {"digest":"5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc","names":[],"sources":[]}, @@ -328,7 +328,7 @@ {"digest":"6ab45ac76839722df912f3ba50f1c6b41f2d614bde11f1aabfae04117ccdc80d","names":[],"sources":[]}, {"digest":"6b23ed9ce1b397e602788dbe033693bf97642a69e23fcab1cc45bf6f13b6d619","names":[],"sources":[]}, {"digest":"6bbe793f6a93dc8d50a4d4d3fbb6f8ed15650bcb7e151d28669628f7b7c3fc25","names":["packages/goal/goal/src/types.ts#GoalSnapshot"],"sources":["packages/goal/goal/src/types.ts:60"]}, - {"digest":"6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5","names":[],"sources":["packages/core/session/src/types.ts:331"]}, + {"digest":"6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5","names":[],"sources":["packages/core/session/src/types.ts:332"]}, {"digest":"6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800","names":[],"sources":["packages/core/session/src/types.ts:192"]}, {"digest":"6c1cccb433ddc153facb380c7dda956237ba5c31f8a532a69142dc277890cc9b","names":[],"sources":[]}, {"digest":"6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d","names":[],"sources":["packages/core/session/src/types.ts:193"]}, @@ -358,7 +358,7 @@ {"digest":"763c8a20af487263a0080548274f7437ef4a86e0ba8769127d1ced10a72c664d","names":[],"sources":[]}, {"digest":"76632533f67879dcb346fcae640540dbc89b2472b0bce88c59f7e48fc5c0e668","names":[],"sources":[]}, {"digest":"78a9be340090b735a39980e7222ce730c972fbcf1de7c9e0aef2125884b7caee","names":[],"sources":[]}, - {"digest":"79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985","names":[],"sources":["packages/core/session/src/types.ts:213"]}, + {"digest":"79650cfa10aa3c52440328d85e8a25f0ffadc8d7efd784e3c0819d8bb74a1985","names":[],"sources":["packages/core/session/src/types.ts:214"]}, {"digest":"79a4c87f8bfb4d6d05cd9952b99210d6a7db3b478c4a01d94b4c50602308c056","names":[],"sources":[]}, {"digest":"79ddc907312f97cf9553d4841e8b3fc937097bd8d97900a790efad3c05255e99","names":[],"sources":["packages/todo/tool-todo/src/types.ts:33"]}, {"digest":"7a651f3b672c52fb615f22c0ce9cb3cc5b22aad92e6bbeefb0808fd7b9233a50","names":[],"sources":[]}, @@ -440,7 +440,7 @@ {"digest":"99f0e98184709ad10f27bfdeaafb4457d9d2b413f402331764798cdb7d3cbe4d","names":[],"sources":[]}, {"digest":"9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:64"]}, {"digest":"9a410ddf56792b2b7cd4a224a2e54dc4dee30a8e8e6b1c2b9a1d19992b217adc","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowAgentStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:20"]}, - {"digest":"9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7","names":["packages/core/session/src/types.ts#EpochHeader"],"sources":["packages/core/session/src/types.ts:241"]}, + {"digest":"9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7","names":["packages/core/session/src/types.ts#EpochHeader"],"sources":["packages/core/session/src/types.ts:242"]}, {"digest":"9ac52f0f84fec2eb9f71c2937e497d759db5ca0da4836d93a679d113684141f2","names":[],"sources":[]}, {"digest":"9acbe713f3f641921dd3333b240aa72e176d795327c24e8d9db9b68b16771b49","names":[],"sources":[]}, {"digest":"9b4fd974c124c83743efe030ba4e1250e087505f3f74588716a521fb8d453267","names":[],"sources":[]}, @@ -471,7 +471,7 @@ {"digest":"a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:14"]}, {"digest":"a720757f704a2512e9d2f20da4a093e582472176236a75ab8b8eb7aaff17d85a","names":[],"sources":[]}, {"digest":"a7cf43ce7c2a4c038feed1885cd7a00d5c6ee2d90a7e0d56b46f78a3e1ca327f","names":[],"sources":[]}, - {"digest":"a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735","names":[],"sources":["packages/core/session/src/types.ts:384","packages/core/tool-executor-ptc/src/types.ts:27"]}, + {"digest":"a81059ca06999da1e712414520c2c65e491d052fcf9640fae20aa38f0a5dc735","names":[],"sources":["packages/core/session/src/types.ts:385","packages/core/tool-executor-ptc/src/types.ts:27"]}, {"digest":"a853902cfab417b8f08aa51ad6855fea46f34ed4588a74e47403035111d0fb86","names":[],"sources":["packages/interaction/commands/src/types.ts:105"]}, {"digest":"a8a2b9011fc067862df7ce40748868467e5778283d7ac193c13f77684a914c57","names":[],"sources":[]}, {"digest":"a9059a81430b320792bbb7c2ee1f8f6c77ff71e40ee44c18aec72e157c522694","names":[],"sources":[]}, @@ -485,10 +485,10 @@ {"digest":"aa93010d0e521ad7c42273f58d5c9b8bf1dfc94edf1b805a3971b364a35c1877","names":[],"sources":[]}, {"digest":"aacda84a69739238aa782eea902d3073017d9d74b9808de2bf5a83c9738cbdc6","names":[],"sources":[]}, {"digest":"aae343bc3d663c83f2e8b5e1c7eea5d509dc7a5361bc8bd8b5ac3bb8d3b1ed56","names":[],"sources":[]}, - {"digest":"ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7","names":[],"sources":["packages/core/session/src/types.ts:215","packages/llm/llm/src/types.ts:159"]}, + {"digest":"ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7","names":[],"sources":["packages/core/session/src/types.ts:216","packages/llm/llm/src/types.ts:159"]}, {"digest":"aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba","names":[],"sources":[]}, {"digest":"abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c","names":["packages/web/web-search-deepseek/src/provider.ts#DeepSeekSearchLlmRequest"],"sources":["packages/web/web-search-deepseek/src/provider.ts:55"]}, - {"digest":"ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585","names":[],"sources":["packages/core/session/src/types.ts:391"]}, + {"digest":"ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585","names":[],"sources":["packages/core/session/src/types.ts:392"]}, {"digest":"ad22a5ca5bbaab2e1440779cd3648e85ddfc6f73b5207394eda699555cf31430","names":[],"sources":[]}, {"digest":"ad3b56aa2fc1ad4250e7399295d34a8eae592e1907e85852e2291b2e498a30bc","names":[],"sources":[]}, {"digest":"ad92f473a03ae72599ff26c86e897c25e16269519ad2a87340f0bea946517af8","names":[],"sources":[]}, @@ -502,7 +502,7 @@ {"digest":"b0127044ab31a702bddfd785d345f5abd7a70876746e895ce443afa3e60ddf2d","names":[],"sources":[]}, {"digest":"b062078e899958f99ae464514578b8c093924dfe34bd9a835932b420ff2150b1","names":[],"sources":[]}, {"digest":"b0b0eb1b16490f6bee135b2377e8f8c39227974c799ad7d49ff418af23ecbc35","names":["packages/attachment/attachment/src/types.ts#ImageAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:11"]}, - {"digest":"b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081","names":["packages/core/session/src/types.ts#RequestContext"],"sources":["packages/core/session/src/types.ts:255"]}, + {"digest":"b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081","names":["packages/core/session/src/types.ts#RequestContext"],"sources":["packages/core/session/src/types.ts:256"]}, {"digest":"b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7","names":[],"sources":[]}, {"digest":"b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1","names":[],"sources":["packages/experimental/agent-team/src/types.ts:230"]}, {"digest":"b1f62380f6746fedd629e71065e3583cef83334875b499ac9665c2eb87acfbf5","names":[],"sources":[]}, @@ -542,7 +542,7 @@ {"digest":"bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3","names":[],"sources":[]}, {"digest":"bb94f3217aa56c8876bbff0b8460d6a73cbead545659abb29e76cd0cf2cb92d6","names":[],"sources":[]}, {"digest":"bbc5696e3f13c758237b316e3cf08cda0b9fd51ffe672539883457769faa185d","names":[],"sources":[]}, - {"digest":"bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825","names":[],"sources":["packages/core/session/src/types.ts:465"]}, + {"digest":"bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825","names":[],"sources":["packages/core/session/src/types.ts:466"]}, {"digest":"bd499eac047efe091a4df7382eadd06d25cf0cb31fee3981e8b24d85762841cd","names":[],"sources":[]}, {"digest":"bf16d2e98a7f13894ded2cffe5ce857bf473954a0e3c0ed9bc7739e2e1c7b78a","names":[],"sources":[]}, {"digest":"c0ea97bc89dfc46fa94eab956f5c3ee6af2f964aa7db6327cb18b451f207bef7","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowAgentEndData"],"sources":["packages/workflow/tool-workflow/src/types.ts:29"]}, @@ -613,8 +613,8 @@ {"digest":"e41bdebe246abe17154de7e7a1d81035437eee8d20e7f1edff0d91e2598ad828","names":[],"sources":[]}, {"digest":"e42b0f40b5d0b628c6e1c44a8fb9eda0780037a81959e1b93d2dfb47b46b0e87","names":[],"sources":[]}, {"digest":"e438a9d4fb883b3e4a8d9fc8913aa1550ed50eb384bfbf943100a5605b537498","names":[],"sources":[]}, - {"digest":"e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654","names":[],"sources":["packages/core/session/src/types.ts:298"]}, - {"digest":"e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1","names":[],"sources":["packages/core/session/src/types.ts:362"]}, + {"digest":"e481c46af3813e0010558e93f578b2986acd658404cec2d1679e3ac2a6c48654","names":[],"sources":["packages/core/session/src/types.ts:299"]}, + {"digest":"e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1","names":[],"sources":["packages/core/session/src/types.ts:363"]}, {"digest":"e4cac694f8b6e1d52e48c699464f1c4c26111ef87e558f7931040d00fdc8d486","names":[],"sources":[]}, {"digest":"e5d3828df1ec3e2a66879de0659e0f4866d9cfffc00825ee731a66f8a0c03d98","names":[],"sources":[]}, {"digest":"e6063d0451dc02026fd9b54ad3f77c7b1b6392ad3e872a7737ac84e13ca72344","names":["packages/schedule/schedule/src/types.ts#EveryScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:244"]}, @@ -630,18 +630,18 @@ {"digest":"eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c","names":[],"sources":["packages/core/session/src/types.ts:197"]}, {"digest":"ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8","names":[],"sources":[]}, {"digest":"ec38b5949af8eacaf00df002f4acbe344f934f8a061e9cdc65a52a48e5f6dd93","names":[],"sources":[]}, - {"digest":"ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7","names":[],"sources":["packages/core/session/src/types.ts:229"]}, + {"digest":"ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7","names":[],"sources":["packages/core/session/src/types.ts:230"]}, {"digest":"edbbfff1128099fda7b792c56330d2cb04debc9790988e66d1c3f4026e813e0e","names":[],"sources":[]}, {"digest":"edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf","names":[],"sources":[]}, {"digest":"ee577a0cc18664c9daee50e9455153321155604f8f1817362f8f4a4b6fb9e1ad","names":[],"sources":[]}, {"digest":"eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4","names":["packages/schedule/schedule/src/types.ts#ScheduleCreateChange"],"sources":["packages/schedule/schedule/src/types.ts:223"]}, {"digest":"eefbea819caeeea91ccb02dfafc16c68dd7f961cf9c1b2be25a2084509cf5c5a","names":[],"sources":[]}, - {"digest":"ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545","names":[],"sources":["packages/core/session/src/types.ts:300","packages/core/session/src/types.ts:302"]}, + {"digest":"ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545","names":[],"sources":["packages/core/session/src/types.ts:301","packages/core/session/src/types.ts:303"]}, {"digest":"ef226a90ddac6cd8e631a3a337a3a3e27f9494be92befb7c718b404681d75e21","names":[],"sources":[]}, {"digest":"ef4f00923b9edbae15c7ef05320280bf61147ca17146cf59690359bfd5e5da45","names":[],"sources":[]}, {"digest":"f05fb85e715af4ab4de0b6ba111166dd0435bd8bb74a0fa0f32b9d174113fc7c","names":[],"sources":[]}, {"digest":"f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b","names":["packages/core/agent/src/types.ts#ModelSelection"],"sources":["packages/core/agent/src/types.ts:79"]}, - {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:233"]}, + {"digest":"f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402","names":["packages/core/session/src/types.ts#TurnEndReason"],"sources":["packages/core/session/src/types.ts:234"]}, {"digest":"f1996af2602e6f62b5ab179ca5c4af00d8753938b74cc6ef102de09e99e74a7e","names":[],"sources":[]}, {"digest":"f19bee84bf3d20904553cdcd57465232bc1c2a194f54c4d195292ba0487223a6","names":["packages/attachment/attachment/src/types.ts#FileAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:39"]}, {"digest":"f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515","names":[],"sources":["packages/llm/llm/src/types.ts:476"]}, @@ -650,7 +650,7 @@ {"digest":"f2da0f27c1e6add59982c37b15e4a4912c5b33466859cce3b13d503600e24aef","names":["packages/llm/llm/src/types.ts#FileBlock"],"sources":["packages/llm/llm/src/types.ts:98"]}, {"digest":"f311671e07bc7fa645a0b6597de9966b97147956565296ba76a36543801b66c5","names":["packages/llm/llm/src/types.ts#SystemPromptUpdate"],"sources":["packages/llm/llm/src/types.ts:414"]}, {"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]}, - {"digest":"f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb","names":[],"sources":["packages/core/session/src/types.ts:312"]}, + {"digest":"f4ed4717b4c259e933b550a8dcd90dc93628cda8a3c7affcaa53b9c13c1d53eb","names":[],"sources":["packages/core/session/src/types.ts:313"]}, {"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]}, {"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]}, {"digest":"f6329fb30c7ea8013e8975ca5e78284fb7685cc6bd620e8aa4e9a99bc81d45eb","names":[],"sources":[]}, @@ -663,7 +663,7 @@ {"digest":"f731ffe80810b0289b3e694d8f40af6f01865c02a622ee457be90ca808b66e87","names":["packages/subagent/subagent/src/catalog.ts#SubagentCatalogEvent"],"sources":["packages/subagent/subagent/src/catalog.ts:28"]}, {"digest":"f789af5ab844827eb5a4f357c0afae1eeed108c6c22d8ca1a56e586b349a7c85","names":[],"sources":[]}, {"digest":"f88f1b7b6bb733f685f5fb6a8744a5db9199fa53c90463ea1a33bad51153671d","names":[],"sources":[]}, - {"digest":"f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d","names":[],"sources":["packages/core/session/src/types.ts:289","packages/deliverables/workspace-changes/src/types.ts:106"]}, + {"digest":"f90eb4ab2d3897bc20c521a038e3119d581f791ec974b1a0004f63a8ab9e232d","names":[],"sources":["packages/core/session/src/types.ts:290","packages/deliverables/workspace-changes/src/types.ts:106"]}, {"digest":"f97f47b0eb87905ed77cc27c5e4ed75ef805cb372c98905253709de1aab9b63c","names":[],"sources":[]}, {"digest":"f9cfc89e8fe085b4fcc9cd32b74b6f103608c54d7d8cd97b47c01de34f252ba3","names":[],"sources":[]}, {"digest":"fa106c5b33b657e8ef16e8cbf39f3b7d44e5cbcdf4f9303d9db6410f28951e42","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md index 8413bb42c9..e9369b0702 100644 --- a/docs/subsystems/session.md +++ b/docs/subsystems/session.md @@ -708,8 +708,9 @@ interface TurnEndReasonMap { blocked: { kind: 'blocked' } /** * The turn failed. `error` is always a structured failure: the `LlmError` - * facts verbatim, or `{ message: errorChain(error), code: 'UNKNOWN' }` - * flattened from any other error. + * facts verbatim, or `{ message: errorChain(error), code }` flattened from + * any other error, where `code` is `TOOL_ACTIVATION_FAILED` for a failed + * tool condition and `UNKNOWN` otherwise. */ error: { kind: 'error'; error: LlmFailure } /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */ diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md index 2a7400af4f..7971f5e7fd 100644 --- a/docs/subsystems/session.zh.md +++ b/docs/subsystems/session.zh.md @@ -712,8 +712,9 @@ interface TurnEndReasonMap { blocked: { kind: 'blocked' } /** * The turn failed. `error` is always a structured failure: the `LlmError` - * facts verbatim, or `{ message: errorChain(error), code: 'UNKNOWN' }` - * flattened from any other error. + * facts verbatim, or `{ message: errorChain(error), code }` flattened from + * any other error, where `code` is `TOOL_ACTIVATION_FAILED` for a failed + * tool condition and `UNKNOWN` otherwise. */ error: { kind: 'error'; error: LlmFailure } /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */ diff --git a/docs/subsystems/tools.i18n.yaml b/docs/subsystems/tools.i18n.yaml index b05b723c74..f35d7ae166 100644 --- a/docs/subsystems/tools.i18n.yaml +++ b/docs/subsystems/tools.i18n.yaml @@ -14,6 +14,9 @@ /tools/toolrestriction-one-scope-s-live-filter-over-what-it-inherits: en: 8c3fc4ca26f7e314 zh: 2e27263cb25243b9 +/tools/conditional-activation-step-owned-admission: + en: 472eefe8fab01e57 + zh: 0b98e74f87a6c9c0 /tools/executors-and-raw-call-batches: en: 14522295539ea2fb zh: 572c462f2c6b70ad diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index 8d4992e519..e94206a685 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -177,6 +177,50 @@ interface ToolRestriction { } ``` +## Conditional activation — step-owned admission + +A registration may carry a `when` condition. AgentLoop calls `ctx.tools.resolve()` once per proposed step with the captured model selection; the returned set decides that step's tool declarations, executor sections, and every call in its batch, including PTC program subcalls. `ctx.tools.executable()` applies the set at execution and, without one, excludes conditional registrations. A same-name replacement or a new restriction stops unstarted calls from using an admitted registration, and the loop disposes the set once the step's batch settles. + +```ts type-equiv +/** Inputs for a tool's step-time activation condition. */ +interface ToolActivationContext { + /** Agent preparing the step. */ + readonly agent: Agent + /** Provider, model, and optional reasoning effort captured for the step. */ + readonly modelSelection: Readonly + /** Cancellation of step preparation; asynchronous conditions must observe it. */ + readonly signal: AbortSignal +} +``` + +```ts type-equiv +/** Lifecycle-owned conditions for a registered tool. */ +interface ToolRegistrationOptions { + /** + * Decide whether the step's requests may call the tool. Omission enables + * it. False excludes it from both declarations and dispatch; rejection fails + * step preparation. Conditions must not mutate registrations or start tool work. + * @param context - preparing agent, captured model selection, and cancellation signal. + * @returns whether the tool participates in this step. + */ + readonly when?: (context: ToolActivationContext) => boolean | Promise +} +``` + +```ts type-equiv +/** One step's admitted registrations, also used by nested PTC calls. */ +interface ResolvedToolSet { + /** Close admission after the step's tool batch settles. */ + dispose(): void + /** + * Read admitted registrations that remain visible in their original scope. + * @param scope - exact requesting agent; another scope is never admitted. + * @returns original definitions excluding removed or restricted registrations. + */ + view(scope: ScopeKey | undefined): ReadonlyMap +} +``` + ## Executors and raw call batches `ctx.tools.execute()` delegates a complete raw model-call batch to the nearest scoped executor. The service selects the current provider when each batch starts; prompt assembly returns only model input. `agent` is absent for standalone service calls; `log` is absent for programmatic calls outside a model step, such as initialization hooks. An Agent without `log` still scopes tool access but produces no root call/result events. Tool-owned events may still use its Session. diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 43ff3465d3..e18dfbbe5d 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -177,6 +177,50 @@ interface ToolRestriction { } ``` +## 条件准入 — 步骤拥有的准入集合 + +注册可以携带 `when` 条件。AgentLoop 为每个拟议步骤以捕获的模型选择调用一次 `ctx.tools.resolve()`;返回的集合决定该步骤的工具声明、执行器分区以及批次中的每次调用,包括 PTC 程序的子调用。`ctx.tools.executable()` 在执行时应用集合,没有集合时排除条件注册。同名替换或新的限制会阻止尚未开始的调用使用已准入的注册,步骤的批次结束后循环释放集合。 + +```ts type-equiv +/** Inputs for a tool's step-time activation condition. */ +interface ToolActivationContext { + /** Agent preparing the step. */ + readonly agent: Agent + /** Provider, model, and optional reasoning effort captured for the step. */ + readonly modelSelection: Readonly + /** Cancellation of step preparation; asynchronous conditions must observe it. */ + readonly signal: AbortSignal +} +``` + +```ts type-equiv +/** Lifecycle-owned conditions for a registered tool. */ +interface ToolRegistrationOptions { + /** + * Decide whether the step's requests may call the tool. Omission enables + * it. False excludes it from both declarations and dispatch; rejection fails + * step preparation. Conditions must not mutate registrations or start tool work. + * @param context - preparing agent, captured model selection, and cancellation signal. + * @returns whether the tool participates in this step. + */ + readonly when?: (context: ToolActivationContext) => boolean | Promise +} +``` + +```ts type-equiv +/** One step's admitted registrations, also used by nested PTC calls. */ +interface ResolvedToolSet { + /** Close admission after the step's tool batch settles. */ + dispose(): void + /** + * Read admitted registrations that remain visible in their original scope. + * @param scope - exact requesting agent; another scope is never admitted. + * @returns original definitions excluding removed or restricted registrations. + */ + view(scope: ScopeKey | undefined): ReadonlyMap +} +``` + ## 执行器与原始调用批次 `ctx.tools.execute()` 把完整的原始模型调用批次委托给最近作用域的执行器。服务在每个批次开始时选择当前提供者;提示词组装仅返回模型输入。`agent` 在独立服务调用中不存在;`log` 在模型步骤之外的程序调用(例如初始化钩子)中不存在。有 Agent 而没有 `log` 时,调用仍受该 Agent 的工具作用域约束,但不记录根调用/结果事件。工具自身的事件仍可使用 Agent 的 Session。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.i18n.yaml index 6198062ddf..3ca37a1f2a 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 4edb4c80b402de77 zh: 856160ec69c515ea /declare-conditional-tools-through-step-admission/change: - en: 71aba6399833cd1d - zh: b820e301baf72e4e + en: e140ab052beb78ed + zh: 9603c44ae7731ab8 /declare-conditional-tools-through-step-admission/migration: - en: e5130eb20b0fc6b9 - zh: 919131accac0b26f + en: 364c2a62343a608b + zh: c00ab4611b1fc4e3 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md index 672ba0ad20..30d37bca41 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md +++ b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.md @@ -11,15 +11,15 @@ English | [中文](guide.zh.md) `ctx.tools.register(definition, { when })` adds a synchronous or asynchronous condition. AgentLoop resolves conditions once per proposed step with `{ agent, modelSelection, signal }`, before prompt assembly and `agent/pre-step`, and uses the resulting `ResolvedToolSet` for tool declarations, Native dispatch, PTC bindings, and nested calls in that step and its retries. A false condition removes the tool from all of them; a thrown condition ends the turn with `TOOL_ACTIVATION_FAILED`. -The `system-prompt/assemble` waterfall now receives sections, contexts, and variables (`PromptPresentation`) without a tool array, and a returned `tools` field is ignored. Plugins that removed or added tool declarations in that waterfall are affected; their removals no longer reach the request. +The `system-prompt/assemble` waterfall now receives sections, contexts, and variables (`PromptPresentation`) without a tool array, and a returned `tools` field is ignored. Plugins that removed or added tool declarations in that waterfall are affected; their removals no longer reach the request, and a listener that reads `assembly.tools` receives `undefined` and fails at runtime. -Model tool calls run only through their step's admitted set. A call to a conditional tool without a resolved set, a call after the set is disposed, and a pending call whose registration was replaced or removed during the step return `UNKNOWN_TOOL` instead of running. +Model tool calls run only through their step's admitted set. A call to a conditional tool without a resolved set, a call after the set is disposed, and a pending call whose registration was replaced or removed during the step return `UNKNOWN_TOOL` instead of running. Replacement applies to every tool, so a hot reload, MCP reconnect, or skill reload that re-registers a tool mid-step fails that step's unstarted calls of it. Callers that pass no set, such as the experimental `claude-code-mods` `$.tool.call`, cannot call conditional tools. `exit_plan_mode` is declared from the first step whose selected plan state is active and stays declared for the rest of the Session, so requests of a Session that never entered plan mode no longer list it. Existing Sessions require no format migration. ## Migration -1. Replace tool filtering in `system-prompt/assemble` listeners with a `when` condition on the registration; read the step's provider, model, and reasoning effort from the condition's `modelSelection`. Keep only section, context, and variable changes in the waterfall. +1. Replace tool filtering and reads of `assembly.tools` in `system-prompt/assemble` listeners with a `when` condition on the registration; read the step's provider, model, and reasoning effort from the condition's `modelSelection`. Keep only section, context, and variable changes in the waterfall. 2. Make tool guidance follow the same admission: section callbacks pass `context.toolSet` to `ctx.tools.get()` or `ctx.tools.schemas()`. 3. For programmatic calls of conditional tools, call `ctx.tools.resolve({ agent, modelSelection, signal })`, pass the returned `toolSet` to `assemble()` and the `ctx.tools.execute()` batch, and dispose it after the batch settles. A custom executor that does not use the shared pipeline looks up each call with `ctx.tools.executable(name, agent, toolSet)`. 4. Update expectations that listed `exit_plan_mode` before a Session entered plan mode. Verify that a disabled tool is absent from the request, that calling its name returns `UNKNOWN_TOOL` without reaching the implementation, and that a failing condition ends the turn with `TOOL_ACTIVATION_FAILED`. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.zh.md index e5f5b33a26..ee1644a36e 100644 --- a/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-rc.2/conditional-tools/guide.zh.md @@ -11,15 +11,15 @@ description: "工具声明只来自步骤准入的注册:`system-prompt/assemb `ctx.tools.register(definition, { when })` 可以附加同步或异步条件。AgentLoop 在提示词组装与 `agent/pre-step` 之前,以 `{ agent, modelSelection, signal }` 为每个拟议步骤计算一次条件,并在该步骤及其重试中用得到的 `ResolvedToolSet` 决定工具声明、原生分发、PTC 绑定和嵌套调用。条件返回 false 时,工具从以上所有位置移除;条件抛错时,轮次以 `TOOL_ACTIVATION_FAILED` 结束。 -`system-prompt/assemble` waterfall 现在接收不含工具数组的段落、上下文与变量(`PromptPresentation`),返回的 `tools` 字段会被忽略。在这个 waterfall 中删除或添加工具声明的插件会受到影响:它们做的删除不再进入请求。 +`system-prompt/assemble` waterfall 现在接收不含工具数组的段落、上下文与变量(`PromptPresentation`),返回的 `tools` 字段会被忽略。在这个 waterfall 中删除或添加工具声明的插件会受到影响:它们做的删除不再进入请求;读取 `assembly.tools` 的监听器会拿到 `undefined`,并在运行时出错。 -模型的工具调用只通过所属步骤的准入集合执行。没有已解析集合的条件工具调用、集合释放之后的调用,以及注册在步骤内被替换或移除时尚未开始的调用,都会返回 `UNKNOWN_TOOL`,不会执行。 +模型的工具调用只通过所属步骤的准入集合执行。没有已解析集合的条件工具调用、集合释放之后的调用,以及注册在步骤内被替换或移除时尚未开始的调用,都会返回 `UNKNOWN_TOOL`,不会执行。替换规则适用于所有工具,因此在步骤中途重新注册工具的热重载、MCP 重连或 skill 重载会让该步骤里这个工具尚未开始的调用失败。不传集合的调用方(例如实验性 `claude-code-mods` 的 `$.tool.call`)无法调用条件工具。 `exit_plan_mode` 从已选计划状态首次为激活的步骤起声明,并在会话剩余部分保持声明,因此从未进入计划模式的会话,其请求不再列出它。现有 Session 无需格式迁移。 ## 迁移 -1. 把 `system-prompt/assemble` 监听器中的工具过滤改为注册时的 `when` 条件;从条件的 `modelSelection` 读取该步骤的提供方、模型与推理强度。waterfall 中只保留段落、上下文与变量的修改。 +1. 把 `system-prompt/assemble` 监听器中的工具过滤和对 `assembly.tools` 的读取改为注册时的 `when` 条件;从条件的 `modelSelection` 读取该步骤的提供方、模型与推理强度。waterfall 中只保留段落、上下文与变量的修改。 2. 让工具指引跟随同一准入:段落回调把 `context.toolSet` 传给 `ctx.tools.get()` 或 `ctx.tools.schemas()`。 3. 程序化调用条件工具时,调用 `ctx.tools.resolve({ agent, modelSelection, signal })`,把返回的 `toolSet` 传给 `assemble()` 与 `ctx.tools.execute()` 批次,并在批次结束后释放。不使用共享 pipeline 的自定义执行器用 `ctx.tools.executable(name, agent, toolSet)` 查找每次调用。 4. 更新在会话进入计划模式之前仍列出 `exit_plan_mode` 的期望。验证被禁用的工具不出现在请求中,用其名称调用会返回 `UNKNOWN_TOOL` 且不进入实现,条件失败时轮次以 `TOOL_ACTIVATION_FAILED` 结束。 diff --git a/packages/core/session/src/types.ts b/packages/core/session/src/types.ts index e0931f2240..f88777ae0d 100644 --- a/packages/core/session/src/types.ts +++ b/packages/core/session/src/types.ts @@ -207,8 +207,9 @@ export interface TurnEndReasonMap { blocked: { kind: 'blocked' } /** * The turn failed. `error` is always a structured failure: the `LlmError` - * facts verbatim, or `{ message: errorChain(error), code: 'UNKNOWN' }` - * flattened from any other error. + * facts verbatim, or `{ message: errorChain(error), code }` flattened from + * any other error, where `code` is `TOOL_ACTIVATION_FAILED` for a failed + * tool condition and `UNKNOWN` otherwise. */ error: { kind: 'error'; error: LlmFailure } /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */ diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index 2e7e7157d2..771d7514e9 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -21,8 +21,8 @@ en: 9d2e6caa39c53d62 zh: 096a777f828c7565 /deepseek-ai-dsh-tools/use-this-package/conditional-tools: - en: ca32a43ccbf90983 - zh: 172893865d2b88f5 + en: eb80334754c2493a + zh: b431635ec1f4664f /deepseek-ai-dsh-tools/use-this-package/select-an-executor: en: bdf27b6f339ea866 zh: b89205eedea1db0a diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index a2391641a0..22473d0c21 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -67,7 +67,7 @@ The unified schema DSL supports `string`, `number`, `integer`, `boolean`, `null` `register(definition, { when })` evaluates a synchronous or asynchronous condition once for each model step. The condition receives `{ agent, modelSelection, signal }`; `modelSelection` is the provider, model, and reasoning effort that step preparation captured for every request attempt in the step, the same value as `AssembleContext.modelSelection`. False omits the tool from the executor's description, PTC bindings, and execution. A thrown condition fails step preparation as `TOOL_ACTIVATION_FAILED`; it is not treated as ordinary unavailability. Conditions must observe cancellation and must not change registrations or perform tool work. -`resolve({ agent, modelSelection, signal })` returns a step-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and the step's `ctx.tools.execute()` batch, then dispose it after the batch settles; retries in the step reuse it. Executors apply the batch's set to every call, including PTC program subcalls. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, cancellation, or same-name replacement prevent unstarted calls from using it. Started operations retain their cooperative cancellation obligations. Conditional calls in a batch without a resolved set return `UNKNOWN_TOOL`. +`resolve({ agent, modelSelection, signal })` returns a step-owned `ResolvedToolSet`. Pass it as `toolSet` to prompt assembly and the step's `ctx.tools.execute()` batch, then dispose it after the batch settles; retries in the step reuse it. Executors apply the batch's set to every call, including PTC program subcalls. Registrations stay effect-owned; each selection admits only the original registration in its exact agent scope. Disposal, new restrictions, or same-name replacement prevent unstarted calls from using it; after cancellation, calls settle with the shared pipeline's cancellation results. Started operations retain their cooperative cancellation obligations. Conditional calls in a batch without a resolved set return `UNKNOWN_TOOL`. `get(name, scope, toolSet)`, `definitions(scope, toolSet)`, and `schemas(scope, toolSet)` inspect an admitted set; omitting `toolSet` inspects registered definitions without evaluating conditions. `executable(name, scope, toolSet)` is the execution lookup: it applies the set, and without one it excludes conditional registrations. Executor descriptions and sections receive the same selection as `AssembleContext.toolSet`. A presentation transform cannot add or remove callable tools. diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index 385c524b0a..0f621304c7 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -67,7 +67,7 @@ ctx.tools.register(defineTool({ `register(definition, { when })` 为每个模型步骤计算一次同步或异步条件。条件接收 `{ agent, modelSelection, signal }`;`modelSelection` 是步骤准备时为该步骤所有请求尝试捕获的提供方、模型与推理强度,与 `AssembleContext.modelSelection` 相同。返回 false 会从执行器的描述、PTC 绑定和执行集合中排除工具。条件抛错会以 `TOOL_ACTIVATION_FAILED` 中止步骤准备,不会被当成正常不可用。条件必须响应取消,不得改变注册或执行工具操作。 -`resolve({ agent, modelSelection, signal })` 返回步骤拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及该步骤的 `ctx.tools.execute()` 批次,批次结束后释放;同一步骤内的重试复用它。执行器把批次的集合应用到每次调用,包括 PTC 程序的子调用。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制、取消或同名替换会阻止尚未开始的调用继续使用它。已经开始的操作保留协作取消义务。批次没有已解析集合时,条件工具调用返回 `UNKNOWN_TOOL`。 +`resolve({ agent, modelSelection, signal })` 返回步骤拥有的 `ResolvedToolSet`。将它作为 `toolSet` 传给提示词组装以及该步骤的 `ctx.tools.execute()` 批次,批次结束后释放;同一步骤内的重试复用它。执行器把批次的集合应用到每次调用,包括 PTC 程序的子调用。注册仍由 effect 持有;每份集合只准入原 agent scope 中的原注册。注销、新的限制或同名替换会阻止尚未开始的调用继续使用它;取消之后,调用以共享 pipeline 的取消结果结束。已经开始的操作保留协作取消义务。批次没有已解析集合时,条件工具调用返回 `UNKNOWN_TOOL`。 `get(name, scope, toolSet)`、`definitions(scope, toolSet)` 和 `schemas(scope, toolSet)` 读取已准入集合;省略 `toolSet` 时只查看已注册定义,不计算条件。`executable(name, scope, toolSet)` 是执行时的查找:它应用集合,没有集合时排除条件注册。执行器的描述与分区通过 `AssembleContext.toolSet` 接收同一集合。展示变换不能增删可调用工具。 diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index 9697d7633c..d2d10d6b5b 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -283,7 +283,7 @@ export class ToolsService extends Service { dispose: () => { closed = true }, view: (scope: ScopeKey | undefined): ReadonlyMap => { const visible = new Map() - if (closed || scope !== agent || signal.aborted) return visible + if (closed || scope !== agent) return visible const current = this.view(agent) for (const [name, definition] of admitted) { if (current.visible.get(name) === definition diff --git a/packages/core/tools/tests/activation.spec.ts b/packages/core/tools/tests/activation.spec.ts index 7cffd2a2a9..eab5565af8 100644 --- a/packages/core/tools/tests/activation.spec.ts +++ b/packages/core/tools/tests/activation.spec.ts @@ -8,7 +8,7 @@ import { ToolCallId } from '@deepseek-ai/dsh-llm' import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import { SessionId } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRuntime, { defineTool, ToolActivationError } from '@deepseek-ai/dsh-tools' +import ToolRuntime, { defineTool, TOOL_ABORTED_BEFORE_DISPATCH, ToolActivationError } from '@deepseek-ai/dsh-tools' import type { ToolExecutionInput, ToolExecutionResult } from '@deepseek-ai/dsh-tools' const TEST_MODEL_SELECTION = { provider: 'test', model: 'test' } @@ -90,6 +90,28 @@ it('applies live restrictions and closes step admission permanently', async () = expect(h.calls()).toBe(1) }) +it('settles calls of a cancelled step through cancellation with their finalizers', async () => { + const h = await setup() + h.ctx.tools.register({ ...h.tool, finalizeContent: () => [{ type: 'text', text: 'finalized' }] }, { when: () => true }) + const toolSet = await h.resolve() + h.controller.abort() + const result = await h.execute({ toolSet }) + expect(result.error?.info?.code).toBe(TOOL_ABORTED_BEFORE_DISPATCH) + expect(result.content).toEqual([{ type: 'text', text: 'finalized' }]) + expect(h.calls()).toBe(0) +}) + +it('reports a wrapper result completed at cancellation as cancelled rather than unknown', async () => { + const h = await setup() + h.ctx.tools.register(h.tool, { when: () => true }) + const toolSet = await h.resolve() + h.ctx.on('tools/execute', async () => { + h.controller.abort() + return { isError: false, value: 'wrapped', content: [{ type: 'text', text: 'wrapped' }] } + }) + expect((await h.execute({ toolSet })).error?.info?.code).toBe(TOOL_ABORTED_BEFORE_DISPATCH) +}) + it('does not substitute a same-name registration after admission', async () => { const h = await setup() const unregister = h.ctx.tools.register(h.tool, { when: () => true }) diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 88bfc0ea7d..06af5c2828 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -299,10 +299,9 @@ export class PlanModeController extends Service { }], }, execute: async (args, exec) => { - // oxlint-disable-next-line typescript/no-non-null-assertion -- conditional admission requires the step's Agent - const agent = exec.agent! + const agent = exec.agent // Admission outlives plan mode and follows the selected state, so check the committed state. - if (!this.loggedActive(agent.session)) { + if (agent === undefined || !this.loggedActive(agent.session)) { throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`) } if (!/^#\s+\S/.test(args.plan.trim())) { diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 478961bd2e..88f401bcf2 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -7,6 +7,7 @@ import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-test import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' +import type { ToolExecutionToken, ToolRunContext } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' import { Session, SessionId, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' @@ -832,6 +833,18 @@ describe('exit_plan_mode', () => { expect(result.content).toEqual([{ type: 'text', text: 'Error: unknown tool "exit_plan_mode"' }]) }) + it('rejects a direct execution without a calling Agent', async () => { + const ctx = await setup() + const exit = ctx.tools.get(EXIT_PLAN_MODE) + expect(exit).toBeDefined() + const exec: ToolRunContext = { + callId: ToolCallId('direct-exit'), rootCallId: ToolCallId('direct-exit'), name: EXIT_PLAN_MODE, + arguments: { plan: '# P' }, token: Symbol('direct-exit') as ToolExecutionToken, signal: testToolSignal, + deferContext() {}, concludeTurn() {}, + } + await expect(exit?.execute({ plan: '# P' }, exec)).rejects.toThrow(`${EXIT_PLAN_MODE} is only available in plan mode`) + }) + it('keeps the exit tool after leaving plan mode and rejects a call outside it', async () => { const ctx = await setup() const agent = await agentWithSession(ctx, 'left-plan', { active: true }) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index bcc8266f22..c89a9ed98f 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -756,6 +756,9 @@ export const LINK_MAP: Readonly> = { ToolCallResult: 'tools.md', ToolBatchResult: 'tools.md', ToolRestriction: 'tools.md', + ToolActivationContext: 'tools.md', + ToolRegistrationOptions: 'tools.md', + ResolvedToolSet: 'tools.md', ToolSchema: 'tools.md', SettingsNamespace: 'settings.md', SettingsDescriptor: 'settings.md', @@ -983,9 +986,6 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { 'upgrade route registration contract is owned by packages/host/webserver/src/index.ts', JsonValue: 'JSON value union is owned by packages/core/session/src/json.ts', KnobState: 'projection unit state fields are owned by packages/interaction/permission-presets/README.md', - ToolActivationContext: 'conditional activation inputs are owned by packages/core/tools/README.md', - ToolRegistrationOptions: 'conditional registration options are owned by packages/core/tools/README.md', - ResolvedToolSet: 'step-owned admission is owned by packages/core/tools/README.md', PromptAssembly: 'assembly result is owned by packages/core/system-prompt/README.md', PromptPresentation: 'presentation inputs are owned by packages/core/system-prompt/README.md', RequestRunId: 'dynamic-package payload contract is owned by packages/extensions/cordis-host-runner/src/types.ts', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 6f4a54de55..9031f0f2c5 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1001,6 +1001,21 @@ "symbol": "ToolRestriction", "source": "packages/core/tools/src/contracts.ts" }, + { + "doc": "docs/subsystems/tools.md", + "symbol": "ToolActivationContext", + "source": "packages/core/tools/src/contracts.ts" + }, + { + "doc": "docs/subsystems/tools.md", + "symbol": "ToolRegistrationOptions", + "source": "packages/core/tools/src/contracts.ts" + }, + { + "doc": "docs/subsystems/tools.md", + "symbol": "ResolvedToolSet", + "source": "packages/core/tools/src/contracts.ts" + }, { "doc": "docs/subsystems/tools.md", "symbol": "ToolFailure",