From aaf50dc39adcad8c34e4909b7d8d9c5dd9fcd874 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 19 Aug 2026 13:50:41 +0800 Subject: [PATCH 01/26] refactor(agent): back Inbox with a durable projection --- ...claimed-pre-step-inbox-lifecycle.i18n.yaml | 4 +- ...-07-31-claimed-pre-step-inbox-lifecycle.md | 8 +- ...-31-claimed-pre-step-inbox-lifecycle.zh.md | 8 +- apps/cli/composition.md | 3 + apps/cli/tests/fixtures/dsh-badge/snapshot.ts | 5 +- docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 4 + docs/capability-seams.zh.md | 4 + docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 4 +- docs/config-catalog.zh.md | 4 +- docs/event-producer-consumer.i18n.yaml | 4 +- docs/event-producer-consumer.md | 6 +- docs/event-producer-consumer.zh.md | 6 +- docs/module-graph.i18n.yaml | 4 +- docs/module-graph.md | 325 +++++++++--------- docs/module-graph.zh.md | 325 +++++++++--------- docs/persistence-catalog.i18n.yaml | 4 +- docs/persistence-catalog.md | 4 +- docs/persistence-catalog.zh.md | 4 +- docs/subsystems/core.i18n.yaml | 4 +- docs/subsystems/core.md | 19 +- docs/subsystems/core.zh.md | 19 +- docs/subsystems/session-projection.i18n.yaml | 4 +- docs/subsystems/session-projection.md | 6 +- docs/subsystems/session-projection.zh.md | 6 +- .../headless-agent/tests/code-mode.e2e.ts | 6 + .../tests/fixtures/e2b/e2b/bin.ts | 4 +- packages/bundle/base/cordis.patch.yml | 3 + .../bundle/headless/tests/headless.spec.ts | 9 +- .../context/agent-instructions/package.json | 1 + .../tests/agent-instructions.e2e.ts | 15 +- .../tests/agent-instructions.spec.ts | 29 +- .../time-context/tests/time-context.spec.ts | 6 +- .../tmux-context/tests/tmux-context.spec.ts | 6 +- packages/core/agent-loop/package.json | 1 + packages/core/agent-loop/src/agent.ts | 9 +- packages/core/agent-loop/src/index.ts | 2 +- .../agent-loop/tests/agent-initiator.spec.ts | 8 + packages/core/agent-loop/tests/agent.spec.ts | 4 + packages/core/agent-loop/tests/cancel.spec.ts | 6 + .../tests/config-session-id.spec.ts | 16 + .../tests/contract-regressions.spec.ts | 18 + .../agent-loop/tests/coverage-edges.spec.ts | 4 + .../agent-loop/tests/interception.spec.ts | 4 + packages/core/agent-loop/tests/loop.spec.ts | 24 ++ .../core/agent-loop/tests/properties.spec.ts | 4 + .../agent-loop/tests/request-cache.e2e.ts | 4 + .../agent-loop/tests/request-error.spec.ts | 4 + .../tests/request-reconstruction.spec.ts | 8 + packages/core/agent-loop/tests/resume.spec.ts | 22 ++ .../agent-loop/tests/scope-lifecycle.spec.ts | 4 + .../core/agent-loop/tests/settings.spec.ts | 4 + .../core/agent-loop/tests/tool-calls.spec.ts | 10 + .../core/agent-loop/tests/tool-order.spec.ts | 4 + packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 4 +- packages/core/agent/README.zh.md | 4 +- packages/core/agent/package.json | 13 + packages/core/agent/src/inbox-projection.ts | 20 ++ packages/core/agent/src/inbox.ts | 180 +++++----- packages/core/agent/src/types.ts | 4 +- packages/core/agent/tests/agent.spec.ts | 136 ++++++-- packages/core/agent/tsconfig.json | 3 + packages/e2b/e2b/tests/composition.e2e.ts | 3 +- .../examples/agent-spine-demo/package.json | 2 + .../examples/agent-spine-demo/src/index.ts | 4 + .../extensions/tool-cordis/src/api-catalog.ts | 21 +- .../tests/command-feedback.spec.ts | 4 +- .../tests/loader-composition.spec.ts | 4 +- .../tests/tools.spec.ts | 3 +- .../command-goal/tests/command-goal.spec.ts | 6 +- packages/goal/goal/tests/goal.spec.ts | 69 +++- packages/goal/goal/tests/projection.spec.ts | 19 +- .../goal/tool-goal/tests/tool-goal.spec.ts | 33 +- packages/host/apiproxy/src/api-proxy.ts | 16 +- .../apiproxy/tests/api-proxy-jobs.spec.ts | 14 +- .../tests/api-proxy-projections.spec.ts | 100 +++++- .../tests/api-proxy-workspace.spec.ts | 6 +- packages/jobs/jobs-local/tests/jobs.spec.ts | 3 +- packages/llm/llm-retry/package.json | 1 + .../tests/loader-composition.spec.ts | 6 + packages/llm/llm-retry/tests/retry.spec.ts | 15 +- .../plan/plan-mode/tests/integration.spec.ts | 4 + packages/preset/agent-presets/package.json | 1 + .../agent-presets/tests/invariant.spec.ts | 4 + .../preset/agent-presets/tests/mount.spec.ts | 8 + .../agent-presets/tests/settings.spec.ts | 4 + .../schedule/schedule/tests/runtime.spec.ts | 4 +- .../schedule/schedule/tests/tools.spec.ts | 7 +- .../session-projection/README.i18n.yaml | 4 +- packages/session/session-projection/README.md | 10 +- .../session/session-projection/README.zh.md | 10 +- .../session/session-projection/src/index.ts | 26 +- .../tests/loader-composition.spec.ts | 3 +- .../tool-bash-persistent/tests/tools.spec.ts | 3 +- .../skill/tool-skill/tests/tool-skill.spec.ts | 12 +- .../subagent/tests/list-children.spec.ts | 23 +- .../tests/list-agents.spec.ts | 2 - .../tests/tool-subagent-control.spec.ts | 2 - .../terminal-bash/tests/index.spec.ts | 12 +- .../terminal-bash/tests/local.spec.ts | 6 +- .../terminal/terminal/tests/service.spec.ts | 3 +- .../tests/loader-composition.spec.ts | 3 +- .../tool-terminal/tests/tools.spec.ts | 3 +- .../agent-loop-testkit/package.json | 2 + .../agent-loop-testkit/src/index.ts | 4 + .../tests/loader-composition.spec.ts | 3 +- .../tests/workflow-worker-thread.e2e.ts | 13 +- pnpm-lock.yaml | 25 ++ scripts/gen-cordis-catalog.ts | 2 + scripts/gen-doc-graphs.ts | 8 + tsconfig.base.json | 2 + 113 files changed, 1264 insertions(+), 677 deletions(-) create mode 100644 packages/core/agent/src/inbox-projection.ts diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml index 9b41e2e0cf..3c9a697dd3 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md -2026-07-31-claimed-pre-step-inbox-lifecycle.md: 73768e1eee8957f8976d40812b0a31a2961f0825 -2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 343816abaf394b8f64924cf36b753c6b1b2e34ca +2026-07-31-claimed-pre-step-inbox-lifecycle.md: c46c22cde3e96fb774233d9621acf1abf4ba0c33 +2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 51ada096a105a5c97cffd70c2d40782a71beddf7 diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md index 73768e1eee..c46c22cde3 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md @@ -12,17 +12,17 @@ Occurrence-local inbox wrappers also duplicated the identity already carried by ## Decision -Before every proposed step, `Inbox.claim(target)` atomically removes the complete batch: all `next-step` messages and, at a turn boundary, one `next-turn` message. At the initial boundary the loop first commits `turn/start`, so the claim and its single `agent/pre-step` decision have durable turn ownership. Claiming records normalized `agent/inbox/spliced` pure deletions with no outcome. The loop then emits `agent/inbox/claimed { message, turn }` once per claimed message and awaits the waterfall with that exclusive batch and `{ turn, step, signal }`. +Before every proposed step, `Inbox.claim(target)` atomically removes the complete batch: all `next-step` messages and, at a turn boundary, one `next-turn` message. At the initial boundary the loop first commits `turn/start`, so the claim and its single `agent/pre-step` decision have durable turn ownership. Claiming records normalized `agent/inbox/spliced` pure deletions with no outcome, emits `agent/inbox/claimed { message, turn }` once per claimed message, and returns the exclusive batch for the loop's waterfall with `{ turn, step, signal }`. `PreStepDecision` is `{ kind: 'reject' } | { kind: 'enter'; messages: UserMessage[] }`. Reject opens no step, leaves the claimed batch removed, and closes the turn as blocked without any step events. Empty entry, cancellation, and failure before `step/start` likewise close a balanced no-step turn. Enter supplies the complete batch appended as `user/message` events after `step/start`. A listener wrapping `next()` preserves downstream changes unless it intentionally replaces them, so all message rewrites settle once in the final return value. There is no `agent/prompt-prepare`, `agent/prompt-submit`, or `agent/step` extension point. -The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming is the loop's internal step-boundary operation on the inbox and records pure deletions without notifications or an outcome, so the loop can publish claimed events itself. These live events add no placement, outcome, or batch fields. +The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming records pure deletions without an outcome and emits claimed events from Inbox itself. These live events add no placement, outcome, or batch fields. -The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. Whole-queue consumers, including the Web queue projection and reconnect baseline, use the durable `agent/inbox/spliced` stream; UI edits and removals route through `Inbox.splice()` or another Inbox mutation method so the same projection records every change. +The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `InboxService` registers the standard `inbox` projection over the durable `agent/inbox/spliced` stream for whole-state consumers and live restoration; UI edits and removals route through an Inbox mutation method so the same projection records every change. Plugins that need current-step atomic rewriting return messages from `agent/pre-step`. Plugins that only need later context may mutate `agent.inbox` directly. Workspace context uses both paths: asynchronous filesystem projections stage one replaceable `next-step` item, while the next entering pre-step folds that item or a newly composed baseline into its final batch and removes the pending copy. Rejection keeps the item queued. -The archived [addressable queue occurrence decision](../../archived/feature/2026-07-29-addressable-queue-operations.md) describes the superseded occurrence-wrapper design. `MessageId` now owns addressability, while the retained Host queue mirror derives its snapshots from the durable splice projection. +The archived [addressable queue occurrence decision](../../archived/feature/2026-07-29-addressable-queue-operations.md) describes the superseded occurrence-wrapper design. `MessageId` now owns addressability, while `InboxService` registers `inbox` as the standard session projection over durable splices. The generic projection carrier serves that fold for live updates, history-tail reconnect baselines, and cold process-restart recovery without a live Agent mirror. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md index 343816abaf..51ada096a1 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md @@ -12,17 +12,17 @@ Status: implemented ## 决策 -每个拟议步骤之前,`Inbox.claim(target)` 会原子移除完整批次:全部 `next-step` 消息,以及轮次边界上的一条 `next-turn` 消息。在首次边界,循环会先提交 `turn/start`,使领取及其唯一一次 `agent/pre-step` 决策拥有持久轮次归属。领取会记录规范化、不带 outcome 的纯删除 `agent/inbox/spliced`。随后,循环针对每条已领取消息发出一次 `agent/inbox/claimed { message, turn }`,并用该独占批次与 `{ turn, step, signal }` 等待 waterfall(瀑布式事件)。 +每个拟议步骤之前,`Inbox.claim(target)` 会原子移除完整批次:全部 `next-step` 消息,以及轮次边界上的一条 `next-turn` 消息。在首次边界,循环会先提交 `turn/start`,使领取及其唯一一次 `agent/pre-step` 决策拥有持久轮次归属。领取会记录规范化、不带 outcome 的纯删除 `agent/inbox/spliced`,针对每条已领取消息发出一次 `agent/inbox/claimed { message, turn }`,并把独占批次返回给循环,由后者用 `{ turn, step, signal }` 等待 waterfall(瀑布式事件)。 `PreStepDecision` 为 `{ kind: 'reject' } | { kind: 'enter'; messages: UserMessage[] }`。reject 不会打开步骤,会让已领取批次保持已删除,并将轮次关闭为 blocked,且不产生任何步骤事件。空的 enter、取消以及 `step/start` 前的失败同样会关闭一个边界平衡的无步骤轮次。enter 提供在 `step/start` 后以 `user/message` 追加的完整批次。包装 `next()` 的监听器会保留下游变更,除非有意替换,因此全部消息改写只在最终返回值中一次性结算。系统不再存在 `agent/prompt-prepare`、`agent/prompt-submit` 或 `agent/step` 扩展点。 -持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取是循环在 inbox 上的内部步骤边界操作,记录不带通知或 outcome 的纯删除,因此循环可以自行发布 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 +持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取记录不带 outcome 的纯删除,并由 Inbox 自行发出 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 -两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。包括 Web 队列投影和重连基线在内的整体队列消费方使用持久 `agent/inbox/spliced` 流;UI 编辑与移除通过 `Inbox.splice()` 或其他 Inbox 变更方法处理,从而让同一投影记录所有变化。 +两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`InboxService` 在持久 `agent/inbox/spliced` 流上注册标准 `inbox` 投影,供整体状态消费方与 live 恢复使用;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。 必须对当前步骤进行原子改写的插件从 `agent/pre-step` 返回消息。只需要稍后上下文的插件可以直接修改 `agent.inbox`。Workspace context 同时使用两条路径:异步文件系统投影会暂存一条可替换的 `next-step` 消息,而下一次进入步骤的 pre-step 会把该消息或新组合的基线折入最终批次,并移除仍待处理的副本。reject 会让该条目继续排队。 -已归档的[可寻址队列项决策](../../archived/feature/2026-07-29-addressable-queue-operations.md)描述了已被取代的单次出现包装层设计。现在由 `MessageId` 负责寻址,而保留的 Host 队列镜像根据持久 splice 投影派生快照。 +已归档的[可寻址队列项决策](../../archived/feature/2026-07-29-addressable-queue-operations.md)描述了已被取代的单次出现包装层设计。现在由 `MessageId` 负责寻址,而 `InboxService` 把 `inbox` 注册为持久 splice 上的标准会话投影。通用投影传输层会将该折叠结果用于实时更新、历史尾页的重连基线和冷进程重启恢复,无需 live Agent 镜像。 ## 曾考虑的替代方案 diff --git a/apps/cli/composition.md b/apps/cli/composition.md index 4d37b9186a..08e5d4db39 100644 --- a/apps/cli/composition.md +++ b/apps/cli/composition.md @@ -30,6 +30,8 @@ flowchart LR cfg --> plugin_dsh_base_user_questions plugin_dsh_base_agent["agent
@deepseek-ai/dsh-agent"] cfg --> plugin_dsh_base_agent + plugin_dsh_base_agent_inbox["agent-inbox
@deepseek-ai/dsh-agent/inbox"] + cfg --> plugin_dsh_base_agent_inbox plugin_dsh_base_agent_default_model["agent-default-model
@deepseek-ai/dsh-agent-default-model"] cfg --> plugin_dsh_base_agent_default_model plugin_dsh_base_jobs["jobs
@deepseek-ai/dsh-jobs-local"] @@ -179,6 +181,7 @@ flowchart LR | `session-title-llm` | `@deepseek-ai/dsh-session-title-first-prompt-llm` | | `user-questions` | `@deepseek-ai/dsh-user-questions` | | `agent` | `@deepseek-ai/dsh-agent` | +| `agent-inbox` | `@deepseek-ai/dsh-agent/inbox` | | `agent-default-model` | `@deepseek-ai/dsh-agent-default-model` | | `jobs` | `@deepseek-ai/dsh-jobs-local` | | `llm-retry` | `@deepseek-ai/dsh-llm-retry` | diff --git a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts index cdc4dbb6d3..87254a8d2d 100644 --- a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts +++ b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts @@ -1,6 +1,6 @@ import { fileURLToPath } from 'node:url' import { Context } from '@deepseek-ai/cordis' -import { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { CallId } from '@deepseek-ai/dsh-llm' import { boot, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot' import { SessionId } from '@deepseek-ai/dsh-session' @@ -24,7 +24,7 @@ try { id: agentId, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', send: () => {}, followup: () => {}, @@ -34,6 +34,7 @@ try { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', { messages: [], turn: 1, step: 1, signal: new AbortController().signal }, diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index e12756c849..1042393b52 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/capability-seams.md -capability-seams.md: 710c399510b6b123123e0a9586d86bfc3a96dff9 -capability-seams.zh.md: e0559d464ba1ecd2160eaba40c24bfd829e4a0d6 +capability-seams.md: 41ec9859d2dbf4c2c237059458803a5651bb9504 +capability-seams.zh.md: 100486445e55bb411f062637ec6cff636806cb97 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 710c399510..41ec9859d2 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -31,6 +31,7 @@ flowchart LR pkg_subagent_inprocess["subagent-inprocess"] pkg_invariants["invariants"] pkg_message_feedback["message-feedback"] + svc_inboxes["ctx.inboxes
Durable pending-input facade"] svc_invariants["ctx.invariants
Package-owned invariant registry"] pkg_scope["scope"] pkg_typert_registry["typert-registry"] @@ -198,6 +199,7 @@ flowchart LR svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] pkg_acp --> svc_approval pkg_agent --> svc_agents + pkg_agent --> svc_inboxes pkg_agent_default_model --> svc_agentDefaultModel pkg_agent_loop --> svc_agentLoop pkg_agent_presets --> svc_agentPresets @@ -321,6 +323,7 @@ flowchart LR svc_e2b --> pkg_fs_e2b svc_e2b --> pkg_subprocess_e2b svc_fs --> pkg_tool_fs + svc_inboxes --> pkg_agent_loop svc_invariants --> pkg_agent svc_invariants --> pkg_agent_loop svc_invariants --> pkg_scope @@ -421,6 +424,7 @@ flowchart LR | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Owns isolated per-session replay folds; pressure consumers share immutable revisioned measurements. | | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Rewrites oversized current tool results through replayable single-node surface replacements before summary compaction. | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), `subagent-inprocess`, [`invariants`](../packages/runtime-diagnostics/invariants), [`message-feedback`](../packages/feedback/message-feedback) | - | Owns append-only Session instances and emits the durable session event feed. | +| `ctx.inboxes` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop) | - | Registers the standard Inbox projection and creates command facades over its sole live state. | | `ctx.invariants` | `core` | [`invariants`](../packages/runtime-diagnostics/invariants) | - | [`session`](../packages/core/session), [`agent`](../packages/core/agent), [`scope`](../packages/core/scope), [`agent-loop`](../packages/core/agent-loop) | - | Companion subpaths register owner-local checks; the service owns selection, uniqueness, child fibers, and package-attributed failures. | | `ctx.typert` | `core` | [`typert-registry`](../packages/typert/registry) | - | [`typert-loader`](../packages/typert/loader), [`api-gateway`](../packages/api/gateway) | - | Plugins register live zod contributions directly or through dsh-typert-loader; the API gateway consumes invocation descriptors and providers, while other runtime consumers query schemas and reflection metadata at their own edges. | | `ctx.typertGateway` | `core` | [`api-gateway`](../packages/api/gateway) | - | - | - | Associates generated Remote descriptors with live Cordis services, resolves registered identities, and exposes unary calls through the shared Connection RPC carrier. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index e0559d464b..100486445e 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -33,6 +33,7 @@ flowchart LR pkg_subagent_inprocess["subagent-inprocess"] pkg_invariants["invariants"] pkg_message_feedback["message-feedback"] + svc_inboxes["ctx.inboxes
Durable pending-input facade"] svc_invariants["ctx.invariants
Package-owned invariant registry"] pkg_scope["scope"] pkg_typert_registry["typert-registry"] @@ -200,6 +201,7 @@ flowchart LR svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] pkg_acp --> svc_approval pkg_agent --> svc_agents + pkg_agent --> svc_inboxes pkg_agent_default_model --> svc_agentDefaultModel pkg_agent_loop --> svc_agentLoop pkg_agent_presets --> svc_agentPresets @@ -323,6 +325,7 @@ flowchart LR svc_e2b --> pkg_fs_e2b svc_e2b --> pkg_subprocess_e2b svc_fs --> pkg_tool_fs + svc_inboxes --> pkg_agent_loop svc_invariants --> pkg_agent svc_invariants --> pkg_agent_loop svc_invariants --> pkg_scope @@ -423,6 +426,7 @@ flowchart LR | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 拥有按会话隔离的回放折叠区;压力消费方共享不可变且带修订版本的测量结果。 | | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 在摘要压缩前,通过可回放的单节点表层替换来改写过大的当前工具结果。 | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), `subagent-inprocess`, [`invariants`](../packages/runtime-diagnostics/invariants), [`message-feedback`](../packages/feedback/message-feedback) | - | 拥有仅追加的 Session 实例,并发出持久的会话事件流。 | +| `ctx.inboxes` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop) | - | 注册标准 Inbox 投影,并在其唯一 live 状态上创建命令 facade。 | | `ctx.invariants` | `core` | [`invariants`](../packages/runtime-diagnostics/invariants) | - | [`session`](../packages/core/session), [`agent`](../packages/core/agent), [`scope`](../packages/core/scope), [`agent-loop`](../packages/core/agent-loop) | - | 配套子路径注册所属包本地的检查;该服务负责选择、唯一性、子 fiber,以及标明所属包的失败。 | | `ctx.typert` | `core` | [`typert-registry`](../packages/typert/registry) | - | [`typert-loader`](../packages/typert/loader), [`api-gateway`](../packages/api/gateway) | - | 插件直接或通过 dsh-typert-loader 注册实时 zod 贡献;API 网关消费调用描述符和提供方,其他运行时消费方则在各自边界查询 schema 与反射元数据。 | | `ctx.typertGateway` | `core` | [`api-gateway`](../packages/api/gateway) | - | - | - | 将生成的 Remote 描述符与实时 Cordis 服务关联,解析已注册的身份,并通过共享的 Connection RPC 载体提供一元调用。 | diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index fa7dcdafdc..7f32d0a130 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 54b966fb19de14637d8d6ba89b50d9e1e0e00762 -config-catalog.zh.md: 53c43c616a1d3fbb6b855bf5ebc69263023413ff +config-catalog.md: 9c4d4fd1c4e198973940bf93eb5e66d9e7c47d04 +config-catalog.zh.md: 9a62d1d62703bba3ceb5a9a21752d86a3a72f2d6 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 54b966fb19..9c4d4fd1c4 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -136,7 +136,7 @@ Source: [`packages/context/agent-instructions/src/config.ts:18`](../packages/con ## `@deepseek-ai/dsh-agent-loop` -Requires: `agents` · `sessions` · `llm` · `tools` · `systemPrompt` +Requires: `agents` · `inboxes` · `sessions` · `llm` · `tools` · `systemPrompt` ```ts config-catalog /** Agent-loop plugin configuration. */ @@ -292,7 +292,7 @@ export interface GoalConfig { Depends on: [`AgentLoopConfig`](#deepseek-aidsh-agent-loop) · [`GoalDomainConfig`](#deepseek-aidsh-goal) · [`InvariantConfig`](#deepseek-aidsh-invariants) · [`JobsConfig`](#deepseek-aidsh-jobs-local) · [`SessionTitleConfig`](#deepseek-aidsh-session-title) · [`SkillFileSystem`](../packages/skill/skill-filesystem/src/index.ts) · [`SkillRegistryConfig`](#deepseek-aidsh-skill) · [`SystemPromptConfig`](#deepseek-aidsh-system-prompt) · [`toolBash`](../packages/shell/tool-bash/src/index.ts) · [`toolGoal`](../packages/goal/tool-goal/src/index.ts) · [`toolJobs`](../packages/jobs/tool-jobs/src/index.ts) · [`ToolsConfig`](#deepseek-aidsh-tools) · [`toolSkill`](../packages/skill/tool-skill/src/index.ts) · [`workspaceContext`](../packages/context/agent-instructions/src/index.ts) -Source: [`packages/examples/agent-spine-demo/src/index.ts:92`](../packages/examples/agent-spine-demo/src/index.ts) +Source: [`packages/examples/agent-spine-demo/src/index.ts:94`](../packages/examples/agent-spine-demo/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 53c43c616a..9a62d1d627 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -138,7 +138,7 @@ export interface Config { ## `@deepseek-ai/dsh-agent-loop` -需要:`agents` · `sessions` · `llm` · `tools` · `systemPrompt` +需要:`agents` · `inboxes` · `sessions` · `llm` · `tools` · `systemPrompt` ```ts config-catalog /** Agent-loop plugin configuration. */ @@ -294,7 +294,7 @@ export interface GoalConfig { 依赖:[`AgentLoopConfig`](#deepseek-aidsh-agent-loop) · [`GoalDomainConfig`](#deepseek-aidsh-goal) · [`InvariantConfig`](#deepseek-aidsh-invariants) · [`JobsConfig`](#deepseek-aidsh-jobs-local) · [`SessionTitleConfig`](#deepseek-aidsh-session-title) · [`SkillFileSystem`](../packages/skill/skill-filesystem/src/index.ts) · [`SkillRegistryConfig`](#deepseek-aidsh-skill) · [`SystemPromptConfig`](#deepseek-aidsh-system-prompt) · [`toolBash`](../packages/shell/tool-bash/src/index.ts) · [`toolGoal`](../packages/goal/tool-goal/src/index.ts) · [`toolJobs`](../packages/jobs/tool-jobs/src/index.ts) · [`ToolsConfig`](#deepseek-aidsh-tools) · [`toolSkill`](../packages/skill/tool-skill/src/index.ts) · [`workspaceContext`](../packages/context/agent-instructions/src/index.ts) -来源:[`packages/examples/agent-spine-demo/src/index.ts:92`](../packages/examples/agent-spine-demo/src/index.ts) +来源:[`packages/examples/agent-spine-demo/src/index.ts:94`](../packages/examples/agent-spine-demo/src/index.ts) diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index d933130f59..c72e3f9fdd 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/event-producer-consumer.md -event-producer-consumer.md: c906ee6329fac66e7391c266213dd150dd5b8e09 -event-producer-consumer.zh.md: 77bf401b7215bd263c0d84f04e0eabe6b28b7915 +event-producer-consumer.md: e5d09f9ac963a401d267ac924e1a8aa681cc186b +event-producer-consumer.zh.md: daf8690cff14771182cc903759c5137577607220 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index c906ee6329..e5d09f9ac9 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -12,9 +12,9 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:159`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), [`tool-team`](../packages/experimental/tool-team) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:168`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-team`](../packages/experimental/tool-team) | | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `apiproxy`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`session-telemetry`](../packages/session/session-telemetry) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:197`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:205`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:186`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:197`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:205`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:186`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:231`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:244`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:260`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 77bf401b72..daf8690cff 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -14,9 +14,9 @@ | `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:159`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), [`tool-team`](../packages/experimental/tool-team) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:168`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-team`](../packages/experimental/tool-team) | | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `apiproxy`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`session-telemetry`](../packages/session/session-telemetry) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:197`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:205`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:186`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:197`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:205`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:186`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:231`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:244`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:260`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) | diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index 1b0e8fad9c..ac07a9f002 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/module-graph.md -module-graph.md: 0bd5f80534ba65e0d483bd04228cdac321e082bc -module-graph.zh.md: 6239520b7d819eb14c2b859afa44a0c987545200 +module-graph.md: af584780da1a00ea515fb7ade824270cb660e231 +module-graph.zh.md: 0ccbf94e41d301793fb6e99b14883ce472f31674 diff --git a/docs/module-graph.md b/docs/module-graph.md index 0bd5f80534..af584780da 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -436,12 +436,6 @@ flowchart TD pkg_lsp --> pkg_brand pkg_lsp --> pkg_invariants pkg_lsp --> pkg_llm - pkg_agent --> pkg_invariants - pkg_agent --> pkg_llm - pkg_agent --> pkg_scope - pkg_agent --> pkg_session - pkg_agent --> pkg_system_prompt - pkg_agent --> pkg_typert_protocol pkg_skill_badge --> pkg_invariants pkg_skill_badge --> pkg_skill pkg_web_fetch_http --> pkg_invariants @@ -478,6 +472,60 @@ flowchart TD pkg_session_projection --> pkg_session pkg_acp_snapshot --> pkg_invariants pkg_acp_snapshot --> pkg_session + pkg_agent --> pkg_invariants + pkg_agent --> pkg_llm + pkg_agent --> pkg_scope + pkg_agent --> pkg_session + pkg_agent --> pkg_session_projection + pkg_agent --> pkg_system_prompt + pkg_agent --> pkg_typert_protocol + pkg_fs --> pkg_brand + pkg_fs --> pkg_invariants + pkg_fs --> pkg_llm + pkg_fs --> pkg_sandbox + pkg_spill_local --> pkg_invariants + pkg_spill_local --> pkg_spill + pkg_message_feedback --> pkg_brand + pkg_message_feedback --> pkg_invariants + pkg_message_feedback --> pkg_llm + pkg_message_feedback --> pkg_session + pkg_message_feedback --> pkg_session_persistence + pkg_message_feedback --> pkg_storage_domain + pkg_message_feedback --> pkg_typert_protocol + pkg_sandbox_local --> pkg_invariants + pkg_sandbox_local --> pkg_llm + pkg_sandbox_local --> pkg_sandbox + pkg_sandbox_local --> pkg_session + pkg_session_persistence_jsonl --> pkg_invariants + pkg_session_persistence_jsonl --> pkg_session + pkg_session_persistence_jsonl --> pkg_session_persistence + pkg_session_persistence_sqlite --> pkg_invariants + pkg_session_persistence_sqlite --> pkg_session + pkg_session_persistence_sqlite --> pkg_session_persistence + pkg_session_projection_cache --> pkg_invariants + pkg_session_projection_cache --> pkg_session + pkg_session_projection_cache --> pkg_session_persistence + pkg_session_projection_cache --> pkg_session_projection + pkg_session_projection_cache --> pkg_storage_domain + pkg_session_stats --> pkg_invariants + pkg_session_stats --> pkg_llm + pkg_session_stats --> pkg_session + pkg_session_stats --> pkg_session_projection + pkg_session_title --> pkg_brand + pkg_session_title --> pkg_invariants + pkg_session_title --> pkg_llm + pkg_session_title --> pkg_session + pkg_session_title --> pkg_session_projection + pkg_shell --> pkg_invariants + pkg_shell --> pkg_sandbox + pkg_shell --> pkg_settings + pkg_shell --> pkg_subprocess + pkg_workspace --> pkg_brand + pkg_workspace --> pkg_invariants + pkg_workspace --> pkg_session + pkg_workspace --> pkg_session_persistence + pkg_workspace --> pkg_storage + pkg_workspace --> pkg_storage_domain pkg_llm_retry --> pkg_agent pkg_llm_retry --> pkg_brand pkg_llm_retry --> pkg_invariants @@ -496,10 +544,14 @@ flowchart TD pkg_goal --> pkg_session pkg_goal --> pkg_session_projection pkg_goal --> pkg_typert_protocol - pkg_fs --> pkg_brand - pkg_fs --> pkg_invariants - pkg_fs --> pkg_llm - pkg_fs --> pkg_sandbox + pkg_fs_local --> pkg_fs + pkg_fs_local --> pkg_invariants + pkg_fs_observation_policy --> pkg_fs + pkg_fs_observation_policy --> pkg_invariants + pkg_skill_filesystem --> pkg_fs + pkg_skill_filesystem --> pkg_home_paths + pkg_skill_filesystem --> pkg_invariants + pkg_skill_filesystem --> pkg_skill pkg_web_search_deepseek --> pkg_agent pkg_web_search_deepseek --> pkg_credentials pkg_web_search_deepseek --> pkg_invariants @@ -507,18 +559,25 @@ flowchart TD pkg_web_search_deepseek --> pkg_session pkg_web_search_deepseek --> pkg_settings pkg_web_search_deepseek --> pkg_web - pkg_spill_local --> pkg_invariants - pkg_spill_local --> pkg_spill + pkg_hook_protocol --> pkg_invariants + pkg_hook_protocol --> pkg_session + pkg_hook_protocol --> pkg_shell + pkg_session_query --> pkg_brand + pkg_session_query --> pkg_invariants + pkg_session_query --> pkg_llm + pkg_session_query --> pkg_session + pkg_session_query --> pkg_session_persistence + pkg_session_query --> pkg_session_title pkg_time_context --> pkg_agent pkg_time_context --> pkg_invariants pkg_time_context --> pkg_session - pkg_message_feedback --> pkg_brand - pkg_message_feedback --> pkg_invariants - pkg_message_feedback --> pkg_llm - pkg_message_feedback --> pkg_session - pkg_message_feedback --> pkg_session_persistence - pkg_message_feedback --> pkg_storage_domain - pkg_message_feedback --> pkg_typert_protocol + pkg_tmux_context --> pkg_agent + pkg_tmux_context --> pkg_invariants + pkg_tmux_context --> pkg_session + pkg_tmux_context --> pkg_shell + pkg_fs_e2b --> pkg_e2b + pkg_fs_e2b --> pkg_fs + pkg_fs_e2b --> pkg_invariants pkg_commands --> pkg_agent pkg_commands --> pkg_attachment pkg_commands --> pkg_brand @@ -541,6 +600,13 @@ flowchart TD pkg_jobs --> pkg_brand pkg_jobs --> pkg_invariants pkg_jobs --> pkg_session + pkg_lsp_stdio --> pkg_brand + pkg_lsp_stdio --> pkg_fs + pkg_lsp_stdio --> pkg_invariants + pkg_lsp_stdio --> pkg_llm + pkg_lsp_stdio --> pkg_lsp + pkg_lsp_stdio --> pkg_subprocess + pkg_lsp_stdio --> pkg_timeout pkg_agent_presets --> pkg_agent pkg_agent_presets --> pkg_atomic_write pkg_agent_presets --> pkg_home_paths @@ -549,42 +615,29 @@ flowchart TD pkg_agent_presets --> pkg_session pkg_agent_presets --> pkg_settings pkg_agent_presets --> pkg_system_prompt - pkg_sandbox_local --> pkg_invariants - pkg_sandbox_local --> pkg_llm - pkg_sandbox_local --> pkg_sandbox - pkg_sandbox_local --> pkg_session pkg_sandbox_policy --> pkg_agent pkg_sandbox_policy --> pkg_invariants pkg_sandbox_policy --> pkg_sandbox pkg_sandbox_policy --> pkg_session pkg_sandbox_policy --> pkg_system_prompt - pkg_session_persistence_jsonl --> pkg_invariants - pkg_session_persistence_jsonl --> pkg_session - pkg_session_persistence_jsonl --> pkg_session_persistence - pkg_session_persistence_sqlite --> pkg_invariants - pkg_session_persistence_sqlite --> pkg_session - pkg_session_persistence_sqlite --> pkg_session_persistence - pkg_session_projection_cache --> pkg_invariants - pkg_session_projection_cache --> pkg_session - pkg_session_projection_cache --> pkg_session_persistence - pkg_session_projection_cache --> pkg_session_projection - pkg_session_projection_cache --> pkg_storage_domain - pkg_session_stats --> pkg_invariants - pkg_session_stats --> pkg_llm - pkg_session_stats --> pkg_session - pkg_session_stats --> pkg_session_projection pkg_session_telemetry --> pkg_agent pkg_session_telemetry --> pkg_invariants pkg_session_telemetry --> pkg_session - pkg_session_title --> pkg_brand - pkg_session_title --> pkg_invariants - pkg_session_title --> pkg_llm - pkg_session_title --> pkg_session - pkg_session_title --> pkg_session_projection - pkg_shell --> pkg_invariants - pkg_shell --> pkg_sandbox - pkg_shell --> pkg_settings - pkg_shell --> pkg_subprocess + pkg_session_title_llm --> pkg_invariants + pkg_session_title_llm --> pkg_llm + pkg_session_title_llm --> pkg_session + pkg_session_title_llm --> pkg_session_title + pkg_session_title_llm --> pkg_timeout + pkg_bash_local --> pkg_invariants + pkg_bash_local --> pkg_settings + pkg_bash_local --> pkg_shell + pkg_bash_local --> pkg_subprocess + pkg_bash_local --> pkg_timeout + pkg_pwsh_local --> pkg_invariants + pkg_pwsh_local --> pkg_settings + pkg_pwsh_local --> pkg_shell + pkg_pwsh_local --> pkg_subprocess + pkg_pwsh_local --> pkg_timeout pkg_terminal --> pkg_agent pkg_terminal --> pkg_brand pkg_terminal --> pkg_invariants @@ -597,12 +650,6 @@ flowchart TD pkg_workflow --> pkg_invariants pkg_workflow --> pkg_llm pkg_workflow --> pkg_session - pkg_workspace --> pkg_brand - pkg_workspace --> pkg_invariants - pkg_workspace --> pkg_session - pkg_workspace --> pkg_session_persistence - pkg_workspace --> pkg_storage - pkg_workspace --> pkg_storage_domain pkg_tools --> pkg_agent pkg_tools --> pkg_code_runtime pkg_tools --> pkg_invariants @@ -620,23 +667,15 @@ flowchart TD pkg_goal_round_driver --> pkg_invariants pkg_goal_round_driver --> pkg_llm pkg_goal_round_driver --> pkg_session - pkg_fs_local --> pkg_fs - pkg_fs_local --> pkg_invariants - pkg_fs_observation_policy --> pkg_fs - pkg_fs_observation_policy --> pkg_invariants - pkg_skill_filesystem --> pkg_fs - pkg_skill_filesystem --> pkg_home_paths - pkg_skill_filesystem --> pkg_invariants - pkg_skill_filesystem --> pkg_skill - pkg_hook_protocol --> pkg_invariants - pkg_hook_protocol --> pkg_session - pkg_hook_protocol --> pkg_shell - pkg_session_query --> pkg_brand - pkg_session_query --> pkg_invariants - pkg_session_query --> pkg_llm - pkg_session_query --> pkg_session - pkg_session_query --> pkg_session_persistence - pkg_session_query --> pkg_session_title + pkg_fs_sandbox --> pkg_fs + pkg_fs_sandbox --> pkg_fs_local + pkg_fs_sandbox --> pkg_invariants + pkg_fs_sandbox --> pkg_sandbox + pkg_fs_sandbox --> pkg_sandbox_policy + pkg_session_query_sqlite --> pkg_invariants + pkg_session_query_sqlite --> pkg_session + pkg_session_query_sqlite --> pkg_session_persistence + pkg_session_query_sqlite --> pkg_session_query pkg_acp --> pkg_agent pkg_acp --> pkg_attachment pkg_acp --> pkg_invariants @@ -653,13 +692,6 @@ flowchart TD pkg_compaction --> pkg_invariants pkg_compaction --> pkg_llm pkg_compaction --> pkg_session - pkg_tmux_context --> pkg_agent - pkg_tmux_context --> pkg_invariants - pkg_tmux_context --> pkg_session - pkg_tmux_context --> pkg_shell - pkg_fs_e2b --> pkg_e2b - pkg_fs_e2b --> pkg_fs - pkg_fs_e2b --> pkg_invariants pkg_command_feedback --> pkg_anonymous_user_id pkg_command_feedback --> pkg_commands pkg_command_feedback --> pkg_invariants @@ -679,28 +711,26 @@ flowchart TD pkg_jobs_local --> pkg_jobs pkg_jobs_local --> pkg_scope pkg_jobs_local --> pkg_timeout - pkg_lsp_stdio --> pkg_brand - pkg_lsp_stdio --> pkg_fs - pkg_lsp_stdio --> pkg_invariants - pkg_lsp_stdio --> pkg_llm - pkg_lsp_stdio --> pkg_lsp - pkg_lsp_stdio --> pkg_subprocess - pkg_lsp_stdio --> pkg_timeout - pkg_session_title_llm --> pkg_invariants - pkg_session_title_llm --> pkg_llm - pkg_session_title_llm --> pkg_session - pkg_session_title_llm --> pkg_session_title - pkg_session_title_llm --> pkg_timeout - pkg_bash_local --> pkg_invariants - pkg_bash_local --> pkg_settings - pkg_bash_local --> pkg_shell - pkg_bash_local --> pkg_subprocess - pkg_bash_local --> pkg_timeout - pkg_pwsh_local --> pkg_invariants - pkg_pwsh_local --> pkg_settings - pkg_pwsh_local --> pkg_shell - pkg_pwsh_local --> pkg_subprocess - pkg_pwsh_local --> pkg_timeout + pkg_session_title_all_prompts_llm --> pkg_invariants + pkg_session_title_all_prompts_llm --> pkg_llm + pkg_session_title_all_prompts_llm --> pkg_session + pkg_session_title_all_prompts_llm --> pkg_session_title + pkg_session_title_all_prompts_llm --> pkg_session_title_llm + pkg_session_title_first_prompt_llm --> pkg_invariants + pkg_session_title_first_prompt_llm --> pkg_llm + pkg_session_title_first_prompt_llm --> pkg_session + pkg_session_title_first_prompt_llm --> pkg_session_title + pkg_session_title_first_prompt_llm --> pkg_session_title_llm + pkg_bash_sandbox --> pkg_bash_local + pkg_bash_sandbox --> pkg_invariants + pkg_bash_sandbox --> pkg_sandbox + pkg_bash_sandbox --> pkg_sandbox_policy + pkg_bash_sandbox --> pkg_shell + pkg_pwsh_sandbox --> pkg_invariants + pkg_pwsh_sandbox --> pkg_pwsh_local + pkg_pwsh_sandbox --> pkg_sandbox + pkg_pwsh_sandbox --> pkg_sandbox_policy + pkg_pwsh_sandbox --> pkg_shell pkg_terminal_bash --> pkg_agent pkg_terminal_bash --> pkg_invariants pkg_terminal_bash --> pkg_sandbox @@ -731,11 +761,6 @@ flowchart TD pkg_tool_goal --> pkg_session pkg_tool_goal --> pkg_system_prompt pkg_tool_goal --> pkg_tools - pkg_fs_sandbox --> pkg_fs - pkg_fs_sandbox --> pkg_fs_local - pkg_fs_sandbox --> pkg_invariants - pkg_fs_sandbox --> pkg_sandbox - pkg_fs_sandbox --> pkg_sandbox_policy pkg_tool_fs --> pkg_attachment pkg_tool_fs --> pkg_fs pkg_tool_fs --> pkg_invariants @@ -812,10 +837,6 @@ flowchart TD pkg_hooks_codex --> pkg_session pkg_hooks_codex --> pkg_session_persistence pkg_hooks_codex --> pkg_tools - pkg_session_query_sqlite --> pkg_invariants - pkg_session_query_sqlite --> pkg_session - pkg_session_query_sqlite --> pkg_session_persistence - pkg_session_query_sqlite --> pkg_session_query pkg_tool_session_query --> pkg_invariants pkg_tool_session_query --> pkg_llm pkg_tool_session_query --> pkg_session @@ -897,26 +918,6 @@ flowchart TD pkg_session_telemetry_otel --> pkg_llm pkg_session_telemetry_otel --> pkg_session pkg_session_telemetry_otel --> pkg_session_telemetry - pkg_session_title_all_prompts_llm --> pkg_invariants - pkg_session_title_all_prompts_llm --> pkg_llm - pkg_session_title_all_prompts_llm --> pkg_session - pkg_session_title_all_prompts_llm --> pkg_session_title - pkg_session_title_all_prompts_llm --> pkg_session_title_llm - pkg_session_title_first_prompt_llm --> pkg_invariants - pkg_session_title_first_prompt_llm --> pkg_llm - pkg_session_title_first_prompt_llm --> pkg_session - pkg_session_title_first_prompt_llm --> pkg_session_title - pkg_session_title_first_prompt_llm --> pkg_session_title_llm - pkg_bash_sandbox --> pkg_bash_local - pkg_bash_sandbox --> pkg_invariants - pkg_bash_sandbox --> pkg_sandbox - pkg_bash_sandbox --> pkg_sandbox_policy - pkg_bash_sandbox --> pkg_shell - pkg_pwsh_sandbox --> pkg_invariants - pkg_pwsh_sandbox --> pkg_pwsh_local - pkg_pwsh_sandbox --> pkg_sandbox - pkg_pwsh_sandbox --> pkg_sandbox_policy - pkg_pwsh_sandbox --> pkg_shell pkg_shell_env --> pkg_home_paths pkg_shell_env --> pkg_invariants pkg_shell_env --> pkg_session_persistence @@ -939,6 +940,7 @@ flowchart TD pkg_agent_loop_testkit --> pkg_invariants pkg_agent_loop_testkit --> pkg_llm pkg_agent_loop_testkit --> pkg_session + pkg_agent_loop_testkit --> pkg_session_projection pkg_agent_loop_testkit --> pkg_system_prompt pkg_agent_loop_testkit --> pkg_tools pkg_llm_replay --> pkg_compaction @@ -1106,6 +1108,7 @@ flowchart TD pkg_agent_spine_demo --> pkg_llm_retry pkg_agent_spine_demo --> pkg_scope pkg_agent_spine_demo --> pkg_session + pkg_agent_spine_demo --> pkg_session_projection pkg_agent_spine_demo --> pkg_session_title pkg_agent_spine_demo --> pkg_shell_env pkg_agent_spine_demo --> pkg_skill @@ -1470,7 +1473,6 @@ flowchart TD | [`skill`](../packages/skill/skill) | `skill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`web`](../packages/web/web) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | -| [`agent`](../packages/core/agent) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`skill-badge`](../packages/skill/skill-badge) | `skill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`skill`](../packages/skill/skill) | | [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) | @@ -1483,58 +1485,64 @@ flowchart TD | [`session-persistence`](../packages/session/session-persistence) | `session` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`session-projection`](../packages/session/session-projection) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`acp-snapshot`](../packages/test-support/acp-snapshot) | `test-support` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | -| [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`settings`](../packages/settings/settings) | -| [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | +| [`agent`](../packages/core/agent) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | -| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`spill`](../packages/spill/spill) | -| [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol) | -| [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | -| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | -| [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | -| [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | -| [`agent-presets`](../packages/preset/agent-presets) | `preset` | [`agent`](../packages/core/agent), [`atomic-write`](../packages/util/atomic-write), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | -| [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) | | [`session-stats`](../packages/session/session-stats) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | -| [`session-telemetry`](../packages/session/session-telemetry) | `session` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`session-title`](../packages/session/session-title) | `session` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`shell`](../packages/shell/shell) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) | -| [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) | -| [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workspace`](../packages/workspace/workspace) | `workspace` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain) | -| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | -| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | -| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | +| [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`settings`](../packages/settings/settings) | +| [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | | [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`fs-observation-policy`](../packages/fs/fs-observation-policy) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`skill-filesystem`](../packages/skill/skill-filesystem) | `skill` | [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`skill`](../packages/skill/skill) | +| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`web`](../packages/web/web) | | [`hook-protocol`](../packages/hooks/hook-protocol) | `hooks` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`shell`](../packages/shell/shell) | | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-title`](../packages/session/session-title) | -| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`user-approval`](../packages/interaction/user-approval) | -| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`shell`](../packages/shell/shell) | | [`fs-e2b`](../packages/e2b/fs-e2b) | `e2b` | [`e2b`](../packages/e2b/e2b), [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants) | -| [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) | -| [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`user-approval`](../packages/interaction/user-approval) | -| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | +| [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | +| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | +| [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | +| [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`agent-presets`](../packages/preset/agent-presets) | `preset` | [`agent`](../packages/core/agent), [`atomic-write`](../packages/util/atomic-write), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt) | +| [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | +| [`session-telemetry`](../packages/session/session-telemetry) | `session` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`bash-local`](../packages/shell/bash-local) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) | +| [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | +| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | +| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | +| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | +| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`user-approval`](../packages/interaction/user-approval) | +| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) | +| [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`user-approval`](../packages/interaction/user-approval) | +| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | +| [`session-title-all-prompts-llm`](../packages/session/session-title-all-prompts-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | +| [`session-title-first-prompt-llm`](../packages/session/session-title-first-prompt-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | +| [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | +| [`pwsh-sandbox`](../packages/shell/pwsh-sandbox) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`pwsh-local`](../packages/shell/pwsh-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | | [`terminal-bash`](../packages/terminal/terminal-bash) | `terminal` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`terminal`](../packages/terminal/terminal) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`agent-tool-presentation`](../packages/core/agent-tool-presentation) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | | [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) | @@ -1545,7 +1553,6 @@ flowchart TD | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | | [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`hooks-codex`](../packages/hooks/hooks-codex) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | -| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`tool-session-query`](../packages/session-query/tool-session-query) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | @@ -1560,14 +1567,10 @@ flowchart TD | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | | [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy) | `session` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) | -| [`session-title-all-prompts-llm`](../packages/session/session-title-all-prompts-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | -| [`session-title-first-prompt-llm`](../packages/session/session-title-first-prompt-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | -| [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | -| [`pwsh-sandbox`](../packages/shell/pwsh-sandbox) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`pwsh-local`](../packages/shell/pwsh-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | | [`shell-env`](../packages/shell/shell-env) | `shell` | [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`session-persistence`](../packages/session/session-persistence), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) | | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-terminal`](../packages/terminal/tool-terminal) | `terminal` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`llm-replay`](../packages/test-support/llm-replay) | `test-support` | [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | @@ -1592,7 +1595,7 @@ flowchart TD | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`invariants`](../packages/runtime-diagnostics/invariants), [`subagent`](../packages/subagent/subagent), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver) | | [`client-connection`](../packages/client/connection) | `client` | [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`host-apiproxy`](../packages/host/apiproxy), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | | [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | -| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs-local`](../packages/jobs/jobs-local), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`shell-env`](../packages/shell/shell-env), [`skill`](../packages/skill/skill), [`skill-filesystem`](../packages/skill/skill-filesystem), [`system-prompt`](../packages/core/system-prompt), [`tool-bash`](../packages/shell/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-skill`](../packages/skill/tool-skill), [`tools`](../packages/core/tools) | +| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs-local`](../packages/jobs/jobs-local), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-title`](../packages/session/session-title), [`shell-env`](../packages/shell/shell-env), [`skill`](../packages/skill/skill), [`skill-filesystem`](../packages/skill/skill-filesystem), [`system-prompt`](../packages/core/system-prompt), [`tool-bash`](../packages/shell/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-skill`](../packages/skill/tool-skill), [`tools`](../packages/core/tools) | | [`tool-team`](../packages/experimental/tool-team) | `experimental` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`team`](../packages/experimental/team), [`tools`](../packages/core/tools) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 6239520b7d..0ccbf94e41 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -438,12 +438,6 @@ flowchart TD pkg_lsp --> pkg_brand pkg_lsp --> pkg_invariants pkg_lsp --> pkg_llm - pkg_agent --> pkg_invariants - pkg_agent --> pkg_llm - pkg_agent --> pkg_scope - pkg_agent --> pkg_session - pkg_agent --> pkg_system_prompt - pkg_agent --> pkg_typert_protocol pkg_skill_badge --> pkg_invariants pkg_skill_badge --> pkg_skill pkg_web_fetch_http --> pkg_invariants @@ -480,6 +474,60 @@ flowchart TD pkg_session_projection --> pkg_session pkg_acp_snapshot --> pkg_invariants pkg_acp_snapshot --> pkg_session + pkg_agent --> pkg_invariants + pkg_agent --> pkg_llm + pkg_agent --> pkg_scope + pkg_agent --> pkg_session + pkg_agent --> pkg_session_projection + pkg_agent --> pkg_system_prompt + pkg_agent --> pkg_typert_protocol + pkg_fs --> pkg_brand + pkg_fs --> pkg_invariants + pkg_fs --> pkg_llm + pkg_fs --> pkg_sandbox + pkg_spill_local --> pkg_invariants + pkg_spill_local --> pkg_spill + pkg_message_feedback --> pkg_brand + pkg_message_feedback --> pkg_invariants + pkg_message_feedback --> pkg_llm + pkg_message_feedback --> pkg_session + pkg_message_feedback --> pkg_session_persistence + pkg_message_feedback --> pkg_storage_domain + pkg_message_feedback --> pkg_typert_protocol + pkg_sandbox_local --> pkg_invariants + pkg_sandbox_local --> pkg_llm + pkg_sandbox_local --> pkg_sandbox + pkg_sandbox_local --> pkg_session + pkg_session_persistence_jsonl --> pkg_invariants + pkg_session_persistence_jsonl --> pkg_session + pkg_session_persistence_jsonl --> pkg_session_persistence + pkg_session_persistence_sqlite --> pkg_invariants + pkg_session_persistence_sqlite --> pkg_session + pkg_session_persistence_sqlite --> pkg_session_persistence + pkg_session_projection_cache --> pkg_invariants + pkg_session_projection_cache --> pkg_session + pkg_session_projection_cache --> pkg_session_persistence + pkg_session_projection_cache --> pkg_session_projection + pkg_session_projection_cache --> pkg_storage_domain + pkg_session_stats --> pkg_invariants + pkg_session_stats --> pkg_llm + pkg_session_stats --> pkg_session + pkg_session_stats --> pkg_session_projection + pkg_session_title --> pkg_brand + pkg_session_title --> pkg_invariants + pkg_session_title --> pkg_llm + pkg_session_title --> pkg_session + pkg_session_title --> pkg_session_projection + pkg_shell --> pkg_invariants + pkg_shell --> pkg_sandbox + pkg_shell --> pkg_settings + pkg_shell --> pkg_subprocess + pkg_workspace --> pkg_brand + pkg_workspace --> pkg_invariants + pkg_workspace --> pkg_session + pkg_workspace --> pkg_session_persistence + pkg_workspace --> pkg_storage + pkg_workspace --> pkg_storage_domain pkg_llm_retry --> pkg_agent pkg_llm_retry --> pkg_brand pkg_llm_retry --> pkg_invariants @@ -498,10 +546,14 @@ flowchart TD pkg_goal --> pkg_session pkg_goal --> pkg_session_projection pkg_goal --> pkg_typert_protocol - pkg_fs --> pkg_brand - pkg_fs --> pkg_invariants - pkg_fs --> pkg_llm - pkg_fs --> pkg_sandbox + pkg_fs_local --> pkg_fs + pkg_fs_local --> pkg_invariants + pkg_fs_observation_policy --> pkg_fs + pkg_fs_observation_policy --> pkg_invariants + pkg_skill_filesystem --> pkg_fs + pkg_skill_filesystem --> pkg_home_paths + pkg_skill_filesystem --> pkg_invariants + pkg_skill_filesystem --> pkg_skill pkg_web_search_deepseek --> pkg_agent pkg_web_search_deepseek --> pkg_credentials pkg_web_search_deepseek --> pkg_invariants @@ -509,18 +561,25 @@ flowchart TD pkg_web_search_deepseek --> pkg_session pkg_web_search_deepseek --> pkg_settings pkg_web_search_deepseek --> pkg_web - pkg_spill_local --> pkg_invariants - pkg_spill_local --> pkg_spill + pkg_hook_protocol --> pkg_invariants + pkg_hook_protocol --> pkg_session + pkg_hook_protocol --> pkg_shell + pkg_session_query --> pkg_brand + pkg_session_query --> pkg_invariants + pkg_session_query --> pkg_llm + pkg_session_query --> pkg_session + pkg_session_query --> pkg_session_persistence + pkg_session_query --> pkg_session_title pkg_time_context --> pkg_agent pkg_time_context --> pkg_invariants pkg_time_context --> pkg_session - pkg_message_feedback --> pkg_brand - pkg_message_feedback --> pkg_invariants - pkg_message_feedback --> pkg_llm - pkg_message_feedback --> pkg_session - pkg_message_feedback --> pkg_session_persistence - pkg_message_feedback --> pkg_storage_domain - pkg_message_feedback --> pkg_typert_protocol + pkg_tmux_context --> pkg_agent + pkg_tmux_context --> pkg_invariants + pkg_tmux_context --> pkg_session + pkg_tmux_context --> pkg_shell + pkg_fs_e2b --> pkg_e2b + pkg_fs_e2b --> pkg_fs + pkg_fs_e2b --> pkg_invariants pkg_commands --> pkg_agent pkg_commands --> pkg_attachment pkg_commands --> pkg_brand @@ -543,6 +602,13 @@ flowchart TD pkg_jobs --> pkg_brand pkg_jobs --> pkg_invariants pkg_jobs --> pkg_session + pkg_lsp_stdio --> pkg_brand + pkg_lsp_stdio --> pkg_fs + pkg_lsp_stdio --> pkg_invariants + pkg_lsp_stdio --> pkg_llm + pkg_lsp_stdio --> pkg_lsp + pkg_lsp_stdio --> pkg_subprocess + pkg_lsp_stdio --> pkg_timeout pkg_agent_presets --> pkg_agent pkg_agent_presets --> pkg_atomic_write pkg_agent_presets --> pkg_home_paths @@ -551,42 +617,29 @@ flowchart TD pkg_agent_presets --> pkg_session pkg_agent_presets --> pkg_settings pkg_agent_presets --> pkg_system_prompt - pkg_sandbox_local --> pkg_invariants - pkg_sandbox_local --> pkg_llm - pkg_sandbox_local --> pkg_sandbox - pkg_sandbox_local --> pkg_session pkg_sandbox_policy --> pkg_agent pkg_sandbox_policy --> pkg_invariants pkg_sandbox_policy --> pkg_sandbox pkg_sandbox_policy --> pkg_session pkg_sandbox_policy --> pkg_system_prompt - pkg_session_persistence_jsonl --> pkg_invariants - pkg_session_persistence_jsonl --> pkg_session - pkg_session_persistence_jsonl --> pkg_session_persistence - pkg_session_persistence_sqlite --> pkg_invariants - pkg_session_persistence_sqlite --> pkg_session - pkg_session_persistence_sqlite --> pkg_session_persistence - pkg_session_projection_cache --> pkg_invariants - pkg_session_projection_cache --> pkg_session - pkg_session_projection_cache --> pkg_session_persistence - pkg_session_projection_cache --> pkg_session_projection - pkg_session_projection_cache --> pkg_storage_domain - pkg_session_stats --> pkg_invariants - pkg_session_stats --> pkg_llm - pkg_session_stats --> pkg_session - pkg_session_stats --> pkg_session_projection pkg_session_telemetry --> pkg_agent pkg_session_telemetry --> pkg_invariants pkg_session_telemetry --> pkg_session - pkg_session_title --> pkg_brand - pkg_session_title --> pkg_invariants - pkg_session_title --> pkg_llm - pkg_session_title --> pkg_session - pkg_session_title --> pkg_session_projection - pkg_shell --> pkg_invariants - pkg_shell --> pkg_sandbox - pkg_shell --> pkg_settings - pkg_shell --> pkg_subprocess + pkg_session_title_llm --> pkg_invariants + pkg_session_title_llm --> pkg_llm + pkg_session_title_llm --> pkg_session + pkg_session_title_llm --> pkg_session_title + pkg_session_title_llm --> pkg_timeout + pkg_bash_local --> pkg_invariants + pkg_bash_local --> pkg_settings + pkg_bash_local --> pkg_shell + pkg_bash_local --> pkg_subprocess + pkg_bash_local --> pkg_timeout + pkg_pwsh_local --> pkg_invariants + pkg_pwsh_local --> pkg_settings + pkg_pwsh_local --> pkg_shell + pkg_pwsh_local --> pkg_subprocess + pkg_pwsh_local --> pkg_timeout pkg_terminal --> pkg_agent pkg_terminal --> pkg_brand pkg_terminal --> pkg_invariants @@ -599,12 +652,6 @@ flowchart TD pkg_workflow --> pkg_invariants pkg_workflow --> pkg_llm pkg_workflow --> pkg_session - pkg_workspace --> pkg_brand - pkg_workspace --> pkg_invariants - pkg_workspace --> pkg_session - pkg_workspace --> pkg_session_persistence - pkg_workspace --> pkg_storage - pkg_workspace --> pkg_storage_domain pkg_tools --> pkg_agent pkg_tools --> pkg_code_runtime pkg_tools --> pkg_invariants @@ -622,23 +669,15 @@ flowchart TD pkg_goal_round_driver --> pkg_invariants pkg_goal_round_driver --> pkg_llm pkg_goal_round_driver --> pkg_session - pkg_fs_local --> pkg_fs - pkg_fs_local --> pkg_invariants - pkg_fs_observation_policy --> pkg_fs - pkg_fs_observation_policy --> pkg_invariants - pkg_skill_filesystem --> pkg_fs - pkg_skill_filesystem --> pkg_home_paths - pkg_skill_filesystem --> pkg_invariants - pkg_skill_filesystem --> pkg_skill - pkg_hook_protocol --> pkg_invariants - pkg_hook_protocol --> pkg_session - pkg_hook_protocol --> pkg_shell - pkg_session_query --> pkg_brand - pkg_session_query --> pkg_invariants - pkg_session_query --> pkg_llm - pkg_session_query --> pkg_session - pkg_session_query --> pkg_session_persistence - pkg_session_query --> pkg_session_title + pkg_fs_sandbox --> pkg_fs + pkg_fs_sandbox --> pkg_fs_local + pkg_fs_sandbox --> pkg_invariants + pkg_fs_sandbox --> pkg_sandbox + pkg_fs_sandbox --> pkg_sandbox_policy + pkg_session_query_sqlite --> pkg_invariants + pkg_session_query_sqlite --> pkg_session + pkg_session_query_sqlite --> pkg_session_persistence + pkg_session_query_sqlite --> pkg_session_query pkg_acp --> pkg_agent pkg_acp --> pkg_attachment pkg_acp --> pkg_invariants @@ -655,13 +694,6 @@ flowchart TD pkg_compaction --> pkg_invariants pkg_compaction --> pkg_llm pkg_compaction --> pkg_session - pkg_tmux_context --> pkg_agent - pkg_tmux_context --> pkg_invariants - pkg_tmux_context --> pkg_session - pkg_tmux_context --> pkg_shell - pkg_fs_e2b --> pkg_e2b - pkg_fs_e2b --> pkg_fs - pkg_fs_e2b --> pkg_invariants pkg_command_feedback --> pkg_anonymous_user_id pkg_command_feedback --> pkg_commands pkg_command_feedback --> pkg_invariants @@ -681,28 +713,26 @@ flowchart TD pkg_jobs_local --> pkg_jobs pkg_jobs_local --> pkg_scope pkg_jobs_local --> pkg_timeout - pkg_lsp_stdio --> pkg_brand - pkg_lsp_stdio --> pkg_fs - pkg_lsp_stdio --> pkg_invariants - pkg_lsp_stdio --> pkg_llm - pkg_lsp_stdio --> pkg_lsp - pkg_lsp_stdio --> pkg_subprocess - pkg_lsp_stdio --> pkg_timeout - pkg_session_title_llm --> pkg_invariants - pkg_session_title_llm --> pkg_llm - pkg_session_title_llm --> pkg_session - pkg_session_title_llm --> pkg_session_title - pkg_session_title_llm --> pkg_timeout - pkg_bash_local --> pkg_invariants - pkg_bash_local --> pkg_settings - pkg_bash_local --> pkg_shell - pkg_bash_local --> pkg_subprocess - pkg_bash_local --> pkg_timeout - pkg_pwsh_local --> pkg_invariants - pkg_pwsh_local --> pkg_settings - pkg_pwsh_local --> pkg_shell - pkg_pwsh_local --> pkg_subprocess - pkg_pwsh_local --> pkg_timeout + pkg_session_title_all_prompts_llm --> pkg_invariants + pkg_session_title_all_prompts_llm --> pkg_llm + pkg_session_title_all_prompts_llm --> pkg_session + pkg_session_title_all_prompts_llm --> pkg_session_title + pkg_session_title_all_prompts_llm --> pkg_session_title_llm + pkg_session_title_first_prompt_llm --> pkg_invariants + pkg_session_title_first_prompt_llm --> pkg_llm + pkg_session_title_first_prompt_llm --> pkg_session + pkg_session_title_first_prompt_llm --> pkg_session_title + pkg_session_title_first_prompt_llm --> pkg_session_title_llm + pkg_bash_sandbox --> pkg_bash_local + pkg_bash_sandbox --> pkg_invariants + pkg_bash_sandbox --> pkg_sandbox + pkg_bash_sandbox --> pkg_sandbox_policy + pkg_bash_sandbox --> pkg_shell + pkg_pwsh_sandbox --> pkg_invariants + pkg_pwsh_sandbox --> pkg_pwsh_local + pkg_pwsh_sandbox --> pkg_sandbox + pkg_pwsh_sandbox --> pkg_sandbox_policy + pkg_pwsh_sandbox --> pkg_shell pkg_terminal_bash --> pkg_agent pkg_terminal_bash --> pkg_invariants pkg_terminal_bash --> pkg_sandbox @@ -733,11 +763,6 @@ flowchart TD pkg_tool_goal --> pkg_session pkg_tool_goal --> pkg_system_prompt pkg_tool_goal --> pkg_tools - pkg_fs_sandbox --> pkg_fs - pkg_fs_sandbox --> pkg_fs_local - pkg_fs_sandbox --> pkg_invariants - pkg_fs_sandbox --> pkg_sandbox - pkg_fs_sandbox --> pkg_sandbox_policy pkg_tool_fs --> pkg_attachment pkg_tool_fs --> pkg_fs pkg_tool_fs --> pkg_invariants @@ -814,10 +839,6 @@ flowchart TD pkg_hooks_codex --> pkg_session pkg_hooks_codex --> pkg_session_persistence pkg_hooks_codex --> pkg_tools - pkg_session_query_sqlite --> pkg_invariants - pkg_session_query_sqlite --> pkg_session - pkg_session_query_sqlite --> pkg_session_persistence - pkg_session_query_sqlite --> pkg_session_query pkg_tool_session_query --> pkg_invariants pkg_tool_session_query --> pkg_llm pkg_tool_session_query --> pkg_session @@ -899,26 +920,6 @@ flowchart TD pkg_session_telemetry_otel --> pkg_llm pkg_session_telemetry_otel --> pkg_session pkg_session_telemetry_otel --> pkg_session_telemetry - pkg_session_title_all_prompts_llm --> pkg_invariants - pkg_session_title_all_prompts_llm --> pkg_llm - pkg_session_title_all_prompts_llm --> pkg_session - pkg_session_title_all_prompts_llm --> pkg_session_title - pkg_session_title_all_prompts_llm --> pkg_session_title_llm - pkg_session_title_first_prompt_llm --> pkg_invariants - pkg_session_title_first_prompt_llm --> pkg_llm - pkg_session_title_first_prompt_llm --> pkg_session - pkg_session_title_first_prompt_llm --> pkg_session_title - pkg_session_title_first_prompt_llm --> pkg_session_title_llm - pkg_bash_sandbox --> pkg_bash_local - pkg_bash_sandbox --> pkg_invariants - pkg_bash_sandbox --> pkg_sandbox - pkg_bash_sandbox --> pkg_sandbox_policy - pkg_bash_sandbox --> pkg_shell - pkg_pwsh_sandbox --> pkg_invariants - pkg_pwsh_sandbox --> pkg_pwsh_local - pkg_pwsh_sandbox --> pkg_sandbox - pkg_pwsh_sandbox --> pkg_sandbox_policy - pkg_pwsh_sandbox --> pkg_shell pkg_shell_env --> pkg_home_paths pkg_shell_env --> pkg_invariants pkg_shell_env --> pkg_session_persistence @@ -941,6 +942,7 @@ flowchart TD pkg_agent_loop_testkit --> pkg_invariants pkg_agent_loop_testkit --> pkg_llm pkg_agent_loop_testkit --> pkg_session + pkg_agent_loop_testkit --> pkg_session_projection pkg_agent_loop_testkit --> pkg_system_prompt pkg_agent_loop_testkit --> pkg_tools pkg_llm_replay --> pkg_compaction @@ -1108,6 +1110,7 @@ flowchart TD pkg_agent_spine_demo --> pkg_llm_retry pkg_agent_spine_demo --> pkg_scope pkg_agent_spine_demo --> pkg_session + pkg_agent_spine_demo --> pkg_session_projection pkg_agent_spine_demo --> pkg_session_title pkg_agent_spine_demo --> pkg_shell_env pkg_agent_spine_demo --> pkg_skill @@ -1472,7 +1475,6 @@ flowchart TD | [`skill`](../packages/skill/skill) | `skill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`web`](../packages/web/web) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | -| [`agent`](../packages/core/agent) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`skill-badge`](../packages/skill/skill-badge) | `skill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`skill`](../packages/skill/skill) | | [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) | @@ -1485,58 +1487,64 @@ flowchart TD | [`session-persistence`](../packages/session/session-persistence) | `session` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`session-projection`](../packages/session/session-projection) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`acp-snapshot`](../packages/test-support/acp-snapshot) | `test-support` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | -| [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`settings`](../packages/settings/settings) | -| [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | +| [`agent`](../packages/core/agent) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | -| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`invariants`](../packages/runtime-diagnostics/invariants), [`spill`](../packages/spill/spill) | -| [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol) | -| [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | -| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | -| [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | -| [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | -| [`agent-presets`](../packages/preset/agent-presets) | `preset` | [`agent`](../packages/core/agent), [`atomic-write`](../packages/util/atomic-write), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | -| [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) | | [`session-stats`](../packages/session/session-stats) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | -| [`session-telemetry`](../packages/session/session-telemetry) | `session` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`session-title`](../packages/session/session-title) | `session` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`shell`](../packages/shell/shell) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) | -| [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) | -| [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workspace`](../packages/workspace/workspace) | `workspace` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain) | -| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | -| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | -| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | +| [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`settings`](../packages/settings/settings) | +| [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | | [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`fs-observation-policy`](../packages/fs/fs-observation-policy) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`skill-filesystem`](../packages/skill/skill-filesystem) | `skill` | [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`skill`](../packages/skill/skill) | +| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`invariants`](../packages/runtime-diagnostics/invariants), [`launch-environment`](../packages/util/launch-environment), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`web`](../packages/web/web) | | [`hook-protocol`](../packages/hooks/hook-protocol) | `hooks` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`shell`](../packages/shell/shell) | | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-title`](../packages/session/session-title) | -| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`user-approval`](../packages/interaction/user-approval) | -| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`shell`](../packages/shell/shell) | | [`fs-e2b`](../packages/e2b/fs-e2b) | `e2b` | [`e2b`](../packages/e2b/e2b), [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants) | -| [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) | -| [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`user-approval`](../packages/interaction/user-approval) | -| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | +| [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | +| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | +| [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | +| [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`agent-presets`](../packages/preset/agent-presets) | `preset` | [`agent`](../packages/core/agent), [`atomic-write`](../packages/util/atomic-write), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt) | +| [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | +| [`session-telemetry`](../packages/session/session-telemetry) | `session` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`bash-local`](../packages/shell/bash-local) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants) | +| [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | +| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm) | +| [`goal-round-driver`](../packages/goal/goal-round-driver) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | +| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | +| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`user-approval`](../packages/interaction/user-approval) | +| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) | +| [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`shell`](../packages/shell/shell), [`user-approval`](../packages/interaction/user-approval) | +| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | +| [`session-title-all-prompts-llm`](../packages/session/session-title-all-prompts-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | +| [`session-title-first-prompt-llm`](../packages/session/session-title-first-prompt-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | +| [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | +| [`pwsh-sandbox`](../packages/shell/pwsh-sandbox) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`pwsh-local`](../packages/shell/pwsh-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | | [`terminal-bash`](../packages/terminal/terminal-bash) | `terminal` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`terminal`](../packages/terminal/terminal) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`agent-tool-presentation`](../packages/core/agent-tool-presentation) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | | [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) | @@ -1547,7 +1555,6 @@ flowchart TD | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) | | [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`hooks-codex`](../packages/hooks/hooks-codex) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | -| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`tool-session-query`](../packages/session-query/tool-session-query) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`command-compact`](../packages/compaction/command-compact) | `compaction` | [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants) | | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | @@ -1562,14 +1569,10 @@ flowchart TD | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | | [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy) | `session` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) | -| [`session-title-all-prompts-llm`](../packages/session/session-title-all-prompts-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | -| [`session-title-first-prompt-llm`](../packages/session/session-title-first-prompt-llm) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | -| [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | -| [`pwsh-sandbox`](../packages/shell/pwsh-sandbox) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`pwsh-local`](../packages/shell/pwsh-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | | [`shell-env`](../packages/shell/shell-env) | `shell` | [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`session-persistence`](../packages/session/session-persistence), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) | | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-terminal`](../packages/terminal/tool-terminal) | `terminal` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`llm-replay`](../packages/test-support/llm-replay) | `test-support` | [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | @@ -1594,7 +1597,7 @@ flowchart TD | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`invariants`](../packages/runtime-diagnostics/invariants), [`subagent`](../packages/subagent/subagent), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver) | | [`client-connection`](../packages/client/connection) | `client` | [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`host-apiproxy`](../packages/host/apiproxy), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | | [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | -| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs-local`](../packages/jobs/jobs-local), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`shell-env`](../packages/shell/shell-env), [`skill`](../packages/skill/skill), [`skill-filesystem`](../packages/skill/skill-filesystem), [`system-prompt`](../packages/core/system-prompt), [`tool-bash`](../packages/shell/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-skill`](../packages/skill/tool-skill), [`tools`](../packages/core/tools) | +| [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs-local`](../packages/jobs/jobs-local), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-title`](../packages/session/session-title), [`shell-env`](../packages/shell/shell-env), [`skill`](../packages/skill/skill), [`skill-filesystem`](../packages/skill/skill-filesystem), [`system-prompt`](../packages/core/system-prompt), [`tool-bash`](../packages/shell/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-skill`](../packages/skill/tool-skill), [`tools`](../packages/core/tools) | | [`tool-team`](../packages/experimental/tool-team) | `experimental` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`team`](../packages/experimental/team), [`tools`](../packages/core/tools) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 295a69a8a8..4e74c063fb 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/persistence-catalog.md -persistence-catalog.md: b680bccf22f7840663e5268eb3feeb6b16f7fd42 -persistence-catalog.zh.md: 4b50582fa55dbdc672d8c45debe108b97a55f0e2 +persistence-catalog.md: eb035b2b2529c0b36e7d2ad55dbe7990995d9093 +persistence-catalog.zh.md: ad4c70b0e1d36beac173e19a309dadefb0a6c349 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index b680bccf22..eb035b2b25 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -103,8 +103,8 @@ Sources: [`packages/core/session/src/types.ts:336`](../packages/core/session/src ```ts persistence-catalog /** * One normalized mutation of an agent's durable pending-message lists. - * Live dispatch precedes projection mutation, so synchronous observers may - * read the pre-splice inbox to recover the removed messages. + * The session-projection registry applies the committed event before + * `Session.append()` returns; Inbox live notifications follow that commit. */ 'agent/inbox/spliced': { target: InboxTarget diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 4b50582fa5..ad4c70b0e1 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -105,8 +105,8 @@ export type SessionEvent = { ```ts persistence-catalog /** * One normalized mutation of an agent's durable pending-message lists. - * Live dispatch precedes projection mutation, so synchronous observers may - * read the pre-splice inbox to recover the removed messages. + * The session-projection registry applies the committed event before + * `Session.append()` returns; Inbox live notifications follow that commit. */ 'agent/inbox/spliced': { target: InboxTarget diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 1265b726fe..022720323d 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/core.md -core.md: d14ad52e57572d5b0b110a0b16ff734e3499bdf5 -core.zh.md: 9ace28731f2532f571b66f2e7f6a3ea4a2c4e345 +core.md: 6e919d02ac1c23cf4f49e92e5ce50a8983ac449d +core.zh.md: 853d9500cd7e51b02ec2f9595bd7f294f7b1d66f diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index d14ad52e57..6e919d02ac 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -175,7 +175,7 @@ The inbox is the delivery vocabulary — two ordered pending-message lists the a type InboxTarget = 'next-turn' | 'next-step' ``` -Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. `Inbox.append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. `claim(target)` removes the proposed step batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without emitting discarded notifications, and the loop separately emits per-message claimed notifications. Whole-queue consumers such as UI projections reconstruct `nextTurn` and `nextStep` from the durable splices, while consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. +Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. `Inbox.append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. `claim(target)` removes the proposed step batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without emitting discarded notifications, then Inbox emits per-message claimed notifications. `InboxService` registers the standard `inbox` projection; its registry cell is the sole live state and the same fold serves cold consumers. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. Cancellation: @@ -722,6 +722,23 @@ roots(): Agent[] Source: [`packages/core/agent/src/index.ts:256`](../../packages/core/agent/src/index.ts) + + +### `ctx.inboxes` — `InboxService` + +Root Inbox service: creates live inboxes and owns their durable projection. + +```ts cordis-catalog +/** + * Restore one live Inbox for an agent and publish its committed mutations. + * @param agent - agent that owns the durable session and live Inbox events. + * @returns the restored Inbox. + */ +create(agent: Agent): Inbox +``` + +Source: [`packages/core/agent/src/inbox.ts:25`](../../packages/core/agent/src/inbox.ts) + ### `agent/*` events diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 9ace28731f..853d9500cd 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -179,7 +179,7 @@ inbox 即投递词汇——agent 以持久投影形式拥有的两条有序待 type InboxTarget = 'next-turn' | 'next-step' ``` -每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。`Inbox.append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。`claim(target)` 通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知;循环另行逐条发出 claimed 通知。UI 投影等整体队列消费方通过持久 splice 重建 `nextTurn` 与 `nextStep`,而跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 +每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。`Inbox.append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。`claim(target)` 通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后由 Inbox 逐条发出 claimed 通知。`InboxService` 注册标准 `inbox` 投影;其注册表 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 取消: @@ -730,6 +730,23 @@ roots(): Agent[] Source: [`packages/core/agent/src/index.ts:256`](../../packages/core/agent/src/index.ts) + + +### `ctx.inboxes` — `InboxService` + +Root Inbox service: creates live inboxes and owns their durable projection. + +```ts cordis-catalog +/** + * Restore one live Inbox for an agent and publish its committed mutations. + * @param agent - agent that owns the durable session and live Inbox events. + * @returns the restored Inbox. + */ +create(agent: Agent): Inbox +``` + +Source: [`packages/core/agent/src/inbox.ts:25`](../../packages/core/agent/src/inbox.ts) + ### `agent/*` events diff --git a/docs/subsystems/session-projection.i18n.yaml b/docs/subsystems/session-projection.i18n.yaml index 2b0653542d..de82e52bc4 100644 --- a/docs/subsystems/session-projection.i18n.yaml +++ b/docs/subsystems/session-projection.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/session-projection.md -session-projection.md: 281e7630eed6480de07a66bf7050798c83396f77 -session-projection.zh.md: bc1448e8baa0f38b3a9ffed1c6005e8905c93bcd +session-projection.md: de7443a2c5eab4835e6217d3db796fc0d0504494 +session-projection.zh.md: 5c1c4e3585a13cddd56def083d670c19c48da83f diff --git a/docs/subsystems/session-projection.md b/docs/subsystems/session-projection.md index 281e7630ee..de7443a2c5 100644 --- a/docs/subsystems/session-projection.md +++ b/docs/subsystems/session-projection.md @@ -90,7 +90,7 @@ type ProjectionChangeListener = ( ## The registry: `ctx.sessionProjections` -`SessionProjectionRegistry` ([signatures](#ctxsessionprojections--sessionprojectionregistry)) owns the drive: one `session/event` subscription, eager `apply` over every registered unit, and per-session per-unit watermark cells. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect whose disposer rides the calling fiber: an unloaded domain plugin's key (with its cached cells) disappears from subsequent drives and snapshots, and clients read that as capability absence; duplicate keys throw. Domain plugins register under `ctx.inject(['sessionProjections'], …)` so headless assemblies without the registry stay unaffected. +`SessionProjectionRegistry` ([signatures](#ctxsessionprojections--sessionprojectionregistry)) owns the drive through one `session/event` subscription and per-session per-unit watermark cells. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect whose disposer rides the calling fiber: an unloaded domain plugin's key (with its cached cells) disappears from subsequent drives and snapshots, and clients read that as capability absence; duplicate keys throw. Domain plugins declare `sessionProjections` as a dependency so assemblies without the registry stay unaffected. @@ -154,7 +154,7 @@ Source: [`packages/session/session-projection-cache/src/index.ts:71`](../../pack ### `ctx.sessionProjections` — `SessionProjectionRegistry` -`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. Domain plugins register under `ctx.inject(['sessionProjections'], …)` so headless assemblies without the registry stay unaffected. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads. +`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the full in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. A domain that requires this capability declares a Cordis service dependency; an optional contributor may register under `ctx.inject(['sessionProjections'], …)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads. ```ts cordis-catalog /** @@ -258,5 +258,5 @@ restore(checkpoint: ProjectionCheckpoint, events: readonly SessionEvent[], baseS Types: [Session](session.md) · [SessionEvent](session.md) -Source: [`packages/session/session-projection/src/index.ts:171`](../../packages/session/session-projection/src/index.ts) +Source: [`packages/session/session-projection/src/index.ts:167`](../../packages/session/session-projection/src/index.ts) diff --git a/docs/subsystems/session-projection.zh.md b/docs/subsystems/session-projection.zh.md index bc1448e8ba..5c1c4e3585 100644 --- a/docs/subsystems/session-projection.zh.md +++ b/docs/subsystems/session-projection.zh.md @@ -90,7 +90,7 @@ type ProjectionChangeListener = ( ## 注册表:`ctx.sessionProjections` -`SessionProjectionRegistry`([签名](#ctxsessionprojections--sessionprojectionregistry))拥有驱动权:一份 `session/event` 订阅、对每个已注册单元即时调用 `apply`,以及每会话每单元的水位线(watermark)cell。cell 惰性构建:在事件流过之后才注册的单元,或比注册表更早的会话,都在首次触达(事件或读取)时从 `init` 出发在内存日志上折叠。注册是一个 effect,其 disposer 随调用方 fiber 走:领域插件卸载后,其 key(连同缓存的 cell)从后续驱动与快照中消失,客户端将其读作能力缺失;key 重复直接 throw。领域插件在 `ctx.inject(['sessionProjections'], …)` 下注册,因此不带注册表的 headless 组装完全不受影响。 +`SessionProjectionRegistry`([签名](#ctxsessionprojections--sessionprojectionregistry))通过一份 `session/event` 订阅以及每会话每单元的水位线(watermark)cell 拥有驱动权。cell 惰性构建:在事件流过之后才注册的单元,或比注册表更早的会话,都在首次触达(事件或读取)时从 `init` 出发在内存日志上折叠。注册是一个 effect,其 disposer 随调用方 fiber 走:领域插件卸载后,其 key(连同缓存的 cell)从后续驱动与快照中消失,客户端将其读作能力缺失;key 重复直接 throw。领域插件把 `sessionProjections` 声明为依赖,因此不含注册表的组装不受影响。 @@ -154,7 +154,7 @@ Source: [`packages/session/session-projection-cache/src/index.ts:71`](../../pack ### `ctx.sessionProjections` — `SessionProjectionRegistry` -`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. Domain plugins register under `ctx.inject(['sessionProjections'], …)` so headless assemblies without the registry stay unaffected. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads. +`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the full in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. A domain that requires this capability declares a Cordis service dependency; an optional contributor may register under `ctx.inject(['sessionProjections'], …)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads. ```ts cordis-catalog /** @@ -258,5 +258,5 @@ restore(checkpoint: ProjectionCheckpoint, events: readonly SessionEvent[], baseS Types: [Session](session.md) · [SessionEvent](session.md) -Source: [`packages/session/session-projection/src/index.ts:171`](../../packages/session/session-projection/src/index.ts) +Source: [`packages/session/session-projection/src/index.ts:167`](../../packages/session/session-projection/src/index.ts) diff --git a/examples/headless-agent/tests/code-mode.e2e.ts b/examples/headless-agent/tests/code-mode.e2e.ts index cca7641575..64413599d6 100644 --- a/examples/headless-agent/tests/code-mode.e2e.ts +++ b/examples/headless-agent/tests/code-mode.e2e.ts @@ -6,10 +6,12 @@ import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, CallId, HarnessError } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { RUN_CODE_NAME, defineTool } from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' @@ -53,6 +55,8 @@ async function codeModeHarness(cwd: string): Promise { const harness = new Context() await harness.plugin(LlmRuntime) await harness.plugin(SessionStore) + await harness.plugin(SessionProjectionRegistry) + await harness.plugin(InboxService) await harness.plugin(SystemPrompt, { persona: PERSONA }) await harness.plugin(ToolRuntime, { mode: 'code' }) await harness.plugin(AgentRegistry) @@ -70,6 +74,8 @@ async function workspaceCodeModeHarness(): Promise { const harness = new Context() await harness.plugin(LlmRuntime) await harness.plugin(SessionStore) + await harness.plugin(SessionProjectionRegistry) + await harness.plugin(InboxService) await harness.plugin(SystemPrompt, { persona: PERSONA }) await harness.plugin(ToolRuntime, { mode: 'code' }) await harness.plugin(AgentRegistry) diff --git a/examples/headless-agent/tests/fixtures/e2b/e2b/bin.ts b/examples/headless-agent/tests/fixtures/e2b/e2b/bin.ts index 4e4ffc120e..9446fcb7b2 100644 --- a/examples/headless-agent/tests/fixtures/e2b/e2b/bin.ts +++ b/examples/headless-agent/tests/fixtures/e2b/e2b/bin.ts @@ -1,7 +1,6 @@ import { readFile } from 'node:fs/promises' import { resolve } from 'node:path' import { boot } from '@deepseek-ai/dsh-app-boot' -import { Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { Session, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-fs-e2b' @@ -20,7 +19,7 @@ const owner: Agent = { id: ownerId, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: ownerFiber.ctx, send() {}, @@ -31,6 +30,7 @@ const owner: Agent = { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } +Object.assign(owner, { inbox: ctx.inboxes.create(owner) }) const unregisterOwner = ctx.agents.register(owner) let terminalId: Awaited>['sessionId'] | undefined try { diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index e9567d9206..6e1656e3f3 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -58,6 +58,9 @@ - id: agent name: '@deepseek-ai/dsh-agent' + - id: agent-inbox + name: '@deepseek-ai/dsh-agent/inbox' + # The transport-independent default for Agents created by entry points. # Settings may supply a saved selection; consumers read it at creation time. - id: agent-default-model diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index ffe564870b..6e69d8c5d3 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -2,11 +2,13 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import type { Agent, AgentHandle, CreateAgentOptions } from '@deepseek-ai/dsh-agent' import AgentDefaultModelConfig from '@deepseek-ai/dsh-agent-default-model' import { createAssistantMessage } from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' import { apply, Config, internals } from '../src/index.ts' @@ -54,6 +56,8 @@ async function bench(script: Script): Promise<{ }> { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(AgentRegistry) await ctx.plugin(AgentDefaultModelConfig, { provider: 'test-provider', model: 'test-model' }) ctx.agents.setFactory({ @@ -68,7 +72,7 @@ async function bench(script: Script): Promise<{ id: session.id, options: options.agentOptions ?? {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: agentCtx, cancel: () => {}, @@ -82,6 +86,7 @@ async function bench(script: Script): Promise<{ inject: () => {}, whenIdle: () => idle, } satisfies Partial) + Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) await options.setup?.(agentCtx) script.before?.(session) ctx.agents.register(agent) diff --git a/packages/context/agent-instructions/package.json b/packages/context/agent-instructions/package.json index d7b3cdf81d..ce38dc5f2a 100644 --- a/packages/context/agent-instructions/package.json +++ b/packages/context/agent-instructions/package.json @@ -48,6 +48,7 @@ "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-fs": "workspace:^", "@deepseek-ai/dsh-fs-local": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", diff --git a/packages/context/agent-instructions/tests/agent-instructions.e2e.ts b/packages/context/agent-instructions/tests/agent-instructions.e2e.ts index 392936b4c2..8d8552182b 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.e2e.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.e2e.ts @@ -4,13 +4,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import LlmRuntime from '@deepseek-ai/dsh-llm' -import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRuntime from '@deepseek-ai/dsh-tools' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import { SessionId } from '@deepseek-ai/dsh-session' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import * as WorkspaceContext from '@deepseek-ai/dsh-agent-instructions' import { candidateScopeKey } from '../src/render.ts' @@ -37,11 +34,9 @@ async function harness(): Promise<{ ctx: Context; agent: Agent }> { await mkdir(join(workdir, '.git'), { recursive: true }) await writeFile(join(workdir, 'AGENTS.md'), `If the user asks for the workspace context handshake, reply with exactly this string and nothing else: ${PROBE}.\n`) ctx = new Context() - await ctx.plugin(LlmRuntime) - await ctx.plugin(SessionStore) - await ctx.plugin(SystemPrompt, { persona: 'Answer the user exactly and concisely.' }) - await ctx.plugin(ToolRuntime) - await ctx.plugin(AgentRegistry) + await mountAgentLoopTestDependencies(ctx, { + systemPrompt: { persona: 'Answer the user exactly and concisely.' }, + }) await ctx.plugin(LocalFileSystem, { cwd: '/' }) await ctx.plugin(ToolFs) await ctx.plugin(WorkspaceContext, { maxBytes: 65536 }) diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index fe37fef48a..c84ed08986 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -6,9 +6,11 @@ import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import * as workspaceContext from '@deepseek-ai/dsh-agent-instructions' import LlmRuntime, { createUserMessage, CallId, type Message, type StreamChunk } from '@deepseek-ai/dsh-llm' -import SessionStore, { Session, SessionId, SESSION_FORMAT_VERSION, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import SessionStore, { SessionId, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' +import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { FileSystem, FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs' import type { FsDirEntry, @@ -47,6 +49,11 @@ import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent const sk = (directory: string, candidateName: string): string => candidateScopeKey(directory, candidateName) const testToolSignal = new AbortController().signal +const isolatedInboxCtx = new Context() +await isolatedInboxCtx.plugin(SessionStore) +await isolatedInboxCtx.plugin(SessionProjectionRegistry) +await isolatedInboxCtx.plugin(InboxService) +let nextStubSession = 1 async function tempRepo(): Promise { return mkdtemp(join(tmpdir(), 'dsh-workspace-context-')) @@ -181,14 +188,18 @@ async function mountFileToolsAndWorkspaceContext(ctx: Context, config: workspace } function stubAgent(cwd?: string, seed: SessionEvent[] = []): Agent { - const id = SessionId('s1') - const session = Session.create(id, seed, cwd === undefined ? undefined : { version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd }) - return { - ctx: new Context(), + const id = SessionId(`agent-instructions-${String(nextStubSession++)}`) + const agentCtx = isolatedInboxCtx + const session = agentCtx.sessions.create(id, { + seed, + ...cwd === undefined ? {} : { meta: { createdAt: 0, cwd } }, + }) + const agent: Agent = { + ctx: agentCtx, id: SessionId('a1'), options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', send: () => {}, followup: () => {}, @@ -198,6 +209,8 @@ function stubAgent(cwd?: string, seed: SessionEvent[] = []): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: agentCtx.inboxes.create(agent) }) + return agent } function stubToolExecution( @@ -2509,6 +2522,8 @@ describe('dynamic nested workspace context injection', () => { ]) await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index 833f7e4b9c..581bf0ca8c 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -36,11 +36,11 @@ async function mount(config: Config = {}) { } function sessionAgent(session: Session, id = 'agent'): Agent { - return { + const agent: Agent = { id: SessionId(id), options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'running', ctx: new Context(), send: () => {}, @@ -51,6 +51,8 @@ function sessionAgent(session: Session, id = 'agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + return agent } function openMessageTurn(session: Session, turn: number, clientTimeZone?: string): void { diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index 94b058b2d1..6f02f08e74 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -92,11 +92,11 @@ async function mount( } function sessionAgent(session: Session, id = 'agent'): Agent { - return { + const agent: Agent = { id: SessionId(id), options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'running', ctx: new Context(), send: () => {}, @@ -107,6 +107,8 @@ function sessionAgent(session: Session, id = 'agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + return agent } function openMessageTurn(session: Session, turn: number): void { diff --git a/packages/core/agent-loop/package.json b/packages/core/agent-loop/package.json index b922d98f59..0c2a66963e 100644 --- a/packages/core/agent-loop/package.json +++ b/packages/core/agent-loop/package.json @@ -53,6 +53,7 @@ "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/cordis": "workspace:^", diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 668ef65826..ca98c94dab 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -11,11 +11,12 @@ import type { AgentOptions, AgentStatus, CancelOptions, + Inbox, InboxTarget, PreStepDecision, RequestErrorAction, } from '@deepseek-ai/dsh-agent' -import { Inbox, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' +import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm' import { BlockAssembler, @@ -84,11 +85,7 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, ) { this.dispatch = agentEvents(loopCtx, this) - this.inbox = new Inbox(session, { - inserted: (message) => { this.dispatch.emit('agent/inbox/inserted', { message }) }, - discarded: (message) => { this.dispatch.emit('agent/inbox/discarded', { message }) }, - claimed: (message, turn) => { this.dispatch.emit('agent/inbox/claimed', { message, turn }) }, - }) + this.inbox = loopCtx.inboxes.create(this) const lastTurn = session.events.findLast(event => event.type === 'turn/start')?.data.turn ?? 0 this.phase = { kind: 'idle', lastTurn } this.scope = createScope(loopCtx, this) diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 371154a7c9..79bb469f25 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -294,7 +294,7 @@ function validateConfiguredAgents(agents: Config['agents']): void { /** Concrete agent factory and driver service. */ export class AgentLoop extends Service implements AgentFactory { - static inject = ['agents', 'sessions', 'llm', 'tools', 'systemPrompt'] + static inject = ['agents', 'inboxes', 'sessions', 'llm', 'tools', 'systemPrompt'] /** Runtime schema for declarative agents. */ static Config = z.object({ diff --git a/packages/core/agent-loop/tests/agent-initiator.spec.ts b/packages/core/agent-loop/tests/agent-initiator.spec.ts index 0cd3ac39e4..a5ca4cd36f 100644 --- a/packages/core/agent-loop/tests/agent-initiator.spec.ts +++ b/packages/core/agent-loop/tests/agent-initiator.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context, type Fiber } from '@deepseek-ai/cordis' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' @@ -21,6 +23,8 @@ async function harness(adapter: LlmAdapter): Promise { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) const agentsFiber = await ctx.plugin(AgentRegistry) @@ -121,6 +125,8 @@ describe('AgentLoop initiator scope', () => { const adapter = new OverlapAdapter(ctx) await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -380,6 +386,8 @@ describe('AgentLoop initiator scope', () => { const adapter = new ReloadAdapter() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/agent.spec.ts b/packages/core/agent-loop/tests/agent.spec.ts index 29073353e3..ea933ff374 100644 --- a/packages/core/agent-loop/tests/agent.spec.ts +++ b/packages/core/agent-loop/tests/agent.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -13,6 +15,8 @@ async function harness(adapter: MockAdapter): Promise { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index 28423bb430..647bf81175 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' /** * Tests for the queue-aware `Agent.cancel()` primitive. The default clears @@ -25,6 +27,8 @@ async function harness(adapter: MockAdapter) { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -514,6 +518,8 @@ describe('Agent.cancel()', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/config-session-id.spec.ts b/packages/core/agent-loop/tests/config-session-id.spec.ts index b08c076dad..5b043f6277 100644 --- a/packages/core/agent-loop/tests/config-session-id.spec.ts +++ b/packages/core/agent-loop/tests/config-session-id.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -29,6 +31,8 @@ async function makeCoreContext(): Promise { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -327,6 +331,8 @@ describe('config-driven session id', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -352,6 +358,8 @@ describe('config-driven session id', () => { const ctx1 = new Context() await ctx1.plugin(LlmRuntime) await ctx1.plugin(SessionStore) + await ctx1.plugin(SessionProjectionRegistry) + await ctx1.plugin(InboxService) await ctx1.plugin(SystemPrompt) await ctx1.plugin(ToolRuntime) await ctx1.plugin(AgentRegistry) @@ -371,6 +379,8 @@ describe('config-driven session id', () => { const ctx2 = new Context() await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) + await ctx2.plugin(SessionProjectionRegistry) + await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -395,6 +405,8 @@ describe('config-driven session id', () => { const ctx1 = new Context() await ctx1.plugin(LlmRuntime) await ctx1.plugin(SessionStore) + await ctx1.plugin(SessionProjectionRegistry) + await ctx1.plugin(InboxService) await ctx1.plugin(SystemPrompt) await ctx1.plugin(ToolRuntime) await ctx1.plugin(AgentRegistry) @@ -411,6 +423,8 @@ describe('config-driven session id', () => { const ctx2 = new Context() await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) + await ctx2.plugin(SessionProjectionRegistry) + await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -436,6 +450,8 @@ describe('config-driven session id', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index c085dc7de0..a2b93a5fc0 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, CallId, LlmError, MessageSource, ProviderRequestId, StreamChunk } from '@deepseek-ai/dsh-llm' @@ -30,6 +32,8 @@ async function harness(adapter: MockAdapter) { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -525,6 +529,8 @@ describe('turn numbering continues across seeded sessions', () => { const ctx2 = new Context() await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) + await ctx2.plugin(SessionProjectionRegistry) + await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -676,6 +682,8 @@ describe('turn and step boundary recovery', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1108,6 +1116,8 @@ describe('disposal and cancellation during pre-step assembly', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1158,6 +1168,8 @@ describe('disposal and cancellation during pre-step assembly', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1208,6 +1220,8 @@ describe('disposal and cancellation during pre-step assembly', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1254,6 +1268,8 @@ describe('disposal and cancellation during pre-step assembly', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1302,6 +1318,8 @@ describe('disposal and cancellation during pre-step assembly', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/coverage-edges.spec.ts b/packages/core/agent-loop/tests/coverage-edges.spec.ts index 21506c9a0b..85cc720fed 100644 --- a/packages/core/agent-loop/tests/coverage-edges.spec.ts +++ b/packages/core/agent-loop/tests/coverage-edges.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, CallId, LlmError, StreamChunk, errorChain } from '@deepseek-ai/dsh-llm' @@ -18,6 +20,8 @@ async function harness(adapter: MockAdapter) { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/interception.spec.ts b/packages/core/agent-loop/tests/interception.spec.ts index 72e3165f78..60a3be7d01 100644 --- a/packages/core/agent-loop/tests/interception.spec.ts +++ b/packages/core/agent-loop/tests/interception.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, CallId } from '@deepseek-ai/dsh-llm' @@ -31,6 +33,8 @@ async function harness(adapter: MockAdapter) { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index 2105b86f42..7515e88c91 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, CallId, LlmError, StreamChunk } from '@deepseek-ai/dsh-llm' @@ -17,6 +19,8 @@ async function harness(adapter: MockAdapter, persona = '') { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -132,6 +136,22 @@ describe('agent loop', () => { expect(adapter.requests).toHaveLength(1) }) + it('rejects overlapping maintenance work', async () => { + const ctx = await harness(new MockAdapter([])) + const agent = ctx.agentLoop.create(SessionId('overlapping-maintenance'), { + provider: 'mock', + model: 'mock', + }) + const finish = Promise.withResolvers() + const maintenance = agent.runMaintenance(() => finish.promise) + + expect(() => agent.runMaintenance(async () => undefined)) + .toThrow('agent "overlapping-maintenance" already has active work') + + finish.resolve(undefined) + await maintenance + }) + it('suppresses the replay when a latched maintenance wake is removed', async () => { const adapter = new MockAdapter([]) const ctx = await harness(adapter) @@ -1433,6 +1453,8 @@ describe('agent loop', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1457,6 +1479,8 @@ describe('agent loop', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/properties.spec.ts b/packages/core/agent-loop/tests/properties.spec.ts index 2757a633be..90e733c19a 100644 --- a/packages/core/agent-loop/tests/properties.spec.ts +++ b/packages/core/agent-loop/tests/properties.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** * Property-based tests for the agent loop's inbox/turn scheduling (the * property-testing Agent Note). Deterministic by construction: schedules are driven @@ -39,6 +41,8 @@ async function harness() { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/request-cache.e2e.ts b/packages/core/agent-loop/tests/request-cache.e2e.ts index d47fbccbb1..a14c5f4bae 100644 --- a/packages/core/agent-loop/tests/request-cache.e2e.ts +++ b/packages/core/agent-loop/tests/request-cache.e2e.ts @@ -6,9 +6,11 @@ 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 } from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** * With-key proof that log-derived requests translate into real provider cache hits: a @@ -41,6 +43,8 @@ async function loopHarness(): Promise { const created = new Context() await created.plugin(LlmRuntime) await created.plugin(SessionStore) + await created.plugin(SessionProjectionRegistry) + await created.plugin(InboxService) await created.plugin(SystemPrompt, { persona: SYSTEM }) await created.plugin(ToolRuntime) await created.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/request-error.spec.ts b/packages/core/agent-loop/tests/request-error.spec.ts index 9d1c2a42c3..776280765b 100644 --- a/packages/core/agent-loop/tests/request-error.spec.ts +++ b/packages/core/agent-loop/tests/request-error.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' @@ -13,6 +15,8 @@ async function harness(adapter: MockAdapter): Promise { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/request-reconstruction.spec.ts b/packages/core/agent-loop/tests/request-reconstruction.spec.ts index 287e73303c..1b178a127f 100644 --- a/packages/core/agent-loop/tests/request-reconstruction.spec.ts +++ b/packages/core/agent-loop/tests/request-reconstruction.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** * Loop-level reconstructability: every request the loop sends is a pure function of the * session log — messages derive at the step/start boundary and the header is the latest @@ -28,6 +30,8 @@ async function harnessRoutes( const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -255,6 +259,8 @@ describe('request stability across the loop', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: 'stable base' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -373,6 +379,8 @@ describe('request stability across the loop', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: 'stable base' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/resume.spec.ts b/packages/core/agent-loop/tests/resume.spec.ts index 1c140e1b2e..d1278f77cf 100644 --- a/packages/core/agent-loop/tests/resume.spec.ts +++ b/packages/core/agent-loop/tests/resume.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -28,6 +30,8 @@ async function mountPersistentHarness(root: string, adapter: MockAdapter): Promi const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -244,6 +248,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', const ctx2 = new Context() await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) + await ctx2.plugin(SessionProjectionRegistry) + await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -272,6 +278,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', const ctx2 = new Context() await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) + await ctx2.plugin(SessionProjectionRegistry) + await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -522,6 +530,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -585,6 +595,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', const ctx2 = new Context() await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) + await ctx2.plugin(SessionProjectionRegistry) + await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -617,6 +629,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', const ctx2 = new Context() await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) + await ctx2.plugin(SessionProjectionRegistry) + await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -653,6 +667,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', const ctx2 = new Context() await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) + await ctx2.plugin(SessionProjectionRegistry) + await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -686,6 +702,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -875,6 +893,8 @@ describe('configured-start failure edges', () => { const configured = new Context() await configured.plugin(LlmRuntime) await configured.plugin(SessionStore) + await configured.plugin(SessionProjectionRegistry) + await configured.plugin(InboxService) await configured.plugin(SystemPrompt) await configured.plugin(ToolRuntime) await configured.plugin(AgentRegistry) @@ -920,6 +940,8 @@ describe('configured-start failure edges', () => { const configured = new Context() await configured.plugin(LlmRuntime) await configured.plugin(SessionStore) + await configured.plugin(SessionProjectionRegistry) + await configured.plugin(InboxService) await configured.plugin(SystemPrompt) await configured.plugin(ToolRuntime) await configured.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts index abe3730fd1..9e7e441665 100644 --- a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { describe, expect, it } from 'vitest' import { Context, symbols, type EffectMeta, type Fiber } from '@deepseek-ai/cordis' @@ -17,6 +19,8 @@ async function harnessWithLoop(adapter: MockAdapter = new MockAdapter([textRespo const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: 'You are the deployment.' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/settings.spec.ts b/packages/core/agent-loop/tests/settings.spec.ts index 4b45baab44..5f0f98d5a9 100644 --- a/packages/core/agent-loop/tests/settings.spec.ts +++ b/packages/core/agent-loop/tests/settings.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** The `agent-loop` settings section layered over the composition entry. */ import { describe, expect, it } from 'vitest' @@ -34,6 +36,8 @@ async function boot(): Promise<{ ctx: Context; settingsFiber: Fiber; loopFiber: const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/tool-calls.spec.ts b/packages/core/agent-loop/tests/tool-calls.spec.ts index 87f69cc7d0..276838654e 100644 --- a/packages/core/agent-loop/tests/tool-calls.spec.ts +++ b/packages/core/agent-loop/tests/tool-calls.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** * Exercises scheduler ordering and cancellation with deterministic gated tools. * ACP expected outputs own transcript-facing coverage. @@ -20,6 +22,8 @@ async function harness(adapter: MockAdapter, maxParallelToolCalls?: number) { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -278,6 +282,8 @@ describe('tool-call scheduler: rolling pool honors maxParallelToolCalls', () => const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -346,6 +352,8 @@ describe('tool-call scheduler: rolling pool honors maxParallelToolCalls', () => const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -704,6 +712,8 @@ describe('code-mode native-tool denial through the agent loop', () => { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime, { mode: 'code' }) // eslint-disable-next-line @typescript-eslint/no-explicit-any -- FakeCodeRuntime is an internal test helper with an opaque type shape diff --git a/packages/core/agent-loop/tests/tool-order.spec.ts b/packages/core/agent-loop/tests/tool-order.spec.ts index a9af9f56bb..da9d59d6e0 100644 --- a/packages/core/agent-loop/tests/tool-order.spec.ts +++ b/packages/core/agent-loop/tests/tool-order.spec.ts @@ -1,3 +1,5 @@ +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' /** * Loop-level tool-order determinism: the request/header event — and therefore the frozen @@ -23,6 +25,8 @@ async function harness(adapter: MockAdapter, toolOrder?: SystemPromptConfig['too const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: 'stable base', ...toolOrder !== undefined ? { toolOrder } : {} }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 7b36d3c58e..07b8e54cc2 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent/README.md -README.md: f6b698e93b254c97786155e7d2c7e81f07c0d981 -README.zh.md: 787c4f353909a1e2dbc60c33abb3c101e677e011 +README.md: 6af7e57bdb0ae710a6d1e6e58ca2ac187a45eeb8 +README.zh.md: 1533f918e037c7dc7d131c7046d25fc259d33580 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index f6b698e93b..6af7e57bdb 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -54,7 +54,7 @@ Most interception points are cooperative waterfalls. `agent/pre-step` receives a `PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages }`. The enter branch is the complete identified, frozen batch for the proposed step. A listener that wraps downstream entry preserves that batch unless it intentionally replaces it; additions follow the waterfall's natural return order. Claiming already removed the offered messages from the inbox, so rejection does not retain them. Messages inserted after the claim remain pending for a later boundary. -Inbox live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. They complement the durable `agent/inbox/spliced` projection without adding another lifecycle envelope. +`InboxService` owns the standard `inbox` session projection. The projection registry folds durable `agent/inbox/spliced` events once and remains the sole owner of the live `{ 'next-turn', 'next-step' }` state; Inbox is a command facade that reads the registry snapshot rather than replaying or copying the fold. Inbox live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. Inbox emits them as it commits the corresponding mutation, without adding another lifecycle envelope. Turn and step boundaries and the model token stream are durable `session/event` facts rather than mirrored `agent/*` notifications. Consumers read `turn/*`, `step/*`, and `assistant/chunk` from the session feed; tool policy and outcome observation belong to the complete pipeline documented by [`dsh-tools`](../tools/README.md). @@ -64,7 +64,7 @@ Turn and step boundaries and the model token stream are durable `session/event` The handle every plugin programs against: -- `agent.inbox` — the agent-owned projection of durable `agent/inbox/spliced` events. `nextTurn` and `nextStep` expose pending `UserMessage` values. `append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` mutate them; `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists. Replacement may change identity and publishes the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are durable cancellations and emit `agent/inbox/discarded`. `claim(target)` removes the next proposed batch with pure deletion splices; the loop then emits `agent/inbox/claimed`. `MessageId` is the only occurrence identity and must remain unique while pending. +- `agent.inbox` — the live face of the standard durable `inbox` projection. `nextTurn` and `nextStep` expose pending `UserMessage` values. `append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` mutate them; `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists. Replacement may change identity and publishes the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are durable cancellations and emit `agent/inbox/discarded`. `claim(target)` removes the next proposed batch with pure deletion splices and emits `agent/inbox/claimed` for each claimed message. `MessageId` is the only occurrence identity and must remain unique while pending. - `agent.followup(message)` — queue an ordinary `next-turn` message and wake the driver. It returns no completion handle; the message id identifies inbox insertion, claim, and discard facts, not a later output or `turn/end`. - `agent.steer(message)` — queue waking `next-step` input. An idle agent starts a turn synchronously; a running driver consumes later steering at its next step boundary. - `agent.inject(message)` — queue non-waking `next-step` context. A running driver claims it at the nearest later pre-step boundary; an idle driver leaves it pending until `followup()` or `steer()` wakes the driver. It may miss a request whose pre-step already claimed its batch. diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index 787c4f3539..1533f918e0 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -54,7 +54,7 @@ Agent *创建* 由实现 `AgentFactory` 的插件(`dsh-agent-loop`)提供, `PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages }`。enter 分支是拟进入步骤的完整、带标识且冻结的批次。包装下游 enter 的监听器会保留该批次,除非有意替换它;新增消息遵循 waterfall 的自然返回顺序。领取操作已经把候选消息从 inbox 删除,因此 reject 不会保留它们;领取后插入的消息仍等待后续边界。 -inbox 的实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。它们补充持久 `agent/inbox/spliced` 投影,但不引入另一层生命周期封套。 +`InboxService` 拥有标准 `inbox` 会话投影。投影注册表只折叠一次持久 `agent/inbox/spliced` 事件,并继续作为 live `{ 'next-turn', 'next-step' }` 状态的唯一所有者;Inbox 是读取注册表快照的命令 facade,不会重新回放或复制折叠结果。Inbox 的实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。Inbox 在提交对应变更时自行发出这些通知,不引入另一层生命周期封套。 轮次和步骤边界以及模型 token 流是持久 `session/event` 事实,而不是镜像的 `agent/*` 通知。消费方从会话事件流读取 `turn/*`、`step/*` 和 `assistant/chunk`;工具策略与结果观测属于 [`dsh-tools`](../tools/README.md) 记录的完整流水线。 @@ -64,7 +64,7 @@ inbox 的实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserte 每个插件面向的 handle: -- `agent.inbox`:agent 所拥有的持久 `agent/inbox/spliced` 事件投影。`nextTurn` 与 `nextStep` 暴露待处理的 `UserMessage` 值。`append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 用于变更队列;`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都是持久取消,并发出 `agent/inbox/discarded`。`claim(target)` 通过纯删除 splice 移除下一个候选批次,随后由循环发出 `agent/inbox/claimed`。`MessageId` 是唯一的入队项标识,在消息待处理期间必须保持唯一。 +- `agent.inbox`:标准持久 `inbox` 投影的 live 接口。`nextTurn` 与 `nextStep` 暴露待处理的 `UserMessage` 值。`append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 用于变更队列;`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都是持久取消,并发出 `agent/inbox/discarded`。`claim(target)` 通过纯删除 splice 移除下一个候选批次,并为每条已认领消息发出 `agent/inbox/claimed`。`MessageId` 是唯一的入队项标识,在消息待处理期间必须保持唯一。 - `agent.followup(message)`:将一条普通 `next-turn` 消息排队并唤醒驱动器。它不返回完成 handle;消息 id 标识 inbox 的插入、领取与丢弃事实,而不标识之后的输出或 `turn/end`。 - `agent.steer(message)`:将会唤醒的 `next-step` steering(中途引导)输入排队。agent 空闲时会同步启动一个轮次;驱动器运行期间收到的后续 steering 会在下一个步骤边界被消费。 - `agent.inject(message)`:将不会唤醒的 `next-step` 上下文排队。运行中的驱动器会在最近的后续 pre-step 边界领取它;idle 驱动器则会让它保持待处理,直至 `followup()` 或 `steer()` 唤醒驱动器。若某次请求的 pre-step 已经领取完批次,它可能赶不上该请求。 diff --git a/packages/core/agent/package.json b/packages/core/agent/package.json index 6144f8679a..c40b00c0f5 100644 --- a/packages/core/agent/package.json +++ b/packages/core/agent/package.json @@ -18,6 +18,14 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./inbox": { + "types": "./lib/types/inbox.d.ts", + "default": "./lib/types/inbox.js" + }, + "./inbox-projection": { + "types": "./lib/types/inbox-projection.d.ts", + "default": "./lib/types/inbox-projection.js" + }, "./invariant": { "types": "./lib/types/invariant.d.ts", "default": "./lib/invariant.js" @@ -41,15 +49,20 @@ "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-typert-protocol": "workspace:^", "@deepseek-ai/cordis": "workspace:^" }, + "dependencies": { + "zod": "^4.4.3" + }, "devDependencies": { "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-typert-protocol": "workspace:^", "@deepseek-ai/dsh-typert-registry": "workspace:^", diff --git a/packages/core/agent/src/inbox-projection.ts b/packages/core/agent/src/inbox-projection.ts new file mode 100644 index 0000000000..24602d17a7 --- /dev/null +++ b/packages/core/agent/src/inbox-projection.ts @@ -0,0 +1,20 @@ +/** Inbox projection schema and its inferred wire value. */ + +import type { UserMessage } from '@deepseek-ai/dsh-llm/types' +import { z } from 'zod' + +/** Wire validation for pending agent input reconstructed from durable inbox splices. */ +export const inboxProjectionSchema = z.object({ + 'next-turn': z.array(z.custom()).readonly(), + 'next-step': z.array(z.custom()).readonly(), +}).readonly() + +/** Complete pending Inbox value reconstructed from durable splices. */ +export type InboxState = z.infer + +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionMap { + /** Pending agent input reconstructed from durable inbox splices. */ + inbox: InboxState + } +} diff --git a/packages/core/agent/src/inbox.ts b/packages/core/agent/src/inbox.ts index c6b9204c92..8f25da7f3a 100644 --- a/packages/core/agent/src/inbox.ts +++ b/packages/core/agent/src/inbox.ts @@ -4,54 +4,82 @@ * @module @deepseek-ai/dsh-agent/inbox */ +import { Context, Service } from '@deepseek-ai/cordis' import type { MessageId } from '@deepseek-ai/dsh-llm' -import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' +import type { SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' +import { agentEvents } from './dispatch.ts' +import type { AgentEventDispatch } from './dispatch.ts' +import { inboxProjectionSchema } from './inbox-projection.ts' +import type { InboxState } from './inbox-projection.ts' +import type { Agent } from './runtime-types.ts' import type { InboxTarget } from './types.ts' -/** Mutable state privately owned by an {@link Inbox}. */ -type InboxState = Record - -/** Live notifications committed by inbox mutations. */ -export interface InboxNotifications { - /** Publish one inserted message. */ - inserted(message: UserMessage): void - /** Publish one discarded message. */ - discarded(message: UserMessage): void - /** Publish one claimed message inside its owning turn. */ - claimed(message: UserMessage, turn: number): void +declare module '@deepseek-ai/cordis' { + interface Context { + inboxes: InboxService + } } -/** A replay-once projection that incrementally consumes later inbox splices. */ -export class Inbox { - private readonly state: InboxState = { 'next-turn': [], 'next-step': [] } +/** Root Inbox service: creates live inboxes and owns their durable projection. */ +export class InboxService extends Service { + static inject = ['sessionProjections'] - constructor( - private readonly session: Session, - private readonly notifications: InboxNotifications, - ) { - for (const event of session.events.slice(session.header.seedLength ?? 0)) { - if (event.type !== 'agent/inbox/spliced') continue - try { - this.apply(event.data) - } catch (error: unknown) { - throw new Error(`invalid persisted inbox splice at session seq ${event.seq}`, { cause: error }) - } - } + constructor(ctx: Context) { + super(ctx, 'inboxes') + ctx.sessionProjections.register({ + key: 'inbox', + schema: inboxProjectionSchema, + init: () => ({ 'next-turn': [], 'next-step': [] }), + apply(state, event) { + if (event.type !== 'agent/inbox/spliced') return state + const splice = event.data + const next = state[splice.target].toSpliced( + splice.start, + splice.removedCount ?? 0, + ...splice.inserted, + ) + return splice.target === 'next-turn' + ? { 'next-turn': next, 'next-step': state['next-step'] } + : { 'next-turn': state['next-turn'], 'next-step': next } + }, + view: state => state, + stateVersion: 1, + } satisfies ProjectionDefinition<'inbox', InboxState>) + } + + /** + * Restore one live Inbox for an agent and publish its committed mutations. + * @param agent - agent that owns the durable session and live Inbox events. + * @returns the restored Inbox. + */ + create(agent: Agent): Inbox { + return new Inbox(this.ctx, agent) + } +} + +/** Agent-owned command facade over the standard durable Inbox projection. */ +export class Inbox { + private readonly dispatch: AgentEventDispatch + + constructor(private readonly ctx: Context, private readonly agent: Agent) { + this.dispatch = agentEvents(ctx, agent) } /** Prompts awaiting individual turns. */ get nextTurn(): readonly UserMessage[] { - return this.state['next-turn'] + return this.current()['next-turn'] } /** Input awaiting the next step boundary. */ get nextStep(): readonly UserMessage[] { - return this.state['next-step'] + return this.current()['next-step'] } /** Whether either pending-message list contains work. */ get hasPending(): boolean { - return this.nextTurn.length > 0 || this.nextStep.length > 0 + const state = this.current() + return state['next-turn'].length > 0 || state['next-step'].length > 0 } /** Durably cancel all pending input, clearing next-step before next-turn. */ @@ -61,50 +89,41 @@ export class Inbox { } /** - * Remove and return the complete batch proposed for one step, publishing - * each claimed message. The durable splices are pure deletions. + * Remove and return the complete batch proposed for one step. * @param target - whether this boundary also consumes one queued turn. * @param turn - turn that will own the claimed batch. * @returns next-step input followed by the queued turn, when requested. - * @internal - The agent loop's step-boundary operation, not a plugin extension point. */ claim(target: InboxTarget, turn: number): UserMessage[] { const claimed = this.mutate('next-step', 0, this.nextStep.length, [], false) - if (target === 'next-turn') { - claimed.push(...this.mutate('next-turn', 0, 1, [], false)) - } - for (const message of claimed) this.notifications.claimed(message, turn) + if (target === 'next-turn') claimed.push(...this.mutate('next-turn', 0, 1, [], false)) + for (const message of claimed) this.dispatch.emit('agent/inbox/claimed', { message, turn }) return claimed } /** - * Append one message to a pending list and durably record the insertion. + * Append one message to a pending list. * @param target - pending list to extend. * @param message - message to append. - * @throws if the message identity is already pending. */ append(target: InboxTarget, message: UserMessage): void { - this.splice(target, this.state[target].length, 0, [message]) + this.splice(target, this.current()[target].length, 0, [message]) } /** - * Prepend one message to a pending list and durably record the insertion. + * Prepend one message to a pending list. * @param target - pending list to extend. * @param message - message to prepend. - * @throws if the message identity is already pending. */ prepend(target: InboxTarget, message: UserMessage): void { this.splice(target, 0, 0, [message]) } /** - * Replace one pending message in place, possibly changing its identity. A - * successful replacement publishes the old message as discarded and the new - * message as inserted. + * Replace one pending message in place. * @param messageId - identity of the pending message to replace. * @param newMessage - replacement message. * @returns whether the message was still pending. - * @throws if the replacement duplicates another pending message identity. */ replace(messageId: MessageId, newMessage: UserMessage): boolean { const location = this.locate(messageId) @@ -114,7 +133,7 @@ export class Inbox { } /** - * Remove one pending message and durably record its cancellation. + * Remove one pending message. * @param messageId - identity of the pending message to remove. * @returns whether the message was still pending. */ @@ -127,9 +146,6 @@ export class Inbox { /** * Apply standard splice semantics and durably record the normalized result. - * The durable event commits before the live projection mutates, so synchronous - * `session/event` observers see the pre-splice lists and can reconstruct the - * removed messages from the normalized coordinates. * @param target - pending list to mutate. * @param start - splice position. * @param deleteCount - maximum number of messages to remove. @@ -147,14 +163,22 @@ export class Inbox { /** Locate one pending identity across both owned lists. */ private locate(messageId: MessageId): { target: InboxTarget; index: number } | undefined { + const state = this.current() for (const target of ['next-turn', 'next-step'] as const) { - const index = this.state[target].findIndex(message => message.id === messageId) + const index = state[target].findIndex(message => message.id === messageId) if (index >= 0) return { target, index } } return undefined } - /** Commit one normalized mutation and publish its live notifications. */ + /** Read the current durable projection value. */ + private current(): InboxState { + // InboxService registers this required projection before creating an Inbox. + // oxlint-disable-next-line typescript/no-non-null-assertion + return this.ctx.sessionProjections.snapshot(this.agent.session).values.inbox! + } + + /** Commit one normalized mutation and publish its live events. */ private mutate( target: InboxTarget, start: number, @@ -162,7 +186,8 @@ export class Inbox { inserted: UserMessage[], discardRemoved: boolean, ): UserMessage[] { - const inbox = this.state[target] + const state = this.current() + const inbox = state[target] const truncatedStart = Math.trunc(start) const offset = Number.isNaN(truncatedStart) ? 0 : truncatedStart const actualStart = offset < 0 @@ -174,47 +199,32 @@ export class Inbox { inbox.length - actualStart, ) if (actualDeleteCount === 0 && inserted.length === 0) return [] + const candidate = inbox.toSpliced(actualStart, actualDeleteCount, ...inserted) + const ids = new Set() + for (const message of target === 'next-turn' + ? [...candidate, ...state['next-step']] + : [...state['next-turn'], ...candidate]) { + if (ids.has(message.id)) throw new Error(`message "${message.id}" is already pending`) + ids.add(message.id) + } const outcome = discardRemoved && actualDeleteCount > 0 ? 'canceled' as const : undefined - const splice = { + const splice: SessionEventMap['agent/inbox/spliced'] = { target, start: actualStart, ...(actualDeleteCount === 0 ? {} : { removedCount: actualDeleteCount }), inserted, ...(outcome === undefined ? {} : { outcome }), } - this.validate(splice) - const event = this.session.append('agent/inbox/spliced', splice) - const removed = inbox.splice(actualStart, actualDeleteCount, ...event.data.inserted) + const removed = inbox.slice(actualStart, actualStart + actualDeleteCount) + const event = this.agent.session.append('agent/inbox/spliced', splice) if (discardRemoved) { - for (const message of removed) this.notifications.discarded(message) + for (const message of removed) this.dispatch.emit('agent/inbox/discarded', { message }) + } + for (const message of event.data.inserted) { + this.dispatch.emit('agent/inbox/inserted', { message }) } - for (const message of event.data.inserted) this.notifications.inserted(message) return removed } - - /** Apply one normalized durable splice to the projection. */ - private apply(splice: SessionEventMap['agent/inbox/spliced']): UserMessage[] { - this.validate(splice) - const inbox = this.state[splice.target] - return inbox.splice(splice.start, splice.removedCount ?? 0, ...splice.inserted) - } - - /** Validate one normalized splice against the current projection. */ - private validate(splice: SessionEventMap['agent/inbox/spliced']): void { - const inbox = this.state[splice.target] - const removedCount = splice.removedCount ?? 0 - if (!Number.isSafeInteger(splice.start) || splice.start < 0 || splice.start > inbox.length - || !Number.isSafeInteger(removedCount) || removedCount < 0 - || splice.start + removedCount > inbox.length) { - throw new Error('invalid inbox splice') - } - const candidate = inbox.toSpliced(splice.start, removedCount, ...splice.inserted) - const ids = new Set() - for (const message of splice.target === 'next-turn' - ? [...candidate, ...this.nextStep] - : [...this.nextTurn, ...candidate]) { - if (ids.has(message.id)) throw new Error(`message "${message.id}" is already pending`) - ids.add(message.id) - } - } } + +export default InboxService diff --git a/packages/core/agent/src/types.ts b/packages/core/agent/src/types.ts index b54e56ea8f..2430ee21ce 100644 --- a/packages/core/agent/src/types.ts +++ b/packages/core/agent/src/types.ts @@ -13,8 +13,8 @@ declare module '@deepseek-ai/dsh-session/types' { interface SessionEventMap { /** * One normalized mutation of an agent's durable pending-message lists. - * Live dispatch precedes projection mutation, so synchronous observers may - * read the pre-splice inbox to recover the removed messages. + * The session-projection registry applies the committed event before + * `Session.append()` returns; Inbox live notifications follow that commit. */ 'agent/inbox/spliced': { target: InboxTarget diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index 4876e38809..af25e7e870 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -1,11 +1,13 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { Context, Service, symbols } from '@deepseek-ai/cordis' import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm' -import { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session' +import SessionStore, { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session' import AgentRegistry, { agentEvents, - Inbox, + InboxService, } from '@deepseek-ai/dsh-agent' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import type {} from '@deepseek-ai/dsh-agent/inbox-projection' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import type { @@ -19,14 +21,17 @@ import type { function stubAgent(rawId: string, overrides: Partial = {}): Agent { const id = SessionId(rawId) - const session = Session.create(id) + const session = overrides.session ?? Session.create(id) + const ctx = overrides.ctx ?? new Context() const agent: Agent = { id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: { + nextTurn: [], nextStep: [], hasPending: false, + } as never, status: 'idle', - ctx: new Context(), + ctx, send: () => {}, followup: () => {}, steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }), @@ -34,32 +39,52 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { cancel() {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), + ...overrides, } - return Object.assign(agent, overrides) + return agent +} + +async function inboxAgent(rawId: string): Promise<{ ctx: Context; session: Session; agent: Agent }> { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) + const session = ctx.sessions.create(SessionId(rawId)) + const agent = stubAgent(rawId, { ctx, session }) + Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) + return { ctx, session, agent } } describe('Inbox', () => { - it('rejects an invalid durable splice during reconstruction', () => { - const session = Session.create(SessionId('invalid-inbox-replay')) - session.append('agent/inbox/spliced', { - target: 'next-turn', - start: 1, - inserted: [], + it('projects inherited Inbox events in a forked session', async () => { + const { ctx, session: parent, agent: parentAgent } = await inboxAgent('inbox-fork-parent') + const inherited = createUserMessage({ + content: [{ type: 'text', text: 'parent pending' }], + source: { kind: 'user' }, }) + parentAgent.inbox.append('next-turn', inherited) + const child = ctx.sessions.fork(parent, undefined, SessionId('inbox-fork-child')) + const childAgent = stubAgent('inbox-fork-child', { ctx, session: child }) + Object.assign(childAgent, { inbox: ctx.inboxes.create(childAgent) }) - expect(() => new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })) - .toThrow('invalid persisted inbox splice at session seq 0') + expect(child.header.seedLength).toBe(parent.events.length) + expect(childAgent.inbox.nextTurn).toEqual([inherited]) + expect(childAgent.inbox.nextStep).toEqual([]) + const own = createUserMessage({ + content: [{ type: 'text', text: 'child pending' }], + source: { kind: 'user' }, + }) + childAgent.inbox.append('next-turn', own) + expect(childAgent.inbox.nextTurn).toEqual([inherited, own]) }) - it('replaces a pending message by identity across both lists', () => { - const session = Session.create(SessionId('replace-inbox')) + it('replaces a pending message by identity across both lists', async () => { + const { ctx, agent } = await inboxAgent('replace-inbox') const inserted: UserMessage[] = [] const discarded: UserMessage[] = [] - const inbox = new Inbox(session, { - claimed: () => {}, - inserted: message => void inserted.push(message), - discarded: message => void discarded.push(message), - }) + ctx.on('agent/inbox/inserted', ({ message }) => void inserted.push(message)) + ctx.on('agent/inbox/discarded', ({ message }) => void discarded.push(message)) + const { inbox } = agent const original = createUserMessage({ content: [{ type: 'text', text: 'original' }], source: { kind: 'user' }, @@ -93,9 +118,9 @@ describe('Inbox', () => { .toThrow(`message "${replacement.id}" is already pending`) }) - it('normalizes splice coordinates, rejects duplicate identities, and reports missing removals', () => { - const session = Session.create(SessionId('splice-inbox')) - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) + it('normalizes splice coordinates, rejects duplicate identities, and reports missing removals', async () => { + const { agent } = await inboxAgent('splice-inbox') + const { inbox } = agent const first = createUserMessage({ content: [{ type: 'text', text: 'first' }], source: { kind: 'user' }, @@ -104,22 +129,25 @@ describe('Inbox', () => { content: [{ type: 'text', text: 'second' }], source: { kind: 'user' }, }) + const prefixed = createUserMessage({ + content: [{ type: 'text', text: 'prefixed' }], + source: { kind: 'user' }, + }) inbox.splice('next-turn', Number.NaN, Number.NaN, [first, second]) expect(inbox.nextTurn).toEqual([first, second]) expect(inbox.splice('next-turn', -1, 1, [])).toEqual([second]) + inbox.prepend('next-turn', prefixed) + expect(inbox.nextTurn).toEqual([prefixed, first]) expect(inbox.remove(second.id)).toBe(false) expect(() => { inbox.append('next-step', first) }).toThrow(`message "${first.id}" is already pending`) }) - it('clears both pending lists as durable cancellations', () => { - const session = Session.create(SessionId('clear-inbox')) + it('clears both pending lists as durable cancellations', async () => { + const { ctx, session, agent } = await inboxAgent('clear-inbox') const discarded: UserMessage[] = [] - const inbox = new Inbox(session, { - claimed: () => {}, - inserted: () => {}, - discarded: message => void discarded.push(message), - }) + ctx.on('agent/inbox/discarded', ({ message }) => void discarded.push(message)) + const { inbox } = agent const nextTurn = createUserMessage({ content: [{ type: 'text', text: 'turn' }], source: { kind: 'user' } }) const nextStep = createUserMessage({ content: [{ type: 'text', text: 'step' }], source: { kind: 'user' } }) inbox.append('next-turn', nextTurn) @@ -140,6 +168,52 @@ describe('Inbox', () => { inbox.clear() expect(session.events).toHaveLength(beforeClear + 2) }) + + it('registers the durable Inbox projection from the Inbox service', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + const inboxFiber = ctx.plugin(InboxService) + await inboxFiber + const session = ctx.sessions.create(SessionId('inbox-projection')) + const agent = stubAgent('inbox-projection', { ctx, session }) + Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) + const pending = createUserMessage({ + content: [{ type: 'text', text: 'pending' }], + source: { kind: 'user' }, + }) + + agent.inbox.append('next-turn', pending) + + expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ + 'next-turn': [pending], + 'next-step': [], + }) + await inboxFiber.dispose() + expect(ctx.sessionProjections.snapshot(session).values).toEqual({}) + }) + + it('uses the projection cell as the sole live state after direct durable appends', async () => { + const { ctx, session, agent } = await inboxAgent('inbox-live-projection') + const pending = createUserMessage({ + content: [{ type: 'text', text: 'direct' }], + source: { kind: 'user' }, + }) + let observed: readonly UserMessage[] | undefined + ctx.on('session/event', (_session, event) => { + if (event.type === 'agent/inbox/spliced') observed = agent.inbox.nextTurn + }) + + session.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, inserted: [pending], + }) + + expect(observed).toEqual([pending]) + expect(agent.inbox.nextTurn).toEqual([pending]) + expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ + 'next-turn': [pending], 'next-step': [], + }) + }) }) describe('AgentRegistry', () => { diff --git a/packages/core/agent/tsconfig.json b/packages/core/agent/tsconfig.json index dfa66f16ff..068c1e6b8f 100644 --- a/packages/core/agent/tsconfig.json +++ b/packages/core/agent/tsconfig.json @@ -23,6 +23,9 @@ { "path": "../../core/session" }, + { + "path": "../../session/session-projection" + }, { "path": "../../core/system-prompt" }, diff --git a/packages/e2b/e2b/tests/composition.e2e.ts b/packages/e2b/e2b/tests/composition.e2e.ts index 952da5320d..9793105dbc 100644 --- a/packages/e2b/e2b/tests/composition.e2e.ts +++ b/packages/e2b/e2b/tests/composition.e2e.ts @@ -85,7 +85,7 @@ describe.skipIf(!process.env.E2B_API_KEY)('E2B live Loader composition', () => { id: ownerId, options: {}, session: ownerSession, - inbox: new Inbox(ownerSession, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx, send() {}, @@ -96,6 +96,7 @@ describe.skipIf(!process.env.E2B_API_KEY)('E2B live Loader composition', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(owner, { inbox: new Inbox(owner.ctx, owner) }) const backend = new BashTerminalBackend(ctx, { backendType: 'shell', shellPath: '/bin/bash', shellArgs: ['--noprofile', '--norc', '-i'], rows: 24, cols: 80, diff --git a/packages/examples/agent-spine-demo/package.json b/packages/examples/agent-spine-demo/package.json index 9f872e6dd6..4099235e25 100644 --- a/packages/examples/agent-spine-demo/package.json +++ b/packages/examples/agent-spine-demo/package.json @@ -43,6 +43,7 @@ "@deepseek-ai/dsh-llm-retry": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-skill": "workspace:^", "@deepseek-ai/dsh-skill-filesystem": "workspace:^", @@ -78,6 +79,7 @@ "@deepseek-ai/dsh-sandbox-policy": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-skill": "workspace:^", "@deepseek-ai/dsh-skill-filesystem": "workspace:^", diff --git a/packages/examples/agent-spine-demo/src/index.ts b/packages/examples/agent-spine-demo/src/index.ts index 87098c38da..4cf542540b 100644 --- a/packages/examples/agent-spine-demo/src/index.ts +++ b/packages/examples/agent-spine-demo/src/index.ts @@ -13,12 +13,14 @@ import Timer from '@deepseek-ai/cordis-plugin-timer' import z from '@deepseek-ai/schemastery' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SessionTitleService, { type Config as SessionTitleConfig } from '@deepseek-ai/dsh-session-title' import SystemPrompt, { type Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools' import SkillRegistry, { type Config as SkillRegistryConfig } from '@deepseek-ai/dsh-skill' import * as SkillFileSystem from '@deepseek-ai/dsh-skill-filesystem' import AgentRegistry from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import GoalService, { type Config as GoalDomainConfig } from '@deepseek-ai/dsh-goal' import * as goalSession from '@deepseek-ai/dsh-goal-round-driver' import * as toolGoal from '@deepseek-ai/dsh-tool-goal' @@ -220,6 +222,7 @@ export function apply(ctx: Context, config: Config): void { ctx.plugin(Timer) ctx.plugin(LlmRuntime) ctx.plugin(SessionStore) + ctx.plugin(SessionProjectionRegistry) ctx.plugin(SessionTitleService, config.sessionTitle ?? EXAMPLE_SESSION_TITLE_CONFIG) // Owner schemas resolve defaults; forward toolOrder only when explicitly set. ctx.plugin(SystemPrompt, { @@ -235,6 +238,7 @@ export function apply(ctx: Context, config: Config): void { ctx.plugin(SkillFileSystem, Object.assign({}, config.skills?.filesystem, { dshHome })) } ctx.plugin(AgentRegistry) + ctx.plugin(InboxService) ctx.plugin(llmRetry) if (config.goals !== undefined && config.goals !== false) { ctx.plugin(GoalService, config.goals.domain ?? {}) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index f6f998a383..19d6299f74 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -715,6 +715,19 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'inboxes', + summary: 'Root Inbox service: creates live inboxes and owns their durable projection.', + description: 'Root Inbox service: creates live inboxes and owns their durable projection.', + methods: [ + { + signature: 'create(agent: Agent): Inbox', + description: 'Restore one live Inbox for an agent and publish its committed mutations.', + parameters: [{ name: 'agent', description: 'agent that owns the durable session and live Inbox events.' }], + returns: 'the restored Inbox.', + }, + ], + }, { key: 'invariants', summary: 'Package-owned invariant registry with global and regex-based selection.', @@ -1110,7 +1123,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { key: 'sessionProjections', summary: '`ctx.sessionProjections`: the projection unit table and its drive.', - description: '`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit\'s `apply` (eager drive), and a changed state reference notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin\'s key disappears from snapshots and clients read it as capability absence. Domain plugins register under `ctx.inject([\'sessionProjections\'], …)` so headless assemblies without the registry stay unaffected. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads.', + description: '`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit\'s `apply` (eager drive), and a changed state reference notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the full in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin\'s key disappears from snapshots and clients read it as capability absence. A domain that requires this capability declares a Cordis service dependency; an optional contributor may register under `ctx.inject([\'sessionProjections\'], …)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads.', methods: [ { signature: 'register(definition: ProjectionDefinition): () => void', @@ -3241,11 +3254,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Inbox', - declaration: 'export class Inbox {\n constructor(private readonly session: Session, private readonly notifications: InboxNotifications);\n get nextTurn(): readonly UserMessage[];\n get nextStep(): readonly UserMessage[];\n get hasPending(): boolean;\n clear(): void;\n claim(target: InboxTarget, turn: number): UserMessage[];\n append(target: InboxTarget, message: UserMessage): void;\n prepend(target: InboxTarget, message: UserMessage): void;\n replace(messageId: MessageId, newMessage: UserMessage): boolean;\n remove(messageId: MessageId): boolean;\n splice(target: InboxTarget, start: number, deleteCount: number, inserted: UserMessage[]): UserMessage[];\n}', - }, - { - name: 'InboxNotifications', - declaration: 'export interface InboxNotifications {\n inserted(message: UserMessage): void;\n discarded(message: UserMessage): void;\n claimed(message: UserMessage, turn: number): void;\n}', + declaration: 'export class Inbox {\n constructor(private readonly ctx: Context, private readonly agent: Agent);\n get nextTurn(): readonly UserMessage[];\n get nextStep(): readonly UserMessage[];\n get hasPending(): boolean;\n clear(): void;\n claim(target: InboxTarget, turn: number): UserMessage[];\n append(target: InboxTarget, message: UserMessage): void;\n prepend(target: InboxTarget, message: UserMessage): void;\n replace(messageId: MessageId, newMessage: UserMessage): boolean;\n remove(messageId: MessageId): boolean;\n splice(target: InboxTarget, start: number, deleteCount: number, inserted: UserMessage[]): UserMessage[];\n}', }, { name: 'InboxTarget', diff --git a/packages/feedback/command-feedback/tests/command-feedback.spec.ts b/packages/feedback/command-feedback/tests/command-feedback.spec.ts index 3c567df332..4f58bfbdc7 100644 --- a/packages/feedback/command-feedback/tests/command-feedback.spec.ts +++ b/packages/feedback/command-feedback/tests/command-feedback.spec.ts @@ -43,13 +43,12 @@ class FakeTelemetry extends SessionTelemetryBackend { /** Build a live idle agent over a store-owned session, as an app's spine does. */ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } { const session = ctx.sessions.create(SessionId(id)) - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) let status: AgentStatus = 'idle' const agent: Agent = { id: session.id, options: {}, session, - inbox, + inbox: undefined as never, ctx: new Context(), get status() { return status }, send: () => {}, @@ -60,6 +59,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) return { agent, session } } diff --git a/packages/feedback/command-feedback/tests/loader-composition.spec.ts b/packages/feedback/command-feedback/tests/loader-composition.spec.ts index d133d86830..4f01449b15 100644 --- a/packages/feedback/command-feedback/tests/loader-composition.spec.ts +++ b/packages/feedback/command-feedback/tests/loader-composition.spec.ts @@ -29,13 +29,12 @@ function agent(ctx: Context): Agent { const scope = ctx.plugin(() => {}) const id = SessionId('feedback-loader-agent') const session = ctx.sessions.create(id) - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) let status: AgentStatus = 'idle' const value: Agent = { id, options: {}, session, - inbox, + inbox: undefined as never, ctx: scope.ctx, get status() { return status }, send: () => {}, @@ -46,6 +45,7 @@ function agent(ctx: Context): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(value, { inbox: new Inbox(value.ctx, value) }) ctx.agents.register(value) return value } 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 e363666606..69d931673a 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -33,7 +33,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -44,6 +44,7 @@ function agent(ctx: Context, cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(value, { inbox: new Inbox(value.ctx, value) }) ctx.agents.register(value) return value } diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 2127844646..d03054b717 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -20,23 +20,23 @@ interface Harness { function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } { // Store-created: the command executor durably logs lifecycle events on it. const session = ctx.sessions.create(SessionId(id)) - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) let status: AgentStatus = 'idle' const agent: Agent = { id: session.id, options: {}, session, - inbox, + inbox: undefined as never, ctx: new Context(), get status() { return status }, send: () => {}, followup: () => {}, steer: () => {}, - inject(input) { inbox.append('next-step', input) }, + inject(input) { this.inbox.append('next-step', input) }, cancel() { status = 'idle' }, runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) return { agent, session } } diff --git a/packages/goal/goal/tests/goal.spec.ts b/packages/goal/goal/tests/goal.spec.ts index e94e0754a0..8d664dbe9c 100644 --- a/packages/goal/goal/tests/goal.spec.ts +++ b/packages/goal/goal/tests/goal.spec.ts @@ -1,9 +1,11 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import type { Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage, HarnessError } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import GoalService, { GoalError, GoalId, @@ -17,6 +19,12 @@ interface StubAgent { session: Session } +const isolatedInboxCtx = new Context() +await isolatedInboxCtx.plugin(SessionStore) +await isolatedInboxCtx.plugin(SessionProjectionRegistry) +await isolatedInboxCtx.plugin(InboxService) +const sessionStubs = new WeakMap() + /** Number the next balanced test-fixture turn. */ function nextTurn(session: Session): number { return session.events.reduce((max, event) => event.type === 'turn/start' ? Math.max(max, event.data.turn) : max, 0) + 1 @@ -24,41 +32,59 @@ function nextTurn(session: Session): number { /** Mirror the public Agent.inject contract for domain tests. */ function appendInjection(session: Session, input: UserMessage): void { - new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }).append('next-step', input) + stubAgentForSession(session).agent.inbox.append('next-step', input) } /** Build a registry-compatible agent around one concrete session. */ -function stubAgentForSession(session: Session): StubAgent { +function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent { + const existing = sessionStubs.get(session) + if (existing !== undefined) return existing const id = session.id - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) + const agentCtx = suppliedCtx ?? isolatedInboxCtx + if (suppliedCtx === undefined) { + agentCtx.sessions.enter(session) + } const agent: Agent = { id, options: {}, session, - inbox, - ctx: new Context(), + inbox: undefined as never, + ctx: agentCtx, status: 'idle', send: () => {}, followup: () => {}, steer: () => {}, - inject(input) { inbox.append('next-step', input) }, + inject(input) { this.inbox.append('next-step', input) }, cancel() {}, runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - return { + Object.assign(agent, { inbox: agentCtx.inboxes.create(agent) }) + const stub = { agent, session, } + sessionStubs.set(session, stub) + return stub } /** Build a registry-compatible agent around a fresh session. */ -function stubAgent(rawId: string, seed?: readonly import('@deepseek-ai/dsh-session').SessionEvent[]): StubAgent { - return stubAgentForSession(Session.create(SessionId(rawId), seed)) +function stubAgent( + rawId: string, + seed?: readonly import('@deepseek-ai/dsh-session').SessionEvent[], + ctx?: Context, +): StubAgent { + const session = ctx === undefined + ? Session.create(SessionId(rawId), seed) + : ctx.sessions.create(SessionId(rawId), { ...(seed === undefined ? {} : { seed }) }) + return stubAgentForSession(session, ctx) } async function harness(config: { defaultMaxGoalRounds?: number } = {}) { const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService, config) const stub = stubAgent(`goal-test-${Math.random()}`) @@ -168,14 +194,16 @@ describe('GoalService creation and replay', () => { it('inherits the completed-turn goal prefix through SessionStore.fork with child activation disarmed', async () => { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService) - const parent = stubAgentForSession(ctx.sessions.create(SessionId('goal-fork-parent'))) + const parent = stubAgentForSession(ctx.sessions.create(SessionId('goal-fork-parent')), ctx) ctx.agents.register(parent.agent) const goal = ctx.goals.create(parent.agent, { objective: 'inherit through fork', maxGoalRounds: 5 }) appendRound(parent.session, goal, 1) - const child = stubAgentForSession(ctx.sessions.fork(parent.session)) + const child = stubAgentForSession(ctx.sessions.fork(parent.session), ctx) ctx.agents.register(child.agent) expect(ctx.goals.get(child.agent)).toMatchObject({ id: goal.id, @@ -235,7 +263,7 @@ describe('GoalService creation and replay', () => { const { ctx, agent } = await harness() // A same-id agent backed by a different session object — the live-instance // check must reject it even though the ids match. - const impostor = stubAgentForSession(Session.create(agent.id)).agent + const impostor = { ...agent, session: Session.create(agent.id) } as Agent expect(() => ctx.goals.get(impostor)).toThrow(expect.objectContaining({ code: 'GOAL_AGENT_NOT_LIVE' })) expect(() => ctx.goals.create(impostor, { objective: 'no' })).toThrow(expect.objectContaining({ code: 'GOAL_AGENT_NOT_LIVE', @@ -422,9 +450,11 @@ describe('GoalService mutations', () => { it('publishes a mutation consistently to a reentrant session observer', async () => { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService) - const stub = stubAgentForSession(ctx.sessions.create(SessionId('goal-reentrant-observer'))) + const stub = stubAgentForSession(ctx.sessions.create(SessionId('goal-reentrant-observer')), ctx) ctx.agents.register(stub.agent) let observed: ReturnType ctx.on('session/event', (session, event) => { @@ -481,7 +511,7 @@ describe('GoalService mutations', () => { }) }) - it('reports the same corrupt unseen event after committing its valid prefix', async () => { + it('rejects a corrupt append while preserving the valid prefix', async () => { const { ctx, agent, session } = await harness() expect(ctx.goals.get(agent)).toBeUndefined() const change: GoalSnapshotChangeMeta = { @@ -500,10 +530,11 @@ describe('GoalService mutations', () => { updatedAt: 12, } session.append('goal/change', change) - session.append('goal/change', { ...change, operation: 'edit', extra: true } as never) + expect(() => { + session.append('goal/change', { ...change, operation: 'edit', extra: true } as never) + }).toThrow('snapshot change must have exactly') - expect(() => ctx.goals.get(agent)).toThrow('snapshot change must have exactly') - expect(() => ctx.goals.get(agent)).toThrow('snapshot change must have exactly') + expect(ctx.goals.get(agent)).toMatchObject({ id: change.goal.id, objective: 'valid prefix' }) }) }) @@ -570,7 +601,7 @@ describe('goal replay validation', () => { content: [{ type: 'text', text: 'unrelated pending context' }], source: { kind: 'plugin', plugin: 'test' }, }) - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) + const inbox = stubAgentForSession(session).agent.inbox inbox.append('next-step', message) expect(inbox.remove(message.id)).toBe(true) expect(foldGoal(session.events)).toMatchObject({ goal: { id: change.goal.id, revision: 1 } }) diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index 6282a6f739..0286e93103 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -10,7 +10,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { UserMessage } from '@deepseek-ai/dsh-session' @@ -31,19 +31,18 @@ interface Bench { /** Register a minimal registry-compatible live agent over a store session. */ function liveAgent(ctx: Context, session: Session): Agent { const status: AgentStatus = 'idle' - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) const agent: Agent = { id: session.id, options: {}, session, - inbox, + inbox: { nextTurn: [], nextStep: [], hasPending: false } as never, ctx, get status() { return status }, send: () => {}, followup: () => {}, steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }), inject(input: UserMessage) { - inbox.append('next-step', input) + this.inbox.append('next-step', input) }, cancel() {}, runMaintenance: task => task(new AbortController().signal), @@ -130,10 +129,14 @@ describe('goal projection unit', () => { const created = bench.ctx.goals.create(bench.agent, { objective: 'stay cleared' }) bench.ctx.goals.clear(bench.agent, created) - bench.agent.inbox.prepend('next-step', createUserMessage({ - content: [{ type: 'text', text: 'unrelated pending context' }], - source: { kind: 'plugin', plugin: 'test' }, - })) + bench.session.append('agent/inbox/spliced', { + target: 'next-step', + start: 0, + inserted: [createUserMessage({ + content: [{ type: 'text', text: 'unrelated pending context' }], + source: { kind: 'plugin', plugin: 'test' }, + })], + }) expect(bench.tailValues().goal).toBeNull() expect(foldGoal(bench.session.events).goal).toBeUndefined() diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index cb5a2a9874..7e25c3f5b7 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -1,13 +1,15 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import GoalService, { GoalId } from '@deepseek-ai/dsh-goal' import type { GoalRef } from '@deepseek-ai/dsh-goal' import { createUserMessage, CallId } from '@deepseek-ai/dsh-llm' import type { MessageSource } from '@deepseek-ai/dsh-llm' -import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' +import SessionStore, { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' @@ -21,17 +23,28 @@ interface StubAgent { setStatus(status: AgentStatus): void } +const isolatedInboxCtx = new Context() +await isolatedInboxCtx.plugin(SessionStore) +await isolatedInboxCtx.plugin(SessionProjectionRegistry) +await isolatedInboxCtx.plugin(InboxService) + /** Build one registry-compatible live agent whose injections enter the durable inbox. */ -function stubAgent(rawId: string, supplied?: Session): StubAgent { - const session = supplied ?? Session.create(SessionId(rawId)) +function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): StubAgent { + const agentCtx = suppliedCtx ?? isolatedInboxCtx + const session = supplied ?? (suppliedCtx === undefined + ? agentCtx.sessions.create(SessionId(rawId)) + : suppliedCtx.sessions.create(SessionId(rawId))) + if (suppliedCtx === undefined) { + if (agentCtx.sessions.get(session.id) !== session) agentCtx.sessions.enter(session) + } let status: AgentStatus = 'running' const agent: Agent = { id: session.id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, get status() { return status }, - ctx: new Context(), + ctx: agentCtx, send: () => {}, followup: () => {}, steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }), @@ -42,6 +55,7 @@ function stubAgent(rawId: string, supplied?: Session): StubAgent { runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } + Object.assign(agent, { inbox: agentCtx.inboxes.create(agent) }) return { agent, session, setStatus(value) { status = value } } } @@ -71,12 +85,15 @@ function closeTurn(stub: StubAgent, turn: number): void { async function harness(config: toolGoal.Config = {}) { const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(AgentRegistry) await ctx.plugin(ToolRuntime) await ctx.plugin(GoalService) const fiber = await ctx.plugin(toolGoal, config) - const root = stubAgent(`goal-tool-root-${Math.random()}`) + const root = stubAgent(`goal-tool-root-${Math.random()}`, undefined, ctx) ctx.agents.register(root.agent) return { ctx, fiber, root } } @@ -243,7 +260,7 @@ describe('goal tool execution authority', () => { openTurn(root, { kind: 'user' }) // A distinct agent object over root's exact session: same id, not the live // registered instance, so the executor must reject it. - const stale = stubAgent('goal-tool-stale', root.agent.session).agent + const stale = stubAgent('goal-tool-stale', root.agent.session, ctx).agent const staleResult = await execute(ctx, 'get_goal', {}, stale, stale) expect(staleResult.error?.info?.code).toBe('GOAL_TOOL_DRIVER_REQUIRED') diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index ab8f6aa127..11d633fa28 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -16,7 +16,7 @@ import { contentHasImage, createUserMessage, freezeMessage, ReasoningEffortId } import { errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' import { isAppendSurfaceEvent, isJsonValue } from '@deepseek-ai/dsh-session' -import type { JsonValue, Session, SessionEvent, SessionEventMap, SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session' +import type { JsonValue, Session, SessionEvent, SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session' import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import { SessionQueryError, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' import { SubagentError } from '@deepseek-ai/dsh-subagent' @@ -1267,16 +1267,10 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro }) }) - /** Project both durable inbox lists, optionally including the splice currently being emitted. */ - const queueItems = ( - agent: Agent, - splice?: SessionEventMap['agent/inbox/spliced'], - ): QueuedInboxItem[] => { + /** Project both durable inbox lists from their committed state. */ + const queueItems = (agent: Agent): QueuedInboxItem[] => { const project = (target: 'next-turn' | 'next-step'): readonly UserMessage[] => { - const messages = target === 'next-turn' ? agent.inbox.nextTurn : agent.inbox.nextStep - return splice?.target === target - ? messages.toSpliced(splice.start, splice.removedCount ?? 0, ...splice.inserted) - : messages + return target === 'next-turn' ? agent.inbox.nextTurn : agent.inbox.nextStep } return [ ...project('next-turn').map(message => ({ id: message.id, placement: 'queued' as const, message })), @@ -1295,7 +1289,7 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro if (event.type !== 'agent/inbox/spliced') return const agent = ctx.agents.get(session.id) if (agent?.session !== session) return - broadcast({ type: 'session/queue', sessionId: session.id, items: queueItems(agent, event.data) }) + broadcast({ type: 'session/queue', sessionId: session.id, items: queueItems(agent) }) }) /** Remove a wait before settling it: synchronous deletion makes the first claimant win. */ diff --git a/packages/host/apiproxy/tests/api-proxy-jobs.spec.ts b/packages/host/apiproxy/tests/api-proxy-jobs.spec.ts index d61e618a96..7e61b1eff7 100644 --- a/packages/host/apiproxy/tests/api-proxy-jobs.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-jobs.spec.ts @@ -9,7 +9,7 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' @@ -56,11 +56,19 @@ async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: const session = ctx.sessions.create() const agent = { id: session.id, + options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: { nextTurn: [], nextStep: [], hasPending: false } as never, status: 'idle', ctx, - } as Agent + send() {}, + followup() {}, + steer() {}, + inject() {}, + cancel() {}, + runMaintenance: task => task(new AbortController().signal), + whenIdle: () => Promise.resolve(), + } satisfies Agent ctx.agents.register(agent) return { ctx, session, agent } } diff --git a/packages/host/apiproxy/tests/api-proxy-projections.spec.ts b/packages/host/apiproxy/tests/api-proxy-projections.spec.ts index 0fb88c766d..fb6af25efb 100644 --- a/packages/host/apiproxy/tests/api-proxy-projections.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-projections.spec.ts @@ -10,7 +10,9 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { z } from 'zod' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' +import type {} from '@deepseek-ai/dsh-agent/inbox-projection' import { AttachmentStore } from '@deepseek-ai/dsh-attachment' import type { Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' @@ -52,10 +54,28 @@ async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: await ctx.plugin(SessionStore) await ctx.plugin(UserQuestionService) await ctx.plugin(AgentRegistry) - if (withRegistry) await ctx.plugin(SessionProjectionRegistry) + if (withRegistry) { + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) + } const session = ctx.sessions.create() - // The gateway reads both the session and durable inbox baseline. - ctx.agents.register({ id: session.id, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), status: 'idle', ctx } as Agent) + const agent = { + id: session.id, + options: {}, + session, + inbox: { nextTurn: [], nextStep: [], hasPending: false } as never, + status: 'idle', + ctx, + send() {}, + followup() {}, + steer() {}, + inject() {}, + cancel() {}, + runMaintenance: task => task(new AbortController().signal), + whenIdle: () => Promise.resolve(), + } satisfies Agent + if (withRegistry) Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) + ctx.agents.register(agent) return { ctx, session } } @@ -87,6 +107,78 @@ describe('session.history projections block', () => { expect(events.at(-1)?.event.seq).toBe(projections?.asOfSeq) }) + it('reconstructs a cold persisted queue without publishing or resuming an Agent', async () => { + const { ctx } = await harness(true) + const coldId = SessionId('cold-persisted-queue') + const meta = { version: 0 as const, id: coldId, createdAt: 1, cwd: '/tmp' } + const message = createUserMessage({ + content: [{ type: 'text', text: 'survive process restart' }], + source: { kind: 'user' }, + }) + const events = [{ + type: 'agent/inbox/spliced', + seq: 0, + time: 2, + data: { target: 'next-turn', start: 0, inserted: [message] }, + }] as const + ctx.provide('sessionPersistence', { + list: () => Promise.resolve([meta]), + inspect: () => Promise.resolve({ meta, events }), + } as never) + const response = await api(ctx).sessions.history(request({ sessionId: coldId })) + if (!response.result.ok) throw new Error('history failed') + + expect(response.result.value.projections?.values.inbox).toEqual({ + 'next-turn': [message], + 'next-step': [], + }) + expect(ctx.agents.get(coldId)).toBeUndefined() + expect(ctx.sessions.get(coldId)).toBeUndefined() + }) + + it('removes claimed steering from the pending Inbox projection immediately', async () => { + const { ctx, session } = await harness(true) + const proxy = api(ctx) + const message = createUserMessage({ + content: [{ type: 'text', text: 'apply this now' }], + source: { kind: 'user' }, + }) + const agent = ctx.agents.get(session.id) + if (agent === undefined) throw new Error('missing Agent') + agent.inbox.append('next-step', message) + agent.inbox.claim('next-step', 1) + + const during = await proxy.sessions.history(request({ sessionId: session.id })) + if (!during.result.ok) throw new Error('history failed') + expect(during.result.value.projections?.values.inbox).toEqual({ + 'next-turn': [], + 'next-step': [], + }) + + session.append('user/message', message, { surfaceOp: 'append' }) + const settled = await proxy.sessions.history(request({ sessionId: session.id })) + if (!settled.result.ok) throw new Error('history failed') + expect(settled.result.value.projections?.values.inbox).toEqual({ + 'next-turn': [], + 'next-step': [], + }) + + const rejected = createUserMessage({ + content: [{ type: 'text', text: 'reject this pre-step' }], + source: { kind: 'user' }, + }) + session.append('turn/start', { turn: 1 }) + agent.inbox.append('next-step', rejected) + agent.inbox.claim('next-step', 1) + session.append('turn/end', { turn: 1, reason: { kind: 'blocked' } }) + const closed = await proxy.sessions.history(request({ sessionId: session.id })) + if (!closed.result.ok) throw new Error('history failed') + expect(closed.result.value.projections?.values.inbox).toEqual({ + 'next-turn': [], + 'next-step': [], + }) + }) + it('publishes the attachments imageLimits as a constant unit while both seams are composed', async () => { const { ctx, session } = await harness(true) const limits = { diff --git a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts index 54bdb015e4..0bb9eb55b9 100644 --- a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts @@ -40,11 +40,11 @@ async function nextHostFrame( } function stubAgent(session: Session): Agent { - return { + const agent: Agent = { id: session.id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: new Context(), send: () => {}, @@ -55,6 +55,8 @@ function stubAgent(session: Session): Agent { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + return agent } /** Compose the API over real Session, Agent, Storage, Domain, and Workspace services. */ diff --git a/packages/jobs/jobs-local/tests/jobs.spec.ts b/packages/jobs/jobs-local/tests/jobs.spec.ts index 33ea29ba68..b333b87222 100644 --- a/packages/jobs/jobs-local/tests/jobs.spec.ts +++ b/packages/jobs/jobs-local/tests/jobs.spec.ts @@ -34,7 +34,7 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle' as const, ctx: agentCtx, send: () => {}, @@ -45,6 +45,7 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { runMaintenance: (job: (signal: AbortSignal) => Promise) => job(new AbortController().signal), whenIdle() { return Promise.resolve() }, } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) agentScopeDisposers.set(agent, async () => { await scopeFiber.dispose() }) return agent } diff --git a/packages/llm/llm-retry/package.json b/packages/llm/llm-retry/package.json index 44386ce78b..cb57cc7b41 100644 --- a/packages/llm/llm-retry/package.json +++ b/packages/llm/llm-retry/package.json @@ -59,6 +59,7 @@ "@deepseek-ai/dsh-llm-deepseek": "workspace:^", "@deepseek-ai/dsh-llm-mock-server": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-session-persistence-sqlite": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", diff --git a/packages/llm/llm-retry/tests/loader-composition.spec.ts b/packages/llm/llm-retry/tests/loader-composition.spec.ts index 367e8f46f4..7d869af764 100644 --- a/packages/llm/llm-retry/tests/loader-composition.spec.ts +++ b/packages/llm/llm-retry/tests/loader-composition.spec.ts @@ -7,10 +7,12 @@ import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import AgentRegistry from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import LlmRuntime, { createUserMessage, LlmAdapter, LlmError, resolveRetryPolicy } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, ResolvedRetryPolicy, StreamChunk } from '@deepseek-ai/dsh-llm' 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 from '@deepseek-ai/dsh-tools' import * as retry from '../src/index.ts' @@ -60,9 +62,11 @@ async function loadYaml(lines: readonly string[]): Promise { const modules = new Map([ ['@deepseek-ai/dsh-llm', LlmRuntime], ['@deepseek-ai/dsh-session', SessionStore], + ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry], ['@deepseek-ai/dsh-system-prompt', SystemPrompt], ['@deepseek-ai/dsh-tools', ToolRuntime], ['@deepseek-ai/dsh-agent', AgentRegistry], + ['@deepseek-ai/dsh-agent/inbox', InboxService], ['@deepseek-ai/dsh-llm-retry', retry], ['@deepseek-ai/dsh-agent-loop', AgentLoop], ]) @@ -89,9 +93,11 @@ describe('real Loader composition', () => { const loaded = await loadYaml([ "- name: '@deepseek-ai/dsh-llm'", "- name: '@deepseek-ai/dsh-session'", + "- name: '@deepseek-ai/dsh-session-projection'", "- name: '@deepseek-ai/dsh-system-prompt'", "- name: '@deepseek-ai/dsh-tools'", "- name: '@deepseek-ai/dsh-agent'", + "- name: '@deepseek-ai/dsh-agent/inbox'", "- name: '@deepseek-ai/dsh-llm-retry'", "- name: '@deepseek-ai/dsh-agent-loop'", ]) diff --git a/packages/llm/llm-retry/tests/retry.spec.ts b/packages/llm/llm-retry/tests/retry.spec.ts index c2643a6d45..236355cd01 100644 --- a/packages/llm/llm-retry/tests/retry.spec.ts +++ b/packages/llm/llm-retry/tests/retry.spec.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import type { Fiber } from '@deepseek-ai/cordis' -import LlmRuntime, { createUserMessage, CallId, EMPTY_RESPONSE_CODE, LlmAdapter, LlmError, resolveRetryPolicy } from '@deepseek-ai/dsh-llm' +import { createUserMessage, CallId, EMPTY_RESPONSE_CODE, LlmAdapter, LlmError, resolveRetryPolicy } from '@deepseek-ai/dsh-llm' import type { AlwaysRetryPolicyConfig, BackoffConfig, @@ -11,14 +11,13 @@ import type { RetryPolicyConfig, StreamChunk, } from '@deepseek-ai/dsh-llm' -import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session' import type { LlmRetryEventData } from '@deepseek-ai/dsh-llm-retry/types' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' import type { Agent, RequestErrorAction } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import * as retry from '../src/index.ts' type ScriptEntry = Error | Iterable | AsyncIterable @@ -105,11 +104,7 @@ async function harness( internals: retry.RetryInternals = {}, ): Promise<{ ctx: Context; retryFiber: Fiber; disposeAdapter: () => void }> { const ctx = new Context() - await ctx.plugin(LlmRuntime) - await ctx.plugin(SessionStore) - await ctx.plugin(SystemPrompt) - await ctx.plugin(ToolRuntime) - await ctx.plugin(AgentRegistry) + await mountAgentLoopTestDependencies(ctx) beforeRetry?.(ctx) adapter.configureRetryPolicies(policies) const retryFiber = await ctx.plugin(Object.assign((inner: Context) => { diff --git a/packages/plan/plan-mode/tests/integration.spec.ts b/packages/plan/plan-mode/tests/integration.spec.ts index 77efc3beb3..959b36f2ac 100644 --- a/packages/plan/plan-mode/tests/integration.spec.ts +++ b/packages/plan/plan-mode/tests/integration.spec.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import LlmRuntime, { createUserMessage, type StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, type SessionEvent } 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 AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' @@ -23,6 +25,8 @@ async function harness(adapter: MockAdapter): Promise { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/preset/agent-presets/package.json b/packages/preset/agent-presets/package.json index a8f374d765..78c45d8d8e 100644 --- a/packages/preset/agent-presets/package.json +++ b/packages/preset/agent-presets/package.json @@ -64,6 +64,7 @@ "@deepseek-ai/dsh-home-paths": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-settings": "workspace:^", "@deepseek-ai/dsh-settings-file": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", diff --git a/packages/preset/agent-presets/tests/invariant.spec.ts b/packages/preset/agent-presets/tests/invariant.spec.ts index dda3644f55..f1e26a79d7 100644 --- a/packages/preset/agent-presets/tests/invariant.spec.ts +++ b/packages/preset/agent-presets/tests/invariant.spec.ts @@ -1,10 +1,12 @@ import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { Context } from '@deepseek-ai/cordis' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import LlmRuntime from '@deepseek-ai/dsh-llm' 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 from '@deepseek-ai/dsh-tools' import AgentRegistry, { assembleContextFor } from '@deepseek-ai/dsh-agent' @@ -27,6 +29,8 @@ async function harness(roster: Partial = {}): Promise { ctx.loader.builtins.include = Include await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/preset/agent-presets/tests/mount.spec.ts b/packages/preset/agent-presets/tests/mount.spec.ts index 824308e009..23a56112e7 100644 --- a/packages/preset/agent-presets/tests/mount.spec.ts +++ b/packages/preset/agent-presets/tests/mount.spec.ts @@ -3,10 +3,12 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { Context } from '@deepseek-ai/cordis' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import LlmRuntime from '@deepseek-ai/dsh-llm' 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 from '@deepseek-ai/dsh-tools' import AgentRegistry, { assembleContextFor, type Agent } from '@deepseek-ai/dsh-agent' @@ -45,6 +47,8 @@ async function harness(roster: Config = { default: 'standard', roots: ROOTS, inc ctx.loader.builtins.include = Include await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -414,6 +418,8 @@ describe('the preset file is an input, never a persistence target', () => { scoped.loader.builtins.include = Include await scoped.plugin(LlmRuntime) await scoped.plugin(SessionStore) + await scoped.plugin(SessionProjectionRegistry) + await scoped.plugin(InboxService) await scoped.plugin(SystemPrompt, { persona: '' }) await scoped.plugin(ToolRuntime) await scoped.plugin(AgentRegistry) @@ -579,6 +585,8 @@ describe('replacing a composition', () => { scoped.loader.builtins.include = Include await scoped.plugin(LlmRuntime) await scoped.plugin(SessionStore) + await scoped.plugin(SessionProjectionRegistry) + await scoped.plugin(InboxService) await scoped.plugin(SystemPrompt, { persona: '' }) await scoped.plugin(ToolRuntime) await scoped.plugin(AgentRegistry) diff --git a/packages/preset/agent-presets/tests/settings.spec.ts b/packages/preset/agent-presets/tests/settings.spec.ts index e3af9e1ec1..4b09b1b663 100644 --- a/packages/preset/agent-presets/tests/settings.spec.ts +++ b/packages/preset/agent-presets/tests/settings.spec.ts @@ -16,7 +16,9 @@ import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import AgentRegistry from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import FileSettingsProvider from '@deepseek-ai/dsh-settings-file' import { settingsNamespace } from '@deepseek-ai/dsh-settings' import { describe, expect, it } from 'vitest' @@ -43,6 +45,8 @@ async function harness( ctx.loader.builtins.include = Include await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/schedule/schedule/tests/runtime.spec.ts b/packages/schedule/schedule/tests/runtime.spec.ts index d49f33b715..106725c8ad 100644 --- a/packages/schedule/schedule/tests/runtime.spec.ts +++ b/packages/schedule/schedule/tests/runtime.spec.ts @@ -57,12 +57,11 @@ async function harness(): Promise { onFollowup: undefined as (() => void) | undefined, idle: Promise.withResolvers(), } - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) const agent: Agent = { id: session.id, options: {}, session, - inbox, + inbox: undefined as never, status: 'idle', ctx: new Context(), send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {}, @@ -97,6 +96,7 @@ async function harness(): Promise { steer(_message: UserMessage) {}, inject(_message: UserMessage) {}, } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) const disposeAgent = ctx.agents.register(agent) ctx.on('session/event', (_session, event) => { if (event.type === 'schedule/change' && event.data.operation === 'dispatch') order.push('dispatch') diff --git a/packages/schedule/schedule/tests/tools.spec.ts b/packages/schedule/schedule/tests/tools.spec.ts index 63f080a678..7b387c7ef5 100644 --- a/packages/schedule/schedule/tests/tools.spec.ts +++ b/packages/schedule/schedule/tests/tools.spec.ts @@ -24,12 +24,11 @@ interface ToolHarness { function stubAgent(ctx: Context, id: string): Agent { const session = ctx.sessions.create(SessionId(id)) - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) - return { + const agent: Agent = { id: session.id, options: {}, session, - inbox, + inbox: undefined as never, status: 'idle', ctx: new Context(), send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {}, @@ -40,6 +39,8 @@ function stubAgent(ctx: Context, id: string): Agent { steer(_message: UserMessage) {}, inject(_message: UserMessage) {}, } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + return agent } async function harness(withPersistence = true): Promise { diff --git a/packages/session/session-projection/README.i18n.yaml b/packages/session/session-projection/README.i18n.yaml index fb26401df9..2cab04c6bb 100644 --- a/packages/session/session-projection/README.i18n.yaml +++ b/packages/session/session-projection/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/session/session-projection/README.md -README.md: 9018b133bb69ed4717fede14c9a2070a07c3fa62 -README.zh.md: 2a3af5620f84ff9697268101a6cfb894232b68b7 +README.md: 68bbd9ea98b7e45ac215dc549444e52e97ac66fc +README.zh.md: 2e69c2da59cadb8ab1eeec0b94cc751ec6cbd3f2 diff --git a/packages/session/session-projection/README.md b/packages/session/session-projection/README.md index 9018b133bb..68bbd9ea98 100644 --- a/packages/session/session-projection/README.md +++ b/packages/session/session-projection/README.md @@ -2,13 +2,13 @@ English | [中文](README.zh.md) -Session-projection Service Definition and drive registry. It owns `ctx.sessionProjections`, the registry that drives every registered projection unit over committed session events and serves finished whole values to carriers, currently the api-proxy history tail page and `session/projection` push frame. A domain registers pure mathematics; the framework owns the drive. The [session-projection RFC](../../../.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md) records the design rationale. +Session-projection Service Definition and drive registry. It owns `ctx.sessionProjections`, the registry that folds committed session events through every registered projection and serves finished whole values to carriers, currently the api-proxy history tail page and `session/projection` push frame. A domain registers pure mathematics; the framework owns the drive. The [session-projection RFC](../../../.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md) records the design rationale. ## Service: `SessionProjectionRegistry` (ctx key: `sessionProjections`) ### Public API -- `ctx.sessionProjections.register(definition): () => void` Register one domain's unit. Duplicate keys and invalid `stateVersion` throw; the registration is an effect on the calling fiber, so an unloaded domain plugin's key (with its cached cells) disappears from subsequent drives and snapshots — clients read that as capability absence. +- `ctx.sessionProjections.register(definition): () => void` Register one domain's unit. Registrants with the same key and `stateVersion` share its cells; an incompatible version or invalid `stateVersion` throws. The registration is an effect on the calling fiber, so the last unload removes the key and its cached cells from subsequent drives and snapshots. - `ctx.sessionProjections.onChanged(listener): () => void` Subscribe to the change feed: one call per unit whose state reference changed, per committed event, carrying the schema-validated view and the causing seq. Effect-tied like `register`. - `ctx.sessionProjections.snapshot(session): ProjectionSnapshot` One consistent synchronous cut over every registered unit — `{ asOfSeq, values }` with `asOfSeq` = the seq of the last event every value reflects (`-1` for an empty log). @@ -19,13 +19,13 @@ Session-projection Service Definition and drive registry. It owns `ctx.sessionPr ## Contract -- **The framework drives, the domain computes.** The registry subscribes to `session/event` once; every committed event passes every unit's `apply` eagerly. Domains hold no subscriptions. Cells (`{state, observedSeq}` per unit per session, WeakMap-keyed) build lazily — a unit registered after events flowed, or a read of a session predating the registration, folds `init` over the in-memory log on first touch. +- **The framework drives, the domain computes.** The registry subscribes to `session/event` once and runs every unit's `apply` over each committed event. Domains hold no subscriptions. Cells (`{state, observedSeq}` per unit per session, WeakMap-keyed) build lazily — a unit registered after events flowed, or a read of a session predating the registration, folds `init` over the in-memory log on first touch. - **Same-reference means no work.** `apply` MUST return the same state reference for events that do not concern the unit; the drive gates the change feed on `Object.is`, so non-matching events cost one call and nothing downstream. - **Whole-value event rule (load-bearing).** A state-carrying log event MUST carry the complete post-change state, never a bare delta — it keeps every transition trivially cheap and every served value self-describing (last-wins for consumers). - **Synchronous unit discipline.** `init`/`apply`/`view` MUST be synchronous; carriers read `snapshot()` in the same tick as their page slice, which is what makes `asOfSeq` one consistent cut. An accidentally-async `view` returns a Promise, which fails the boundary `schema.parse` loudly. - **State is plain JSON, `stateVersion` is its invalidation anchor.** The persisted projection cache stores `(sessionId, key, ver, seq, val)` rows; bump `stateVersion` whenever the state shape or the fold semantics change so stale rows are discarded instead of forward-applied into garbage. - **No wire vocabulary here.** The registry exposes only the change feed and the snapshot read face; carriers (api-proxy) mint their own frames (`session/projection`) and blocks from them. -- **Optional capability.** Domain plugins register under `ctx.inject(['sessionProjections'], …)` so headless assemblies without the registry stay unaffected; carriers use `ctx.get('sessionProjections')` and omit their block/frames entirely when the registry is absent. +- **Dependency follows use.** A domain that requires projection state declares `sessionProjections` as a Cordis service dependency; optional contributors may register under `ctx.inject(['sessionProjections'], …)`. Carriers use `ctx.get('sessionProjections')` and omit their block or frames when the registry is absent. ## Role @@ -43,6 +43,6 @@ None; projections never assemble or send provider requests. - **Every tail page carries every registered key** — there is no per-key opt-out or lazy-key request shape yet; acceptable while values are UI-scale whole states (a todo list, a goal snapshot), revisit if a domain's value grows large. - **The unit table is process-wide, so key presence is not a per-session capability signal** — a key registered by ANY agent preset appears in every session's snapshot, including sessions whose own composition mounts nothing that produces it. A client must read the VALUE (`plan.active`, an empty todo list) rather than treat an absent key as absence of the feature; a unit whose empty value is indistinguishable from a real one belongs on the host plane instead, which is why `dsh-token-meter` sits there. -- **Eager drive touches every unit per event** — cheap by construction (whole-value rule, same-reference gate), but a hot path would justify per-unit event-type prefilters, addable without contract change. +- **Eager drive touches every unit per event** — bounded by each unit's transition and the same-reference gate, but a hot path would justify per-unit event-type prefilters, addable without contract change. - **Registry cells live in memory only** — a restart rebuilds by folding the log on first touch; compositions that mount `dsh-session-projection-cache` seed that fold from persisted rows instead. - **Synchronous unit discipline is only partially mechanical** — the boundary `schema.parse` rejects a Promise-returning `view`, but an `apply` that blocks or reads torn non-session state is a review concern; the invariant companion documents why no runtime check exists. diff --git a/packages/session/session-projection/README.zh.md b/packages/session/session-projection/README.zh.md index 2a3af5620f..2e69c2da59 100644 --- a/packages/session/session-projection/README.zh.md +++ b/packages/session/session-projection/README.zh.md @@ -2,13 +2,13 @@ [English](README.md) | 中文 -会话投影 Service Definition 与驱动注册表。它拥有 `ctx.sessionProjections`:该注册表在已提交的会话事件上驱动每个已注册的投影单元,并向载体提供完整的最终值,目前包括 api-proxy 历史尾页和 `session/projection` 推送帧。领域注册的只是纯数学;驱动权归框架。[session-projection RFC](../../../.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md) 记录了设计理由。 +会话投影 Service Definition 与驱动注册表。它拥有 `ctx.sessionProjections`:该注册表把已提交的会话事件折叠进每个已注册投影,并向载体提供完整的最终值,目前包括 api-proxy 历史尾页和 `session/projection` 推送帧。领域注册的只是纯数学;驱动权归框架。[session-projection RFC](../../../.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md) 记录了设计理由。 ## 服务:`SessionProjectionRegistry`(ctx 键:`sessionProjections`) ### 公开 API -- `ctx.sessionProjections.register(definition): () => void` 注册一个领域的单元。key 重复或 `stateVersion` 非法都会 throw;注册是挂在调用方 fiber 上的 effect,领域插件卸载后其 key(连同缓存的 cell)从后续驱动与快照中消失——客户端将其读作能力缺失。 +- `ctx.sessionProjections.register(definition): () => void` 注册一个领域单元。具有相同 key 和 `stateVersion` 的注册方共享其 cell;版本不兼容或 `stateVersion` 非法时会 throw。注册是挂在调用方 fiber 上的 effect,最后一个注册方卸载后,key 及其缓存 cell 会从后续驱动与快照中消失。 - `ctx.sessionProjections.onChanged(listener): () => void` 订阅变更流:每个已提交事件、每个状态引用发生变化的单元各回调一次,携带经 schema 校验的 view 与致因 seq。与 `register` 一样绑定 effect。 - `ctx.sessionProjections.snapshot(session): ProjectionSnapshot` 对全部已注册单元做一次一致的同步切面——`{ asOfSeq, values }`,其中 `asOfSeq` = 所有值共同反映到的最后一个事件的 seq(空日志为 `-1`)。 @@ -19,13 +19,13 @@ ## 约定 -- **框架负责驱动,领域负责计算。** 注册表只订阅一次 `session/event`;每个已提交事件都会主动经过每个单元的 `apply`。领域不持有任何订阅。cell(每会话每单元一份 `{state, observedSeq}`,以 WeakMap 为键)惰性构建——在事件流过之后才注册的单元,或读取一个早于该注册的会话,都在首次触达时从 `init` 出发在内存日志上折叠。 +- **框架负责驱动,领域负责计算。** 注册表只订阅一次 `session/event`,并让每个单元的 `apply` 处理每个已提交事件。领域不持有任何订阅。cell(每会话每单元一份 `{state, observedSeq}`,以 WeakMap 为键)惰性构建——在事件流过之后才注册的单元,或读取一个早于该注册的会话,都在首次触达时从 `init` 出发在内存日志上折叠。 - **同引用即无工作。** 对与单元无关的事件,`apply` 必须返回同一个状态引用;驱动以 `Object.is` 把守变更流,因此不匹配的事件只花一次调用,不产生任何下游工作。 - **全量值事件规则(承重)。** 携带状态的日志事件必须携带变更后的完整状态,绝不携带裸增量——这让每次状态转移始终足够廉价,也让每个被供给的值自描述(对消费方即 last-wins)。 - **单元的同步纪律。**`init`/`apply`/`view` 必须是同步的;载体在切出页面切片的同一 tick 内读取 `snapshot()`,`asOfSeq` 之所以是一个一致切面正系于此。误写成异步的 `view` 会返回 Promise,让边界的 `schema.parse` 当场大声失败。 - **状态是纯 JSON,`stateVersion` 是其失效锚点。** 持久投影缓存(persisted projection cache)存储 `(sessionId, key, ver, seq, val)` 行;状态形状或折叠语义一旦变化就递增 `stateVersion`,使陈旧行被丢弃,而不是被正向 apply 成垃圾。 - **本层没有协议词汇。** 注册表只暴露变更流与快照读取面;载体(api-proxy)据此自铸各自的帧(`session/projection`)与块。 -- **可选能力。** 领域插件在 `ctx.inject(['sessionProjections'], …)` 下注册,因此不带注册表的 headless 组装完全不受影响;载体使用 `ctx.get('sessionProjections')`,注册表缺席时完全省略自己的块与帧。 +- **依赖方式由用途决定。** 必须使用投影状态的领域把 `sessionProjections` 声明为 Cordis 服务依赖;可选贡献方可以在 `ctx.inject(['sessionProjections'], …)` 下注册。载体使用 `ctx.get('sessionProjections')`,注册表缺席时省略自己的块或帧。 ## 职责 @@ -43,6 +43,6 @@ - **每个尾页携带每个已注册的 key**——尚无逐 key 的 opt-out 或惰性 key 请求形状;在值都是 UI 量级的全量状态(一张 todo 清单、一份 goal 快照)时可以接受,若某领域的值变大再重议。 - **单元表是进程级的,因此 key 是否存在不能当作逐会话的能力信号**——只要**任何**一个 agent preset 注册了某个 key,它就出现在每个会话的快照里,包括自身组装完全不产出该值的会话。客户端必须读**值**(`plan.active`、空的 todo 列表),不能把 key 缺席当作功能缺席;如果某个单元的空值与真实值无法区分,它就该待在宿主平面——`dsh-token-meter` 正因如此留在那里。 -- **主动驱动(eager drive)逐事件触达每个单元**——按构造开销很低(全量值规则、同引用闸门),但若出现热点路径,可加按单元的事件类型预过滤,约定不变。 +- **eager 驱动逐事件触达每个单元**——成本受每个单元的 transition 与同引用闸门约束;若出现热点路径,可加按单元的事件类型预过滤,约定不变。 - **注册表 cell 只活在内存里**——重启后首次触达时靠折叠日志重建;挂载了 `dsh-session-projection-cache` 的组合改由持久行播种该折叠。 - **单元同步纪律只有部分可机械把关**——边界 `schema.parse` 能拒绝返回 Promise 的 `view`,但阻塞的 `apply`、或读取撕裂的非会话状态的 `apply`,只能靠评审把关;invariant 配套项记载了为何不存在运行时检查。 diff --git a/packages/session/session-projection/src/index.ts b/packages/session/session-projection/src/index.ts index 9f0c24e72e..b575c25b9a 100644 --- a/packages/session/session-projection/src/index.ts +++ b/packages/session/session-projection/src/index.ts @@ -5,14 +5,10 @@ * forward eagerly over committed session events. Domain host plugins * contribute pure mathematics (init/apply/view); the framework owns the * subscription, the per-session watermark cache, and change notification; - * carriers consume the snapshot read face and the change feed. Neither side - * knows the other - * (capability-seam three-way split). Design authority: the session-projection - * RFC (.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md). - * - * Whole-value event rule (load-bearing): a state-carrying log event MUST - * carry the complete post-change state, never a bare delta — it keeps every - * unit's transition trivially cheap and every served value self-describing. + * carriers consume the snapshot read face and the change feed. Source events + * may carry whole values or domain operations; every `view` returns a complete + * current value. Design authority: the session-projection RFC + * (.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md). * * @module @deepseek-ai/dsh-session-projection */ @@ -158,15 +154,15 @@ interface Registration { * every registered unit's `apply` (eager drive), and a changed state * reference notifies the change feed with the schema-validated view. * Cells build lazily — a unit registered after events flowed, or a session - * older than the registry, folds `init` over the in-memory log on first + * older than the registry, folds `init` over the full in-memory log on first * touch (event or read). Registration is an effect (disposer rides the * calling fiber): an unloaded domain plugin's key disappears from snapshots - * and clients read it as capability absence. Domain - * plugins register under `ctx.inject(['sessionProjections'], …)` so headless - * assemblies without the registry stay unaffected. Registrants sharing a key - * share one unit and are counted: the same tool package mounted in N agent - * presets registers N times, and the key survives until the last one - * unloads. + * and clients read it as capability absence. A domain that requires this + * capability declares a Cordis service dependency; an optional contributor + * may register under `ctx.inject(['sessionProjections'], …)`. Registrants + * sharing a key share one unit and are counted: the same tool package mounted + * in N agent presets registers N times, and the key survives until the last + * one unloads. */ export class SessionProjectionRegistry extends Service { private readonly registrations = new Map() diff --git a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts index 6d6affdb44..5fade7b924 100644 --- a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts @@ -44,7 +44,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -55,6 +55,7 @@ function agent(ctx: Context, cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(value, { inbox: new Inbox(value.ctx, value) }) ctx.agents.register(value) return value } diff --git a/packages/shell/tool-bash-persistent/tests/tools.spec.ts b/packages/shell/tool-bash-persistent/tests/tools.spec.ts index 0386295c4c..b1885f420b 100644 --- a/packages/shell/tool-bash-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/tools.spec.ts @@ -39,7 +39,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -50,6 +50,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(value, { inbox: new Inbox(value.ctx, value) }) ctx.agents.register(value) return value } diff --git a/packages/skill/tool-skill/tests/tool-skill.spec.ts b/packages/skill/tool-skill/tests/tool-skill.spec.ts index d8dd9df2f4..ff9e14bf5f 100644 --- a/packages/skill/tool-skill/tests/tool-skill.spec.ts +++ b/packages/skill/tool-skill/tests/tool-skill.spec.ts @@ -39,12 +39,12 @@ async function setup(home: string, config: toolSkill.Config = {}): Promise {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', send: () => {}, followup: () => {}, @@ -54,14 +54,16 @@ function agentForCwd(cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + return agent } function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent { - return { + const agent: Agent = { id: SessionId(id), options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'running', ctx: new Context(), send: () => {}, @@ -72,6 +74,8 @@ function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + return agent } function openMessageTurn(session: Session, turn = 1): void { diff --git a/packages/subagent/subagent/tests/list-children.spec.ts b/packages/subagent/subagent/tests/list-children.spec.ts index 3fd303e7f6..a2d9be0214 100644 --- a/packages/subagent/subagent/tests/list-children.spec.ts +++ b/packages/subagent/subagent/tests/list-children.spec.ts @@ -34,7 +34,7 @@ afterEach(() => { /** Boot the continuable stack with real JSONL session persistence. */ async function setup( script: Script, - options: { sessionProjections?: boolean; projectionCache?: boolean } = {}, + options: { projectionCache?: boolean } = {}, ) { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) @@ -42,7 +42,6 @@ async function setup( roots.push(root) await ctx.plugin(JsonlSessionPersistence, { root }) await ctx.plugin(AgentLoop, { agents: [] }) - if (options.sessionProjections !== false) await ctx.plugin(SessionProjectionRegistry) if (options.projectionCache === true) { await ctx.plugin(Storage) ctx.storage.backend.register('memory', new MemoryStorageBackend(new MemoryMediaPool())) @@ -59,6 +58,13 @@ async function setup( return { ctx, parent } } +async function setupWithoutProjections(): Promise { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SubagentRuntime) + return ctx +} + const testSignal = new AbortController().signal /** Start one continuable child through the real service path and await Activation release. */ @@ -175,8 +181,8 @@ describe('SubagentRuntime.listChildren', () => { }) it('fails loud when the projection registry is not mounted, even with no children', async () => { - const { ctx, parent } = await setup([], { sessionProjections: false }) - await expect(ctx.subagents.listChildren(parent.id)).rejects.toThrow( + const ctx = await setupWithoutProjections() + await expect(ctx.subagents.listChildren(SessionId('no-projections-parent'))).rejects.toThrow( expect.objectContaining({ code: 'SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE' }) as Error, ) }) @@ -966,8 +972,9 @@ describe('SubagentRuntime.listChildren', () => { }) it('SubagentError from listChildren is typed with its stable code', async () => { - const { ctx, parent } = await setup([], { sessionProjections: false }) - const caught: unknown = await ctx.subagents.listChildren(parent.id).catch((error: unknown) => error) + const ctx = await setupWithoutProjections() + const caught: unknown = await ctx.subagents.listChildren(SessionId('typed-no-projections-parent')) + .catch((error: unknown) => error) expect(caught).toBeInstanceOf(SubagentError) expect((caught as SubagentError).code).toBe('SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE') }) @@ -1206,8 +1213,8 @@ describe('SubagentRuntime.listDescendants', () => { }) it('fails loud when the projection registry is not mounted', async () => { - const { ctx, parent } = await setup([], { sessionProjections: false }) - await expect(ctx.subagents.listDescendants(parent.id)).rejects.toThrow( + const ctx = await setupWithoutProjections() + await expect(ctx.subagents.listDescendants(SessionId('no-projections-root'))).rejects.toThrow( expect.objectContaining({ code: 'SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE' }) as Error, ) }) diff --git a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts index 4eb8008c3b..752abaecbc 100644 --- a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts @@ -8,7 +8,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { SessionId } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SubagentRuntime from '@deepseek-ai/dsh-subagent' import type { SubagentListEntry } from '@deepseek-ai/dsh-subagent' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' @@ -58,7 +57,6 @@ async function setupWith(adapter: MockAdapter | GatedAdapter) { roots.push(root) await ctx.plugin(JsonlSessionPersistence, { root }) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) await ctx.plugin(tool) diff --git a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts index 0636254841..1f88265219 100644 --- a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts @@ -8,7 +8,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { SessionId } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SubagentRuntime from '@deepseek-ai/dsh-subagent' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' @@ -57,7 +56,6 @@ async function setupWith(adapter: MockAdapter | GatedAdapter) { roots.push(root) await ctx.plugin(JsonlSessionPersistence, { root }) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) await ctx.plugin(tool) diff --git a/packages/terminal/terminal-bash/tests/index.spec.ts b/packages/terminal/terminal-bash/tests/index.spec.ts index 2a4d7848df..0e104d43c5 100644 --- a/packages/terminal/terminal-bash/tests/index.spec.ts +++ b/packages/terminal/terminal-bash/tests/index.spec.ts @@ -47,8 +47,8 @@ function config(): ResolvedConfig { function agent(ctx: Context, cwd?: string): Agent { const id = SessionId('agent') const session = Session.create(id, undefined, { version: 0, id, createdAt: 0, ...cwd === undefined ? {} : { cwd } }) - return { - id, options: {}, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + const agent: Agent = { + id, options: {}, session, inbox: undefined as never, status: 'idle', ctx, send: () => {}, @@ -56,6 +56,8 @@ function agent(ctx: Context, cwd?: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + return agent } function terminalHandle(): SubprocessTerminalHandle { @@ -391,7 +393,7 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { - id: session.id, options: {}, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + id: session.id, options: {}, session, inbox: undefined as never, status: 'idle', ctx: ownerFiber.ctx, send: () => {}, @@ -399,6 +401,7 @@ describe('terminal-bash plugin shape', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(owner, { inbox: new Inbox(owner.ctx, owner) }) ctx.agents.register(owner) const providerFiber = await registerStubLocalBackend(ctx, () => stubLocalSession()) const created = await ctx.terminals.spawn(owner, { type: 'stub' }) @@ -440,7 +443,7 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('pending-mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { - id: session.id, options: {}, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + id: session.id, options: {}, session, inbox: undefined as never, status: 'idle', ctx: ownerFiber.ctx, send: () => {}, @@ -448,6 +451,7 @@ describe('terminal-bash plugin shape', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(owner, { inbox: new Inbox(owner.ctx, owner) }) ctx.agents.register(owner) const gate = Promise.withResolvers() await registerStubLocalBackend(ctx, () => stubLocalSession(() => gate.promise)) diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index c7af8668a3..392a106f30 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -35,8 +35,8 @@ function stubAgent(ctx: Context, rawId: string): Agent { const id = SessionId(rawId) const scope = ctx.plugin(() => {}) const session = Session.create(id) - return { - id, options: {}, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + const agent: Agent = { + id, options: {}, session, inbox: undefined as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -44,6 +44,8 @@ function stubAgent(ctx: Context, rawId: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + return agent } async function harness( diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index 10484d3c5c..7b73ebfbd7 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -26,7 +26,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: scopeFiber.ctx, send: () => {}, @@ -37,6 +37,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) agentScopeDisposers.set(agent, async () => { await scopeFiber.dispose() }) return agent } diff --git a/packages/terminal/tool-terminal/tests/loader-composition.spec.ts b/packages/terminal/tool-terminal/tests/loader-composition.spec.ts index ada46ef78f..1262156be2 100644 --- a/packages/terminal/tool-terminal/tests/loader-composition.spec.ts +++ b/packages/terminal/tool-terminal/tests/loader-composition.spec.ts @@ -41,7 +41,7 @@ function agent(ctx: Context): Agent { const id = SessionId('pty-loader-agent') const session = Session.create(id) const value: Agent = { - id, options: {}, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + id, options: {}, session, inbox: undefined as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -49,6 +49,7 @@ function agent(ctx: Context): Agent { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(value, { inbox: new Inbox(value.ctx, value) }) ctx.agents.register(value) return value } diff --git a/packages/terminal/tool-terminal/tests/tools.spec.ts b/packages/terminal/tool-terminal/tests/tools.spec.ts index 9feaf1e7b0..4c50898355 100644 --- a/packages/terminal/tool-terminal/tests/tools.spec.ts +++ b/packages/terminal/tool-terminal/tests/tools.spec.ts @@ -18,7 +18,7 @@ function fakeAgent(ctx: Context, rawId: string): Agent { const id = SessionId(rawId) const session = Session.create(id) const agent: Agent = { - id, options: {}, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + id, options: {}, session, inbox: undefined as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -26,6 +26,7 @@ function fakeAgent(ctx: Context, rawId: string): Agent { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) ctx.agents.register(agent) return agent } diff --git a/packages/test-support/agent-loop-testkit/package.json b/packages/test-support/agent-loop-testkit/package.json index e677c8befd..bbc9dd9b1d 100644 --- a/packages/test-support/agent-loop-testkit/package.json +++ b/packages/test-support/agent-loop-testkit/package.json @@ -36,6 +36,7 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/cordis": "workspace:^" @@ -46,6 +47,7 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/cordis": "workspace:^" diff --git a/packages/test-support/agent-loop-testkit/src/index.ts b/packages/test-support/agent-loop-testkit/src/index.ts index e2ae19653d..8b327edc4b 100644 --- a/packages/test-support/agent-loop-testkit/src/index.ts +++ b/packages/test-support/agent-loop-testkit/src/index.ts @@ -7,8 +7,10 @@ import type { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' +import InboxService from '@deepseek-ai/dsh-agent/inbox' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' @@ -40,6 +42,8 @@ export async function mountAgentLoopTestDependencies( ): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, options.systemPrompt ?? {}) await ctx.plugin(ToolRuntime, options.tools ?? {}) await ctx.plugin(AgentRegistry) diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index 945b2e84e5..24199f8f10 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -32,12 +32,13 @@ function agent(ctx: Context): Agent { const id = SessionId('todo-loader-agent') const session = Session.create(id) const value: Agent = { - id, options: {}, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + id, options: {}, session, inbox: undefined as never, status: 'idle', ctx: scope.ctx, followup: () => {}, steer: () => {}, inject: () => {}, send: () => {}, cancel() {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(value, { inbox: new Inbox(value.ctx, value) }) ctx.agents.register(value) return value } diff --git a/packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.e2e.ts b/packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.e2e.ts index b87d0eb62a..d9a118c7bb 100644 --- a/packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.e2e.ts +++ b/packages/workflow/workflow-worker-thread/tests/workflow-worker-thread.e2e.ts @@ -1,12 +1,9 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import LlmRuntime from '@deepseek-ai/dsh-llm' -import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRuntime from '@deepseek-ai/dsh-tools' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import { SessionId } from '@deepseek-ai/dsh-session' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import SubagentRuntime from '@deepseek-ai/dsh-subagent' import * as Spawn from '@deepseek-ai/dsh-subagent-spawn-in-process' @@ -30,11 +27,7 @@ afterEach(async () => { async function harness(): Promise { const built = new Context() - await built.plugin(LlmRuntime) - await built.plugin(SessionStore) - await built.plugin(SystemPrompt) - await built.plugin(ToolRuntime) - await built.plugin(AgentRegistry) + await mountAgentLoopTestDependencies(built) await built.plugin(AgentLoop, { agents: [] }) await built.plugin(LlmDeepSeek) await built.plugin(SubagentRuntime) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7849f183aa..8b729ed9ad 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3311,6 +3311,9 @@ importers: '@deepseek-ai/dsh-agent-loop': specifier: workspace:^ version: link:../../core/agent-loop + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-fs': specifier: workspace:^ version: link:../../fs/fs @@ -3439,6 +3442,10 @@ importers: version: link:../../core/system-prompt packages/core/agent: + dependencies: + zod: + specifier: ^4.4.3 + version: 4.4.3 devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ @@ -3455,6 +3462,9 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:^ + version: link:../../session/session-projection '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../system-prompt @@ -3517,6 +3527,9 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-session-projection': + specifier: workspace:^ + version: link:../../session/session-projection '@deepseek-ai/dsh-settings': specifier: workspace:^ version: link:../../settings/settings @@ -3870,6 +3883,9 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:^ + version: link:../../session/session-projection '@deepseek-ai/dsh-session-title': specifier: workspace:^ version: link:../../session/session-title @@ -5426,6 +5442,9 @@ importers: '@deepseek-ai/dsh-session-persistence-sqlite': specifier: workspace:^ version: link:../../session/session-persistence-sqlite + '@deepseek-ai/dsh-session-projection': + specifier: workspace:^ + version: link:../../session/session-projection '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt @@ -5696,6 +5715,9 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:^ + version: link:../../session/session-projection '@deepseek-ai/dsh-settings': specifier: workspace:^ version: link:../../settings/settings @@ -7777,6 +7799,9 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:^ + version: link:../../session/session-projection '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index fac02f9db3..fec6cbf6bc 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -54,6 +54,7 @@ export const SERVICE_PAGE: Record = { agentDefaultModel: 'core.md', agentPresets: 'core.md', agents: 'core.md', + inboxes: 'core.md', apiProxy: 'typert.md', approval: 'approval.md', attachments: 'attachment.md', @@ -225,6 +226,7 @@ export const LINK_MAP: Readonly> = { ContentBlock: 'llm-streaming.md', CreateAgentOptions: 'core.md', GenerateOptions: 'llm-streaming.md', + Inbox: 'core.md', InboxItem: 'core.md', InboxPlacement: 'core.md', MessageId: 'llm-streaming.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 1cd41fe3de..4be1cd9d33 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -139,6 +139,14 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['agent-loop', 'agent', 'session-persistence', 'session-query', 'session-query-sqlite', 'subagent-inprocess', 'invariants', 'message-feedback'], note: 'Owns append-only Session instances and emits the durable session event feed.', }, + { + key: 'inboxes', + pkg: 'agent', + title: 'Durable pending-input facade', + mode: 'core', + consumers: ['agent-loop'], + note: 'Registers the standard Inbox projection and creates command facades over its sole live state.', + }, { key: 'invariants', pkg: 'invariants', diff --git a/tsconfig.base.json b/tsconfig.base.json index 4f97108033..3a74653569 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -95,6 +95,8 @@ "@deepseek-ai/dsh-user-questions/types": ["./packages/interaction/user-questions/src/types.ts"], "@deepseek-ai/dsh-agent/types": ["./packages/core/agent/src/types.ts"], "@deepseek-ai/dsh-agent/brand": ["./packages/core/agent/src/brand.ts"], + "@deepseek-ai/dsh-agent/inbox": ["./packages/core/agent/src/inbox.ts"], + "@deepseek-ai/dsh-agent/inbox-projection": ["./packages/core/agent/src/inbox-projection.ts"], "@deepseek-ai/dsh-agent/invariant": ["./packages/core/agent/src/invariant.ts"], "@deepseek-ai/dsh-scope/invariant": ["./packages/core/scope/src/invariant.ts"], "@deepseek-ai/dsh-agent-loop/invariant": ["./packages/core/agent-loop/src/invariant.ts"], From bd3b651ea8909440b2eec36f5dbd7bf4e2ddb6e1 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 21 Aug 2026 11:19:36 +0800 Subject: [PATCH 02/26] refactor(agent): remove inbox service --- ...claimed-pre-step-inbox-lifecycle.i18n.yaml | 4 +- ...-07-31-claimed-pre-step-inbox-lifecycle.md | 4 +- ...-31-claimed-pre-step-inbox-lifecycle.zh.md | 4 +- apps/cli/composition.md | 3 - apps/cli/tests/fixtures/dsh-badge/snapshot.ts | 4 +- docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 4 - docs/capability-seams.zh.md | 4 - docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 4 +- docs/config-catalog.zh.md | 4 +- docs/module-graph.i18n.yaml | 4 +- docs/module-graph.md | 3 +- docs/module-graph.zh.md | 3 +- docs/subsystems/core.i18n.yaml | 4 +- docs/subsystems/core.md | 21 +----- docs/subsystems/core.zh.md | 21 +----- .../headless-agent/tests/code-mode.e2e.ts | 3 - .../tests/fixtures/e2b/e2b/bin.ts | 4 +- packages/bundle/base/cordis.patch.yml | 3 - .../bundle/headless/tests/headless.spec.ts | 6 +- .../tests/agent-instructions.spec.ts | 8 +- .../time-context/tests/time-context.spec.ts | 2 +- .../tmux-context/tests/tmux-context.spec.ts | 2 +- packages/core/agent-loop/package.json | 1 + packages/core/agent-loop/src/agent.ts | 5 +- packages/core/agent-loop/src/index.ts | 2 +- .../agent-loop/tests/agent-initiator.spec.ts | 4 - packages/core/agent-loop/tests/agent.spec.ts | 2 - packages/core/agent-loop/tests/cancel.spec.ts | 3 - .../tests/config-session-id.spec.ts | 8 -- .../tests/contract-regressions.spec.ts | 9 --- .../agent-loop/tests/coverage-edges.spec.ts | 2 - .../agent-loop/tests/interception.spec.ts | 2 - packages/core/agent-loop/tests/loop.spec.ts | 4 - .../core/agent-loop/tests/properties.spec.ts | 2 - .../agent-loop/tests/request-cache.e2e.ts | 2 - .../agent-loop/tests/request-error.spec.ts | 2 - .../tests/request-reconstruction.spec.ts | 4 - packages/core/agent-loop/tests/resume.spec.ts | 11 --- .../agent-loop/tests/scope-lifecycle.spec.ts | 2 - .../core/agent-loop/tests/settings.spec.ts | 2 - .../core/agent-loop/tests/tool-calls.spec.ts | 5 -- .../core/agent-loop/tests/tool-order.spec.ts | 2 - packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 2 +- packages/core/agent/README.zh.md | 2 +- packages/core/agent/package.json | 8 -- packages/core/agent/src/inbox-projection.ts | 25 +++++++ packages/core/agent/src/inbox.ts | 75 ++++--------------- packages/core/agent/src/index.ts | 6 ++ packages/core/agent/tests/agent.spec.ts | 19 +++-- packages/e2b/e2b/tests/composition.e2e.ts | 4 +- .../examples/agent-spine-demo/src/index.ts | 2 - .../extensions/tool-cordis/src/api-catalog.ts | 23 +++--- .../tests/command-feedback.spec.ts | 4 +- .../tests/loader-composition.spec.ts | 4 +- .../tests/tools.spec.ts | 4 +- .../command-goal/tests/command-goal.spec.ts | 4 +- packages/goal/goal/tests/goal.spec.ts | 10 +-- .../goal/tool-goal/tests/tool-goal.spec.ts | 8 +- .../tests/api-proxy-projections.spec.ts | 7 +- .../tests/api-proxy-workspace.spec.ts | 4 +- packages/jobs/jobs-local/tests/jobs.spec.ts | 4 +- .../tests/loader-composition.spec.ts | 3 - .../plan/plan-mode/tests/integration.spec.ts | 2 - .../agent-presets/tests/invariant.spec.ts | 2 - .../preset/agent-presets/tests/mount.spec.ts | 4 - .../agent-presets/tests/settings.spec.ts | 2 - .../schedule/schedule/tests/runtime.spec.ts | 4 +- .../schedule/schedule/tests/tools.spec.ts | 4 +- .../tests/loader-composition.spec.ts | 4 +- .../tool-bash-persistent/tests/tools.spec.ts | 4 +- .../tests/loader-composition.spec.ts | 5 +- .../tool-pwsh-persistent/tests/tools.spec.ts | 5 +- .../skill/tool-skill/tests/tool-skill.spec.ts | 4 +- .../terminal-bash/tests/index.spec.ts | 8 +- .../terminal-bash/tests/local.spec.ts | 4 +- .../terminal/terminal/tests/service.spec.ts | 4 +- .../tests/loader-composition.spec.ts | 4 +- .../tool-terminal/tests/tools.spec.ts | 4 +- .../agent-loop-testkit/src/index.ts | 2 - .../tests/loader-composition.spec.ts | 4 +- scripts/gen-cordis-catalog.ts | 1 - scripts/gen-doc-graphs.ts | 8 -- tsconfig.base.json | 2 - 86 files changed, 160 insertions(+), 344 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml index 3c9a697dd3..84deedb9f9 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md -2026-07-31-claimed-pre-step-inbox-lifecycle.md: c46c22cde3e96fb774233d9621acf1abf4ba0c33 -2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 51ada096a105a5c97cffd70c2d40782a71beddf7 +2026-07-31-claimed-pre-step-inbox-lifecycle.md: 8149c9df09ff69c017ba66a779d6fd3dfc314193 +2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: e855b88b26a55dd9f5c33c87a4b59d67496d00ed diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md index c46c22cde3..8149c9df09 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md @@ -18,11 +18,11 @@ Before every proposed step, `Inbox.claim(target)` atomically removes the complet The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming records pure deletions without an outcome and emits claimed events from Inbox itself. These live events add no placement, outcome, or batch fields. -The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `InboxService` registers the standard `inbox` projection over the durable `agent/inbox/spliced` stream for whole-state consumers and live restoration; UI edits and removals route through an Inbox mutation method so the same projection records every change. +The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `AgentRegistry` contributes the standard `inbox` projection over the durable `agent/inbox/spliced` stream whenever the projection registry is composed; UI edits and removals route through an Inbox mutation method so the same projection records every change. Plugins that need current-step atomic rewriting return messages from `agent/pre-step`. Plugins that only need later context may mutate `agent.inbox` directly. Workspace context uses both paths: asynchronous filesystem projections stage one replaceable `next-step` item, while the next entering pre-step folds that item or a newly composed baseline into its final batch and removes the pending copy. Rejection keeps the item queued. -The archived [addressable queue occurrence decision](../../archived/feature/2026-07-29-addressable-queue-operations.md) describes the superseded occurrence-wrapper design. `MessageId` now owns addressability, while `InboxService` registers `inbox` as the standard session projection over durable splices. The generic projection carrier serves that fold for live updates, history-tail reconnect baselines, and cold process-restart recovery without a live Agent mirror. +The archived [addressable queue occurrence decision](../../archived/feature/2026-07-29-addressable-queue-operations.md) describes the superseded occurrence-wrapper design. `MessageId` owns addressability, while `AgentRegistry` contributes `inbox` as the standard session projection over durable splices. The generic projection carrier serves that fold for live updates, history-tail reconnect baselines, and cold process-restart recovery without a live Agent mirror. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md index 51ada096a1..e855b88b26 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md @@ -18,11 +18,11 @@ Status: implemented 持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取记录不带 outcome 的纯删除,并由 Inbox 自行发出 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 -两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`InboxService` 在持久 `agent/inbox/spliced` 流上注册标准 `inbox` 投影,供整体状态消费方与 live 恢复使用;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。 +两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`AgentRegistry` 会在投影注册表已组合时,在持久 `agent/inbox/spliced` 流上贡献标准 `inbox` 投影;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。 必须对当前步骤进行原子改写的插件从 `agent/pre-step` 返回消息。只需要稍后上下文的插件可以直接修改 `agent.inbox`。Workspace context 同时使用两条路径:异步文件系统投影会暂存一条可替换的 `next-step` 消息,而下一次进入步骤的 pre-step 会把该消息或新组合的基线折入最终批次,并移除仍待处理的副本。reject 会让该条目继续排队。 -已归档的[可寻址队列项决策](../../archived/feature/2026-07-29-addressable-queue-operations.md)描述了已被取代的单次出现包装层设计。现在由 `MessageId` 负责寻址,而 `InboxService` 把 `inbox` 注册为持久 splice 上的标准会话投影。通用投影传输层会将该折叠结果用于实时更新、历史尾页的重连基线和冷进程重启恢复,无需 live Agent 镜像。 +已归档的[可寻址队列项决策](../../archived/feature/2026-07-29-addressable-queue-operations.md)描述了已被取代的单次出现包装层设计。`MessageId` 负责寻址,而 `AgentRegistry` 把 `inbox` 作为持久 splice 上的标准会话投影贡献给投影注册表。通用投影传输层会将该折叠结果用于实时更新、历史尾页的重连基线和冷进程重启恢复,无需 live Agent 镜像。 ## 曾考虑的替代方案 diff --git a/apps/cli/composition.md b/apps/cli/composition.md index 08e5d4db39..4d37b9186a 100644 --- a/apps/cli/composition.md +++ b/apps/cli/composition.md @@ -30,8 +30,6 @@ flowchart LR cfg --> plugin_dsh_base_user_questions plugin_dsh_base_agent["agent
@deepseek-ai/dsh-agent"] cfg --> plugin_dsh_base_agent - plugin_dsh_base_agent_inbox["agent-inbox
@deepseek-ai/dsh-agent/inbox"] - cfg --> plugin_dsh_base_agent_inbox plugin_dsh_base_agent_default_model["agent-default-model
@deepseek-ai/dsh-agent-default-model"] cfg --> plugin_dsh_base_agent_default_model plugin_dsh_base_jobs["jobs
@deepseek-ai/dsh-jobs-local"] @@ -181,7 +179,6 @@ flowchart LR | `session-title-llm` | `@deepseek-ai/dsh-session-title-first-prompt-llm` | | `user-questions` | `@deepseek-ai/dsh-user-questions` | | `agent` | `@deepseek-ai/dsh-agent` | -| `agent-inbox` | `@deepseek-ai/dsh-agent/inbox` | | `agent-default-model` | `@deepseek-ai/dsh-agent-default-model` | | `jobs` | `@deepseek-ai/dsh-jobs-local` | | `llm-retry` | `@deepseek-ai/dsh-llm-retry` | diff --git a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts index 87254a8d2d..049123717b 100644 --- a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts +++ b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts @@ -1,6 +1,6 @@ import { fileURLToPath } from 'node:url' import { Context } from '@deepseek-ai/cordis' -import { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' +import { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' import { CallId } from '@deepseek-ai/dsh-llm' import { boot, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot' import { SessionId } from '@deepseek-ai/dsh-session' @@ -34,7 +34,7 @@ try { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) + Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', { messages: [], turn: 1, step: 1, signal: new AbortController().signal }, diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index a7b8b371b1..e696bc3423 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/capability-seams.md -capability-seams.md: 2f6bc45f9cb60809cedf31f86fcb68785ef80b9a -capability-seams.zh.md: a9eeb06c063a86cdcd6ef3560677129d3adb2798 +capability-seams.md: a84a6d6e0836524e1f39f2fd067ae1f6570741a5 +capability-seams.zh.md: b6b0aba72729f9b9b752347ab00cd76a45c248d9 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 2f6bc45f9c..a84a6d6e08 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -31,7 +31,6 @@ flowchart LR pkg_subagent_inprocess["subagent-inprocess"] pkg_invariants["invariants"] pkg_message_feedback["message-feedback"] - svc_inboxes["ctx.inboxes
Durable pending-input facade"] svc_invariants["ctx.invariants
Package-owned invariant registry"] pkg_scope["scope"] pkg_typert_registry["typert-registry"] @@ -202,7 +201,6 @@ flowchart LR svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] pkg_acp --> svc_approval pkg_agent --> svc_agents - pkg_agent --> svc_inboxes pkg_agent_default_model --> svc_agentDefaultModel pkg_agent_loop --> svc_agentLoop pkg_agent_presets --> svc_agentPresets @@ -329,7 +327,6 @@ flowchart LR svc_e2b --> pkg_fs_e2b svc_e2b --> pkg_subprocess_e2b svc_fs --> pkg_tool_fs - svc_inboxes --> pkg_agent_loop svc_invariants --> pkg_agent svc_invariants --> pkg_agent_loop svc_invariants --> pkg_scope @@ -429,7 +426,6 @@ flowchart LR | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Owns isolated per-session replay folds; pressure consumers share immutable revisioned measurements. | | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Rewrites oversized current tool results through replayable single-node surface replacements before summary compaction. | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), `subagent-inprocess`, [`invariants`](../packages/runtime-diagnostics/invariants), [`message-feedback`](../packages/feedback/message-feedback) | - | Owns append-only Session instances and emits the durable session event feed. | -| `ctx.inboxes` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop) | - | Registers the standard Inbox projection and creates command facades over its sole live state. | | `ctx.invariants` | `core` | [`invariants`](../packages/runtime-diagnostics/invariants) | - | [`session`](../packages/core/session), [`agent`](../packages/core/agent), [`scope`](../packages/core/scope), [`agent-loop`](../packages/core/agent-loop) | - | Companion subpaths register owner-local checks; the service owns selection, uniqueness, child fibers, and package-attributed failures. | | `ctx.typert` | `core` | [`typert-registry`](../packages/typert/registry) | - | [`typert-loader`](../packages/typert/loader), [`api-gateway`](../packages/api/gateway) | - | Plugins register live zod contributions directly or through dsh-typert-loader; the API gateway consumes invocation descriptors and providers, while other runtime consumers query schemas and reflection metadata at their own edges. | | `ctx.typertGateway` | `core` | [`api-gateway`](../packages/api/gateway) | - | - | - | Associates generated Remote descriptors with live Cordis services, resolves registered identities, and exposes unary calls through the shared Connection RPC carrier. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index a9eeb06c06..b6b0aba727 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -33,7 +33,6 @@ flowchart LR pkg_subagent_inprocess["subagent-inprocess"] pkg_invariants["invariants"] pkg_message_feedback["message-feedback"] - svc_inboxes["ctx.inboxes
Durable pending-input facade"] svc_invariants["ctx.invariants
Package-owned invariant registry"] pkg_scope["scope"] pkg_typert_registry["typert-registry"] @@ -204,7 +203,6 @@ flowchart LR svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] pkg_acp --> svc_approval pkg_agent --> svc_agents - pkg_agent --> svc_inboxes pkg_agent_default_model --> svc_agentDefaultModel pkg_agent_loop --> svc_agentLoop pkg_agent_presets --> svc_agentPresets @@ -331,7 +329,6 @@ flowchart LR svc_e2b --> pkg_fs_e2b svc_e2b --> pkg_subprocess_e2b svc_fs --> pkg_tool_fs - svc_inboxes --> pkg_agent_loop svc_invariants --> pkg_agent svc_invariants --> pkg_agent_loop svc_invariants --> pkg_scope @@ -431,7 +428,6 @@ flowchart LR | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 拥有按会话隔离的回放折叠区;压力消费方共享不可变且带修订版本的测量结果。 | | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 在摘要压缩前,通过可回放的单节点表层替换来改写过大的当前工具结果。 | | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), `subagent-inprocess`, [`invariants`](../packages/runtime-diagnostics/invariants), [`message-feedback`](../packages/feedback/message-feedback) | - | 拥有仅追加的 Session 实例,并发出持久的会话事件流。 | -| `ctx.inboxes` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop) | - | 注册标准 Inbox 投影,并在其唯一 live 状态上创建命令 facade。 | | `ctx.invariants` | `core` | [`invariants`](../packages/runtime-diagnostics/invariants) | - | [`session`](../packages/core/session), [`agent`](../packages/core/agent), [`scope`](../packages/core/scope), [`agent-loop`](../packages/core/agent-loop) | - | 配套子路径注册所属包本地的检查;该服务负责选择、唯一性、子 fiber,以及标明所属包的失败。 | | `ctx.typert` | `core` | [`typert-registry`](../packages/typert/registry) | - | [`typert-loader`](../packages/typert/loader), [`api-gateway`](../packages/api/gateway) | - | 插件直接或通过 dsh-typert-loader 注册实时 zod 贡献;API 网关消费调用描述符和提供方,其他运行时消费方则在各自边界查询 schema 与反射元数据。 | | `ctx.typertGateway` | `core` | [`api-gateway`](../packages/api/gateway) | - | - | - | 将生成的 Remote 描述符与实时 Cordis 服务关联,解析已注册的身份,并通过共享的 Connection RPC 载体提供一元调用。 | diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 41dc01f906..8070261be3 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: b35358c651454ed42a9c0cfd466f305c7d632e70 -config-catalog.zh.md: f6bb73d14e3da28e05628d7b1d7c29d053382f24 +config-catalog.md: 453065bec7ddc373627f9f632445db7e16b56f59 +config-catalog.zh.md: 2c2a9d84f051e79437493490af63cea70358c300 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index b35358c651..453065bec7 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -136,7 +136,7 @@ Source: [`packages/context/agent-instructions/src/config.ts:18`](../packages/con ## `@deepseek-ai/dsh-agent-loop` -Requires: `agents` · `inboxes` · `sessions` · `llm` · `tools` · `systemPrompt` +Requires: `agents` · `sessionProjections` · `sessions` · `llm` · `tools` · `systemPrompt` ```ts config-catalog /** Agent-loop plugin configuration. */ @@ -292,7 +292,7 @@ export interface GoalConfig { Depends on: [`AgentLoopConfig`](#deepseek-aidsh-agent-loop) · [`GoalDomainConfig`](#deepseek-aidsh-goal) · [`InvariantConfig`](#deepseek-aidsh-invariants) · [`JobsConfig`](#deepseek-aidsh-jobs-local) · [`SessionTitleConfig`](#deepseek-aidsh-session-title) · [`SkillFileSystem`](../packages/skill/skill-filesystem/src/index.ts) · [`SkillRegistryConfig`](#deepseek-aidsh-skill) · [`SystemPromptConfig`](#deepseek-aidsh-system-prompt) · [`toolBash`](../packages/shell/tool-bash/src/index.ts) · [`toolGoal`](../packages/goal/tool-goal/src/index.ts) · [`toolJobs`](../packages/jobs/tool-jobs/src/index.ts) · [`ToolsConfig`](#deepseek-aidsh-tools) · [`toolSkill`](../packages/skill/tool-skill/src/index.ts) · [`workspaceContext`](../packages/context/agent-instructions/src/index.ts) -Source: [`packages/examples/agent-spine-demo/src/index.ts:94`](../packages/examples/agent-spine-demo/src/index.ts) +Source: [`packages/examples/agent-spine-demo/src/index.ts:93`](../packages/examples/agent-spine-demo/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index f6bb73d14e..2c2a9d84f0 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -138,7 +138,7 @@ export interface Config { ## `@deepseek-ai/dsh-agent-loop` -需要:`agents` · `inboxes` · `sessions` · `llm` · `tools` · `systemPrompt` +需要:`agents` · `sessionProjections` · `sessions` · `llm` · `tools` · `systemPrompt` ```ts config-catalog /** Agent-loop plugin configuration. */ @@ -294,7 +294,7 @@ export interface GoalConfig { 依赖:[`AgentLoopConfig`](#deepseek-aidsh-agent-loop) · [`GoalDomainConfig`](#deepseek-aidsh-goal) · [`InvariantConfig`](#deepseek-aidsh-invariants) · [`JobsConfig`](#deepseek-aidsh-jobs-local) · [`SessionTitleConfig`](#deepseek-aidsh-session-title) · [`SkillFileSystem`](../packages/skill/skill-filesystem/src/index.ts) · [`SkillRegistryConfig`](#deepseek-aidsh-skill) · [`SystemPromptConfig`](#deepseek-aidsh-system-prompt) · [`toolBash`](../packages/shell/tool-bash/src/index.ts) · [`toolGoal`](../packages/goal/tool-goal/src/index.ts) · [`toolJobs`](../packages/jobs/tool-jobs/src/index.ts) · [`ToolsConfig`](#deepseek-aidsh-tools) · [`toolSkill`](../packages/skill/tool-skill/src/index.ts) · [`workspaceContext`](../packages/context/agent-instructions/src/index.ts) -来源:[`packages/examples/agent-spine-demo/src/index.ts:94`](../packages/examples/agent-spine-demo/src/index.ts) +来源:[`packages/examples/agent-spine-demo/src/index.ts:93`](../packages/examples/agent-spine-demo/src/index.ts) diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index 358a4e3b08..1d36b48b41 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/module-graph.md -module-graph.md: 4fa25899f83f2140a8e28af123ed5ff202a437e4 -module-graph.zh.md: ba604a3ee7462584cd2d2324ee90936502ee35f9 +module-graph.md: c9b0d3dd7305bf0444c777f21468c3baa27d12d9 +module-graph.zh.md: b3eaf5a47cb5267fcbaa45017ea932948eaec68d diff --git a/docs/module-graph.md b/docs/module-graph.md index 4fa25899f8..c9b0d3dd73 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -759,6 +759,7 @@ flowchart TD pkg_agent_loop --> pkg_scope pkg_agent_loop --> pkg_session pkg_agent_loop --> pkg_session_persistence + pkg_agent_loop --> pkg_session_projection pkg_agent_loop --> pkg_settings pkg_agent_loop --> pkg_system_prompt pkg_agent_loop --> pkg_tools @@ -1580,7 +1581,7 @@ flowchart TD | [`pwsh-sandbox`](../packages/shell/pwsh-sandbox) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`pwsh-local`](../packages/shell/pwsh-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | | [`terminal-bash`](../packages/terminal/terminal-bash) | `terminal` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`terminal`](../packages/terminal/terminal) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | -| [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`agent-tool-presentation`](../packages/core/agent-tool-presentation) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index ba604a3ee7..b3eaf5a47c 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -760,6 +760,7 @@ flowchart TD pkg_agent_loop --> pkg_scope pkg_agent_loop --> pkg_session pkg_agent_loop --> pkg_session_persistence + pkg_agent_loop --> pkg_session_projection pkg_agent_loop --> pkg_settings pkg_agent_loop --> pkg_system_prompt pkg_agent_loop --> pkg_tools @@ -1581,7 +1582,7 @@ flowchart TD | [`pwsh-sandbox`](../packages/shell/pwsh-sandbox) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`pwsh-local`](../packages/shell/pwsh-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | | [`terminal-bash`](../packages/terminal/terminal-bash) | `terminal` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`terminal`](../packages/terminal/terminal) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`compaction`](../packages/compaction/compaction), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | -| [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`agent-tool-presentation`](../packages/core/agent-tool-presentation) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 022720323d..ce3293a461 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/core.md -core.md: 6e919d02ac1c23cf4f49e92e5ce50a8983ac449d -core.zh.md: 853d9500cd7e51b02ec2f9595bd7f294f7b1d66f +core.md: b978cfdc102c93e0939dfc48c24947c45c96ee6f +core.zh.md: 0dfef5b75ef9273884afe6e038a83e7e5785d9bc diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 6e919d02ac..b978cfdc10 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -175,7 +175,7 @@ The inbox is the delivery vocabulary — two ordered pending-message lists the a type InboxTarget = 'next-turn' | 'next-step' ``` -Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. `Inbox.append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. `claim(target)` removes the proposed step batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without emitting discarded notifications, then Inbox emits per-message claimed notifications. `InboxService` registers the standard `inbox` projection; its registry cell is the sole live state and the same fold serves cold consumers. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. +Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. `Inbox.append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. `claim(target)` removes the proposed step batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without emitting discarded notifications, then Inbox emits per-message claimed notifications. `AgentRegistry` contributes the standard `inbox` projection whenever the projection registry is composed; its cell is the sole live state and the same fold serves cold consumers. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. Cancellation: @@ -720,24 +720,7 @@ list(): Agent[] roots(): Agent[] ``` -Source: [`packages/core/agent/src/index.ts:256`](../../packages/core/agent/src/index.ts) - - - -### `ctx.inboxes` — `InboxService` - -Root Inbox service: creates live inboxes and owns their durable projection. - -```ts cordis-catalog -/** - * Restore one live Inbox for an agent and publish its committed mutations. - * @param agent - agent that owns the durable session and live Inbox events. - * @returns the restored Inbox. - */ -create(agent: Agent): Inbox -``` - -Source: [`packages/core/agent/src/inbox.ts:25`](../../packages/core/agent/src/inbox.ts) +Source: [`packages/core/agent/src/index.ts:259`](../../packages/core/agent/src/index.ts) diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 853d9500cd..0dfef5b75e 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -179,7 +179,7 @@ inbox 即投递词汇——agent 以持久投影形式拥有的两条有序待 type InboxTarget = 'next-turn' | 'next-step' ``` -每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。`Inbox.append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。`claim(target)` 通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后由 Inbox 逐条发出 claimed 通知。`InboxService` 注册标准 `inbox` 投影;其注册表 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 +每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。`Inbox.append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。`claim(target)` 通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后由 Inbox 逐条发出 claimed 通知。`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 投影;其 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 取消: @@ -728,24 +728,7 @@ list(): Agent[] roots(): Agent[] ``` -Source: [`packages/core/agent/src/index.ts:256`](../../packages/core/agent/src/index.ts) - - - -### `ctx.inboxes` — `InboxService` - -Root Inbox service: creates live inboxes and owns their durable projection. - -```ts cordis-catalog -/** - * Restore one live Inbox for an agent and publish its committed mutations. - * @param agent - agent that owns the durable session and live Inbox events. - * @returns the restored Inbox. - */ -create(agent: Agent): Inbox -``` - -Source: [`packages/core/agent/src/inbox.ts:25`](../../packages/core/agent/src/inbox.ts) +Source: [`packages/core/agent/src/index.ts:259`](../../packages/core/agent/src/index.ts) diff --git a/examples/headless-agent/tests/code-mode.e2e.ts b/examples/headless-agent/tests/code-mode.e2e.ts index 64413599d6..cbab8b3f39 100644 --- a/examples/headless-agent/tests/code-mode.e2e.ts +++ b/examples/headless-agent/tests/code-mode.e2e.ts @@ -11,7 +11,6 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { RUN_CODE_NAME, defineTool } from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' @@ -56,7 +55,6 @@ async function codeModeHarness(cwd: string): Promise { await harness.plugin(LlmRuntime) await harness.plugin(SessionStore) await harness.plugin(SessionProjectionRegistry) - await harness.plugin(InboxService) await harness.plugin(SystemPrompt, { persona: PERSONA }) await harness.plugin(ToolRuntime, { mode: 'code' }) await harness.plugin(AgentRegistry) @@ -75,7 +73,6 @@ async function workspaceCodeModeHarness(): Promise { await harness.plugin(LlmRuntime) await harness.plugin(SessionStore) await harness.plugin(SessionProjectionRegistry) - await harness.plugin(InboxService) await harness.plugin(SystemPrompt, { persona: PERSONA }) await harness.plugin(ToolRuntime, { mode: 'code' }) await harness.plugin(AgentRegistry) diff --git a/examples/headless-agent/tests/fixtures/e2b/e2b/bin.ts b/examples/headless-agent/tests/fixtures/e2b/e2b/bin.ts index 9446fcb7b2..54e71feefd 100644 --- a/examples/headless-agent/tests/fixtures/e2b/e2b/bin.ts +++ b/examples/headless-agent/tests/fixtures/e2b/e2b/bin.ts @@ -1,7 +1,7 @@ import { readFile } from 'node:fs/promises' import { resolve } from 'node:path' import { boot } from '@deepseek-ai/dsh-app-boot' -import type { Agent } from '@deepseek-ai/dsh-agent' +import { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' import { Session, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-fs-e2b' import type {} from '@deepseek-ai/dsh-bash-local' @@ -30,7 +30,7 @@ const owner: Agent = { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } -Object.assign(owner, { inbox: ctx.inboxes.create(owner) }) +Object.assign(owner, { inbox: new Inbox(ctx, owner.session, agentEvents(ctx, owner)) }) const unregisterOwner = ctx.agents.register(owner) let terminalId: Awaited>['sessionId'] | undefined try { diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index 6e1656e3f3..e9567d9206 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -58,9 +58,6 @@ - id: agent name: '@deepseek-ai/dsh-agent' - - id: agent-inbox - name: '@deepseek-ai/dsh-agent/inbox' - # The transport-independent default for Agents created by entry points. # Settings may supply a saved selection; consumers read it at creation time. - id: agent-default-model diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index 6e69d8c5d3..3cfffe7d20 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -2,8 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent, AgentHandle, CreateAgentOptions } from '@deepseek-ai/dsh-agent' import AgentDefaultModelConfig from '@deepseek-ai/dsh-agent-default-model' import { createAssistantMessage } from '@deepseek-ai/dsh-llm' @@ -57,7 +56,6 @@ async function bench(script: Script): Promise<{ const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(AgentRegistry) await ctx.plugin(AgentDefaultModelConfig, { provider: 'test-provider', model: 'test-model' }) ctx.agents.setFactory({ @@ -86,7 +84,7 @@ async function bench(script: Script): Promise<{ inject: () => {}, whenIdle: () => idle, } satisfies Partial) - Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) + Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) await options.setup?.(agentCtx) script.before?.(session) ctx.agents.register(agent) diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index 178667dae1..b6cab01c38 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -7,8 +7,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import * as workspaceContext from '@deepseek-ai/dsh-agent-instructions' import LlmRuntime, { createUserMessage, CallId, type Message, type StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' +import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { FileSystem, FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs' @@ -52,7 +51,7 @@ const testToolSignal = new AbortController().signal const isolatedInboxCtx = new Context() await isolatedInboxCtx.plugin(SessionStore) await isolatedInboxCtx.plugin(SessionProjectionRegistry) -await isolatedInboxCtx.plugin(InboxService) +await isolatedInboxCtx.plugin(AgentRegistry) let nextStubSession = 1 async function tempRepo(): Promise { @@ -209,7 +208,7 @@ function stubAgent(cwd?: string, seed: SessionEvent[] = []): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: agentCtx.inboxes.create(agent) }) + Object.assign(agent, { inbox: new Inbox(agentCtx, agent.session, agentEvents(agentCtx, agent)) }) return agent } @@ -2523,7 +2522,6 @@ describe('dynamic nested workspace context injection', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index 581bf0ca8c..1c06c7fdee 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -51,7 +51,7 @@ function sessionAgent(session: Session, id = 'agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index 6f02f08e74..9a2066eb16 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -107,7 +107,7 @@ function sessionAgent(session: Session, id = 'agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/core/agent-loop/package.json b/packages/core/agent-loop/package.json index 76f7884b72..a5e615b30e 100644 --- a/packages/core/agent-loop/package.json +++ b/packages/core/agent-loop/package.json @@ -37,6 +37,7 @@ "@deepseek-ai/dsh-scope": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/cordis": "workspace:^", diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 1950195663..404ecdd7fe 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -11,12 +11,11 @@ import type { AgentOptions, AgentStatus, CancelOptions, - Inbox, InboxTarget, PreStepDecision, RequestErrorAction, } from '@deepseek-ai/dsh-agent' -import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' +import { Inbox, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm' import { BlockAssembler, @@ -85,7 +84,7 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, ) { this.dispatch = agentEvents(loopCtx, this) - this.inbox = loopCtx.inboxes.create(this) + this.inbox = new Inbox(loopCtx, session, this.dispatch) const lastTurn = session.events.findLast(event => event.type === 'turn/start')?.data.turn ?? 0 this.phase = { kind: 'idle', lastTurn } this.scope = createScope(loopCtx, this) diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 79bb469f25..6aad9745b6 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -294,7 +294,7 @@ function validateConfiguredAgents(agents: Config['agents']): void { /** Concrete agent factory and driver service. */ export class AgentLoop extends Service implements AgentFactory { - static inject = ['agents', 'inboxes', 'sessions', 'llm', 'tools', 'systemPrompt'] + static inject = ['agents', 'sessionProjections', 'sessions', 'llm', 'tools', 'systemPrompt'] /** Runtime schema for declarative agents. */ static Config = z.object({ diff --git a/packages/core/agent-loop/tests/agent-initiator.spec.ts b/packages/core/agent-loop/tests/agent-initiator.spec.ts index a5ca4cd36f..b69f5a6739 100644 --- a/packages/core/agent-loop/tests/agent-initiator.spec.ts +++ b/packages/core/agent-loop/tests/agent-initiator.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context, type Fiber } from '@deepseek-ai/cordis' @@ -24,7 +23,6 @@ async function harness(adapter: LlmAdapter): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) const agentsFiber = await ctx.plugin(AgentRegistry) @@ -126,7 +124,6 @@ describe('AgentLoop initiator scope', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -387,7 +384,6 @@ describe('AgentLoop initiator scope', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/agent.spec.ts b/packages/core/agent-loop/tests/agent.spec.ts index ea933ff374..4e6aa9b4df 100644 --- a/packages/core/agent-loop/tests/agent.spec.ts +++ b/packages/core/agent-loop/tests/agent.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { describe, expect, it, vi } from 'vitest' @@ -16,7 +15,6 @@ async function harness(adapter: MockAdapter): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index de44998536..58060a5cf9 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { CallId, createUserMessage } from '@deepseek-ai/dsh-llm' /** @@ -28,7 +27,6 @@ async function harness(adapter: MockAdapter) { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -674,7 +672,6 @@ describe('Agent.cancel()', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/config-session-id.spec.ts b/packages/core/agent-loop/tests/config-session-id.spec.ts index 5b043f6277..96c1d03022 100644 --- a/packages/core/agent-loop/tests/config-session-id.spec.ts +++ b/packages/core/agent-loop/tests/config-session-id.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -32,7 +31,6 @@ async function makeCoreContext(): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -332,7 +330,6 @@ describe('config-driven session id', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -359,7 +356,6 @@ describe('config-driven session id', () => { await ctx1.plugin(LlmRuntime) await ctx1.plugin(SessionStore) await ctx1.plugin(SessionProjectionRegistry) - await ctx1.plugin(InboxService) await ctx1.plugin(SystemPrompt) await ctx1.plugin(ToolRuntime) await ctx1.plugin(AgentRegistry) @@ -380,7 +376,6 @@ describe('config-driven session id', () => { await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) await ctx2.plugin(SessionProjectionRegistry) - await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -406,7 +401,6 @@ describe('config-driven session id', () => { await ctx1.plugin(LlmRuntime) await ctx1.plugin(SessionStore) await ctx1.plugin(SessionProjectionRegistry) - await ctx1.plugin(InboxService) await ctx1.plugin(SystemPrompt) await ctx1.plugin(ToolRuntime) await ctx1.plugin(AgentRegistry) @@ -424,7 +418,6 @@ describe('config-driven session id', () => { await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) await ctx2.plugin(SessionProjectionRegistry) - await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -451,7 +444,6 @@ describe('config-driven session id', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index a2b93a5fc0..cd30160999 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -33,7 +32,6 @@ async function harness(adapter: MockAdapter) { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -530,7 +528,6 @@ describe('turn numbering continues across seeded sessions', () => { await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) await ctx2.plugin(SessionProjectionRegistry) - await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -683,7 +680,6 @@ describe('turn and step boundary recovery', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1117,7 +1113,6 @@ describe('disposal and cancellation during pre-step assembly', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1169,7 +1164,6 @@ describe('disposal and cancellation during pre-step assembly', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1221,7 +1215,6 @@ describe('disposal and cancellation during pre-step assembly', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1269,7 +1262,6 @@ describe('disposal and cancellation during pre-step assembly', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1319,7 +1311,6 @@ describe('disposal and cancellation during pre-step assembly', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/coverage-edges.spec.ts b/packages/core/agent-loop/tests/coverage-edges.spec.ts index 85cc720fed..6fc28f6400 100644 --- a/packages/core/agent-loop/tests/coverage-edges.spec.ts +++ b/packages/core/agent-loop/tests/coverage-edges.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -21,7 +20,6 @@ async function harness(adapter: MockAdapter) { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/interception.spec.ts b/packages/core/agent-loop/tests/interception.spec.ts index 60a3be7d01..5116c778ce 100644 --- a/packages/core/agent-loop/tests/interception.spec.ts +++ b/packages/core/agent-loop/tests/interception.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -34,7 +33,6 @@ async function harness(adapter: MockAdapter) { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index 7515e88c91..5c23522f16 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -20,7 +19,6 @@ async function harness(adapter: MockAdapter, persona = '') { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1454,7 +1452,6 @@ describe('agent loop', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -1480,7 +1477,6 @@ describe('agent loop', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/properties.spec.ts b/packages/core/agent-loop/tests/properties.spec.ts index 90e733c19a..87755f646b 100644 --- a/packages/core/agent-loop/tests/properties.spec.ts +++ b/packages/core/agent-loop/tests/properties.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** * Property-based tests for the agent loop's inbox/turn scheduling (the @@ -42,7 +41,6 @@ async function harness() { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/request-cache.e2e.ts b/packages/core/agent-loop/tests/request-cache.e2e.ts index a14c5f4bae..64394855f0 100644 --- a/packages/core/agent-loop/tests/request-cache.e2e.ts +++ b/packages/core/agent-loop/tests/request-cache.e2e.ts @@ -6,7 +6,6 @@ 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 } from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' @@ -44,7 +43,6 @@ async function loopHarness(): Promise { await created.plugin(LlmRuntime) await created.plugin(SessionStore) await created.plugin(SessionProjectionRegistry) - await created.plugin(InboxService) await created.plugin(SystemPrompt, { persona: SYSTEM }) await created.plugin(ToolRuntime) await created.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/request-error.spec.ts b/packages/core/agent-loop/tests/request-error.spec.ts index 776280765b..c947530b3c 100644 --- a/packages/core/agent-loop/tests/request-error.spec.ts +++ b/packages/core/agent-loop/tests/request-error.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' @@ -16,7 +15,6 @@ async function harness(adapter: MockAdapter): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/request-reconstruction.spec.ts b/packages/core/agent-loop/tests/request-reconstruction.spec.ts index 1b178a127f..dacca2f424 100644 --- a/packages/core/agent-loop/tests/request-reconstruction.spec.ts +++ b/packages/core/agent-loop/tests/request-reconstruction.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** * Loop-level reconstructability: every request the loop sends is a pure function of the @@ -31,7 +30,6 @@ async function harnessRoutes( await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -260,7 +258,6 @@ describe('request stability across the loop', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: 'stable base' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -380,7 +377,6 @@ describe('request stability across the loop', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: 'stable base' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/resume.spec.ts b/packages/core/agent-loop/tests/resume.spec.ts index d1278f77cf..4a6dfb7b01 100644 --- a/packages/core/agent-loop/tests/resume.spec.ts +++ b/packages/core/agent-loop/tests/resume.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -31,7 +30,6 @@ async function mountPersistentHarness(root: string, adapter: MockAdapter): Promi await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -249,7 +247,6 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) await ctx2.plugin(SessionProjectionRegistry) - await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -279,7 +276,6 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) await ctx2.plugin(SessionProjectionRegistry) - await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -531,7 +527,6 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -596,7 +591,6 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) await ctx2.plugin(SessionProjectionRegistry) - await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -630,7 +624,6 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) await ctx2.plugin(SessionProjectionRegistry) - await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -668,7 +661,6 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', await ctx2.plugin(LlmRuntime) await ctx2.plugin(SessionStore) await ctx2.plugin(SessionProjectionRegistry) - await ctx2.plugin(InboxService) await ctx2.plugin(SystemPrompt) await ctx2.plugin(ToolRuntime) await ctx2.plugin(AgentRegistry) @@ -703,7 +695,6 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume', await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -894,7 +885,6 @@ describe('configured-start failure edges', () => { await configured.plugin(LlmRuntime) await configured.plugin(SessionStore) await configured.plugin(SessionProjectionRegistry) - await configured.plugin(InboxService) await configured.plugin(SystemPrompt) await configured.plugin(ToolRuntime) await configured.plugin(AgentRegistry) @@ -941,7 +931,6 @@ describe('configured-start failure edges', () => { await configured.plugin(LlmRuntime) await configured.plugin(SessionStore) await configured.plugin(SessionProjectionRegistry) - await configured.plugin(InboxService) await configured.plugin(SystemPrompt) await configured.plugin(ToolRuntime) await configured.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts index 9e7e441665..25fa383261 100644 --- a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { describe, expect, it } from 'vitest' @@ -20,7 +19,6 @@ async function harnessWithLoop(adapter: MockAdapter = new MockAdapter([textRespo await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: 'You are the deployment.' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/settings.spec.ts b/packages/core/agent-loop/tests/settings.spec.ts index 5f0f98d5a9..d88182a674 100644 --- a/packages/core/agent-loop/tests/settings.spec.ts +++ b/packages/core/agent-loop/tests/settings.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** The `agent-loop` settings section layered over the composition entry. */ @@ -37,7 +36,6 @@ async function boot(): Promise<{ ctx: Context; settingsFiber: Fiber; loopFiber: await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent-loop/tests/tool-calls.spec.ts b/packages/core/agent-loop/tests/tool-calls.spec.ts index 276838654e..8aaa99fd0f 100644 --- a/packages/core/agent-loop/tests/tool-calls.spec.ts +++ b/packages/core/agent-loop/tests/tool-calls.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' /** * Exercises scheduler ordering and cancellation with deterministic gated tools. @@ -23,7 +22,6 @@ async function harness(adapter: MockAdapter, maxParallelToolCalls?: number) { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -283,7 +281,6 @@ describe('tool-call scheduler: rolling pool honors maxParallelToolCalls', () => await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -353,7 +350,6 @@ describe('tool-call scheduler: rolling pool honors maxParallelToolCalls', () => await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -713,7 +709,6 @@ describe('code-mode native-tool denial through the agent loop', () => { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime, { mode: 'code' }) // eslint-disable-next-line @typescript-eslint/no-explicit-any -- FakeCodeRuntime is an internal test helper with an opaque type shape diff --git a/packages/core/agent-loop/tests/tool-order.spec.ts b/packages/core/agent-loop/tests/tool-order.spec.ts index da9d59d6e0..d0e4bd29d6 100644 --- a/packages/core/agent-loop/tests/tool-order.spec.ts +++ b/packages/core/agent-loop/tests/tool-order.spec.ts @@ -1,4 +1,3 @@ -import InboxService from '@deepseek-ai/dsh-agent/inbox' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage } from '@deepseek-ai/dsh-llm' /** @@ -26,7 +25,6 @@ async function harness(adapter: MockAdapter, toolOrder?: SystemPromptConfig['too await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: 'stable base', ...toolOrder !== undefined ? { toolOrder } : {} }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 07b8e54cc2..08c110f474 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent/README.md -README.md: 6af7e57bdb0ae710a6d1e6e58ca2ac187a45eeb8 -README.zh.md: 1533f918e037c7dc7d131c7046d25fc259d33580 +README.md: aeddc6caf24289333a3e5b0f9b29124b1e591316 +README.zh.md: f815283ba638f0374ae30d8a8c3fe4ce6a66968b diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 6af7e57bdb..aeddc6caf2 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -54,7 +54,7 @@ Most interception points are cooperative waterfalls. `agent/pre-step` receives a `PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages }`. The enter branch is the complete identified, frozen batch for the proposed step. A listener that wraps downstream entry preserves that batch unless it intentionally replaces it; additions follow the waterfall's natural return order. Claiming already removed the offered messages from the inbox, so rejection does not retain them. Messages inserted after the claim remain pending for a later boundary. -`InboxService` owns the standard `inbox` session projection. The projection registry folds durable `agent/inbox/spliced` events once and remains the sole owner of the live `{ 'next-turn', 'next-step' }` state; Inbox is a command facade that reads the registry snapshot rather than replaying or copying the fold. Inbox live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. Inbox emits them as it commits the corresponding mutation, without adding another lifecycle envelope. +`AgentRegistry` contributes the standard `inbox` session projection whenever the projection registry is composed. The registry folds durable `agent/inbox/spliced` events once and remains the sole owner of the live `{ 'next-turn', 'next-step' }` state; Inbox is a command facade that reads that unit rather than replaying or copying the fold. Inbox live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. Inbox emits them as it commits the corresponding mutation, without adding another lifecycle envelope. Turn and step boundaries and the model token stream are durable `session/event` facts rather than mirrored `agent/*` notifications. Consumers read `turn/*`, `step/*`, and `assistant/chunk` from the session feed; tool policy and outcome observation belong to the complete pipeline documented by [`dsh-tools`](../tools/README.md). diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index 1533f918e0..f815283ba6 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -54,7 +54,7 @@ Agent *创建* 由实现 `AgentFactory` 的插件(`dsh-agent-loop`)提供, `PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages }`。enter 分支是拟进入步骤的完整、带标识且冻结的批次。包装下游 enter 的监听器会保留该批次,除非有意替换它;新增消息遵循 waterfall 的自然返回顺序。领取操作已经把候选消息从 inbox 删除,因此 reject 不会保留它们;领取后插入的消息仍等待后续边界。 -`InboxService` 拥有标准 `inbox` 会话投影。投影注册表只折叠一次持久 `agent/inbox/spliced` 事件,并继续作为 live `{ 'next-turn', 'next-step' }` 状态的唯一所有者;Inbox 是读取注册表快照的命令 facade,不会重新回放或复制折叠结果。Inbox 的实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。Inbox 在提交对应变更时自行发出这些通知,不引入另一层生命周期封套。 +`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 会话投影。注册表只折叠一次持久 `agent/inbox/spliced` 事件,并继续作为 live `{ 'next-turn', 'next-step' }` 状态的唯一所有者;Inbox 是读取该单元的命令 facade,不会重新回放或复制折叠结果。Inbox 的实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。Inbox 在提交对应变更时自行发出这些通知,不引入另一层生命周期封套。 轮次和步骤边界以及模型 token 流是持久 `session/event` 事实,而不是镜像的 `agent/*` 通知。消费方从会话事件流读取 `turn/*`、`step/*` 和 `assistant/chunk`;工具策略与结果观测属于 [`dsh-tools`](../tools/README.md) 记录的完整流水线。 diff --git a/packages/core/agent/package.json b/packages/core/agent/package.json index 1af7dfbe7d..e056207c36 100644 --- a/packages/core/agent/package.json +++ b/packages/core/agent/package.json @@ -18,14 +18,6 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, - "./inbox": { - "types": "./lib/types/inbox.d.ts", - "default": "./lib/types/inbox.js" - }, - "./inbox-projection": { - "types": "./lib/types/inbox-projection.d.ts", - "default": "./lib/types/inbox-projection.js" - }, "./invariant": { "types": "./lib/types/invariant.d.ts", "default": "./lib/invariant.js" diff --git a/packages/core/agent/src/inbox-projection.ts b/packages/core/agent/src/inbox-projection.ts index 24602d17a7..752bf01593 100644 --- a/packages/core/agent/src/inbox-projection.ts +++ b/packages/core/agent/src/inbox-projection.ts @@ -1,6 +1,7 @@ /** Inbox projection schema and its inferred wire value. */ import type { UserMessage } from '@deepseek-ai/dsh-llm/types' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' import { z } from 'zod' /** Wire validation for pending agent input reconstructed from durable inbox splices. */ @@ -12,6 +13,30 @@ export const inboxProjectionSchema = z.object({ /** Complete pending Inbox value reconstructed from durable splices. */ export type InboxState = z.infer +/** Standard fold that reconstructs pending agent input from durable splices. */ +export const inboxProjectionDefinition = { + key: 'inbox', + stateSchema: inboxProjectionSchema, + init: (): InboxState => ({ 'next-turn': [], 'next-step': [] }), + apply(state: InboxState, event) { + if (event.type !== 'agent/inbox/spliced') return state + const splice = event.data + const next = state[splice.target].toSpliced( + splice.start, + splice.removedCount ?? 0, + ...splice.inserted, + ) + return splice.target === 'next-turn' + ? { 'next-turn': next, 'next-step': state['next-step'] } + : { 'next-turn': state['next-turn'], 'next-step': next } + }, + wire: { + viewSchema: inboxProjectionSchema, + view: (state: InboxState) => state, + }, + stateVersion: 1, +} satisfies ProjectionDefinition<'inbox', InboxState> + declare module '@deepseek-ai/dsh-session-projection/types' { interface SessionProjectionMap { /** Pending agent input reconstructed from durable inbox splices. */ diff --git a/packages/core/agent/src/inbox.ts b/packages/core/agent/src/inbox.ts index 8f25da7f3a..2ffc4bed39 100644 --- a/packages/core/agent/src/inbox.ts +++ b/packages/core/agent/src/inbox.ts @@ -1,70 +1,25 @@ /** - * Incremental projection of durable agent inbox events. + * Command facade over the durable agent Inbox projection. * * @module @deepseek-ai/dsh-agent/inbox */ -import { Context, Service } from '@deepseek-ai/cordis' +import type { Context } from '@deepseek-ai/cordis' import type { MessageId } from '@deepseek-ai/dsh-llm' -import type { SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' -import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' -import { agentEvents } from './dispatch.ts' +// Type-only: resolves ctx.sessionProjections for the required Inbox projection. +import type {} from '@deepseek-ai/dsh-session-projection' +import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' import type { AgentEventDispatch } from './dispatch.ts' -import { inboxProjectionSchema } from './inbox-projection.ts' import type { InboxState } from './inbox-projection.ts' -import type { Agent } from './runtime-types.ts' import type { InboxTarget } from './types.ts' -declare module '@deepseek-ai/cordis' { - interface Context { - inboxes: InboxService - } -} - -/** Root Inbox service: creates live inboxes and owns their durable projection. */ -export class InboxService extends Service { - static inject = ['sessionProjections'] - - constructor(ctx: Context) { - super(ctx, 'inboxes') - ctx.sessionProjections.register({ - key: 'inbox', - schema: inboxProjectionSchema, - init: () => ({ 'next-turn': [], 'next-step': [] }), - apply(state, event) { - if (event.type !== 'agent/inbox/spliced') return state - const splice = event.data - const next = state[splice.target].toSpliced( - splice.start, - splice.removedCount ?? 0, - ...splice.inserted, - ) - return splice.target === 'next-turn' - ? { 'next-turn': next, 'next-step': state['next-step'] } - : { 'next-turn': state['next-turn'], 'next-step': next } - }, - view: state => state, - stateVersion: 1, - } satisfies ProjectionDefinition<'inbox', InboxState>) - } - - /** - * Restore one live Inbox for an agent and publish its committed mutations. - * @param agent - agent that owns the durable session and live Inbox events. - * @returns the restored Inbox. - */ - create(agent: Agent): Inbox { - return new Inbox(this.ctx, agent) - } -} - /** Agent-owned command facade over the standard durable Inbox projection. */ export class Inbox { - private readonly dispatch: AgentEventDispatch - - constructor(private readonly ctx: Context, private readonly agent: Agent) { - this.dispatch = agentEvents(ctx, agent) - } + constructor( + private readonly ctx: Context, + private readonly session: Session, + private readonly dispatch: AgentEventDispatch, + ) {} /** Prompts awaiting individual turns. */ get nextTurn(): readonly UserMessage[] { @@ -171,11 +126,11 @@ export class Inbox { return undefined } - /** Read the current durable projection value. */ + /** Read the current durable projection state. */ private current(): InboxState { - // InboxService registers this required projection before creating an Inbox. + // AgentLoop requires sessionProjections; AgentRegistry contributes this unit to it. // oxlint-disable-next-line typescript/no-non-null-assertion - return this.ctx.sessionProjections.snapshot(this.agent.session).values.inbox! + return this.ctx.sessionProjections.stateOf(this.session, 'inbox')! } /** Commit one normalized mutation and publish its live events. */ @@ -216,7 +171,7 @@ export class Inbox { ...(outcome === undefined ? {} : { outcome }), } const removed = inbox.slice(actualStart, actualStart + actualDeleteCount) - const event = this.agent.session.append('agent/inbox/spliced', splice) + const event = this.session.append('agent/inbox/spliced', splice) if (discardRemoved) { for (const message of removed) this.dispatch.emit('agent/inbox/discarded', { message }) } @@ -226,5 +181,3 @@ export class Inbox { return removed } } - -export default InboxService diff --git a/packages/core/agent/src/index.ts b/packages/core/agent/src/index.ts index 81052096dc..22111e437b 100644 --- a/packages/core/agent/src/index.ts +++ b/packages/core/agent/src/index.ts @@ -12,7 +12,10 @@ import { isPromise } from 'node:util/types' import { scopeTarget } from '@deepseek-ai/dsh-scope' import type { Scoped } from '@deepseek-ai/dsh-scope' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' +// Type-only: resolves ctx.sessionProjections for the optional Inbox projection contribution. +import type {} from '@deepseek-ai/dsh-session-projection' import type { TypertContext, TypertLookup } from '@deepseek-ai/dsh-typert-protocol' +import { inboxProjectionDefinition } from './inbox-projection.ts' import type { Agent, AgentOptions } from './runtime-types.ts' export * from './runtime-types.ts' @@ -265,6 +268,9 @@ export class AgentRegistry extends Service { constructor(ctx: Context) { super(ctx, 'agents') + ctx.inject(['sessionProjections'], (projectionCtx) => { + projectionCtx.sessionProjections.register(inboxProjectionDefinition) + }) ctx.inject(['typert'], (typeCtx) => { typeCtx.typert.lookups.register('agent', { parameter: 'agent', diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index af25e7e870..293ed93e67 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -4,10 +4,9 @@ import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session' import AgentRegistry, { agentEvents, - InboxService, + Inbox, } from '@deepseek-ai/dsh-agent' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' -import type {} from '@deepseek-ai/dsh-agent/inbox-projection' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import type { @@ -48,10 +47,10 @@ async function inboxAgent(rawId: string): Promise<{ ctx: Context; session: Sessi const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) + await ctx.plugin(AgentRegistry) const session = ctx.sessions.create(SessionId(rawId)) const agent = stubAgent(rawId, { ctx, session }) - Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) + Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) return { ctx, session, agent } } @@ -65,7 +64,7 @@ describe('Inbox', () => { parentAgent.inbox.append('next-turn', inherited) const child = ctx.sessions.fork(parent, undefined, SessionId('inbox-fork-child')) const childAgent = stubAgent('inbox-fork-child', { ctx, session: child }) - Object.assign(childAgent, { inbox: ctx.inboxes.create(childAgent) }) + Object.assign(childAgent, { inbox: new Inbox(ctx, childAgent.session, agentEvents(ctx, childAgent)) }) expect(child.header.seedLength).toBe(parent.events.length) expect(childAgent.inbox.nextTurn).toEqual([inherited]) @@ -169,15 +168,15 @@ describe('Inbox', () => { expect(session.events).toHaveLength(beforeClear + 2) }) - it('registers the durable Inbox projection from the Inbox service', async () => { + it('registers the durable Inbox projection from the Agent registry', async () => { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - const inboxFiber = ctx.plugin(InboxService) - await inboxFiber + const agentFiber = ctx.plugin(AgentRegistry) + await agentFiber const session = ctx.sessions.create(SessionId('inbox-projection')) const agent = stubAgent('inbox-projection', { ctx, session }) - Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) + Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) const pending = createUserMessage({ content: [{ type: 'text', text: 'pending' }], source: { kind: 'user' }, @@ -189,7 +188,7 @@ describe('Inbox', () => { 'next-turn': [pending], 'next-step': [], }) - await inboxFiber.dispose() + await agentFiber.dispose() expect(ctx.sessionProjections.snapshot(session).values).toEqual({}) }) diff --git a/packages/e2b/e2b/tests/composition.e2e.ts b/packages/e2b/e2b/tests/composition.e2e.ts index 5b17a19dbd..305aa1cb66 100644 --- a/packages/e2b/e2b/tests/composition.e2e.ts +++ b/packages/e2b/e2b/tests/composition.e2e.ts @@ -3,7 +3,7 @@ import { join, posix } from 'node:path' import { fileURLToPath } from 'node:url' import { Context } from '@deepseek-ai/cordis' import { describe, expect, it } from 'vitest' -import { Inbox } from '@deepseek-ai/dsh-agent' +import { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' import { @@ -96,7 +96,7 @@ describe.skipIf(!process.env.E2B_API_KEY)('E2B live Loader composition', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(owner, { inbox: new Inbox(owner.ctx, owner) }) + Object.assign(owner, { inbox: new Inbox(owner.ctx, owner.session, agentEvents(owner.ctx, owner)) }) const backend = new BashTerminalBackend(ctx, { backendType: 'shell', shellDialect: 'bash', shellPath: '/bin/bash', shellArgs: ['--noprofile', '--norc', '-i'], rows: 24, cols: 80, diff --git a/packages/examples/agent-spine-demo/src/index.ts b/packages/examples/agent-spine-demo/src/index.ts index 4cf542540b..f67efff4bb 100644 --- a/packages/examples/agent-spine-demo/src/index.ts +++ b/packages/examples/agent-spine-demo/src/index.ts @@ -20,7 +20,6 @@ import ToolRuntime, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools' import SkillRegistry, { type Config as SkillRegistryConfig } from '@deepseek-ai/dsh-skill' import * as SkillFileSystem from '@deepseek-ai/dsh-skill-filesystem' import AgentRegistry from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import GoalService, { type Config as GoalDomainConfig } from '@deepseek-ai/dsh-goal' import * as goalSession from '@deepseek-ai/dsh-goal-round-driver' import * as toolGoal from '@deepseek-ai/dsh-tool-goal' @@ -238,7 +237,6 @@ export function apply(ctx: Context, config: Config): void { ctx.plugin(SkillFileSystem, Object.assign({}, config.skills?.filesystem, { dshHome })) } ctx.plugin(AgentRegistry) - ctx.plugin(InboxService) ctx.plugin(llmRetry) if (config.goals !== undefined && config.goals !== false) { ctx.plugin(GoalService, config.goals.domain ?? {}) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 739fc69a2a..86e722f825 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -807,19 +807,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, - { - key: 'inboxes', - summary: 'Root Inbox service: creates live inboxes and owns their durable projection.', - description: 'Root Inbox service: creates live inboxes and owns their durable projection.', - methods: [ - { - signature: 'create(agent: Agent): Inbox', - description: 'Restore one live Inbox for an agent and publish its committed mutations.', - parameters: [{ name: 'agent', description: 'agent that owns the durable session and live Inbox events.' }], - returns: 'the restored Inbox.', - }, - ], - }, { key: 'invariants', summary: 'Package-owned invariant registry with global and regex-based selection.', @@ -2762,6 +2749,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AgentCancelCause', declaration: 'export type AgentCancelCause = {\n readonly kind: \'user\';\n} | {\n readonly kind: \'parent\';\n} | {\n readonly kind: \'hook\';\n readonly reason: string;\n} | {\n readonly kind: \'disposed\';\n};', }, + { + name: 'AgentEventDispatch', + declaration: 'export interface AgentEventDispatch {\n emit(name: K, payload: PayloadRest): void;\n serial(name: K, payload: PayloadRest): Promise>>;\n waterfall(name: K, payload: PayloadRest, ...rest: Tail): Return;\n}', + }, { name: 'AgentFactory', declaration: 'export interface AgentFactory {\n createAgent(ownerCtx: Context, options: CreateAgentOptions): Promise;\n resume(ownerCtx: Context, options: ResumeAgentOptions): Promise;\n}', @@ -2790,6 +2781,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AgentStatus', declaration: 'export type AgentStatus = \'idle\' | \'running\';', }, + { + name: 'AgentSubjectEvent', + declaration: 'export type AgentSubjectEvent = {\n [K in keyof Events]: Events[K] extends (this: Scoped, ...args: infer P) => unknown ? P extends [\n infer Payload,\n ...unknown[]\n ] ? Payload extends {\n agent: Agent;\n } ? K : never : never : never;\n}[keyof Events];', + }, { name: 'ApprovalOutcome', declaration: 'export type ApprovalOutcome = \'allowed-once\' | \'rejected\' | \'cancelled\' | \'unavailable\';', @@ -3300,7 +3295,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Inbox', - declaration: 'export class Inbox {\n constructor(private readonly ctx: Context, private readonly agent: Agent);\n get nextTurn(): readonly UserMessage[];\n get nextStep(): readonly UserMessage[];\n get hasPending(): boolean;\n clear(): void;\n claim(target: InboxTarget, turn: number): UserMessage[];\n append(target: InboxTarget, message: UserMessage): void;\n prepend(target: InboxTarget, message: UserMessage): void;\n replace(messageId: MessageId, newMessage: UserMessage): boolean;\n remove(messageId: MessageId): boolean;\n splice(target: InboxTarget, start: number, deleteCount: number, inserted: UserMessage[]): UserMessage[];\n}', + declaration: 'export class Inbox {\n constructor(private readonly ctx: Context, private readonly session: Session, private readonly dispatch: AgentEventDispatch);\n get nextTurn(): readonly UserMessage[];\n get nextStep(): readonly UserMessage[];\n get hasPending(): boolean;\n clear(): void;\n claim(target: InboxTarget, turn: number): UserMessage[];\n append(target: InboxTarget, message: UserMessage): void;\n prepend(target: InboxTarget, message: UserMessage): void;\n replace(messageId: MessageId, newMessage: UserMessage): boolean;\n remove(messageId: MessageId): boolean;\n splice(target: InboxTarget, start: number, deleteCount: number, inserted: UserMessage[]): UserMessage[];\n}', }, { name: 'InboxTarget', diff --git a/packages/feedback/command-feedback/tests/command-feedback.spec.ts b/packages/feedback/command-feedback/tests/command-feedback.spec.ts index 4f58bfbdc7..90c48ffa96 100644 --- a/packages/feedback/command-feedback/tests/command-feedback.spec.ts +++ b/packages/feedback/command-feedback/tests/command-feedback.spec.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import SessionStore, { foldSurface, Session, SessionId } from '@deepseek-ai/dsh-session' @@ -59,7 +59,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return { agent, session } } diff --git a/packages/feedback/command-feedback/tests/loader-composition.spec.ts b/packages/feedback/command-feedback/tests/loader-composition.spec.ts index 4f01449b15..831481a702 100644 --- a/packages/feedback/command-feedback/tests/loader-composition.spec.ts +++ b/packages/feedback/command-feedback/tests/loader-composition.spec.ts @@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' @@ -45,7 +45,7 @@ function agent(ctx: Context): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value) }) + Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } 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 69d931673a..eb1aece0c3 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -6,7 +6,7 @@ import { Context } from '@deepseek-ai/cordis' import { FsVersion } from '@deepseek-ai/dsh-fs' import { CallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import * as FsPolicy from '@deepseek-ai/dsh-fs-observation-policy' @@ -44,7 +44,7 @@ function agent(ctx: Context, cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value) }) + Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index d03054b717..ec139886ee 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import GoalService from '@deepseek-ai/dsh-goal' @@ -36,7 +36,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return { agent, session } } diff --git a/packages/goal/goal/tests/goal.spec.ts b/packages/goal/goal/tests/goal.spec.ts index 8d664dbe9c..6888c4eacc 100644 --- a/packages/goal/goal/tests/goal.spec.ts +++ b/packages/goal/goal/tests/goal.spec.ts @@ -1,7 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage, HarnessError } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session' @@ -22,7 +21,7 @@ interface StubAgent { const isolatedInboxCtx = new Context() await isolatedInboxCtx.plugin(SessionStore) await isolatedInboxCtx.plugin(SessionProjectionRegistry) -await isolatedInboxCtx.plugin(InboxService) +await isolatedInboxCtx.plugin(AgentRegistry) const sessionStubs = new WeakMap() /** Number the next balanced test-fixture turn. */ @@ -59,7 +58,7 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: agentCtx.inboxes.create(agent) }) + Object.assign(agent, { inbox: new Inbox(agentCtx, agent.session, agentEvents(agentCtx, agent)) }) const stub = { agent, session, @@ -84,7 +83,6 @@ async function harness(config: { defaultMaxGoalRounds?: number } = {}) { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService, config) const stub = stubAgent(`goal-test-${Math.random()}`) @@ -195,7 +193,6 @@ describe('GoalService creation and replay', () => { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService) const parent = stubAgentForSession(ctx.sessions.create(SessionId('goal-fork-parent')), ctx) @@ -451,7 +448,6 @@ describe('GoalService mutations', () => { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService) const stub = stubAgentForSession(ctx.sessions.create(SessionId('goal-reentrant-observer')), ctx) diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index 7e25c3f5b7..d538fcc4f8 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -1,8 +1,7 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import GoalService, { GoalId } from '@deepseek-ai/dsh-goal' import type { GoalRef } from '@deepseek-ai/dsh-goal' @@ -26,7 +25,7 @@ interface StubAgent { const isolatedInboxCtx = new Context() await isolatedInboxCtx.plugin(SessionStore) await isolatedInboxCtx.plugin(SessionProjectionRegistry) -await isolatedInboxCtx.plugin(InboxService) +await isolatedInboxCtx.plugin(AgentRegistry) /** Build one registry-compatible live agent whose injections enter the durable inbox. */ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): StubAgent { @@ -55,7 +54,7 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: agentCtx.inboxes.create(agent) }) + Object.assign(agent, { inbox: new Inbox(agentCtx, agent.session, agentEvents(agentCtx, agent)) }) return { agent, session, setStatus(value) { status = value } } } @@ -87,7 +86,6 @@ async function harness(config: toolGoal.Config = {}) { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(AgentRegistry) await ctx.plugin(ToolRuntime) diff --git a/packages/host/apiproxy/tests/api-proxy-projections.spec.ts b/packages/host/apiproxy/tests/api-proxy-projections.spec.ts index 0f290621cd..e94dbb420d 100644 --- a/packages/host/apiproxy/tests/api-proxy-projections.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-projections.spec.ts @@ -10,9 +10,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { z } from 'zod' -import AgentRegistry from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' -import type {} from '@deepseek-ai/dsh-agent/inbox-projection' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import { AttachmentStore } from '@deepseek-ai/dsh-attachment' import type { Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' @@ -71,7 +69,6 @@ async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: await ctx.plugin(AgentRegistry) if (withRegistry) { await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) } const session = ctx.sessions.create() const agent = { @@ -89,7 +86,7 @@ async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } satisfies Agent - if (withRegistry) Object.assign(agent, { inbox: ctx.inboxes.create(agent) }) + if (withRegistry) Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) ctx.agents.register(agent) return { ctx, session } } diff --git a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts index 6019da820a..9e63b7a3db 100644 --- a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts @@ -3,7 +3,7 @@ import { homedir, tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent, AgentFactory } from '@deepseek-ai/dsh-agent' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' @@ -55,7 +55,7 @@ function stubAgent(session: Session): Agent { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/jobs/jobs-local/tests/jobs.spec.ts b/packages/jobs/jobs-local/tests/jobs.spec.ts index b333b87222..ce7f2347dc 100644 --- a/packages/jobs/jobs-local/tests/jobs.spec.ts +++ b/packages/jobs/jobs-local/tests/jobs.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, expectTypeOf, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { bindScopeParent, createScope, scopeOf } from '@deepseek-ai/dsh-scope' import type { ScopeKey } from '@deepseek-ai/dsh-scope' @@ -45,7 +45,7 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { runMaintenance: (job: (signal: AbortSignal) => Promise) => job(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) agentScopeDisposers.set(agent, async () => { await scopeFiber.dispose() }) return agent } diff --git a/packages/llm/llm-retry/tests/loader-composition.spec.ts b/packages/llm/llm-retry/tests/loader-composition.spec.ts index 7d869af764..b4bef4c239 100644 --- a/packages/llm/llm-retry/tests/loader-composition.spec.ts +++ b/packages/llm/llm-retry/tests/loader-composition.spec.ts @@ -7,7 +7,6 @@ import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import AgentRegistry from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import LlmRuntime, { createUserMessage, LlmAdapter, LlmError, resolveRetryPolicy } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, ResolvedRetryPolicy, StreamChunk } from '@deepseek-ai/dsh-llm' @@ -66,7 +65,6 @@ async function loadYaml(lines: readonly string[]): Promise { ['@deepseek-ai/dsh-system-prompt', SystemPrompt], ['@deepseek-ai/dsh-tools', ToolRuntime], ['@deepseek-ai/dsh-agent', AgentRegistry], - ['@deepseek-ai/dsh-agent/inbox', InboxService], ['@deepseek-ai/dsh-llm-retry', retry], ['@deepseek-ai/dsh-agent-loop', AgentLoop], ]) @@ -97,7 +95,6 @@ describe('real Loader composition', () => { "- name: '@deepseek-ai/dsh-system-prompt'", "- name: '@deepseek-ai/dsh-tools'", "- name: '@deepseek-ai/dsh-agent'", - "- name: '@deepseek-ai/dsh-agent/inbox'", "- name: '@deepseek-ai/dsh-llm-retry'", "- name: '@deepseek-ai/dsh-agent-loop'", ]) diff --git a/packages/plan/plan-mode/tests/integration.spec.ts b/packages/plan/plan-mode/tests/integration.spec.ts index 959b36f2ac..68d24db709 100644 --- a/packages/plan/plan-mode/tests/integration.spec.ts +++ b/packages/plan/plan-mode/tests/integration.spec.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import LlmRuntime, { createUserMessage, type StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -26,7 +25,6 @@ async function harness(adapter: MockAdapter): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/preset/agent-presets/tests/invariant.spec.ts b/packages/preset/agent-presets/tests/invariant.spec.ts index f1e26a79d7..24514fe0ab 100644 --- a/packages/preset/agent-presets/tests/invariant.spec.ts +++ b/packages/preset/agent-presets/tests/invariant.spec.ts @@ -1,7 +1,6 @@ import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { Context } from '@deepseek-ai/cordis' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import LlmRuntime from '@deepseek-ai/dsh-llm' @@ -30,7 +29,6 @@ async function harness(roster: Partial = {}): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/preset/agent-presets/tests/mount.spec.ts b/packages/preset/agent-presets/tests/mount.spec.ts index 23a56112e7..fe7f2adc53 100644 --- a/packages/preset/agent-presets/tests/mount.spec.ts +++ b/packages/preset/agent-presets/tests/mount.spec.ts @@ -3,7 +3,6 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { Context } from '@deepseek-ai/cordis' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import LlmRuntime from '@deepseek-ai/dsh-llm' @@ -48,7 +47,6 @@ async function harness(roster: Config = { default: 'standard', roots: ROOTS, inc await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) @@ -419,7 +417,6 @@ describe('the preset file is an input, never a persistence target', () => { await scoped.plugin(LlmRuntime) await scoped.plugin(SessionStore) await scoped.plugin(SessionProjectionRegistry) - await scoped.plugin(InboxService) await scoped.plugin(SystemPrompt, { persona: '' }) await scoped.plugin(ToolRuntime) await scoped.plugin(AgentRegistry) @@ -586,7 +583,6 @@ describe('replacing a composition', () => { await scoped.plugin(LlmRuntime) await scoped.plugin(SessionStore) await scoped.plugin(SessionProjectionRegistry) - await scoped.plugin(InboxService) await scoped.plugin(SystemPrompt, { persona: '' }) await scoped.plugin(ToolRuntime) await scoped.plugin(AgentRegistry) diff --git a/packages/preset/agent-presets/tests/settings.spec.ts b/packages/preset/agent-presets/tests/settings.spec.ts index 4b09b1b663..b1bf43b247 100644 --- a/packages/preset/agent-presets/tests/settings.spec.ts +++ b/packages/preset/agent-presets/tests/settings.spec.ts @@ -16,7 +16,6 @@ import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import AgentRegistry from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import FileSettingsProvider from '@deepseek-ai/dsh-settings-file' @@ -46,7 +45,6 @@ async function harness( await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/schedule/schedule/tests/runtime.spec.ts b/packages/schedule/schedule/tests/runtime.spec.ts index 106725c8ad..0c5c6bce54 100644 --- a/packages/schedule/schedule/tests/runtime.spec.ts +++ b/packages/schedule/schedule/tests/runtime.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent, AgentCancelCause, InboxTarget } from '@deepseek-ai/dsh-agent' import type { UserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' @@ -96,7 +96,7 @@ async function harness(): Promise { steer(_message: UserMessage) {}, inject(_message: UserMessage) {}, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) const disposeAgent = ctx.agents.register(agent) ctx.on('session/event', (_session, event) => { if (event.type === 'schedule/change' && event.data.operation === 'dispatch') order.push('dispatch') diff --git a/packages/schedule/schedule/tests/tools.spec.ts b/packages/schedule/schedule/tests/tools.spec.ts index 7b387c7ef5..7343a9529c 100644 --- a/packages/schedule/schedule/tests/tools.spec.ts +++ b/packages/schedule/schedule/tests/tools.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent, AgentCancelCause, InboxTarget } from '@deepseek-ai/dsh-agent' import { CallId } from '@deepseek-ai/dsh-llm' import type { UserMessage } from '@deepseek-ai/dsh-llm' @@ -39,7 +39,7 @@ function stubAgent(ctx: Context, id: string): Agent { steer(_message: UserMessage) {}, inject(_message: UserMessage) {}, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } 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 5fade7b924..e225378ddb 100644 --- a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts @@ -8,7 +8,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import { CallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import * as TerminalLocal from '@deepseek-ai/dsh-terminal-bash' @@ -55,7 +55,7 @@ function agent(ctx: Context, cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value) }) + Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/shell/tool-bash-persistent/tests/tools.spec.ts b/packages/shell/tool-bash-persistent/tests/tools.spec.ts index 5277c04a04..965b3dbbc5 100644 --- a/packages/shell/tool-bash-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/tools.spec.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { CallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import type { @@ -50,7 +50,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value) }) + Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } 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 1a95d7fe23..57abf1d2b1 100644 --- a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts @@ -9,7 +9,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import { CallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import * as TerminalBash from '@deepseek-ai/dsh-terminal-bash' @@ -51,7 +51,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -62,6 +62,7 @@ function agent(ctx: Context, cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts index 8d76abd3a6..4cc139d9d3 100644 --- a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { CallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import type { @@ -39,7 +39,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { id, options: {}, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: undefined as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -50,6 +50,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } + Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/skill/tool-skill/tests/tool-skill.spec.ts b/packages/skill/tool-skill/tests/tool-skill.spec.ts index ff9e14bf5f..6d50d54b4d 100644 --- a/packages/skill/tool-skill/tests/tool-skill.spec.ts +++ b/packages/skill/tool-skill/tests/tool-skill.spec.ts @@ -54,7 +54,7 @@ function agentForCwd(cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } @@ -74,7 +74,7 @@ function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/terminal/terminal-bash/tests/index.spec.ts b/packages/terminal/terminal-bash/tests/index.spec.ts index a4d4b79617..66331fb870 100644 --- a/packages/terminal/terminal-bash/tests/index.spec.ts +++ b/packages/terminal/terminal-bash/tests/index.spec.ts @@ -4,7 +4,7 @@ import { resolve } from 'node:path' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' import SandboxProvider from '@deepseek-ai/dsh-sandbox' import type { ConfinedArgv, SandboxPolicy } from '@deepseek-ai/dsh-sandbox' import SandboxPolicyService, { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' @@ -59,7 +59,7 @@ function agent(ctx: Context, cwd?: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } @@ -530,7 +530,7 @@ describe('terminal-bash plugin shape', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(owner, { inbox: new Inbox(owner.ctx, owner) }) + Object.assign(owner, { inbox: new Inbox(owner.ctx, owner.session, agentEvents(owner.ctx, owner)) }) ctx.agents.register(owner) const providerFiber = await registerStubLocalBackend(ctx, () => stubLocalSession()) const created = await ctx.terminals.spawn(owner, { type: 'stub' }) @@ -580,7 +580,7 @@ describe('terminal-bash plugin shape', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(owner, { inbox: new Inbox(owner.ctx, owner) }) + Object.assign(owner, { inbox: new Inbox(owner.ctx, owner.session, agentEvents(owner.ctx, owner)) }) ctx.agents.register(owner) const gate = Promise.withResolvers() await registerStubLocalBackend(ctx, () => stubLocalSession(() => gate.promise)) diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index 709daf0b3a..bafeffd8b0 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import type { TerminalSendOperation } from '@deepseek-ai/dsh-terminal' @@ -46,7 +46,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index 7b73ebfbd7..7fb957be4e 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService, { TerminalBackendCleanupError, TerminalError, TerminalSessionId } from '@deepseek-ai/dsh-terminal' import type { @@ -37,7 +37,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) agentScopeDisposers.set(agent, async () => { await scopeFiber.dispose() }) return agent } diff --git a/packages/terminal/tool-terminal/tests/loader-composition.spec.ts b/packages/terminal/tool-terminal/tests/loader-composition.spec.ts index 1262156be2..35df0d2d46 100644 --- a/packages/terminal/tool-terminal/tests/loader-composition.spec.ts +++ b/packages/terminal/tool-terminal/tests/loader-composition.spec.ts @@ -8,7 +8,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import { CallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' @@ -49,7 +49,7 @@ function agent(ctx: Context): Agent { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value) }) + Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/terminal/tool-terminal/tests/tools.spec.ts b/packages/terminal/tool-terminal/tests/tools.spec.ts index 4c50898355..e2692f0f74 100644 --- a/packages/terminal/tool-terminal/tests/tools.spec.ts +++ b/packages/terminal/tool-terminal/tests/tools.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { CallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { renderToolsSdk } from '@deepseek-ai/dsh-tools' @@ -26,7 +26,7 @@ function fakeAgent(ctx: Context, rawId: string): Agent { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent) }) + Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) ctx.agents.register(agent) return agent } diff --git a/packages/test-support/agent-loop-testkit/src/index.ts b/packages/test-support/agent-loop-testkit/src/index.ts index 8b327edc4b..7867d00c1e 100644 --- a/packages/test-support/agent-loop-testkit/src/index.ts +++ b/packages/test-support/agent-loop-testkit/src/index.ts @@ -7,7 +7,6 @@ import type { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' -import InboxService from '@deepseek-ai/dsh-agent/inbox' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -43,7 +42,6 @@ export async function mountAgentLoopTestDependencies( await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(InboxService) await ctx.plugin(SystemPrompt, options.systemPrompt ?? {}) await ctx.plugin(ToolRuntime, options.tools ?? {}) await ctx.plugin(AgentRegistry) diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index 24199f8f10..63ba14ed76 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -11,7 +11,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import { CallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' @@ -38,7 +38,7 @@ function agent(ctx: Context): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value) }) + Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 274d0307e4..e932ff9fa6 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -54,7 +54,6 @@ export const SERVICE_PAGE: Record = { agentDefaultModel: 'core.md', agentPresets: 'core.md', agents: 'core.md', - inboxes: 'core.md', apiProxy: 'typert.md', approval: 'approval.md', attachments: 'attachment.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 24550a0a3c..420bad476c 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -139,14 +139,6 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['agent-loop', 'agent', 'session-persistence', 'session-query', 'session-query-sqlite', 'subagent-inprocess', 'invariants', 'message-feedback'], note: 'Owns append-only Session instances and emits the durable session event feed.', }, - { - key: 'inboxes', - pkg: 'agent', - title: 'Durable pending-input facade', - mode: 'core', - consumers: ['agent-loop'], - note: 'Registers the standard Inbox projection and creates command facades over its sole live state.', - }, { key: 'invariants', pkg: 'invariants', diff --git a/tsconfig.base.json b/tsconfig.base.json index 242e848c5e..91e623e2d1 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -98,8 +98,6 @@ "@deepseek-ai/dsh-user-questions/types": ["./packages/interaction/user-questions/src/types.ts"], "@deepseek-ai/dsh-agent/types": ["./packages/core/agent/src/types.ts"], "@deepseek-ai/dsh-agent/brand": ["./packages/core/agent/src/brand.ts"], - "@deepseek-ai/dsh-agent/inbox": ["./packages/core/agent/src/inbox.ts"], - "@deepseek-ai/dsh-agent/inbox-projection": ["./packages/core/agent/src/inbox-projection.ts"], "@deepseek-ai/dsh-agent/invariant": ["./packages/core/agent/src/invariant.ts"], "@deepseek-ai/dsh-scope/invariant": ["./packages/core/scope/src/invariant.ts"], "@deepseek-ai/dsh-agent-loop/invariant": ["./packages/core/agent-loop/src/invariant.ts"], From 90b7ac94e2005a3dc2aa71580ccaf585ec37b653 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 21 Aug 2026 11:25:22 +0800 Subject: [PATCH 03/26] test: trim unrelated inbox changes --- packages/core/agent-loop/tests/loop.spec.ts | 16 ---------------- .../host/apiproxy/tests/api-proxy-jobs.spec.ts | 16 ++-------------- .../apiproxy/tests/api-proxy-projections.spec.ts | 14 ++------------ 3 files changed, 4 insertions(+), 42 deletions(-) diff --git a/packages/core/agent-loop/tests/loop.spec.ts b/packages/core/agent-loop/tests/loop.spec.ts index 5c23522f16..401e45366f 100644 --- a/packages/core/agent-loop/tests/loop.spec.ts +++ b/packages/core/agent-loop/tests/loop.spec.ts @@ -134,22 +134,6 @@ describe('agent loop', () => { expect(adapter.requests).toHaveLength(1) }) - it('rejects overlapping maintenance work', async () => { - const ctx = await harness(new MockAdapter([])) - const agent = ctx.agentLoop.create(SessionId('overlapping-maintenance'), { - provider: 'mock', - model: 'mock', - }) - const finish = Promise.withResolvers() - const maintenance = agent.runMaintenance(() => finish.promise) - - expect(() => agent.runMaintenance(async () => undefined)) - .toThrow('agent "overlapping-maintenance" already has active work') - - finish.resolve(undefined) - await maintenance - }) - it('suppresses the replay when a latched maintenance wake is removed', async () => { const adapter = new MockAdapter([]) const ctx = await harness(adapter) diff --git a/packages/host/apiproxy/tests/api-proxy-jobs.spec.ts b/packages/host/apiproxy/tests/api-proxy-jobs.spec.ts index 7e61b1eff7..3e73ee2616 100644 --- a/packages/host/apiproxy/tests/api-proxy-jobs.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-jobs.spec.ts @@ -55,20 +55,8 @@ async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: } const session = ctx.sessions.create() const agent = { - id: session.id, - options: {}, - session, - inbox: { nextTurn: [], nextStep: [], hasPending: false } as never, - status: 'idle', - ctx, - send() {}, - followup() {}, - steer() {}, - inject() {}, - cancel() {}, - runMaintenance: task => task(new AbortController().signal), - whenIdle: () => Promise.resolve(), - } satisfies Agent + id: session.id, session, inbox: { nextTurn: [], nextStep: [], hasPending: false }, status: 'idle', ctx, + } as Agent ctx.agents.register(agent) return { ctx, session, agent } } diff --git a/packages/host/apiproxy/tests/api-proxy-projections.spec.ts b/packages/host/apiproxy/tests/api-proxy-projections.spec.ts index e94dbb420d..4c1092658d 100644 --- a/packages/host/apiproxy/tests/api-proxy-projections.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-projections.spec.ts @@ -67,25 +67,15 @@ async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: await ctx.plugin(SessionStore) await ctx.plugin(UserQuestionService) await ctx.plugin(AgentRegistry) - if (withRegistry) { - await ctx.plugin(SessionProjectionRegistry) - } + if (withRegistry) await ctx.plugin(SessionProjectionRegistry) const session = ctx.sessions.create() const agent = { id: session.id, - options: {}, session, inbox: { nextTurn: [], nextStep: [], hasPending: false } as never, status: 'idle', ctx, - send() {}, - followup() {}, - steer() {}, - inject() {}, - cancel() {}, - runMaintenance: task => task(new AbortController().signal), - whenIdle: () => Promise.resolve(), - } satisfies Agent + } as Agent if (withRegistry) Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) ctx.agents.register(agent) return { ctx, session } From 8eb0c50e743d59b4ce2c219af2495e6f67aa6576 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 21 Aug 2026 13:24:41 +0800 Subject: [PATCH 04/26] test(session-projection): scope projection assertions --- packages/goal/goal/tests/projection.spec.ts | 4 ++-- packages/plan/plan-mode/tests/projection.spec.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index 0286e93103..3370ab3b41 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -81,7 +81,7 @@ describe('goal projection unit', () => { it('serves null before the first create', async () => { const bench = await harness(true) seedMessage(bench.session) - expect(bench.tailValues()).toEqual({ goal: null }) + expect(bench.tailValues().goal).toBeNull() expect(bench.tailAsOfSeq()).toBe(bench.session.seq - 1) }) @@ -199,7 +199,7 @@ describe('goal projection unit', () => { const bench = await harness(false) seedMessage(bench.session) const fiber = await bench.ctx.plugin(GoalService) - expect(bench.tailValues()).toEqual({ goal: null }) + expect(bench.tailValues().goal).toBeNull() await fiber.dispose() expect('goal' in (bench.tailValues() ?? {})).toBe(false) }) diff --git a/packages/plan/plan-mode/tests/projection.spec.ts b/packages/plan/plan-mode/tests/projection.spec.ts index e0ad20148c..c16078e54a 100644 --- a/packages/plan/plan-mode/tests/projection.spec.ts +++ b/packages/plan/plan-mode/tests/projection.spec.ts @@ -74,7 +74,7 @@ function commitPlanMode(session: Session, active: boolean, turn: number): void { describe('plan projection unit', () => { it('serves inactive/not-pending for the empty log', async () => { const bench = await harness(true) - expect(bench.values()).toEqual({ plan: { active: false, pending: false } }) + expect(bench.values().plan).toEqual({ active: false, pending: false }) }) it('a logged /plan selection reads pending until plan/mode records it', async () => { From f9227e0be6e9702216c59e69d9981992517f8dc7 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 24 Aug 2026 13:14:21 +0800 Subject: [PATCH 05/26] docs(session-projection): keep registry contract unchanged --- docs/subsystems/session-projection.i18n.yaml | 4 +-- docs/subsystems/session-projection.md | 2 +- docs/subsystems/session-projection.zh.md | 2 +- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../session/session-projection/src/index.ts | 26 +++++++++++-------- 5 files changed, 20 insertions(+), 16 deletions(-) diff --git a/docs/subsystems/session-projection.i18n.yaml b/docs/subsystems/session-projection.i18n.yaml index 6fd8c3ce41..f0e253ac1e 100644 --- a/docs/subsystems/session-projection.i18n.yaml +++ b/docs/subsystems/session-projection.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/session-projection.md -session-projection.md: 793cf7257e435b72d188c06d61be0c365b2009b6 -session-projection.zh.md: 4b62402c60b6c4e6ad9c91f2a1a26d69570e0b5e +session-projection.md: 6ab8218f9f019f831625484e8e42f8a31aba80f1 +session-projection.zh.md: 2339d8d4959c4aef09b53f045f54733827a0f534 diff --git a/docs/subsystems/session-projection.md b/docs/subsystems/session-projection.md index 793cf7257e..6ab8218f9f 100644 --- a/docs/subsystems/session-projection.md +++ b/docs/subsystems/session-projection.md @@ -162,7 +162,7 @@ Source: [`packages/session/session-projection-cache/src/index.ts`](../../package ### `ctx.sessionProjections` — `SessionProjectionRegistry` -`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference in a client-visible unit notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the full in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. A domain that requires this capability declares a Cordis service dependency; an optional contributor may register under `ctx.inject(['sessionProjections'], …)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads. +`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference in a client-visible unit notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. Domain plugins register under `ctx.inject(['sessionProjections'], …)` so headless assemblies without the registry stay unaffected. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads. ```ts cordis-catalog /** diff --git a/docs/subsystems/session-projection.zh.md b/docs/subsystems/session-projection.zh.md index 4b62402c60..2339d8d495 100644 --- a/docs/subsystems/session-projection.zh.md +++ b/docs/subsystems/session-projection.zh.md @@ -162,7 +162,7 @@ Source: [`packages/session/session-projection-cache/src/index.ts`](../../package ### `ctx.sessionProjections` — `SessionProjectionRegistry` -`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference in a client-visible unit notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the full in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. A domain that requires this capability declares a Cordis service dependency; an optional contributor may register under `ctx.inject(['sessionProjections'], …)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads. +`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference in a client-visible unit notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. Domain plugins register under `ctx.inject(['sessionProjections'], …)` so headless assemblies without the registry stay unaffected. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads. ```ts cordis-catalog /** diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 1d1a356cad..9d0fc17eb8 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1396,7 +1396,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { key: 'sessionProjections', summary: '`ctx.sessionProjections`: the projection unit table and its drive.', - description: '`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit\'s `apply` (eager drive), and a changed state reference in a client-visible unit notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the full in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin\'s key disappears from snapshots and clients read it as capability absence. A domain that requires this capability declares a Cordis service dependency; an optional contributor may register under `ctx.inject([\'sessionProjections\'], …)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads.', + description: '`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit\'s `apply` (eager drive), and a changed state reference in a client-visible unit notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin\'s key disappears from snapshots and clients read it as capability absence. Domain plugins register under `ctx.inject([\'sessionProjections\'], …)` so headless assemblies without the registry stay unaffected. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads.', methods: [ { signature: 'register< K extends keyof SessionProjectionMap, S extends SessionProjectionStateMap[K], >( definition: Omit, \'wire\'> & { wire: NonNullable[\'wire\']> }, ): () => void', diff --git a/packages/session/session-projection/src/index.ts b/packages/session/session-projection/src/index.ts index 96dbfc8c7a..89d356df02 100644 --- a/packages/session/session-projection/src/index.ts +++ b/packages/session/session-projection/src/index.ts @@ -5,10 +5,14 @@ * forward eagerly over committed session events. Domain host plugins * contribute pure folds and optional client views; the framework owns the * subscription, the per-session watermark cache, and change notification; - * carriers consume the snapshot read face and the change feed. Source events - * may carry whole values or domain operations; every `view` returns a complete - * current value. Design authority: the session-projection RFC - * (.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md). + * carriers consume the snapshot read face and the change feed. Neither side + * knows the other + * (capability-seam three-way split). Design authority: the session-projection + * RFC (.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md). + * + * Whole-value event rule (load-bearing): a state-carrying log event MUST + * carry the complete post-change state, never a bare delta — it keeps every + * unit's transition trivially cheap and every served value self-describing. * * @module @deepseek-ai/dsh-session-projection */ @@ -163,15 +167,15 @@ interface Registration { * reference in a client-visible unit notifies the change feed with the * schema-validated view. * Cells build lazily — a unit registered after events flowed, or a session - * older than the registry, folds `init` over the full in-memory log on first + * older than the registry, folds `init` over the in-memory log on first * touch (event or read). Registration is an effect (disposer rides the * calling fiber): an unloaded domain plugin's key disappears from snapshots - * and clients read it as capability absence. A domain that requires this - * capability declares a Cordis service dependency; an optional contributor - * may register under `ctx.inject(['sessionProjections'], …)`. Registrants - * sharing a key share one unit and are counted: the same tool package mounted - * in N agent presets registers N times, and the key survives until the last - * one unloads. + * and clients read it as capability absence. Domain + * plugins register under `ctx.inject(['sessionProjections'], …)` so headless + * assemblies without the registry stay unaffected. Registrants sharing a key + * share one unit and are counted: the same tool package mounted in N agent + * presets registers N times, and the key survives until the last one + * unloads. */ export class SessionProjectionRegistry extends Service { private readonly registrations = new Map() From e5f2fbd9a2c9babc4273c8cbefc288921cc2960f Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 26 Aug 2026 17:34:36 +0800 Subject: [PATCH 06/26] fix(agent): validate durable inbox reconstruction --- ...claimed-pre-step-inbox-lifecycle.i18n.yaml | 4 +- ...-07-31-claimed-pre-step-inbox-lifecycle.md | 4 +- ...-31-claimed-pre-step-inbox-lifecycle.zh.md | 4 +- docs/subsystems/core.i18n.yaml | 4 +- docs/subsystems/core.md | 2 +- docs/subsystems/core.zh.md | 2 +- packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 2 +- packages/core/agent/README.zh.md | 2 +- packages/core/agent/src/inbox-projection.ts | 50 +++++++++++-------- packages/core/agent/tests/agent.spec.ts | 44 ++++++++++++++++ 11 files changed, 87 insertions(+), 35 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml index 84deedb9f9..87ef2eb913 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md -2026-07-31-claimed-pre-step-inbox-lifecycle.md: 8149c9df09ff69c017ba66a779d6fd3dfc314193 -2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: e855b88b26a55dd9f5c33c87a4b59d67496d00ed +2026-07-31-claimed-pre-step-inbox-lifecycle.md: aee385bec30c572bd23d7aecac3a3515ad8cd98b +2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 79460b9abf25ef12925f459a8d13b78c7e63b604 diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md index 8149c9df09..aee385bec3 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md @@ -18,7 +18,7 @@ Before every proposed step, `Inbox.claim(target)` atomically removes the complet The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming records pure deletions without an outcome and emits claimed events from Inbox itself. These live events add no placement, outcome, or batch fields. -The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `AgentRegistry` contributes the standard `inbox` projection over the durable `agent/inbox/spliced` stream whenever the projection registry is composed; UI edits and removals route through an Inbox mutation method so the same projection records every change. +The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `AgentRegistry` contributes the standard `inbox` projection over the durable `agent/inbox/spliced` stream whenever the projection registry is composed; UI edits and removals route through an Inbox mutation method so the same projection records every change. When that projection reconstructs durable history, it rejects unsafe or out-of-range coordinates and duplicate `MessageId` values across both lists, and reports the offending event seq. Plugins that need current-step atomic rewriting return messages from `agent/pre-step`. Plugins that only need later context may mutate `agent.inbox` directly. Workspace context uses both paths: asynchronous filesystem projections stage one replaceable `next-step` item, while the next entering pre-step folds that item or a newly composed baseline into its final batch and removes the pending copy. Rejection keeps the item queued. @@ -34,7 +34,7 @@ The archived [addressable queue occurrence decision](../../archived/feature/2026 ## Verification -Agent-loop coverage pins turn-start-before-claim-before-pre-step ordering, exact live event payloads, balanced no-step rejection, final-batch rewriting, input inserted after a claim, listener failure, and cancellation. Inbox and consumer tests pin pure claim deletions, canceled ordinary removals, agent-instructions staging, replacement, and same-step entry, plan/goal/hook behavior, UI cleanup, compaction, checkpointing, and resumed durable projection. Generated event and type catalogs expose only the new waterfall and payloads. +Agent-loop coverage pins turn-start-before-claim-before-pre-step ordering, exact live event payloads, balanced no-step rejection, final-batch rewriting, input inserted after a claim, listener failure, and cancellation. Inbox and consumer tests pin pure claim deletions, canceled ordinary removals, agent-instructions staging, replacement, and same-step entry, plan/goal/hook behavior, UI cleanup, compaction, checkpointing, resumed durable projection, and rejection of invalid persisted coordinates or cross-list identities. Generated event and type catalogs expose only the new waterfall and payloads. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md index e855b88b26..79460b9abf 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md @@ -18,7 +18,7 @@ Status: implemented 持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取记录不带 outcome 的纯删除,并由 Inbox 自行发出 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 -两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`AgentRegistry` 会在投影注册表已组合时,在持久 `agent/inbox/spliced` 流上贡献标准 `inbox` 投影;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。 +两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`AgentRegistry` 会在投影注册表已组合时,在持久 `agent/inbox/spliced` 流上贡献标准 `inbox` 投影;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。该投影重建持久历史时,会拒绝不安全或越界的坐标,以及跨两份列表重复的 `MessageId`,并报告出错事件的 seq。 必须对当前步骤进行原子改写的插件从 `agent/pre-step` 返回消息。只需要稍后上下文的插件可以直接修改 `agent.inbox`。Workspace context 同时使用两条路径:异步文件系统投影会暂存一条可替换的 `next-step` 消息,而下一次进入步骤的 pre-step 会把该消息或新组合的基线折入最终批次,并移除仍待处理的副本。reject 会让该条目继续排队。 @@ -34,7 +34,7 @@ Status: implemented ## 验证 -agent loop(智能体循环)覆盖固定先 `turn/start`、再领取、后 pre-step 的顺序、实时事件的确切载荷、边界平衡的无步骤 reject、最终批次改写、领取后插入的输入、监听器失败与取消。Inbox 和消费方测试固定纯领取删除、普通删除的 canceled 结果、agent-instructions 的暂存、替换与同一步骤进入、plan/goal/钩子行为、UI 清理、压缩(compaction)、检查点以及恢复后的持久投影。生成的事件与类型目录只公开新的 waterfall 与载荷。 +agent loop(智能体循环)覆盖固定先 `turn/start`、再领取、后 pre-step 的顺序、实时事件的确切载荷、边界平衡的无步骤 reject、最终批次改写、领取后插入的输入、监听器失败与取消。Inbox 和消费方测试固定纯领取删除、普通删除的 canceled 结果、agent-instructions 的暂存、替换与同一步骤进入、plan/goal/钩子行为、UI 清理、压缩(compaction)、检查点、恢复后的持久投影,以及对非法持久坐标或跨列表重复标识的拒绝。生成的事件与类型目录只公开新的 waterfall 与载荷。 ## 后果 diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index a9e7e5c2e8..00592ec1fe 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/core.md -core.md: 03299a114987d9508b8d58ec24a3c4f919006648 -core.zh.md: bee87294670a7f7ea23169e00beb0ff324846025 +core.md: 2d80985bb16ea2858bffd53e4ab584e096c2dc7a +core.zh.md: 6c731e07decbc50cdd552d81615b511f42266aef diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 03299a1149..2d80985bb1 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -177,7 +177,7 @@ The inbox is the delivery vocabulary — two ordered pending-message lists the a type InboxTarget = 'next-turn' | 'next-step' ``` -Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. `Inbox.append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. `claim(target)` removes the proposed step batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without emitting discarded notifications, then Inbox emits per-message claimed notifications. `AgentRegistry` contributes the standard `inbox` projection whenever the projection registry is composed; its cell is the sole live state and the same fold serves cold consumers. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. +Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. `Inbox.append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. `claim(target)` removes the proposed step batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without emitting discarded notifications, then Inbox emits per-message claimed notifications. `AgentRegistry` contributes the standard `inbox` projection whenever the projection registry is composed; its cell is the sole live state and the same fold serves cold consumers. That fold rejects unsafe or out-of-range splice coordinates and duplicate identities across both lists, identifying malformed durable history by event seq. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. Cancellation: diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index bee8729467..6c731e07de 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -181,7 +181,7 @@ inbox 即投递词汇——agent 以持久投影形式拥有的两条有序待 type InboxTarget = 'next-turn' | 'next-step' ``` -每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。`Inbox.append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。`claim(target)` 通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后由 Inbox 逐条发出 claimed 通知。`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 投影;其 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 +每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。`Inbox.append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。`claim(target)` 通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后由 Inbox 逐条发出 claimed 通知。`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 投影;其 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。该 fold 会拒绝不安全或越界的 splice 坐标,以及跨两份列表重复的标识,并通过事件 seq 指出格式错误的持久历史。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 取消: diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 6cae6d2220..1ac6354659 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent/README.md -README.md: d56a917976e07d99e947703294bfe1e195533f8c -README.zh.md: 3cc0cec48861161bdc61550d9f8b13c78109e94a +README.md: 90e6aa0f570f5bde4a120f2d8213fb308cb7792a +README.zh.md: 8922d78591211a6b48976f2c5632766d90eb3186 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index d56a917976..90e6aa0f57 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -54,7 +54,7 @@ Most interception points are cooperative waterfalls. `agent/pre-step` receives a `PreStepDecision` is either `{ kind: 'reject' }` or `{ kind: 'enter', messages, startsRequestSeries? }`. The enter branch is the complete identified, frozen batch for the proposed step. `startsRequestSeries: true` declares that this admitted batch begins a distinct model-message series; ordinary follow-ups leave it absent. A listener that wraps downstream entry preserves both that declaration and the batch unless it intentionally replaces either one; additions follow the waterfall's natural return order. Claiming already removed the offered messages from the inbox, so rejection does not retain them. Messages inserted after the claim remain pending for a later boundary. -`AgentRegistry` contributes the standard `inbox` session projection whenever the projection registry is composed. The registry folds durable `agent/inbox/spliced` events once and remains the sole owner of the live `{ 'next-turn', 'next-step' }` state; Inbox is a command facade that reads that unit rather than replaying or copying the fold. Inbox live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. Inbox emits them as it commits the corresponding mutation, without adding another lifecycle envelope. +`AgentRegistry` contributes the standard `inbox` session projection whenever the projection registry is composed. The registry folds durable `agent/inbox/spliced` events once and remains the sole owner of the live `{ 'next-turn', 'next-step' }` state; Inbox is a command facade that reads that unit rather than replaying or copying the fold. Reconstruction rejects unsafe or out-of-range splice coordinates and duplicate `MessageId` values across both pending lists, reporting the offending event seq instead of accepting malformed durable history. Inbox live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. Inbox emits them as it commits the corresponding mutation, without adding another lifecycle envelope. Turn and step boundaries and the model token stream are durable `session/event` facts rather than mirrored `agent/*` notifications. Consumers read `turn/*`, `step/*`, and `assistant/chunk` from the session feed; tool policy and outcome observation belong to the complete pipeline documented by [`dsh-tools`](../tools/README.md). diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index 3cc0cec488..8922d78591 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -56,7 +56,7 @@ Agent *创建* 由实现 `AgentFactory` 的插件(`dsh-agent-loop`)提供, `PreStepDecision` 要么是 `{ kind: 'reject' }`,要么是 `{ kind: 'enter', messages, startsRequestSeries? }`。enter 分支是拟进入步骤的完整、带标识且冻结的批次。`startsRequestSeries: true` 声明该接纳批次会开启一个独立的模型消息序列;普通 follow-up 不设置它。包装下游 enter 的监听器会同时保留该声明和消息批次,除非有意替换其中一项;新增消息遵循 waterfall 的自然返回顺序。领取操作已经把候选消息从 inbox 删除,因此 reject 不会保留它们;领取后插入的消息仍等待后续边界。 -`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 会话投影。注册表只折叠一次持久 `agent/inbox/spliced` 事件,并继续作为 live `{ 'next-turn', 'next-step' }` 状态的唯一所有者;Inbox 是读取该单元的命令 facade,不会重新回放或复制折叠结果。Inbox 的实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。Inbox 在提交对应变更时自行发出这些通知,不引入另一层生命周期封套。 +`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 会话投影。注册表只折叠一次持久 `agent/inbox/spliced` 事件,并继续作为 live `{ 'next-turn', 'next-step' }` 状态的唯一所有者;Inbox 是读取该单元的命令 facade,不会重新回放或复制折叠结果。重建过程会拒绝不安全或越界的 splice 坐标,以及跨两份待处理列表重复的 `MessageId`,并报告出错事件的 seq,而不会接受格式错误的持久历史。Inbox 的实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。Inbox 在提交对应变更时自行发出这些通知,不引入另一层生命周期封套。 轮次和步骤边界以及模型 token 流是持久 `session/event` 事实,而不是镜像的 `agent/*` 通知。消费方从会话事件流读取 `turn/*`、`step/*` 和 `assistant/chunk`;工具策略与结果观测属于 [`dsh-tools`](../tools/README.zh.md) 记录的完整流水线。 diff --git a/packages/core/agent/src/inbox-projection.ts b/packages/core/agent/src/inbox-projection.ts index 752bf01593..5eba9ad87a 100644 --- a/packages/core/agent/src/inbox-projection.ts +++ b/packages/core/agent/src/inbox-projection.ts @@ -3,6 +3,7 @@ import type { UserMessage } from '@deepseek-ai/dsh-llm/types' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' import { z } from 'zod' +import type { InboxState, InboxWireState } from './types.ts' /** Wire validation for pending agent input reconstructed from durable inbox splices. */ export const inboxProjectionSchema = z.object({ @@ -10,10 +11,7 @@ export const inboxProjectionSchema = z.object({ 'next-step': z.array(z.custom()).readonly(), }).readonly() -/** Complete pending Inbox value reconstructed from durable splices. */ -export type InboxState = z.infer - -/** Standard fold that reconstructs pending agent input from durable splices. */ +/** Standard fold that reconstructs pending input and rejects invalid durable splice history. */ export const inboxProjectionDefinition = { key: 'inbox', stateSchema: inboxProjectionSchema, @@ -21,25 +19,35 @@ export const inboxProjectionDefinition = { apply(state: InboxState, event) { if (event.type !== 'agent/inbox/spliced') return state const splice = event.data - const next = state[splice.target].toSpliced( - splice.start, - splice.removedCount ?? 0, - ...splice.inserted, - ) - return splice.target === 'next-turn' - ? { 'next-turn': next, 'next-step': state['next-step'] } - : { 'next-turn': state['next-turn'], 'next-step': next } + try { + const inbox = state[splice.target] + const removedCount = splice.removedCount ?? 0 + if (!Number.isSafeInteger(splice.start) || splice.start < 0 || splice.start > inbox.length + || !Number.isSafeInteger(removedCount) || removedCount < 0 + || splice.start + removedCount > inbox.length) { + throw new Error('invalid inbox splice') + } + const next = inbox.toSpliced(splice.start, removedCount, ...splice.inserted) + const ids = new Set() + for (const message of splice.target === 'next-turn' + ? [...next, ...state['next-step']] + : [...state['next-turn'], ...next]) { + if (ids.has(message.id)) throw new Error(`message "${message.id}" is already pending`) + ids.add(message.id) + } + return splice.target === 'next-turn' + ? { 'next-turn': next, 'next-step': state['next-step'] } + : { 'next-turn': state['next-turn'], 'next-step': next } + } catch (error: unknown) { + throw new Error(`invalid persisted inbox splice at session seq ${event.seq}`, { cause: error }) + } }, wire: { - viewSchema: inboxProjectionSchema, - view: (state: InboxState) => state, + // The wire value is the fold state itself: every pending message already + // round-trips the session log as lossless JSON. Only the static type + // narrows to the JSON-safe projection table entry. + viewSchema: inboxProjectionSchema as unknown as z.ZodType, + view: (state: InboxState) => state as unknown as InboxWireState, }, stateVersion: 1, } satisfies ProjectionDefinition<'inbox', InboxState> - -declare module '@deepseek-ai/dsh-session-projection/types' { - interface SessionProjectionMap { - /** Pending agent input reconstructed from durable inbox splices. */ - inbox: InboxState - } -} diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index 41db67d521..f6a82a7a7d 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -54,7 +54,51 @@ async function inboxAgent(rawId: string): Promise<{ ctx: Context; session: Sessi return { ctx, session, agent } } +async function reconstructPersistedInbox( + rawId: string, + populate: (session: Session) => void, +): Promise { + const ctx = new Context() + await ctx.plugin(SessionStore) + const session = ctx.sessions.create(SessionId(rawId)) + populate(session) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + try { + ctx.sessionProjections.stateOf(session, 'inbox') + } catch (error: unknown) { + if (error instanceof Error) return error + throw error + } + throw new Error('persisted inbox reconstruction unexpectedly succeeded') +} + describe('Inbox', () => { + it('rejects invalid durable coordinates and duplicate identities during reconstruction', async () => { + const outOfRange = await reconstructPersistedInbox('invalid-inbox-range', (session) => { + session.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, removedCount: 1, inserted: [], + }) + }) + expect(outOfRange.message).toBe('invalid persisted inbox splice at session seq 0') + expect((outOfRange.cause as Error).message).toBe('invalid inbox splice') + + const pending = createUserMessage({ + content: [{ type: 'text', text: 'duplicate' }], + source: { kind: 'user' }, + }) + const duplicate = await reconstructPersistedInbox('invalid-inbox-duplicate', (session) => { + session.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, inserted: [pending], + }) + session.append('agent/inbox/spliced', { + target: 'next-step', start: 0, inserted: [pending], + }) + }) + expect(duplicate.message).toBe('invalid persisted inbox splice at session seq 1') + expect((duplicate.cause as Error).message).toBe(`message "${pending.id}" is already pending`) + }) + it('projects inherited Inbox events in a forked session', async () => { const { ctx, session: parent, agent: parentAgent } = await inboxAgent('inbox-fork-parent') const inherited = createUserMessage({ From 8b0ea3e46101a022c17ca204a1dd2b66b5f67cdc Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 26 Aug 2026 17:35:55 +0800 Subject: [PATCH 07/26] fix(session-controller): derive queues from projections --- ...claimed-pre-step-inbox-lifecycle.i18n.yaml | 4 +- ...-07-31-claimed-pre-step-inbox-lifecycle.md | 4 +- ...-31-claimed-pre-step-inbox-lifecycle.zh.md | 4 +- .../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/control.ts | 46 ++++++++----------- .../tests/control-queue.host.spec.ts | 32 +++++++++++++ packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 2 +- packages/core/agent-loop/README.zh.md | 2 +- 11 files changed, 66 insertions(+), 40 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml index 87ef2eb913..93176ac3f9 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md -2026-07-31-claimed-pre-step-inbox-lifecycle.md: aee385bec30c572bd23d7aecac3a3515ad8cd98b -2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 79460b9abf25ef12925f459a8d13b78c7e63b604 +2026-07-31-claimed-pre-step-inbox-lifecycle.md: d914b075607181a8b036ede003e2998f18c6be3b +2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 1701b949500c310656f48b9872e1d714a984658a diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md index aee385bec3..d914b07560 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md @@ -18,7 +18,7 @@ Before every proposed step, `Inbox.claim(target)` atomically removes the complet The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming records pure deletions without an outcome and emits claimed events from Inbox itself. These live events add no placement, outcome, or batch fields. -The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `AgentRegistry` contributes the standard `inbox` projection over the durable `agent/inbox/spliced` stream whenever the projection registry is composed; UI edits and removals route through an Inbox mutation method so the same projection records every change. When that projection reconstructs durable history, it rejects unsafe or out-of-range coordinates and duplicate `MessageId` values across both lists, and reports the offending event seq. +The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `AgentRegistry` contributes the standard `inbox` projection over the durable `agent/inbox/spliced` stream whenever the projection registry is composed; UI edits and removals route through an Inbox mutation method so the same projection records every change. When that projection reconstructs durable history, it rejects unsafe or out-of-range coordinates and duplicate `MessageId` values across both lists, and reports the offending event seq. Whole-queue control consumers use the projection change feed: the Session controller publishes the projection frame, then derives the queue replacement from the same post-fold inbox value. Plugins that need current-step atomic rewriting return messages from `agent/pre-step`. Plugins that only need later context may mutate `agent.inbox` directly. Workspace context uses both paths: asynchronous filesystem projections stage one replaceable `next-step` item, while the next entering pre-step folds that item or a newly composed baseline into its final batch and removes the pending copy. Rejection keeps the item queued. @@ -34,7 +34,7 @@ The archived [addressable queue occurrence decision](../../archived/feature/2026 ## Verification -Agent-loop coverage pins turn-start-before-claim-before-pre-step ordering, exact live event payloads, balanced no-step rejection, final-batch rewriting, input inserted after a claim, listener failure, and cancellation. Inbox and consumer tests pin pure claim deletions, canceled ordinary removals, agent-instructions staging, replacement, and same-step entry, plan/goal/hook behavior, UI cleanup, compaction, checkpointing, resumed durable projection, and rejection of invalid persisted coordinates or cross-list identities. Generated event and type catalogs expose only the new waterfall and payloads. +Agent-loop coverage pins turn-start-before-claim-before-pre-step ordering, exact live event payloads, balanced no-step rejection, final-batch rewriting, input inserted after a claim, listener failure, and cancellation. Inbox and consumer tests pin pure claim deletions, canceled ordinary removals, agent-instructions staging, replacement, and same-step entry, plan/goal/hook behavior, UI cleanup, compaction, checkpointing, resumed durable projection, rejection of invalid persisted coordinates or cross-list identities, and post-fold queue replacement when the controller registers before the projection registry. Generated event and type catalogs expose only the new waterfall and payloads. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md index 79460b9abf..1701b94950 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md @@ -18,7 +18,7 @@ Status: implemented 持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取记录不带 outcome 的纯删除,并由 Inbox 自行发出 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 -两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`AgentRegistry` 会在投影注册表已组合时,在持久 `agent/inbox/spliced` 流上贡献标准 `inbox` 投影;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。该投影重建持久历史时,会拒绝不安全或越界的坐标,以及跨两份列表重复的 `MessageId`,并报告出错事件的 seq。 +两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`AgentRegistry` 会在投影注册表已组合时,在持久 `agent/inbox/spliced` 流上贡献标准 `inbox` 投影;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。该投影重建持久历史时,会拒绝不安全或越界的坐标,以及跨两份列表重复的 `MessageId`,并报告出错事件的 seq。整体队列的 control 消费方使用投影变更流:Session controller 先发布 projection frame,再从同一份折叠后的 inbox 值派生 queue replacement。 必须对当前步骤进行原子改写的插件从 `agent/pre-step` 返回消息。只需要稍后上下文的插件可以直接修改 `agent.inbox`。Workspace context 同时使用两条路径:异步文件系统投影会暂存一条可替换的 `next-step` 消息,而下一次进入步骤的 pre-step 会把该消息或新组合的基线折入最终批次,并移除仍待处理的副本。reject 会让该条目继续排队。 @@ -34,7 +34,7 @@ Status: implemented ## 验证 -agent loop(智能体循环)覆盖固定先 `turn/start`、再领取、后 pre-step 的顺序、实时事件的确切载荷、边界平衡的无步骤 reject、最终批次改写、领取后插入的输入、监听器失败与取消。Inbox 和消费方测试固定纯领取删除、普通删除的 canceled 结果、agent-instructions 的暂存、替换与同一步骤进入、plan/goal/钩子行为、UI 清理、压缩(compaction)、检查点、恢复后的持久投影,以及对非法持久坐标或跨列表重复标识的拒绝。生成的事件与类型目录只公开新的 waterfall 与载荷。 +agent loop(智能体循环)覆盖固定先 `turn/start`、再领取、后 pre-step 的顺序、实时事件的确切载荷、边界平衡的无步骤 reject、最终批次改写、领取后插入的输入、监听器失败与取消。Inbox 和消费方测试固定纯领取删除、普通删除的 canceled 结果、agent-instructions 的暂存、替换与同一步骤进入、plan/goal/钩子行为、UI 清理、压缩(compaction)、检查点、恢复后的持久投影、对非法持久坐标或跨列表重复标识的拒绝,以及 controller 早于投影注册表注册时仍使用折叠后队列值。生成的事件与类型目录只公开新的 waterfall 与载荷。 ## 后果 diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index d417370290..67e2d20f79 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/session-controller/README.md -README.md: 510f336c76dd80ed01bdd2bd4a364106f418831f -README.zh.md: 4503a8f9d0bcfc7f669f00cbc4db69e0d3efd3cd +README.md: cbd8f1236ef717c2d37bb03a18d22500966bd441 +README.zh.md: 79bb03e76fd3d61780dc313d0edfea12371cbbe3 diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index 510f336c76..cbd8f1236e 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -8,7 +8,7 @@ History pages and follow opening snapshots carry a discriminated `SessionHistory Each endpoint states its activation policy. List, search, attachment, history pages, and log following can inspect persistence without activating an Agent; queue mutation and cancellation require the corresponding live state; model, rename, and prompt commands may explicitly resume an ordinary Session. Create and fork are the only operations that create a new Agent. 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. -The Client adapter exposes `SessionEventStream`, a Gateway `RemoteJournalStream` bound to one ordinary or direct-subagent address. It opens follow before the initial page, publishes only contiguous `replace`, `prepend`, and `append` changes, and repairs reconnect or sequence gaps through a tail page. Ordinary records cover `[event.seq, event.seq]`; packed rows cover `[event.seq, event.seq + memberCount - 1]`. A business, persistence, or unresolved continuity failure terminates the stream, while only physical carrier loss selects automatic resumption. `SessionControlStream` is a Gateway `RemoteSnapshotStream`; every generation opens with a complete process-local baseline, so reconnect replaces queue, jobs, and projection state instead of treating transient values as durable events. +The Client adapter exposes `SessionEventStream`, a Gateway `RemoteJournalStream` bound to one ordinary or direct-subagent address. It opens follow before the initial page, publishes only contiguous `replace`, `prepend`, and `append` changes, and repairs reconnect or sequence gaps through a tail page. Ordinary records cover `[event.seq, event.seq]`; packed rows cover `[event.seq, event.seq + memberCount - 1]`. A business, persistence, or unresolved continuity failure terminates the stream, while only physical carrier loss selects automatic resumption. `SessionControlStream` is a Gateway `RemoteSnapshotStream`; every generation opens with a complete process-local baseline, so reconnect replaces queue, jobs, and projection state instead of treating transient values as durable events. For each inbox change, the Host publishes the projection frame first and derives the queue replacement from that same validated post-fold value, so listener registration order cannot produce a stale queue frame. ## Model Experience diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 4503a8f9d0..79bb03e76f 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -8,7 +8,7 @@ 每个 endpoint 都声明自己的激活策略。列表、搜索、附件、历史页和日志跟随可以在不激活 Agent 的情况下检查 persistence;queue 变更和取消要求对应 live 状态仍然存在;模型、重命名和 prompt 命令可以显式恢复普通 Session。只有 create 和 fork 会创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。 -Client adapter 提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend` 和 `append` 变更,并通过 tail page 修复重连或 seq 缺口。普通 record 覆盖 `[event.seq, event.seq]`,packed row 覆盖 `[event.seq, event.seq + memberCount - 1]`。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 queue、jobs 和 projection 状态,而不会把瞬态值当作 durable event。 +Client adapter 提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend` 和 `append` 变更,并通过 tail page 修复重连或 seq 缺口。普通 record 覆盖 `[event.seq, event.seq]`,packed row 覆盖 `[event.seq, event.seq + memberCount - 1]`。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 queue、jobs 和 projection 状态,而不会把瞬态值当作 durable event。每次 inbox 变更时,Host 会先发布 projection frame,再从同一份已校验的折叠后值派生 queue replacement,因此监听器注册顺序不会产生陈旧的 queue frame。 ## 模型体验 diff --git a/packages/api/session-controller/src/control.ts b/packages/api/session-controller/src/control.ts index 4068b5536d..31fb2ff756 100644 --- a/packages/api/session-controller/src/control.ts +++ b/packages/api/session-controller/src/control.ts @@ -1,10 +1,10 @@ /** Live Session queue, jobs, and projection state with reconnect baselines. */ import type { Context } from '@deepseek-ai/cordis' -import type { Agent } from '@deepseek-ai/dsh-agent' +import type { Agent, InboxState } from '@deepseek-ai/dsh-agent' import type { JobSnapshot } from '@deepseek-ai/dsh-jobs' import type { - JsonValue, Session, SessionEvent, SessionEventMap, SessionId, UserMessage, + JsonValue, Session, SessionId, } from '@deepseek-ai/dsh-session' import type { SessionControlBaseline, @@ -21,7 +21,6 @@ export class SessionControlController { /** @param ctx - Host context carrying live Agent, projection, and jobs services. */ constructor(private readonly ctx: Context) { - ctx.on('session/event', (session, event) => { this.onSessionEvent(session, event) }) ctx.inject(['sessionProjections'], (projectionCtx) => { projectionCtx.sessionProjections.onChanged((session, key, value, seq) => { this.broadcast({ @@ -31,6 +30,14 @@ export class SessionControlController { value: value as JsonValue, seq, }) + if (key !== 'inbox') return + const agent = this.ctx.agents.get(session.id) + if (agent?.session !== session) return + this.broadcast({ + type: 'queue', + sessionId: session.id, + items: queueItemsFromInbox(value as InboxState), + }) }) }) ctx.inject(['jobs'], (jobsCtx) => { @@ -98,17 +105,6 @@ export class SessionControlController { return blocks } - private onSessionEvent(session: Session, event: SessionEvent): void { - if (event.type !== 'agent/inbox/spliced') return - const agent = this.ctx.agents.get(session.id) - if (agent?.session !== session) return - this.broadcast({ - type: 'queue', - sessionId: session.id, - items: queueItems(agent, event.data), - }) - } - private onJobsChanged(owner: Agent | undefined): void { if (owner !== undefined) { this.broadcast({ type: 'jobs', sessionId: owner.id, jobs: this.jobsFor(owner) }) @@ -174,23 +170,21 @@ class ControlQueue { } } -function queueItems( - agent: Agent, - splice?: SessionEventMap['agent/inbox/spliced'], -): SessionQueuedItem[] { - const project = (target: 'next-turn' | 'next-step'): readonly UserMessage[] => { - const messages = target === 'next-turn' ? agent.inbox.nextTurn : agent.inbox.nextStep - return splice?.target === target - ? messages.toSpliced(splice.start, splice.removedCount ?? 0, ...splice.inserted) - : messages - } +function queueItems(agent: Agent): SessionQueuedItem[] { + return queueItemsFromInbox({ + 'next-turn': agent.inbox.nextTurn, + 'next-step': agent.inbox.nextStep, + }) +} + +function queueItemsFromInbox(inbox: InboxState): SessionQueuedItem[] { return [ - ...project('next-turn').map(message => ({ + ...inbox['next-turn'].map(message => ({ id: message.id, placement: 'queued' as const, message: { id: message.id, content: message.content as unknown as JsonValue[] }, })), - ...project('next-step').map(message => ({ + ...inbox['next-step'].map(message => ({ id: message.id, placement: message.source.kind === 'user' ? 'steering' as const : 'context' as const, message: { id: message.id, content: message.content as unknown as JsonValue[] }, diff --git a/packages/api/session-controller/tests/control-queue.host.spec.ts b/packages/api/session-controller/tests/control-queue.host.spec.ts index 9ce0c453a0..5c48efd4b9 100644 --- a/packages/api/session-controller/tests/control-queue.host.spec.ts +++ b/packages/api/session-controller/tests/control-queue.host.spec.ts @@ -69,6 +69,38 @@ describe('Session control queue projection', () => { await iterator.next() }) + it('derives queue replacements from the completed projection regardless of registration order', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(AgentRegistry) + const control = new SessionControlController(ctx) + await ctx.plugin(SessionProjectionRegistry) + const session = ctx.sessions.create(SessionId('late-projection-queue')) + const agent = { id: session.id, session, inbox: undefined as never, status: 'running', ctx } as unknown as Agent + Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) + ctx.agents.register(agent) + const abort = new AbortController() + const iterator = control.control(abort.signal)[Symbol.asyncIterator]() + await iterator.next() + const pending = message('late projection') + + agent.inbox.append('next-turn', pending) + + await expect(iterator.next()).resolves.toMatchObject({ + value: { + type: 'projection', + key: 'inbox', + value: { 'next-turn': [{ id: pending.id }], 'next-step': [] }, + }, + }) + await expect(nextQueueFrame(iterator)).resolves.toMatchObject({ + items: [{ id: pending.id, placement: 'queued' }], + }) + + abort.abort() + await iterator.next() + }) + it('ignores inbox events without the exact live Agent session', async () => { const { ctx, control, agent, inbox } = await harness() const abort = new AbortController() diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 9fe9297155..0dc6ed0632 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent-loop/README.md -README.md: 8b35b970aac93ac3c20fe570c79c3524abbe079f -README.zh.md: 4a11d81e6cbdbce1c1e7997785a2cf4456609171 +README.md: 63e9542d4a045c1e3e6da3f6b2365e7b4b01d8f0 +README.zh.md: c1eebceb1a70bd5862a902912bf9f6ec416135ff diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 8b35b970aa..63e9542d4a 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -58,7 +58,7 @@ The concrete `ReactLoopAgent`, its inbox, and run controls are package-internal. The unified `send()` primitive routes content and source by (`target` × `wakeup`); `followup`/`steer`/`inject` are its fixed-preset aliases. `followup()` appends to the `next-turn` FIFO and wakes the driver, `steer()` appends to the `next-step` inbox and wakes it, and `inject()` appends to that same `next-step` inbox without waking it. At a turn boundary the driver opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. Claiming removes the batch through pure deletion splices and emits `agent/inbox/claimed { message, turn }` once per message. `agent/pre-step` then returns either rejection or the complete messages entering the proposed step. Rejection leaves the claimed batch removed and closes the turn without a step; input inserted after the claim remains pending, and idle injection waits until follow-up or steering wakes the driver. -Every inbox mutation publishes one normalized `agent/inbox/spliced` event before changing the live projection. Insertions, edits, removals, claiming, and cancellation replay through the same standard splice coordinates. Ordinary removals carry `outcome: 'canceled'` and emit `agent/inbox/discarded { message }`; claiming uses pure deletions with no outcome, after which the loop emits `agent/inbox/claimed`. Every insertion emits `agent/inbox/inserted { message }`. `MessageId` stays unique across both pending lists, and synchronous durable-event observers can reconstruct removed values from the pre-splice projection. +Every inbox mutation commits one normalized `agent/inbox/spliced` event. The projection registry folds that event synchronously, so the live projection reflects the splice when `Session.append()` returns. Insertions, edits, removals, claiming, and cancellation replay through the same standard splice coordinates. Ordinary removals carry `outcome: 'canceled'` and emit `agent/inbox/discarded { message }`; claiming uses pure deletions with no outcome and emits `agent/inbox/claimed`. Every insertion emits `agent/inbox/inserted { message }`. `MessageId` stays unique across both pending lists. Consumers that need a removed message use the claimed or discarded notification instead of depending on a pre-splice `session/event` view. ### Loop lifecycle (`agent.ts`) diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 4a11d81e6c..c1eebceb1a 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -58,7 +58,7 @@ interface Config { 统一的 `send()` 原语按(`target` × `wakeup`)路由内容与来源;`followup`/`steer`/`inject` 是它的固定预设别名。`followup()` 追加到 `next-turn` FIFO 并唤醒驱动器,`steer()` 追加到 `next-step` inbox 并唤醒驱动器,`inject()` 则追加到同一个 `next-step` inbox,但不唤醒驱动器。在轮次边界,驱动器会先打开持久轮次,再原子领取待处理的 next-step 输入和一条排队提示词;在步骤之间则只领取 next-step 输入。领取操作通过仅执行删除的 splice 移除整批消息,并为每条消息各发出一次 `agent/inbox/claimed { message, turn }`。随后 `agent/pre-step` 返回拒绝结果,或返回将进入拟议步骤的完整消息。拒绝后,已领取批次保持已删除,并关闭不含步骤的轮次;领取后插入的输入仍等待后续处理,而空闲注入会一直等待,直到 follow-up 或 steering 唤醒驱动器。 -每次 inbox 变更都会在修改实时投影之前,先发布一条规范化的 `agent/inbox/spliced` 事件。因此,插入、编辑、移除、领取与取消都通过同一组标准 splice 坐标回放。普通删除携带 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`;领取使用不带 outcome 的纯删除,随后由循环发出 `agent/inbox/claimed`。每次插入都会发出 `agent/inbox/inserted { message }`。`MessageId` 在两个待处理列表之间保持唯一,持久事件的同步观察方可以从 splice 前投影重建被移除的值。 +每次 inbox 变更都会提交一条规范化的 `agent/inbox/spliced` 事件。投影注册表会同步折叠该事件,因此 `Session.append()` 返回时,实时投影已经反映该 splice。插入、编辑、移除、领取与取消都通过同一组标准 splice 坐标回放。普通删除携带 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`;领取使用不带 outcome 的纯删除,并发出 `agent/inbox/claimed`。每次插入都会发出 `agent/inbox/inserted { message }`。`MessageId` 在两个待处理列表之间保持唯一。需要被移除消息的消费方应使用 claimed 或 discarded 通知,而不依赖 splice 前的 `session/event` 投影视图。 ### 循环生命周期(`agent.ts`) From c46c3df2f250adc9117416a0f56e1ba5fc604bda Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 26 Aug 2026 18:10:52 +0800 Subject: [PATCH 08/26] test: cover projection-aware session helpers --- .../preset/agent-presets/tests/remote.spec.ts | 2 ++ .../session-query/tests/observation.spec.ts | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/packages/preset/agent-presets/tests/remote.spec.ts b/packages/preset/agent-presets/tests/remote.spec.ts index bd6232e2c8..daf2bca00d 100644 --- a/packages/preset/agent-presets/tests/remote.spec.ts +++ b/packages/preset/agent-presets/tests/remote.spec.ts @@ -17,6 +17,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { TypertRemoteFailure, type RemoteFailure } from '@deepseek-ai/dsh-typert-protocol' import { afterEach, describe, expect, it, vi } from 'vitest' import AgentPresets, { COMPOSITION_FILE, METADATA_FILE } from '@deepseek-ai/dsh-agent-presets' @@ -72,6 +73,7 @@ async function harness( ctx.loader.builtins.include = Include await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SystemPrompt, { persona: '' }) await ctx.plugin(ToolRuntime) await ctx.plugin(AgentRegistry) diff --git a/packages/session-query/session-query/tests/observation.spec.ts b/packages/session-query/session-query/tests/observation.spec.ts index 91bd1e8bc9..639b0ea9a7 100644 --- a/packages/session-query/session-query/tests/observation.spec.ts +++ b/packages/session-query/session-query/tests/observation.spec.ts @@ -89,6 +89,21 @@ describe('SessionObservationReader', () => { await ctx.fiber.dispose() }) + it('omits prepared projections when the registry is absent', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + const meta = header('prepared-without-projections') + ctx.provide('sessionPersistence', { + borrowSession: () => Promise.resolve(preparedSource(meta)), + } as never) + + using observed = await new SessionObservationReader(ctx).read(meta.id) + + expect(observed.source).toBe('prepared') + expect(observed.projections).toBeUndefined() + await ctx.fiber.dispose() + }) + it('reference-counts prepared leases and rejects retention after disposal', async () => { const ctx = new Context() await ctx.plugin(SessionStore) From 77d0ee38d2c2e7db4cb483ad96bbd0d622118cba Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 26 Aug 2026 18:10:58 +0800 Subject: [PATCH 09/26] docs: refresh Claude SDK notices From ea222a1f729f15efb1cbd210b40c535a9111b7d7 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Thu, 27 Aug 2026 13:26:43 +0800 Subject: [PATCH 10/26] fix(agent): report missing inbox projection --- packages/core/agent/src/inbox.ts | 10 +++++++--- packages/core/agent/tests/agent.spec.ts | 11 +++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/core/agent/src/inbox.ts b/packages/core/agent/src/inbox.ts index 2ffc4bed39..5487a843c9 100644 --- a/packages/core/agent/src/inbox.ts +++ b/packages/core/agent/src/inbox.ts @@ -128,9 +128,13 @@ export class Inbox { /** Read the current durable projection state. */ private current(): InboxState { - // AgentLoop requires sessionProjections; AgentRegistry contributes this unit to it. - // oxlint-disable-next-line typescript/no-non-null-assertion - return this.ctx.sessionProjections.stateOf(this.session, 'inbox')! + const state = this.ctx.sessionProjections.stateOf(this.session, 'inbox') + if (state === undefined) { + throw new Error( + `agent "${this.session.id}" cannot read inbox state: session projection "inbox" is not registered; load AgentRegistry with SessionProjectionRegistry before constructing Inbox`, + ) + } + return state } /** Commit one normalized mutation and publish its live events. */ diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index f6a82a7a7d..a6e8e68659 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -74,6 +74,17 @@ async function reconstructPersistedInbox( } describe('Inbox', () => { + it('reports a missing Inbox projection as a composition error', async () => { + const ctx = new Context() + await ctx.plugin(SessionProjectionRegistry) + const agent = stubAgent('missing-inbox-projection', { ctx }) + const inbox = new Inbox(ctx, agent.session, agentEvents(ctx, agent)) + + expect(() => inbox.nextTurn).toThrow( + 'agent "missing-inbox-projection" cannot read inbox state: session projection "inbox" is not registered; load AgentRegistry with SessionProjectionRegistry before constructing Inbox', + ) + }) + it('rejects invalid durable coordinates and duplicate identities during reconstruction', async () => { const outOfRange = await reconstructPersistedInbox('invalid-inbox-range', (session) => { session.append('agent/inbox/spliced', { From 1101422362d08c3646fe97744e73ee660b97055c Mon Sep 17 00:00:00 2001 From: _Kerman Date: Thu, 27 Aug 2026 14:05:29 +0800 Subject: [PATCH 11/26] refactor(agent): keep concrete inbox loop-internal --- ...claimed-pre-step-inbox-lifecycle.i18n.yaml | 4 +- ...-07-31-claimed-pre-step-inbox-lifecycle.md | 6 +- ...-31-claimed-pre-step-inbox-lifecycle.zh.md | 6 +- apps/cli/tests/fixtures/dsh-badge/snapshot.ts | 5 +- docs/event-producer-consumer.i18n.yaml | 4 +- docs/event-producer-consumer.md | 24 +-- docs/event-producer-consumer.zh.md | 24 +-- docs/subsystems/core.i18n.yaml | 4 +- docs/subsystems/core.md | 61 +++++- docs/subsystems/core.zh.md | 61 +++++- packages/api/session-controller/package.json | 1 + .../commands-queue-attachment.host.spec.ts | 13 +- .../tests/control-jobs.host.spec.ts | 8 +- .../tests/control-queue.host.spec.ts | 55 ++++-- .../tests/session-projections.host.spec.ts | 31 +++- packages/bundle/headless/package.json | 1 + .../bundle/headless/tests/headless.spec.ts | 14 +- .../tests/agent-instructions.spec.ts | 27 ++- .../time-context/tests/time-context.spec.ts | 5 +- .../tmux-context/tests/tmux-context.spec.ts | 5 +- packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 3 +- packages/core/agent-loop/README.zh.md | 3 +- packages/core/agent-loop/src/agent.ts | 7 +- .../core/{agent => agent-loop}/src/inbox.ts | 22 +-- packages/core/agent-loop/tests/inbox.spec.ts | 153 +++++++++++++++ .../agent-loop/tests/interception.spec.ts | 6 +- packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 10 +- packages/core/agent/README.zh.md | 10 +- packages/core/agent/src/index.ts | 1 - packages/core/agent/src/runtime-types.ts | 62 ++++++- packages/core/agent/tests/agent.spec.ts | 174 ++++-------------- packages/e2b/e2b/tests/composition.e2e.ts | 4 +- .../e2b/e2b/tests/fixtures/composition/bin.ts | 5 +- .../tests/command-feedback.spec.ts | 5 +- .../tests/loader-composition.spec.ts | 5 +- .../tests/tools.spec.ts | 5 +- packages/goal/command-goal/package.json | 1 + .../command-goal/tests/command-goal.spec.ts | 7 +- packages/goal/goal/package.json | 1 + packages/goal/goal/tests/goal.spec.ts | 5 +- packages/goal/goal/tests/projection.spec.ts | 2 +- packages/goal/tool-goal/package.json | 1 + .../goal/tool-goal/tests/tool-goal.spec.ts | 17 +- packages/jobs/jobs-local/tests/jobs.spec.ts | 5 +- .../schedule/schedule/tests/runtime.spec.ts | 5 +- .../schedule/schedule/tests/tools.spec.ts | 5 +- .../tests/loader-composition.spec.ts | 5 +- .../tool-bash-persistent/tests/tools.spec.ts | 5 +- .../tests/loader-composition.spec.ts | 5 +- .../tool-pwsh-persistent/tests/tools.spec.ts | 5 +- .../skill/tool-skill/tests/tool-skill.spec.ts | 8 +- .../terminal-bash/tests/index.spec.ts | 11 +- .../terminal-bash/tests/local.spec.ts | 5 +- .../terminal/terminal/tests/service.spec.ts | 5 +- .../tests/loader-composition.spec.ts | 5 +- .../tool-terminal/tests/tools.spec.ts | 5 +- .../agent-loop-testkit/README.i18n.yaml | 4 +- .../test-support/agent-loop-testkit/README.md | 21 ++- .../agent-loop-testkit/README.zh.md | 21 ++- .../agent-loop-testkit/package.json | 2 +- .../agent-loop-testkit/src/inbox.ts | 103 +++++++++++ .../agent-loop-testkit/src/index.ts | 7 +- .../tests/agent-loop-testkit.spec.ts | 66 ++++++- .../tests/loader-composition.spec.ts | 5 +- pnpm-lock.yaml | 15 ++ scripts/type-equiv.manifest.json | 5 + 68 files changed, 829 insertions(+), 370 deletions(-) rename packages/core/{agent => agent-loop}/src/inbox.ts (89%) create mode 100644 packages/core/agent-loop/tests/inbox.spec.ts create mode 100644 packages/test-support/agent-loop-testkit/src/inbox.ts diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml index 93176ac3f9..a18e52843f 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md -2026-07-31-claimed-pre-step-inbox-lifecycle.md: d914b075607181a8b036ede003e2998f18c6be3b -2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 1701b949500c310656f48b9872e1d714a984658a +2026-07-31-claimed-pre-step-inbox-lifecycle.md: 2055770e9f2265f905caa25a6d9235e1e70ea1b8 +2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 099066be3e3422a84b6116e23d8f0c6e82fe9fc1 diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md index d914b07560..2055770e9f 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md @@ -12,11 +12,13 @@ Occurrence-local inbox wrappers also duplicated the identity already carried by ## Decision -Before every proposed step, `Inbox.claim(target)` atomically removes the complete batch: all `next-step` messages and, at a turn boundary, one `next-turn` message. At the initial boundary the loop first commits `turn/start`, so the claim and its single `agent/pre-step` decision have durable turn ownership. Claiming records normalized `agent/inbox/spliced` pure deletions with no outcome, emits `agent/inbox/claimed { message, turn }` once per claimed message, and returns the exclusive batch for the loop's waterfall with `{ turn, step, signal }`. +Before every proposed step, the loop's package-internal `ProjectedInbox` atomically claims the complete batch: all `next-step` messages and, at a turn boundary, one `next-turn` message. At the initial boundary the loop first commits `turn/start`, so the claim and its single `agent/pre-step` decision have durable turn ownership. Claiming records normalized `agent/inbox/spliced` pure deletions with no outcome, emits `agent/inbox/claimed { message, turn }` once per claimed message, and returns the exclusive batch for the loop's waterfall with `{ turn, step, signal }`. `PreStepDecision` is `{ kind: 'reject' } | { kind: 'enter'; messages: UserMessage[] }`. Reject opens no step, leaves the claimed batch removed, and closes the turn as blocked without any step events. Empty entry, cancellation, and failure before `step/start` likewise close a balanced no-step turn. Enter supplies the complete batch appended as `user/message` events after `step/start`. A listener wrapping `next()` preserves downstream changes unless it intentionally replaces them, so all message rewrites settle once in the final return value. There is no `agent/prompt-prepare`, `agent/prompt-submit`, or `agent/step` extension point. -The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming records pure deletions without an outcome and emits claimed events from Inbox itself. These live events add no placement, outcome, or batch fields. +The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming records pure deletions without an outcome and emits claimed events from `ProjectedInbox`. These live events add no placement, outcome, or batch fields. + +`Agent.inbox` exposes only the structural `Inbox` interface for reading and mutating pending work; loop-only `hasPending` and claim operations are absent from that public face. dsh-agent-loop constructs one `ProjectedInbox` and uses it for both structural commands and driver operations. The concrete constructor receives `SessionProjectionRegistry` directly instead of the wider Cordis `Context`, and a missing `inbox` projection throws an explicit composition error. The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `AgentRegistry` contributes the standard `inbox` projection over the durable `agent/inbox/spliced` stream whenever the projection registry is composed; UI edits and removals route through an Inbox mutation method so the same projection records every change. When that projection reconstructs durable history, it rejects unsafe or out-of-range coordinates and duplicate `MessageId` values across both lists, and reports the offending event seq. Whole-queue control consumers use the projection change feed: the Session controller publishes the projection frame, then derives the queue replacement from the same post-fold inbox value. diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md index 1701b94950..099066be3e 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md @@ -12,11 +12,13 @@ Status: implemented ## 决策 -每个拟议步骤之前,`Inbox.claim(target)` 会原子移除完整批次:全部 `next-step` 消息,以及轮次边界上的一条 `next-turn` 消息。在首次边界,循环会先提交 `turn/start`,使领取及其唯一一次 `agent/pre-step` 决策拥有持久轮次归属。领取会记录规范化、不带 outcome 的纯删除 `agent/inbox/spliced`,针对每条已领取消息发出一次 `agent/inbox/claimed { message, turn }`,并把独占批次返回给循环,由后者用 `{ turn, step, signal }` 等待 waterfall(瀑布式事件)。 +每个拟议步骤之前,循环包内部的 `ProjectedInbox` 会原子领取完整批次:全部 `next-step` 消息,以及轮次边界上的一条 `next-turn` 消息。在首次边界,循环会先提交 `turn/start`,使领取及其唯一一次 `agent/pre-step` 决策拥有持久轮次归属。领取会记录规范化、不带 outcome 的纯删除 `agent/inbox/spliced`,针对每条已领取消息发出一次 `agent/inbox/claimed { message, turn }`,并把独占批次返回给循环,由后者用 `{ turn, step, signal }` 等待 waterfall(瀑布式事件)。 `PreStepDecision` 为 `{ kind: 'reject' } | { kind: 'enter'; messages: UserMessage[] }`。reject 不会打开步骤,会让已领取批次保持已删除,并将轮次关闭为 blocked,且不产生任何步骤事件。空的 enter、取消以及 `step/start` 前的失败同样会关闭一个边界平衡的无步骤轮次。enter 提供在 `step/start` 后以 `user/message` 追加的完整批次。包装 `next()` 的监听器会保留下游变更,除非有意替换,因此全部消息改写只在最终返回值中一次性结算。系统不再存在 `agent/prompt-prepare`、`agent/prompt-submit` 或 `agent/step` 扩展点。 -持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取记录不带 outcome 的纯删除,并由 Inbox 自行发出 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 +持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取记录不带 outcome 的纯删除,并由 `ProjectedInbox` 发出 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 + +`Agent.inbox` 只暴露用于读取和变更待处理工作的结构化 `Inbox` 接口;仅供循环使用的 `hasPending` 与领取操作不在该公开接口上。dsh-agent-loop 只构造一个 `ProjectedInbox`,同时用于结构化命令与驱动器操作。具体构造函数直接接收 `SessionProjectionRegistry`,而不是更宽泛的 Cordis `Context`;`inbox` 投影缺失时会抛出明确的组合错误。 两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`AgentRegistry` 会在投影注册表已组合时,在持久 `agent/inbox/spliced` 流上贡献标准 `inbox` 投影;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。该投影重建持久历史时,会拒绝不安全或越界的坐标,以及跨两份列表重复的 `MessageId`,并报告出错事件的 seq。整体队列的 control 消费方使用投影变更流:Session controller 先发布 projection frame,再从同一份折叠后的 inbox 值派生 queue replacement。 diff --git a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts index 5108fdfff2..0add35e72e 100644 --- a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts +++ b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts @@ -1,6 +1,6 @@ import { fileURLToPath } from 'node:url' import { Context } from '@deepseek-ai/cordis' -import { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { boot, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot' import { SessionId } from '@deepseek-ai/dsh-session' @@ -24,7 +24,7 @@ try { id: agentId, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', send: () => {}, followup: () => {}, @@ -34,7 +34,6 @@ try { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', { messages: [], turn: 1, step: 1, signal: new AbortController().signal }, diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index 0b215ee0bb..9e6b341b22 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/event-producer-consumer.md -event-producer-consumer.md: 4bc7cfa29b7c32b5e71705096fa8b02a0c7b0adc -event-producer-consumer.zh.md: 6a22d7b6cb152195e3fd3f2eab35b4142a7beb22 +event-producer-consumer.md: c4038407676c5b0e0eeba2b770768a334d2a83e4 +event-producer-consumer.zh.md: 7bf14ba540d917864229ed80743ff73a94f15a81 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 4bc7cfa29b..c403840767 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -9,18 +9,18 @@ This matrix shows which packages dispatch each harness-owned event and which pac | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:183`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:92`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `remotes` | -| `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:166`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:175`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:297`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`session-telemetry`](../packages/session/session-telemetry) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:204`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:212`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:193`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:238`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-reference`](../packages/context/session-reference), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:251`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/webhook/webhook) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:267`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/session-start` | `emit` | [`packages/core/agent/src/runtime-types.ts:224`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | `agent-team`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:185`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:285`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) | +| `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:220`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:229`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`session-telemetry`](../packages/session/session-telemetry) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:258`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:266`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:247`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:292`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-reference`](../packages/context/session-reference), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:305`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/webhook/webhook) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:321`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/session-start` | `emit` | [`packages/core/agent/src/runtime-types.ts:278`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | `agent-team`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:239`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:339`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:502`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:482`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:509`](../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 6a22d7b6cb..7bf14ba540 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -11,18 +11,18 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:183`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:92`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `remotes` | -| `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:166`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:175`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:297`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`session-telemetry`](../packages/session/session-telemetry) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:204`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:212`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:193`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:238`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-reference`](../packages/context/session-reference), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:251`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/webhook/webhook) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:267`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/session-start` | `emit` | [`packages/core/agent/src/runtime-types.ts:224`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | `agent-team`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:185`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:285`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) | +| `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:220`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:229`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`session-telemetry`](../packages/session/session-telemetry) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:258`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:266`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:247`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:292`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent-instructions`](../packages/context/agent-instructions), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-reference`](../packages/context/session-reference), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-cordis`](../packages/extensions/tool-cordis), [`tool-skill`](../packages/skill/tool-skill), [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/request` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:305`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent), [`webhook`](../packages/webhook/webhook) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:321`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/session-start` | `emit` | [`packages/core/agent/src/runtime-types.ts:278`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | `agent-team`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:239`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:339`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:502`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:482`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:509`](../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 87fb11f958..fc4dfe19ed 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/core.md -core.md: 5813cb12db782a2fa36bdb6d69cc4d3f338c63b0 -core.zh.md: f384267f2a9e54755fa8c1c476564cc5c3443786 +core.md: f1e08b11ec6730960d15c64261936de9e83a5ecc +core.zh.md: 4a61f691a5578e38635fbdd700445e1f47ab4cba diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 5813cb12db..f1e08b11ec 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -65,7 +65,7 @@ interface Agent { readonly options: AgentOptions /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session - /** The agent-owned projection of durable pending work. */ + /** Agent-owned access to durable pending work. */ readonly inbox: Inbox /** The current lifecycle state, mirrored on every `agent/status` transition. */ readonly status: AgentStatus @@ -172,12 +172,69 @@ Dispatch requires `provider` and `model` after `agent/request`. An explicit `rea The inbox is the delivery vocabulary — two ordered pending-message lists the agent owns as a durable projection: +```ts type-equiv +/** Agent-owned access to pending work; concrete storage belongs to the driver. */ +interface Inbox { + /** Prompts awaiting individual turns. */ + readonly nextTurn: readonly UserMessage[] + /** Input awaiting the next step boundary. */ + readonly nextStep: readonly UserMessage[] + + /** Durably cancel all pending input, clearing next-step before next-turn. */ + clear(): void + + /** + * Append one message to a pending list. + * @param target - pending list to extend. + * @param message - message to append. + */ + append(target: InboxTarget, message: UserMessage): void + + /** + * Prepend one message to a pending list. + * @param target - pending list to extend. + * @param message - message to prepend. + */ + prepend(target: InboxTarget, message: UserMessage): void + + /** + * Replace one pending message in place. + * @param messageId - identity of the pending message to replace. + * @param newMessage - replacement message. + * @returns whether the message was still pending. + */ + replace(messageId: MessageId, newMessage: UserMessage): boolean + + /** + * Remove one pending message. + * @param messageId - identity of the pending message to remove. + * @returns whether the message was still pending. + */ + remove(messageId: MessageId): boolean + + /** + * Apply standard splice semantics and durably record the normalized result. + * @param target - pending list to mutate. + * @param start - splice position. + * @param deleteCount - maximum number of messages to remove. + * @param inserted - messages to insert at the resolved position. + * @returns messages removed by the splice. + */ + splice( + target: InboxTarget, + start: number, + deleteCount: number, + inserted: UserMessage[], + ): UserMessage[] +} +``` + ```ts type-equiv /** One of the two ordered pending-message lists owned by an agent. */ type InboxTarget = 'next-turn' | 'next-step' ``` -Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. `Inbox.append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim` record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. `claim(target)` removes the proposed step batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without emitting discarded notifications, then Inbox emits per-message claimed notifications. `AgentRegistry` contributes the standard `inbox` projection whenever the projection registry is composed; its cell is the sole live state and the same fold serves cold consumers. That fold rejects unsafe or out-of-range splice coordinates and duplicate identities across both lists, identifying malformed durable history by event seq. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. +Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. The structural `Inbox` methods record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. At a step boundary, dsh-agent-loop's package-internal `ProjectedInbox` removes the proposed batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without discarded notifications, then emits per-message claimed notifications. Loop-only pending detection and claiming are not part of `Agent.inbox`. `AgentRegistry` contributes the standard `inbox` projection whenever the projection registry is composed; its cell is the sole live state and the same fold serves cold consumers. `ProjectedInbox` depends directly on that registry and reports an explicit missing-projection error when composition is broken. The fold rejects unsafe or out-of-range splice coordinates and duplicate identities across both lists, identifying malformed durable history by event seq. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. Cancellation: diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index f384267f2a..4a61f691a5 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -69,7 +69,7 @@ interface Agent { readonly options: AgentOptions /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session - /** The agent-owned projection of durable pending work. */ + /** Agent-owned access to durable pending work. */ readonly inbox: Inbox /** The current lifecycle state, mirrored on every `agent/status` transition. */ readonly status: AgentStatus @@ -176,12 +176,69 @@ interface AgentOptions { inbox 即投递词汇——agent 以持久投影形式拥有的两条有序待处理消息列表: +```ts type-equiv +/** Agent-owned access to pending work; concrete storage belongs to the driver. */ +interface Inbox { + /** Prompts awaiting individual turns. */ + readonly nextTurn: readonly UserMessage[] + /** Input awaiting the next step boundary. */ + readonly nextStep: readonly UserMessage[] + + /** Durably cancel all pending input, clearing next-step before next-turn. */ + clear(): void + + /** + * Append one message to a pending list. + * @param target - pending list to extend. + * @param message - message to append. + */ + append(target: InboxTarget, message: UserMessage): void + + /** + * Prepend one message to a pending list. + * @param target - pending list to extend. + * @param message - message to prepend. + */ + prepend(target: InboxTarget, message: UserMessage): void + + /** + * Replace one pending message in place. + * @param messageId - identity of the pending message to replace. + * @param newMessage - replacement message. + * @returns whether the message was still pending. + */ + replace(messageId: MessageId, newMessage: UserMessage): boolean + + /** + * Remove one pending message. + * @param messageId - identity of the pending message to remove. + * @returns whether the message was still pending. + */ + remove(messageId: MessageId): boolean + + /** + * Apply standard splice semantics and durably record the normalized result. + * @param target - pending list to mutate. + * @param start - splice position. + * @param deleteCount - maximum number of messages to remove. + * @param inserted - messages to insert at the resolved position. + * @returns messages removed by the splice. + */ + splice( + target: InboxTarget, + start: number, + deleteCount: number, + inserted: UserMessage[], + ): UserMessage[] +} +``` + ```ts type-equiv /** One of the two ordered pending-message lists owned by an agent. */ type InboxTarget = 'next-turn' | 'next-step' ``` -每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。`Inbox.append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。`claim(target)` 通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后由 Inbox 逐条发出 claimed 通知。`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 投影;其 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。该 fold 会拒绝不安全或越界的 splice 坐标,以及跨两份列表重复的标识,并通过事件 seq 指出格式错误的持久历史。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 +每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。结构化 `Inbox` 方法会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。在步骤边界,dsh-agent-loop 包内部的 `ProjectedInbox` 会通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后逐条发出 claimed 通知。仅供循环使用的待处理检测与领取操作不属于 `Agent.inbox`。`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 投影;其 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。`ProjectedInbox` 直接依赖该注册表,并在组合关系损坏时报告明确的投影缺失错误。该 fold 会拒绝不安全或越界的 splice 坐标,以及跨两份列表重复的标识,并通过事件 seq 指出格式错误的持久历史。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 取消: diff --git a/packages/api/session-controller/package.json b/packages/api/session-controller/package.json index dabfd8fd6a..ff03e76bc5 100644 --- a/packages/api/session-controller/package.json +++ b/packages/api/session-controller/package.json @@ -110,6 +110,7 @@ "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-default-model": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-agent-presets": "workspace:^", "@deepseek-ai/dsh-api-gateway": "workspace:^", "@deepseek-ai/dsh-attachment": "workspace:^", 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 2ea8744bd1..079860a4ee 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 @@ -1,14 +1,16 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' -import type { Agent, ModelSelectionRef } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import type { Agent, Inbox, ModelSelectionRef } from '@deepseek-ai/dsh-agent' import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import { createAssistantMessage, createUserMessage, MessageId } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it, vi } from 'vitest' import { ApiSessionAgentController } from '../src/agent.ts' import { SessionCommandController } from '../src/commands.ts' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts' async function commandHarness(): Promise<{ @@ -21,21 +23,22 @@ async function commandHarness(): Promise<{ }> { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) const session = ctx.sessions.create(SessionId('commands-session'), { meta: { cwd: '/workspace' } }) - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) const steer = vi.fn() const cancel = vi.fn() const agent = { id: session.id, session, - inbox, + inbox: undefined as never, status: 'running', ctx, steer, followup: vi.fn(), cancel, } as unknown as Agent + Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox }) ctx.agents.register(agent) ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never) ctx.provide('agentDefaultModel', { @@ -52,7 +55,7 @@ async function commandHarness(): Promise<{ serializeImageAdmission: (_agent: Agent, operation: () => Promise) => operation(), composeAgent: () => Promise.resolve({ setup: () => {} }), } as unknown as ApiSessionAgentController - return { ctx, controller: new SessionCommandController(ctx, agents, '/workspace'), agent, inbox, steer, cancel } + return { ctx, controller: new SessionCommandController(ctx, agents, '/workspace'), agent, inbox: agent.inbox, steer, cancel } } async function expectFailure(operation: Promise, code: string): Promise { diff --git a/packages/api/session-controller/tests/control-jobs.host.spec.ts b/packages/api/session-controller/tests/control-jobs.host.spec.ts index f83fa1b3c8..7963e4cb7f 100644 --- a/packages/api/session-controller/tests/control-jobs.host.spec.ts +++ b/packages/api/session-controller/tests/control-jobs.host.spec.ts @@ -1,10 +1,11 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import type { JobOutcome } from '@deepseek-ai/dsh-jobs' import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { SessionControlController } from '../src/control.ts' import type { SessionControlFrame } from '../src/types.ts' @@ -35,6 +36,7 @@ async function harness(withRegistry: boolean): Promise<{ }> { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) if (withRegistry) { await ctx.plugin(LocalJobRegistry) @@ -44,10 +46,10 @@ async function harness(withRegistry: boolean): Promise<{ const agent = { id: session.id, session, - inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx, - } as Agent + } as unknown as Agent ctx.agents.register(agent) const control = new SessionControlController(ctx) await new Promise(resolve => setTimeout(resolve, 0)) diff --git a/packages/api/session-controller/tests/control-queue.host.spec.ts b/packages/api/session-controller/tests/control-queue.host.spec.ts index 5c48efd4b9..770ddfe4a9 100644 --- a/packages/api/session-controller/tests/control-queue.host.spec.ts +++ b/packages/api/session-controller/tests/control-queue.host.spec.ts @@ -1,10 +1,13 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent' -import type { Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import type { Agent, Inbox } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { SessionControlController } from '../src/control.ts' +import type { SessionControlFrame } from '../src/types.ts' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' async function harness(): Promise<{ ctx: Context @@ -14,12 +17,13 @@ async function harness(): Promise<{ }> { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) const session = ctx.sessions.create(SessionId('queue-session')) - const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }) - const agent = { id: session.id, session, inbox, status: 'running', ctx } as Agent + const agent = { id: session.id, session, inbox: undefined as never, status: 'running', ctx } as unknown as Agent + Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox }) ctx.agents.register(agent) - return { ctx, control: new SessionControlController(ctx), agent, inbox } + return { ctx, control: new SessionControlController(ctx), agent, inbox: agent.inbox } } function message(text: string, source: 'user' | 'plugin' = 'user') { @@ -30,6 +34,17 @@ function message(text: string, source: 'user' | 'plugin' = 'user') { } describe('Session control queue projection', () => { + /** Consume frames until the next queue replacement (inbox projection frames interleave). */ + async function nextQueueFrame( + iterator: AsyncIterator, + ): Promise> { + for (;;) { + const next = await iterator.next() + if (next.done) throw new Error('stream ended before a queue frame') + if (next.value.type === 'queue') return next.value + } + } + it('projects both pending lists in baselines and live replacement frames', async () => { const { control, inbox } = await harness() const queued = message('queued') @@ -57,13 +72,11 @@ describe('Session control queue projection', () => { const replacement = message('replacement') inbox.append('next-turn', replacement) - const replaced = await iterator.next() - if (replaced.done || replaced.value.type !== 'queue') throw new Error('missing queue replacement') - expect(replaced.value.items.map(item => item.id)).toContain(replacement.id) + const replaced = await nextQueueFrame(iterator) + expect(replaced.items.map(item => item.id)).toContain(replacement.id) inbox.remove(steering.id) - const removed = await iterator.next() - if (removed.done || removed.value.type !== 'queue') throw new Error('missing queue replacement') - expect(removed.value.items.map(item => item.id)).not.toContain(steering.id) + const removed = await nextQueueFrame(iterator) + expect(removed.items.map(item => item.id)).not.toContain(steering.id) abort.abort() await iterator.next() @@ -77,7 +90,7 @@ describe('Session control queue projection', () => { await ctx.plugin(SessionProjectionRegistry) const session = ctx.sessions.create(SessionId('late-projection-queue')) const agent = { id: session.id, session, inbox: undefined as never, status: 'running', ctx } as unknown as Agent - Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) + Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox }) ctx.agents.register(agent) const abort = new AbortController() const iterator = control.control(abort.signal)[Symbol.asyncIterator]() @@ -139,14 +152,18 @@ describe('Session control queue projection', () => { const { ctx, control, inbox } = await harness() const iterator = control.control(new AbortController().signal)[Symbol.asyncIterator]() await iterator.next() - inbox.append('next-turn', message('first')) - inbox.append('next-turn', message('second')) + const first = message('first') + const second = message('second') + inbox.append('next-turn', first) + inbox.append('next-turn', second) - const first = await iterator.next() - expect(first).toMatchObject({ done: false, value: { type: 'queue' } }) + const queues: Extract[] = [] await ctx.fiber.dispose() - const second = await iterator.next() - expect(second).toMatchObject({ done: false, value: { type: 'queue' } }) - await expect(iterator.next()).resolves.toMatchObject({ done: true }) + for (;;) { + const next = await iterator.next() + if (next.done) break + if (next.value.type === 'queue') queues.push(next.value) + } + expect(queues.map(queue => queue.items.map(item => item.id))).toEqual([[first.id], [first.id, second.id]]) }) }) diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index dab2e449ed..d42d07daf5 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -10,17 +10,18 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { z } from 'zod' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import { AttachmentStore } from '@deepseek-ai/dsh-attachment' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-presets' import type { Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' -import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import type { Session, SessionEvent, UserMessage } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' import { SessionControlController } from '@deepseek-ai/dsh-api-session-controller/src/control.ts' import type { SessionControlFrame, SessionFollowFrame } from '@deepseek-ai/dsh-api-session-controller/types' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { createSessionTestRemote, testSessionPersistence, type TestSessionRemote } from './test-remote.ts' declare module '@deepseek-ai/dsh-session-projection/types' { @@ -91,7 +92,11 @@ const internalCountUnit = () => ({ stateVersion: 1, }) satisfies ProjectionDefinition<'test/internal-count', number> -async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: Session }> { +async function harness(withRegistry: boolean): Promise<{ + ctx: Context + session: Session + readonly claim: (target: 'next-turn' | 'next-step') => UserMessage[] +}> { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(AgentRegistry) @@ -100,13 +105,21 @@ async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: const agent = { id: session.id, session, - inbox: { nextTurn: [], nextStep: [], hasPending: false } as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx, } as unknown as Agent - if (withRegistry) Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) + const fixture = withRegistry ? createInboxFixture(ctx.sessionProjections, session) : undefined + if (fixture !== undefined) Object.assign(agent, { inbox: fixture.inbox }) ctx.agents.register(agent) - return { ctx, session } + return { + ctx, + session, + claim: (target) => { + if (fixture === undefined) throw new Error('inbox fixture is unavailable without the projection registry') + return fixture.claim(target) + }, + } } /** Append `count` user messages so the log has paginable message boundaries. */ @@ -192,7 +205,7 @@ describe('session.history projections block', () => { }) it('removes claimed steering from the pending Inbox projection immediately', async () => { - const { ctx, session } = await harness(true) + const { ctx, session, claim } = await harness(true) const proxy = remote(ctx) const message = createUserMessage({ content: [{ type: 'text', text: 'apply this now' }], @@ -201,7 +214,7 @@ describe('session.history projections block', () => { const agent = ctx.agents.get(session.id) if (agent === undefined) throw new Error('missing Agent') agent.inbox.append('next-step', message) - agent.inbox.claim('next-step', 1) + claim('next-step') const during = await opening(proxy, session.id) expect(during.projections.values.inbox).toEqual({ @@ -222,7 +235,7 @@ describe('session.history projections block', () => { }) session.append('turn/start', { turn: 1 }) agent.inbox.append('next-step', rejected) - agent.inbox.claim('next-step', 1) + claim('next-step') session.append('turn/end', { turn: 1, reason: { kind: 'blocked' } }) const closed = await opening(proxy, session.id) expect(closed.projections.values.inbox).toEqual({ diff --git a/packages/bundle/headless/package.json b/packages/bundle/headless/package.json index d8c97032c1..0a6ae31818 100644 --- a/packages/bundle/headless/package.json +++ b/packages/bundle/headless/package.json @@ -62,6 +62,7 @@ "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-default-model": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index fab2545d18..6fcd318fa9 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -2,13 +2,14 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentHandle, CreateAgentOptions } from '@deepseek-ai/dsh-agent' import AgentDefaultModelConfig from '@deepseek-ai/dsh-agent-default-model' import { createAssistantMessage } from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { apply, Config, internals } from '../src/index.ts' const originalInternals = { ...internals } @@ -70,25 +71,28 @@ async function bench(script: Script): Promise<{ let idle = Promise.resolve() const agent = {} as Agent const agentCtx = ownerCtx.extend({ agent }) + const inbox = createInboxFixture(ctx.sessionProjections, session) Object.assign(agent, { id: session.id, options: options.agentOptions ?? {}, session, - inbox: undefined as never, + inbox: inbox.inbox, status: 'idle', ctx: agentCtx, cancel: () => {}, runMaintenance: () => Promise.reject(new Error('not used')), send: () => {}, followup: (message: UserMessage) => { - agent.inbox.append('next-turn', message) - idle = Promise.resolve().then(() => script.afterPrompt(session, message)) + inbox.inbox.append('next-turn', message) + const claimed = inbox.claim('next-turn') + const [prompt] = claimed + if (prompt === undefined || claimed.length !== 1) throw new Error('scripted Agent expected one claimed prompt') + idle = Promise.resolve().then(() => script.afterPrompt(session, prompt)) }, steer: () => {}, inject: () => {}, whenIdle: () => idle, } satisfies Partial) - Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) await options.setup?.(agentCtx) script.before?.(session) ctx.agents.register(agent) diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index 7ff5483536..6e2ce185c3 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -7,7 +7,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import * as workspaceContext from '@deepseek-ai/dsh-agent-instructions' import LlmRuntime, { createUserMessage, ToolCallId, type Message, type StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { FileSystem, FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs' @@ -43,6 +43,7 @@ import { import { resolveConfig } from '../src/config.ts' import { candidateScopeKey, renderInstructionChanges, renderWorkspaceInstructionSet, USER_GLOBAL_DIRECTORY, USER_GLOBAL_FILE } from '../src/render.ts' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +import { createInboxFixture, type InboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' /** Per-candidate reconciliation scope key: directory paired with the file name. */ const sk = (directory: string, candidateName: string): string => candidateScopeKey(directory, candidateName) @@ -52,8 +53,16 @@ const isolatedInboxCtx = new Context() await isolatedInboxCtx.plugin(SessionStore) await isolatedInboxCtx.plugin(SessionProjectionRegistry) await isolatedInboxCtx.plugin(AgentRegistry) +const inboxFixtures = new WeakMap() let nextStubSession = 1 +/** Test-driver operations for one structural agent inbox. */ +function inboxFixture(agent: Agent): InboxFixture { + const fixture = inboxFixtures.get(agent) + if (fixture === undefined) throw new Error('agent inbox fixture is unavailable') + return fixture +} + async function tempRepo(): Promise { return mkdtemp(join(tmpdir(), 'dsh-workspace-context-')) } @@ -208,7 +217,9 @@ function stubAgent(cwd?: string, seed: SessionEvent[] = []): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agentCtx, agent.session, agentEvents(agentCtx, agent)) }) + const fixture = createInboxFixture(agentCtx.sessionProjections, session) + Object.assign(agent, { inbox: fixture.inbox }) + inboxFixtures.set(agent, fixture) return agent } @@ -260,7 +271,7 @@ function baselineEvents(agent: Agent): SessionEvent[] { async function appendAdditionalContexts(ctx: Context, agent: Agent): Promise { await syncedWorkspaceContext(ctx, agent) let lastSeq: number | undefined - for (const claimed of agent.inbox.claim('next-step', 1)) { + for (const claimed of inboxFixture(agent).claim('next-step')) { if (claimed.source.kind !== 'agent-instructions') continue const event = agent.session.append('user/message', claimed, { surfaceOp: 'append' }) ctx.emit('session/event', agent.session, event) @@ -278,7 +289,7 @@ async function composeBaselinePrefix(ctx: Context, agent: Agent): Promise Promise.resolve({ kind: 'enter' as const, messages: [] }), ) - const claimed = agent.inbox.claim('next-step', 1) + const claimed = inboxFixture(agent).claim('next-step') const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 2, signal }, @@ -1370,7 +1381,7 @@ describe('workspace context request injection', () => { await ctx.plugin(workspaceContext, { dshHome: home, maxBytes: 65536 }) const resumed = stubAgent(root, [...original.session.events]) agentEvents(ctx, resumed).emit('agent/session-start', { source: 'resume' }) - const claimed = resumed.inbox.claim('next-step', 1) + const claimed = inboxFixture(resumed).claim('next-step') const decision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(1000) }, @@ -1416,7 +1427,7 @@ describe('workspace context request injection', () => { await ctx.plugin(workspaceContext, { dshHome: home, maxBytes: 65536 }) const resumed = stubAgent(root, [...original.session.events]) agentEvents(ctx, resumed).emit('agent/session-start', { source: 'resume' }) - const staleClaim = resumed.inbox.claim('next-step', 1) + const staleClaim = inboxFixture(resumed).claim('next-step') const staleDecision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', { messages: staleClaim, turn: 1, step: 1, signal: AbortSignal.timeout(1000) }, @@ -1469,7 +1480,7 @@ describe('workspace context request injection', () => { await resumedCtx.plugin(workspaceContext, { dshHome: home, maxBytes }) const resumed = stubAgent(root, [...original.session.events]) agentEvents(resumedCtx, resumed).emit('agent/session-start', { source: 'resume' }) - const claimed = resumed.inbox.claim('next-step', 1) + const claimed = inboxFixture(resumed).claim('next-step') const decision = await agentEvents(resumedCtx, resumed).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(1000) }, @@ -4624,7 +4635,7 @@ describe('workspace context inbox synchronization', () => { await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) const agent = stubAgent(join(root, 'pkg')) await syncedWorkspaceContext(ctx, agent) - const claimed = agent.inbox.claim('next-step', 1) + const claimed = inboxFixture(agent).claim('next-step') await write(join(root, 'pkg/AGENTS.md'), 'new claimed rule with more detail') const downstream = { kind: 'enter' as const, messages: claimed } diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index 0e9a964b13..cdaf7c9f93 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -4,7 +4,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import { createUserMessage, ToolCallId, LlmAdapter } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' import { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' @@ -40,7 +40,7 @@ function sessionAgent(session: Session, id = 'agent'): Agent { id: SessionId(id), options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'running', ctx: new Context(), send: () => {}, @@ -51,7 +51,6 @@ function sessionAgent(session: Session, id = 'agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index 9a2066eb16..8cb4403a90 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { ShellExecutor } from '@deepseek-ai/dsh-shell' import type { ShellExecRequest, ShellExecSpec, ShellProcess, ShellRunResult } from '@deepseek-ai/dsh-shell' @@ -96,7 +96,7 @@ function sessionAgent(session: Session, id = 'agent'): Agent { id: SessionId(id), options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'running', ctx: new Context(), send: () => {}, @@ -107,7 +107,6 @@ function sessionAgent(session: Session, id = 'agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 7ebcff4924..b974726560 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent-loop/README.md -README.md: bcd9e639ffc36ceee3424020c78e54e790344a47 -README.zh.md: a87034e72d0bba80cfa153d746ad1d3fd3f6c42f +README.md: 5878c92846e3808ed6702e9addf1aa7170df9bd4 +README.zh.md: 48ebd08f409afb1dcbf5b75354565bbd3fd1fb87 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index bcd9e639ff..5878c92846 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -98,6 +98,7 @@ After `agent/request`, `ctx.llm.prepareCall()` validates adapter-owned fields an |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `AgentLoop` service, config schema, declarative agent startup, factory registration | | [`src/agent.ts`](src/agent.ts) | The concrete `ReactLoopAgent` driver: inbox, turn/step machine, cancellation | +| [`src/inbox.ts`](src/inbox.ts) | Package-internal `ProjectedInbox`: structural commands plus loop-only claim state | | [`src/tool-calls.ts`](src/tool-calls.ts) | Tool scheduling: exclusive barriers and the bounded parallel pool | | [`src/runtime-context.ts`](src/runtime-context.ts) | Per-step runtime-context snapshot handling | | [`src/constants.ts`](src/constants.ts) | `DEFAULT_MAX_PARALLEL_TOOL_CALLS` | @@ -109,7 +110,7 @@ Creation is one rollback-covered transaction: construct a private session, concr ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. 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. `agent/pre-step` decides what enters the step; each successful model call appends one `assistant/message` anchor citing its chunk seqs, 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, and result context remain model-ordered. +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. Its single `ProjectedInbox` field receives `SessionProjectionRegistry` directly; a missing standard projection reports the composition failure before any inbox operation can continue. 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. `agent/pre-step` decides what enters the step; each successful model call appends one `assistant/message` anchor citing its chunk seqs, 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, and result context remain model-ordered. ### Failure and cancellation diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index a87034e72d..48ebd08f40 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -98,6 +98,7 @@ const handle = await ctx.agents.create({ |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`AgentLoop` 服务、配置 schema、声明式 agent 启动、工厂注册 | | [`src/agent.ts`](src/agent.ts) | 具体 `ReactLoopAgent` 驱动器:收件箱、轮次/步骤状态机、取消 | +| [`src/inbox.ts`](src/inbox.ts) | 包内部 `ProjectedInbox`:结构化命令与仅供循环使用的领取状态 | | [`src/tool-calls.ts`](src/tool-calls.ts) | 工具调度:独占屏障与有界并行池 | | [`src/runtime-context.ts`](src/runtime-context.ts) | 每步骤 runtime-context 快照处理 | | [`src/constants.ts`](src/constants.ts) | `DEFAULT_MAX_PARALLEL_TOOL_CALLS` | @@ -109,7 +110,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤;每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。它唯一的 `ProjectedInbox` 字段直接接收 `SessionProjectionRegistry`;标准投影缺失时,会先报告组合错误,不让任何 inbox 操作继续。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤;每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 ### 失败与取消 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 8d4f1afb4f..160397ca6a 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -15,7 +15,7 @@ import type { PreStepDecision, RequestErrorAction, } from '@deepseek-ai/dsh-agent' -import { Inbox, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' +import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm' import { BlockAssembler, @@ -32,6 +32,7 @@ import { canonicalHeader, headerEquals } 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 { Context } from '@deepseek-ai/cordis' +import { ProjectedInbox } from './inbox.ts' import { RuntimeContextProjection } from './runtime-context.ts' import { executeToolCalls } from './tool-calls.ts' @@ -67,7 +68,7 @@ function requestProposal(header: EpochHeader): LlmCallConfig { /** Drives one session through turn and step boundaries. */ export class ReactLoopAgent implements Agent { - readonly inbox: Inbox + readonly inbox: ProjectedInbox private phase: Phase private activityDone: Promise = Promise.resolve() @@ -91,7 +92,7 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, ) { this.dispatch = agentEvents(loopCtx, this) - this.inbox = new Inbox(loopCtx, session, this.dispatch) + this.inbox = new ProjectedInbox(loopCtx.sessionProjections, session, this.dispatch) const lastTurn = session.events.findLast(event => event.type === 'turn/start')?.data.turn ?? 0 this.phase = { kind: 'idle', lastTurn } this.scope = createScope(loopCtx, this) diff --git a/packages/core/agent/src/inbox.ts b/packages/core/agent-loop/src/inbox.ts similarity index 89% rename from packages/core/agent/src/inbox.ts rename to packages/core/agent-loop/src/inbox.ts index 5487a843c9..a8b4ccec8a 100644 --- a/packages/core/agent/src/inbox.ts +++ b/packages/core/agent-loop/src/inbox.ts @@ -1,22 +1,18 @@ /** - * Command facade over the durable agent Inbox projection. + * Driver-owned command facade over the durable agent inbox projection. * - * @module @deepseek-ai/dsh-agent/inbox + * @module @deepseek-ai/dsh-agent-loop/inbox */ -import type { Context } from '@deepseek-ai/cordis' import type { MessageId } from '@deepseek-ai/dsh-llm' -// Type-only: resolves ctx.sessionProjections for the required Inbox projection. -import type {} from '@deepseek-ai/dsh-session-projection' +import type SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' -import type { AgentEventDispatch } from './dispatch.ts' -import type { InboxState } from './inbox-projection.ts' -import type { InboxTarget } from './types.ts' +import type { AgentEventDispatch, Inbox, InboxState, InboxTarget } from '@deepseek-ai/dsh-agent' -/** Agent-owned command facade over the standard durable Inbox projection. */ -export class Inbox { +/** Concrete inbox implementation constructed only by ReactLoopAgent. */ +export class ProjectedInbox implements Inbox { constructor( - private readonly ctx: Context, + private readonly projections: SessionProjectionRegistry, private readonly session: Session, private readonly dispatch: AgentEventDispatch, ) {} @@ -128,10 +124,10 @@ export class Inbox { /** Read the current durable projection state. */ private current(): InboxState { - const state = this.ctx.sessionProjections.stateOf(this.session, 'inbox') + const state = this.projections.stateOf(this.session, 'inbox') if (state === undefined) { throw new Error( - `agent "${this.session.id}" cannot read inbox state: session projection "inbox" is not registered; load AgentRegistry with SessionProjectionRegistry before constructing Inbox`, + `agent "${this.session.id}" cannot read inbox state: session projection "inbox" is not registered; load AgentRegistry with SessionProjectionRegistry before constructing ReactLoopAgent`, ) } return state diff --git a/packages/core/agent-loop/tests/inbox.spec.ts b/packages/core/agent-loop/tests/inbox.spec.ts new file mode 100644 index 0000000000..f26af08deb --- /dev/null +++ b/packages/core/agent-loop/tests/inbox.spec.ts @@ -0,0 +1,153 @@ +import { Context } from '@deepseek-ai/cordis' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session' +import type { UserMessage } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import { describe, expect, it } from 'vitest' +import { ProjectedInbox } from '../src/inbox.ts' + +function stubAgent(rawId: string, overrides: Partial = {}): Agent { + const id = SessionId(rawId) + const session = overrides.session ?? Session.create(id) + const ctx = overrides.ctx ?? new Context() + return { + id, + options: {}, + session, + inbox: { nextTurn: [], nextStep: [] } as never, + status: 'idle', + ctx, + send: () => {}, + followup: () => {}, + steer: () => {}, + inject: () => {}, + cancel() {}, + runMaintenance: task => task(new AbortController().signal), + whenIdle: () => Promise.resolve(), + ...overrides, + } +} + +async function inboxAgent(rawId: string): Promise<{ ctx: Context; session: Session; agent: Agent }> { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + const session = ctx.sessions.create(SessionId(rawId)) + const agent = stubAgent(rawId, { ctx, session }) + Object.assign(agent, { + inbox: new ProjectedInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)), + }) + return { ctx, session, agent } +} + +describe('ProjectedInbox', () => { + it('reports a missing inbox projection as a composition error', async () => { + const ctx = new Context() + await ctx.plugin(SessionProjectionRegistry) + const agent = stubAgent('missing-inbox-projection', { ctx }) + const inbox = new ProjectedInbox( + ctx.sessionProjections, + agent.session, + agentEvents(ctx, agent), + ) + + expect(() => inbox.nextTurn).toThrow( + 'agent "missing-inbox-projection" cannot read inbox state: session projection "inbox" is not registered; load AgentRegistry with SessionProjectionRegistry before constructing ReactLoopAgent', + ) + }) + + it('replaces a pending message by identity across both lists', async () => { + const { ctx, agent } = await inboxAgent('replace-inbox') + const inserted: UserMessage[] = [] + const discarded: UserMessage[] = [] + ctx.on('agent/inbox/inserted', ({ message }) => void inserted.push(message)) + ctx.on('agent/inbox/discarded', ({ message }) => void discarded.push(message)) + const { inbox } = agent + const original = createUserMessage({ + content: [{ type: 'text', text: 'original' }], + source: { kind: 'user' }, + }) + const nextStep = createUserMessage({ + content: [{ type: 'text', text: 'step' }], + source: { kind: 'user' }, + }) + const replacement = createUserMessage({ + content: [{ type: 'text', text: 'replacement' }], + source: { kind: 'user' }, + }) + const editedStep = freezeMessage({ + ...nextStep, + content: [{ type: 'text', text: 'edited step' }], + }) + inbox.append('next-turn', original) + inbox.append('next-step', nextStep) + + expect(inbox.replace(createUserMessage({ + content: [{ type: 'text', text: 'missing' }], + source: { kind: 'user' }, + }).id, replacement)).toBe(false) + expect(inbox.replace(original.id, replacement)).toBe(true) + expect(inbox.replace(nextStep.id, editedStep)).toBe(true) + expect(inbox.nextTurn).toEqual([replacement]) + expect(inbox.nextStep).toEqual([editedStep]) + expect(discarded).toEqual([original, nextStep]) + expect(inserted).toEqual([original, nextStep, replacement, editedStep]) + expect(() => { inbox.replace(editedStep.id, replacement) }) + .toThrow(`message "${replacement.id}" is already pending`) + }) + + it('normalizes splice coordinates, rejects duplicate identities, and reports missing removals', async () => { + const { agent } = await inboxAgent('splice-inbox') + const { inbox } = agent + const first = createUserMessage({ + content: [{ type: 'text', text: 'first' }], + source: { kind: 'user' }, + }) + const second = createUserMessage({ + content: [{ type: 'text', text: 'second' }], + source: { kind: 'user' }, + }) + const prefixed = createUserMessage({ + content: [{ type: 'text', text: 'prefixed' }], + source: { kind: 'user' }, + }) + + inbox.splice('next-turn', Number.NaN, Number.NaN, [first, second]) + expect(inbox.nextTurn).toEqual([first, second]) + expect(inbox.splice('next-turn', -1, 1, [])).toEqual([second]) + inbox.prepend('next-turn', prefixed) + expect(inbox.nextTurn).toEqual([prefixed, first]) + expect(inbox.remove(second.id)).toBe(false) + expect(() => { inbox.append('next-step', first) }).toThrow(`message "${first.id}" is already pending`) + }) + + it('clears both pending lists as durable cancellations', async () => { + const { ctx, session, agent } = await inboxAgent('clear-inbox') + const discarded: UserMessage[] = [] + ctx.on('agent/inbox/discarded', ({ message }) => void discarded.push(message)) + const { inbox } = agent + const nextTurn = createUserMessage({ content: [{ type: 'text', text: 'turn' }], source: { kind: 'user' } }) + const nextStep = createUserMessage({ content: [{ type: 'text', text: 'step' }], source: { kind: 'user' } }) + inbox.append('next-turn', nextTurn) + inbox.append('next-step', nextStep) + const beforeClear = session.events.length + + inbox.clear() + + expect(inbox.nextTurn).toEqual([]) + expect(inbox.nextStep).toEqual([]) + expect(discarded).toEqual([nextStep, nextTurn]) + expect(session.events.slice(beforeClear).map(event => event.type === 'agent/inbox/spliced' + ? event.data + : event.type)).toEqual([ + { target: 'next-step', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' }, + { target: 'next-turn', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' }, + ]) + + inbox.clear() + expect(session.events).toHaveLength(beforeClear + 2) + }) +}) diff --git a/packages/core/agent-loop/tests/interception.spec.ts b/packages/core/agent-loop/tests/interception.spec.ts index aa13b45945..c29cb2ce4b 100644 --- a/packages/core/agent-loop/tests/interception.spec.ts +++ b/packages/core/agent-loop/tests/interception.spec.ts @@ -292,7 +292,8 @@ describe('agent/pre-step', () => { decision.resolve({ kind: 'enter', messages: claimed }) await idle - expect(agent.inbox.hasPending).toBe(false) + expect(agent.inbox.nextTurn).toEqual([]) + expect(agent.inbox.nextStep).toEqual([]) const staged = events(agent).filter(event => event.type === 'turn/start' || event.type === 'user/message') @@ -472,7 +473,8 @@ describe('agent/pre-step', () => { send(agent, 'blocked prompt') }).toThrow('append unavailable') expect(events(agent)).toEqual([]) - expect(agent.inbox.hasPending).toBe(false) + expect(agent.inbox.nextTurn).toEqual([]) + expect(agent.inbox.nextStep).toEqual([]) expect(agent.status).toBe('idle') }) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 96b07a463e..b8a4979101 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent/README.md -README.md: 1fe7340c6fd84f7ff7866688f1fd34d5cc71a243 -README.zh.md: a895971a5a624bacd50dc86d277bf7916e16f9dc +README.md: fae67d0c63b902a19fe27d6ab652b04e486f8eb6 +README.zh.md: fcb09fa68d79aa5e08cadd1a036dcdfbf0721ced diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 1fe7340c6f..fae67d0c63 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -86,18 +86,18 @@ The package is built on one separation: the public `Agent` surface and registry ### Durable inbox -`AgentRegistry` contributes the standard `inbox` session projection whenever the projection registry is composed. The registry folds durable `agent/inbox/spliced` events once and remains the sole owner of the live `{ 'next-turn', 'next-step' }` state; `Inbox` is a command facade that reads that unit rather than replaying or copying the fold. Reconstruction rejects unsafe or out-of-range splice coordinates and duplicate `MessageId` values across both pending lists, reporting the offending event seq instead of accepting malformed durable history. +`AgentRegistry` contributes the standard `inbox` session projection whenever the projection registry is composed. The registry folds durable `agent/inbox/spliced` events once and remains the sole owner of the live `{ 'next-turn', 'next-step' }` state. `Agent.inbox` exposes only the structural `Inbox` interface; dsh-agent-loop owns the package-internal `ProjectedInbox` that reads the projection. Missing projection composition fails explicitly, while reconstruction rejects unsafe or out-of-range splice coordinates and duplicate `MessageId` values across both pending lists and reports the offending event seq. -`Inbox` exposes pending `nextTurn` and `nextStep` messages and mutates them through `append`, `prepend`, `replace`, `remove`, `clear`, `splice`, and `claim`. Ordinary removals and `clear()` are durable cancellations; claiming uses pure deletion splices. Its live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. +`Inbox` exposes pending `nextTurn` and `nextStep` messages and mutates them through `append`, `prepend`, `replace`, `remove`, `clear`, and `splice`. Ordinary removals and `clear()` are durable cancellations. At a step boundary, the loop's internal implementation claims pending input through pure deletion splices. Live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. ### Source map | File | Role | |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `AgentRegistry`, factory slot, initiator scope, `CreateAgentOptions`/`ResumeAgentOptions` | -| [`src/runtime-types.ts`](src/runtime-types.ts) | `Agent`, `AgentStatus`, and the `agent/*` event declarations | -| [`src/types.ts`](src/types.ts) | `AgentOptions`, cancellation causes, and inbox vocabulary | -| [`src/inbox.ts`](src/inbox.ts) | The `Inbox` projection over durable `agent/inbox/spliced` events | +| [`src/runtime-types.ts`](src/runtime-types.ts) | `Agent`, structural `Inbox`, `AgentStatus`, and the `agent/*` event declarations | +| [`src/types.ts`](src/types.ts) | `AgentOptions`, cancellation causes, and inbox projection vocabulary | +| [`src/inbox-projection.ts`](src/inbox-projection.ts) | Standard projection over durable `agent/inbox/spliced` events | | [`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 | diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index a895971a5a..fcb09fa68d 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -86,18 +86,18 @@ await handle.agent.whenIdle() ### 持久 inbox -`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 会话投影。注册表只折叠一次持久 `agent/inbox/spliced` 事件,并继续作为实时 `{ 'next-turn', 'next-step' }` 状态的唯一所有者;`Inbox` 是读取该单元的命令 facade,不会重新回放或复制折叠结果。重建过程会拒绝不安全或越界的 splice 坐标,以及跨两份待处理列表重复的 `MessageId`,并报告出错事件的 seq,而不会接受格式错误的持久历史。 +`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 会话投影。注册表只折叠一次持久 `agent/inbox/spliced` 事件,并继续作为实时 `{ 'next-turn', 'next-step' }` 状态的唯一所有者。`Agent.inbox` 只暴露结构化 `Inbox` 接口;dsh-agent-loop 持有读取该投影的包内部 `ProjectedInbox`。投影组合缺失时会明确失败;重建过程则会拒绝不安全或越界的 splice 坐标,以及跨两份待处理列表重复的 `MessageId`,并报告出错事件的 seq。 -`Inbox` 暴露待处理的 `nextTurn` 与 `nextStep` 消息,并通过 `append`、`prepend`、`replace`、`remove`、`clear`、`splice` 与 `claim` 变更它们。普通删除和 `clear()` 都是持久取消;领取使用纯删除 splice。其实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。 +`Inbox` 暴露待处理的 `nextTurn` 与 `nextStep` 消息,并通过 `append`、`prepend`、`replace`、`remove`、`clear` 与 `splice` 变更它们。普通删除和 `clear()` 都是持久取消。在步骤边界,循环的内部实现会通过纯删除 splice 领取待处理输入。实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。 ### 源码地图 | 文件 | 职责 | |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`AgentRegistry`、工厂槽位、发起方作用域、`CreateAgentOptions`/`ResumeAgentOptions` | -| [`src/runtime-types.ts`](src/runtime-types.ts) | `Agent`、`AgentStatus` 与 `agent/*` 事件声明 | -| [`src/types.ts`](src/types.ts) | `AgentOptions`、取消原因与收件箱词汇 | -| [`src/inbox.ts`](src/inbox.ts) | 持久 `agent/inbox/spliced` 事件之上的 `Inbox` 投影 | +| [`src/runtime-types.ts`](src/runtime-types.ts) | `Agent`、结构化 `Inbox`、`AgentStatus` 与 `agent/*` 事件声明 | +| [`src/types.ts`](src/types.ts) | `AgentOptions`、取消原因与收件箱投影词汇 | +| [`src/inbox-projection.ts`](src/inbox-projection.ts) | 持久 `agent/inbox/spliced` 事件之上的标准投影 | | [`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`:把一个选择耦合到组装与路由 | diff --git a/packages/core/agent/src/index.ts b/packages/core/agent/src/index.ts index b8652b900c..f8884652cb 100644 --- a/packages/core/agent/src/index.ts +++ b/packages/core/agent/src/index.ts @@ -20,7 +20,6 @@ import type { AgentOptions } from './runtime-types.ts' export * from './runtime-types.ts' export * from './types.ts' -export * from './inbox.ts' export * from './consumed-work.ts' export * from './model-selection.ts' export { agentCarrier, agentEvents, assembleContextFor, emitAgentEvent } from './dispatch.ts' diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index c8bc08ecbb..4473453c31 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -7,11 +7,10 @@ import type { Context } from '@deepseek-ai/cordis' import type { Scoped } from '@deepseek-ai/dsh-scope' -import type { LlmCallConfig, LlmFailure, ReasoningEffortId, ResolvedRetryPolicy } from '@deepseek-ai/dsh-llm' +import type { LlmCallConfig, LlmFailure, MessageId, ReasoningEffortId, ResolvedRetryPolicy } from '@deepseek-ai/dsh-llm' import type { AgentCancelCause, Session, UserMessage } from '@deepseek-ai/dsh-session' export type { AgentCancelCause } from '@deepseek-ai/dsh-session' -import type { Inbox } from './inbox.ts' -import type { Agent } from './types.ts' +import type { Agent, InboxTarget } from './types.ts' export type { Agent } from './types.ts' import type {} from '@deepseek-ai/dsh-system-prompt' declare module '@deepseek-ai/dsh-system-prompt' { @@ -43,6 +42,61 @@ export interface CancelOptions { keepInbox?: boolean | undefined } +/** Agent-owned access to pending work; concrete storage belongs to the driver. */ +export interface Inbox { + /** Prompts awaiting individual turns. */ + readonly nextTurn: readonly UserMessage[] + /** Input awaiting the next step boundary. */ + readonly nextStep: readonly UserMessage[] + + /** Durably cancel all pending input, clearing next-step before next-turn. */ + clear(): void + + /** + * Append one message to a pending list. + * @param target - pending list to extend. + * @param message - message to append. + */ + append(target: InboxTarget, message: UserMessage): void + + /** + * Prepend one message to a pending list. + * @param target - pending list to extend. + * @param message - message to prepend. + */ + prepend(target: InboxTarget, message: UserMessage): void + + /** + * Replace one pending message in place. + * @param messageId - identity of the pending message to replace. + * @param newMessage - replacement message. + * @returns whether the message was still pending. + */ + replace(messageId: MessageId, newMessage: UserMessage): boolean + + /** + * Remove one pending message. + * @param messageId - identity of the pending message to remove. + * @returns whether the message was still pending. + */ + remove(messageId: MessageId): boolean + + /** + * Apply standard splice semantics and durably record the normalized result. + * @param target - pending list to mutate. + * @param start - splice position. + * @param deleteCount - maximum number of messages to remove. + * @param inserted - messages to insert at the resolved position. + * @returns messages removed by the splice. + */ + splice( + target: InboxTarget, + start: number, + deleteCount: number, + inserted: UserMessage[], + ): UserMessage[] +} + /** * An agent's lifecycle state, emitted on every transition as `agent/status`: * `idle` means no driver is active; `running` begins when waking input starts @@ -74,7 +128,7 @@ declare module './types.ts' { readonly options: AgentOptions /** The live session this agent drives; its log is the durable source of truth. */ readonly session: Session - /** The agent-owned projection of durable pending work. */ + /** Agent-owned access to durable pending work. */ readonly inbox: Inbox /** The current lifecycle state, mirrored on every `agent/status` transition. */ readonly status: AgentStatus diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index a6e8e68659..99817fe475 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -1,11 +1,8 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { Context, Service, symbols } from '@deepseek-ai/cordis' -import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm' +import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session' -import AgentRegistry, { - agentEvents, - Inbox, -} from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' @@ -27,7 +24,7 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { options: {}, session, inbox: { - nextTurn: [], nextStep: [], hasPending: false, + nextTurn: [], nextStep: [], } as never, status: 'idle', ctx, @@ -43,17 +40,6 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { return agent } -async function inboxAgent(rawId: string): Promise<{ ctx: Context; session: Session; agent: Agent }> { - const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(AgentRegistry) - const session = ctx.sessions.create(SessionId(rawId)) - const agent = stubAgent(rawId, { ctx, session }) - Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) - return { ctx, session, agent } -} - async function reconstructPersistedInbox( rawId: string, populate: (session: Session) => void, @@ -73,18 +59,7 @@ async function reconstructPersistedInbox( throw new Error('persisted inbox reconstruction unexpectedly succeeded') } -describe('Inbox', () => { - it('reports a missing Inbox projection as a composition error', async () => { - const ctx = new Context() - await ctx.plugin(SessionProjectionRegistry) - const agent = stubAgent('missing-inbox-projection', { ctx }) - const inbox = new Inbox(ctx, agent.session, agentEvents(ctx, agent)) - - expect(() => inbox.nextTurn).toThrow( - 'agent "missing-inbox-projection" cannot read inbox state: session projection "inbox" is not registered; load AgentRegistry with SessionProjectionRegistry before constructing Inbox', - ) - }) - +describe('Inbox projection', () => { it('rejects invalid durable coordinates and duplicate identities during reconstruction', async () => { const outOfRange = await reconstructPersistedInbox('invalid-inbox-range', (session) => { session.append('agent/inbox/spliced', { @@ -110,134 +85,52 @@ describe('Inbox', () => { expect((duplicate.cause as Error).message).toBe(`message "${pending.id}" is already pending`) }) - it('projects inherited Inbox events in a forked session', async () => { - const { ctx, session: parent, agent: parentAgent } = await inboxAgent('inbox-fork-parent') + it('projects inherited inbox events in a forked session', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + const parent = ctx.sessions.create(SessionId('inbox-fork-parent')) const inherited = createUserMessage({ content: [{ type: 'text', text: 'parent pending' }], source: { kind: 'user' }, }) - parentAgent.inbox.append('next-turn', inherited) + parent.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, inserted: [inherited], + }) const child = ctx.sessions.fork(parent, undefined, SessionId('inbox-fork-child')) - const childAgent = stubAgent('inbox-fork-child', { ctx, session: child }) - Object.assign(childAgent, { inbox: new Inbox(ctx, childAgent.session, agentEvents(ctx, childAgent)) }) expect(child.header.seedLength).toBe(parent.events.length) - expect(childAgent.inbox.nextTurn).toEqual([inherited]) - expect(childAgent.inbox.nextStep).toEqual([]) + expect(ctx.sessionProjections.stateOf(child, 'inbox')).toEqual({ + 'next-turn': [inherited], + 'next-step': [], + }) + const own = createUserMessage({ content: [{ type: 'text', text: 'child pending' }], source: { kind: 'user' }, }) - childAgent.inbox.append('next-turn', own) - expect(childAgent.inbox.nextTurn).toEqual([inherited, own]) + child.append('agent/inbox/spliced', { + target: 'next-turn', start: 1, inserted: [own], + }) + expect(ctx.sessionProjections.stateOf(child, 'inbox')?.['next-turn']).toEqual([inherited, own]) }) - it('replaces a pending message by identity across both lists', async () => { - const { ctx, agent } = await inboxAgent('replace-inbox') - const inserted: UserMessage[] = [] - const discarded: UserMessage[] = [] - ctx.on('agent/inbox/inserted', ({ message }) => void inserted.push(message)) - ctx.on('agent/inbox/discarded', ({ message }) => void discarded.push(message)) - const { inbox } = agent - const original = createUserMessage({ - content: [{ type: 'text', text: 'original' }], - source: { kind: 'user' }, - }) - const nextStep = createUserMessage({ - content: [{ type: 'text', text: 'step' }], - source: { kind: 'user' }, - }) - const replacement = createUserMessage({ - content: [{ type: 'text', text: 'replacement' }], - source: { kind: 'user' }, - }) - const editedStep = freezeMessage({ - ...nextStep, - content: [{ type: 'text', text: 'edited step' }], - }) - inbox.append('next-turn', original) - inbox.append('next-step', nextStep) - - expect(inbox.replace(createUserMessage({ - content: [{ type: 'text', text: 'missing' }], - source: { kind: 'user' }, - }).id, replacement)).toBe(false) - expect(inbox.replace(original.id, replacement)).toBe(true) - expect(inbox.replace(nextStep.id, editedStep)).toBe(true) - expect(inbox.nextTurn).toEqual([replacement]) - expect(inbox.nextStep).toEqual([editedStep]) - expect(discarded).toEqual([original, nextStep]) - expect(inserted).toEqual([original, nextStep, replacement, editedStep]) - expect(() => { inbox.replace(editedStep.id, replacement) }) - .toThrow(`message "${replacement.id}" is already pending`) - }) - - it('normalizes splice coordinates, rejects duplicate identities, and reports missing removals', async () => { - const { agent } = await inboxAgent('splice-inbox') - const { inbox } = agent - const first = createUserMessage({ - content: [{ type: 'text', text: 'first' }], - source: { kind: 'user' }, - }) - const second = createUserMessage({ - content: [{ type: 'text', text: 'second' }], - source: { kind: 'user' }, - }) - const prefixed = createUserMessage({ - content: [{ type: 'text', text: 'prefixed' }], - source: { kind: 'user' }, - }) - - inbox.splice('next-turn', Number.NaN, Number.NaN, [first, second]) - expect(inbox.nextTurn).toEqual([first, second]) - expect(inbox.splice('next-turn', -1, 1, [])).toEqual([second]) - inbox.prepend('next-turn', prefixed) - expect(inbox.nextTurn).toEqual([prefixed, first]) - expect(inbox.remove(second.id)).toBe(false) - expect(() => { inbox.append('next-step', first) }).toThrow(`message "${first.id}" is already pending`) - }) - - it('clears both pending lists as durable cancellations', async () => { - const { ctx, session, agent } = await inboxAgent('clear-inbox') - const discarded: UserMessage[] = [] - ctx.on('agent/inbox/discarded', ({ message }) => void discarded.push(message)) - const { inbox } = agent - const nextTurn = createUserMessage({ content: [{ type: 'text', text: 'turn' }], source: { kind: 'user' } }) - const nextStep = createUserMessage({ content: [{ type: 'text', text: 'step' }], source: { kind: 'user' } }) - inbox.append('next-turn', nextTurn) - inbox.append('next-step', nextStep) - const beforeClear = session.events.length - - inbox.clear() - - expect(inbox.hasPending).toBe(false) - expect(discarded).toEqual([nextStep, nextTurn]) - expect(session.events.slice(beforeClear).map(event => event.type === 'agent/inbox/spliced' - ? event.data - : event.type)).toEqual([ - { target: 'next-step', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' }, - { target: 'next-turn', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' }, - ]) - - inbox.clear() - expect(session.events).toHaveLength(beforeClear + 2) - }) - - it('registers the durable Inbox projection from the Agent registry', async () => { + it('registers the durable inbox projection from the Agent registry', async () => { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) const agentFiber = ctx.plugin(AgentRegistry) await agentFiber const session = ctx.sessions.create(SessionId('inbox-projection')) - const agent = stubAgent('inbox-projection', { ctx, session }) - Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) }) const pending = createUserMessage({ content: [{ type: 'text', text: 'pending' }], source: { kind: 'user' }, }) - agent.inbox.append('next-turn', pending) + session.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, inserted: [pending], + }) expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ 'next-turn': [pending], @@ -247,15 +140,21 @@ describe('Inbox', () => { expect(ctx.sessionProjections.snapshot(session).values).toEqual({}) }) - it('uses the projection cell as the sole live state after direct durable appends', async () => { - const { ctx, session, agent } = await inboxAgent('inbox-live-projection') + it('updates the projection cell before session observers run', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(AgentRegistry) + const session = ctx.sessions.create(SessionId('inbox-live-projection')) const pending = createUserMessage({ content: [{ type: 'text', text: 'direct' }], source: { kind: 'user' }, }) let observed: readonly UserMessage[] | undefined - ctx.on('session/event', (_session, event) => { - if (event.type === 'agent/inbox/spliced') observed = agent.inbox.nextTurn + ctx.on('session/event', (subject, event) => { + if (subject === session && event.type === 'agent/inbox/spliced') { + observed = ctx.sessionProjections.stateOf(session, 'inbox')?.['next-turn'] + } }) session.append('agent/inbox/spliced', { @@ -263,7 +162,6 @@ describe('Inbox', () => { }) expect(observed).toEqual([pending]) - expect(agent.inbox.nextTurn).toEqual([pending]) expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ 'next-turn': [pending], 'next-step': [], }) diff --git a/packages/e2b/e2b/tests/composition.e2e.ts b/packages/e2b/e2b/tests/composition.e2e.ts index f76b10d644..e214dfa3bf 100644 --- a/packages/e2b/e2b/tests/composition.e2e.ts +++ b/packages/e2b/e2b/tests/composition.e2e.ts @@ -3,7 +3,6 @@ import { join, posix } from 'node:path' import { fileURLToPath } from 'node:url' import { Context } from '@deepseek-ai/cordis' import { describe, expect, it } from 'vitest' -import { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke' import { @@ -85,7 +84,7 @@ describe.skipIf(!process.env.E2B_API_KEY)('E2B live Loader composition', () => { id: ownerId, options: {}, session: ownerSession, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx, send() {}, @@ -96,7 +95,6 @@ describe.skipIf(!process.env.E2B_API_KEY)('E2B live Loader composition', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(owner, { inbox: new Inbox(owner.ctx, owner.session, agentEvents(owner.ctx, owner)) }) const backend = new BashTerminalBackend(ctx, { backendType: 'shell', shellDialect: 'bash', shellPath: '/bin/bash', shellArgs: ['--noprofile', '--norc', '-i'], rows: 24, cols: 80, diff --git a/packages/e2b/e2b/tests/fixtures/composition/bin.ts b/packages/e2b/e2b/tests/fixtures/composition/bin.ts index 54e71feefd..78f3d8e84c 100644 --- a/packages/e2b/e2b/tests/fixtures/composition/bin.ts +++ b/packages/e2b/e2b/tests/fixtures/composition/bin.ts @@ -1,7 +1,7 @@ import { readFile } from 'node:fs/promises' import { resolve } from 'node:path' import { boot } from '@deepseek-ai/dsh-app-boot' -import { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import { type Agent } from '@deepseek-ai/dsh-agent' import { Session, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-fs-e2b' import type {} from '@deepseek-ai/dsh-bash-local' @@ -19,7 +19,7 @@ const owner: Agent = { id: ownerId, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: ownerFiber.ctx, send() {}, @@ -30,7 +30,6 @@ const owner: Agent = { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } -Object.assign(owner, { inbox: new Inbox(ctx, owner.session, agentEvents(ctx, owner)) }) const unregisterOwner = ctx.agents.register(owner) let terminalId: Awaited>['sessionId'] | undefined try { diff --git a/packages/feedback/command-feedback/tests/command-feedback.spec.ts b/packages/feedback/command-feedback/tests/command-feedback.spec.ts index 90c48ffa96..4ae24b2840 100644 --- a/packages/feedback/command-feedback/tests/command-feedback.spec.ts +++ b/packages/feedback/command-feedback/tests/command-feedback.spec.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import SessionStore, { foldSurface, Session, SessionId } from '@deepseek-ai/dsh-session' @@ -48,7 +48,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } id: session.id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, ctx: new Context(), get status() { return status }, send: () => {}, @@ -59,7 +59,6 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return { agent, session } } diff --git a/packages/feedback/command-feedback/tests/loader-composition.spec.ts b/packages/feedback/command-feedback/tests/loader-composition.spec.ts index 831481a702..c6a4125dc6 100644 --- a/packages/feedback/command-feedback/tests/loader-composition.spec.ts +++ b/packages/feedback/command-feedback/tests/loader-composition.spec.ts @@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' @@ -34,7 +34,7 @@ function agent(ctx: Context): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, ctx: scope.ctx, get status() { return status }, send: () => {}, @@ -45,7 +45,6 @@ function agent(ctx: Context): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } 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 e84058c5e7..85fb23b836 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -6,7 +6,7 @@ import { Context } from '@deepseek-ai/cordis' import { FsVersion } from '@deepseek-ai/dsh-fs' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import * as FsPolicy from '@deepseek-ai/dsh-fs-observation-policy' @@ -33,7 +33,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -44,7 +44,6 @@ function agent(ctx: Context, cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/goal/command-goal/package.json b/packages/goal/command-goal/package.json index fe0edc727d..5f7bcb04ba 100644 --- a/packages/goal/command-goal/package.json +++ b/packages/goal/command-goal/package.json @@ -41,6 +41,7 @@ "devDependencies": { "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-goal": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index ec139886ee..b7597b96d0 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -1,13 +1,15 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import GoalService from '@deepseek-ai/dsh-goal' import type { GoalRef } from '@deepseek-ai/dsh-goal' import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as commandGoal from '@deepseek-ai/dsh-command-goal' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' interface Harness { readonly ctx: Context @@ -36,7 +38,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) + Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox }) return { agent, session } } @@ -44,6 +46,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } async function harness(): Promise { const ctx = new Context() await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(CommandRuntime) await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService) diff --git a/packages/goal/goal/package.json b/packages/goal/goal/package.json index 5082782244..37698fc9cc 100644 --- a/packages/goal/goal/package.json +++ b/packages/goal/goal/package.json @@ -69,6 +69,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-agent-spine-demo": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", "@deepseek-ai/dsh-session-projection": "workspace:^", diff --git a/packages/goal/goal/tests/goal.spec.ts b/packages/goal/goal/tests/goal.spec.ts index 6888c4eacc..1793c98afc 100644 --- a/packages/goal/goal/tests/goal.spec.ts +++ b/packages/goal/goal/tests/goal.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage, HarnessError } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session' @@ -12,6 +12,7 @@ import GoalService, { foldGoal, } from '@deepseek-ai/dsh-goal' import type { GoalChangeMeta, GoalRef, GoalSnapshotChangeMeta } from '@deepseek-ai/dsh-goal' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' interface StubAgent { agent: Agent @@ -58,7 +59,7 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: new Inbox(agentCtx, agent.session, agentEvents(agentCtx, agent)) }) + Object.assign(agent, { inbox: createInboxFixture(agentCtx.sessionProjections, session).inbox }) const stub = { agent, session, diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index 3370ab3b41..7ae189de66 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -35,7 +35,7 @@ function liveAgent(ctx: Context, session: Session): Agent { id: session.id, options: {}, session, - inbox: { nextTurn: [], nextStep: [], hasPending: false } as never, + inbox: { nextTurn: [], nextStep: [] } as never, ctx, get status() { return status }, send: () => {}, diff --git a/packages/goal/tool-goal/package.json b/packages/goal/tool-goal/package.json index 576b60b235..835c2da8c7 100644 --- a/packages/goal/tool-goal/package.json +++ b/packages/goal/tool-goal/package.json @@ -47,6 +47,7 @@ "devDependencies": { "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-goal": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index d793886474..7b151a3baf 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import GoalService, { GoalId } from '@deepseek-ai/dsh-goal' import type { GoalRef } from '@deepseek-ai/dsh-goal' @@ -13,6 +13,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' import * as toolGoal from '@deepseek-ai/dsh-tool-goal' +import { createInboxFixture, type InboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' const testToolSignal = new AbortController().signal @@ -26,6 +27,14 @@ const isolatedInboxCtx = new Context() await isolatedInboxCtx.plugin(SessionStore) await isolatedInboxCtx.plugin(SessionProjectionRegistry) await isolatedInboxCtx.plugin(AgentRegistry) +const inboxFixtures = new WeakMap() + +/** Test-driver operations for one structural agent inbox. */ +function inboxFixture(agent: Agent): InboxFixture { + const fixture = inboxFixtures.get(agent) + if (fixture === undefined) throw new Error('agent inbox fixture is unavailable') + return fixture +} /** Build one registry-compatible live agent whose injections enter the durable inbox. */ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): StubAgent { @@ -54,7 +63,9 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: new Inbox(agentCtx, agent.session, agentEvents(agentCtx, agent)) }) + const fixture = createInboxFixture(agentCtx.sessionProjections, session) + Object.assign(agent, { inbox: fixture.inbox }) + inboxFixtures.set(agent, fixture) return { agent, session, setStatus(value) { status = value } } } @@ -68,7 +79,7 @@ function openTurn(stub: StubAgent, source: MessageSource, text = 'prompt'): numb source, }) stub.agent.inbox.append('next-turn', message) - const claimed = stub.agent.inbox.claim('next-turn', turn) + const claimed = inboxFixture(stub.agent).claim('next-turn') if (claimed.length === 0) throw new Error('expected queued turn input') stub.session.append('turn/start', { turn }) for (const admitted of claimed) { diff --git a/packages/jobs/jobs-local/tests/jobs.spec.ts b/packages/jobs/jobs-local/tests/jobs.spec.ts index ce7f2347dc..df035ac948 100644 --- a/packages/jobs/jobs-local/tests/jobs.spec.ts +++ b/packages/jobs/jobs-local/tests/jobs.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, expectTypeOf, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { bindScopeParent, createScope, scopeOf } from '@deepseek-ai/dsh-scope' import type { ScopeKey } from '@deepseek-ai/dsh-scope' @@ -34,7 +34,7 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle' as const, ctx: agentCtx, send: () => {}, @@ -45,7 +45,6 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { runMaintenance: (job: (signal: AbortSignal) => Promise) => job(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) agentScopeDisposers.set(agent, async () => { await scopeFiber.dispose() }) return agent } diff --git a/packages/schedule/schedule/tests/runtime.spec.ts b/packages/schedule/schedule/tests/runtime.spec.ts index 7fc4ed2f1f..f3a9c3e058 100644 --- a/packages/schedule/schedule/tests/runtime.spec.ts +++ b/packages/schedule/schedule/tests/runtime.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentCancelCause, InboxTarget } from '@deepseek-ai/dsh-agent' import type { UserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' @@ -61,7 +61,7 @@ async function harness(): Promise { id: session.id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: new Context(), send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {}, @@ -96,7 +96,6 @@ async function harness(): Promise { steer(_message: UserMessage) {}, inject(_message: UserMessage) {}, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) const disposeAgent = ctx.agents.register(agent) ctx.on('session/event', (_session, event) => { if (event.type === 'schedule/change' && event.data.operation === 'dispatch') order.push('dispatch') diff --git a/packages/schedule/schedule/tests/tools.spec.ts b/packages/schedule/schedule/tests/tools.spec.ts index cdb93e940e..b4dd2c6eda 100644 --- a/packages/schedule/schedule/tests/tools.spec.ts +++ b/packages/schedule/schedule/tests/tools.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentCancelCause, InboxTarget } from '@deepseek-ai/dsh-agent' import { ToolCallId } from '@deepseek-ai/dsh-llm' import type { UserMessage } from '@deepseek-ai/dsh-llm' @@ -28,7 +28,7 @@ function stubAgent(ctx: Context, id: string): Agent { id: session.id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: new Context(), send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {}, @@ -39,7 +39,6 @@ function stubAgent(ctx: Context, id: string): Agent { steer(_message: UserMessage) {}, inject(_message: UserMessage) {}, } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } 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 f72079a8a8..0285746297 100644 --- a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts @@ -8,7 +8,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import * as TerminalLocal from '@deepseek-ai/dsh-terminal-bash' @@ -44,7 +44,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -55,7 +55,6 @@ function agent(ctx: Context, cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/shell/tool-bash-persistent/tests/tools.spec.ts b/packages/shell/tool-bash-persistent/tests/tools.spec.ts index 4e3d25c62d..d5f1aeaccf 100644 --- a/packages/shell/tool-bash-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/tools.spec.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import type { @@ -39,7 +39,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -50,7 +50,6 @@ function agent(ctx: Context, cwd: string | undefined): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } 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 7b5adf966c..fcd99b01c9 100644 --- a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts @@ -9,7 +9,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import * as TerminalBash from '@deepseek-ai/dsh-terminal-bash' @@ -51,7 +51,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -62,7 +62,6 @@ function agent(ctx: Context, cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts index 583e473834..99c5937352 100644 --- a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import type { @@ -39,7 +39,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -50,7 +50,6 @@ function agent(ctx: Context, cwd: string | undefined): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/skill/tool-skill/tests/tool-skill.spec.ts b/packages/skill/tool-skill/tests/tool-skill.spec.ts index c9ad26a31d..b3b85906db 100644 --- a/packages/skill/tool-skill/tests/tool-skill.spec.ts +++ b/packages/skill/tool-skill/tests/tool-skill.spec.ts @@ -8,7 +8,7 @@ import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import { Session, SessionId, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools' -import AgentRegistry, { agentEvents, Inbox, type Agent, type PreStepDecision } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, type Agent, type PreStepDecision } from '@deepseek-ai/dsh-agent' import SkillRegistry from '@deepseek-ai/dsh-skill' import * as SkillFileSystem from '@deepseek-ai/dsh-skill-filesystem' import * as toolSkill from '@deepseek-ai/dsh-tool-skill' @@ -44,7 +44,7 @@ function agentForCwd(cwd: string): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', send: () => {}, followup: () => {}, @@ -54,7 +54,6 @@ function agentForCwd(cwd: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } @@ -63,7 +62,7 @@ function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent { id: SessionId(id), options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'running', ctx: new Context(), send: () => {}, @@ -74,7 +73,6 @@ function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/terminal/terminal-bash/tests/index.spec.ts b/packages/terminal/terminal-bash/tests/index.spec.ts index 566fae5c3e..f39428f5a9 100644 --- a/packages/terminal/terminal-bash/tests/index.spec.ts +++ b/packages/terminal/terminal-bash/tests/index.spec.ts @@ -4,7 +4,7 @@ import { resolve } from 'node:path' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox, type Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' import SandboxProvider from '@deepseek-ai/dsh-sandbox' import type { ConfinedArgv, SandboxPolicy } from '@deepseek-ai/dsh-sandbox' import SandboxPolicyService, { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' @@ -51,7 +51,7 @@ function agent(ctx: Context, cwd?: string): Agent { const id = SessionId('agent') const session = Session.create(id, undefined, { version: 0, id, createdAt: 0, ...cwd === undefined ? {} : { cwd } }) const agent: Agent = { - id, options: {}, session, inbox: undefined as never, + id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx, send: () => {}, @@ -59,7 +59,6 @@ function agent(ctx: Context, cwd?: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } @@ -576,7 +575,7 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { - id: session.id, options: {}, session, inbox: undefined as never, + id: session.id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: ownerFiber.ctx, send: () => {}, @@ -584,7 +583,6 @@ describe('terminal-bash plugin shape', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(owner, { inbox: new Inbox(owner.ctx, owner.session, agentEvents(owner.ctx, owner)) }) ctx.agents.register(owner) const providerFiber = await registerStubLocalBackend(ctx, () => stubLocalSession()) const created = await ctx.terminals.spawn(owner, { type: 'stub' }) @@ -626,7 +624,7 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('pending-mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { - id: session.id, options: {}, session, inbox: undefined as never, + id: session.id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: ownerFiber.ctx, send: () => {}, @@ -634,7 +632,6 @@ describe('terminal-bash plugin shape', () => { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(owner, { inbox: new Inbox(owner.ctx, owner.session, agentEvents(owner.ctx, owner)) }) ctx.agents.register(owner) const gate = Promise.withResolvers() await registerStubLocalBackend(ctx, () => stubLocalSession(() => gate.promise)) diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index 662e27e77f..84b60c9cb3 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' import type { TerminalSendOperation } from '@deepseek-ai/dsh-terminal' @@ -38,7 +38,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { const scope = ctx.plugin(() => {}) const session = Session.create(id) const agent: Agent = { - id, options: {}, session, inbox: undefined as never, + id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -46,7 +46,6 @@ function stubAgent(ctx: Context, rawId: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) return agent } diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index 7fb957be4e..2dddafcea3 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService, { TerminalBackendCleanupError, TerminalError, TerminalSessionId } from '@deepseek-ai/dsh-terminal' import type { @@ -26,7 +26,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { id, options: {}, session, - inbox: undefined as never, + inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scopeFiber.ctx, send: () => {}, @@ -37,7 +37,6 @@ function stubAgent(ctx: Context, rawId: string): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) agentScopeDisposers.set(agent, async () => { await scopeFiber.dispose() }) return agent } diff --git a/packages/terminal/tool-terminal/tests/loader-composition.spec.ts b/packages/terminal/tool-terminal/tests/loader-composition.spec.ts index 96a5ed0964..a5437ba28a 100644 --- a/packages/terminal/tool-terminal/tests/loader-composition.spec.ts +++ b/packages/terminal/tool-terminal/tests/loader-composition.spec.ts @@ -8,7 +8,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' @@ -41,7 +41,7 @@ function agent(ctx: Context): Agent { const id = SessionId('pty-loader-agent') const session = Session.create(id) const value: Agent = { - id, options: {}, session, inbox: undefined as never, + id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -49,7 +49,6 @@ function agent(ctx: Context): Agent { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/packages/terminal/tool-terminal/tests/tools.spec.ts b/packages/terminal/tool-terminal/tests/tools.spec.ts index 5698d82a41..67baa2c65a 100644 --- a/packages/terminal/tool-terminal/tests/tools.spec.ts +++ b/packages/terminal/tool-terminal/tests/tools.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { renderToolsSdk } from '@deepseek-ai/dsh-tools' @@ -18,7 +18,7 @@ function fakeAgent(ctx: Context, rawId: string): Agent { const id = SessionId(rawId) const session = Session.create(id) const agent: Agent = { - id, options: {}, session, inbox: undefined as never, + id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, send: () => {}, @@ -26,7 +26,6 @@ function fakeAgent(ctx: Context, rawId: string): Agent { runMaintenance: job => job(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(agent, { inbox: new Inbox(agent.ctx, agent.session, agentEvents(agent.ctx, agent)) }) ctx.agents.register(agent) return agent } diff --git a/packages/test-support/agent-loop-testkit/README.i18n.yaml b/packages/test-support/agent-loop-testkit/README.i18n.yaml index fa0c5af247..11c5a3c8e7 100644 --- a/packages/test-support/agent-loop-testkit/README.i18n.yaml +++ b/packages/test-support/agent-loop-testkit/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/test-support/agent-loop-testkit/README.md -README.md: 26fca33c24c19ac25a00162943e085c2d753efc7 -README.zh.md: 679a586bce4923283f9eee6a05f511a7733e88f2 +README.md: 9a4ebbd62e7930bc5d4cbfb9acd025104e7fa85b +README.zh.md: 5b41a88106748074f0c265baaea639bdb9e73eb4 diff --git a/packages/test-support/agent-loop-testkit/README.md b/packages/test-support/agent-loop-testkit/README.md index 26fca33c24..9a4ebbd62e 100644 --- a/packages/test-support/agent-loop-testkit/README.md +++ b/packages/test-support/agent-loop-testkit/README.md @@ -1,5 +1,5 @@ --- -description: "Shared service mounting for tests that exercise the concrete AgentLoop, for test authors wiring real loop prerequisites." +description: "Shared prerequisite mounting and session-backed structural Inbox fixtures for tests that exercise agent-loop behavior." kind: "package-library" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. Use it when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. +`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. It also creates a session-backed structural `Inbox` for consumer tests without exposing the production `ProjectedInbox` implementation. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. Use it when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. ## Table of Contents @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -This package gives an AgentLoop test a working service topology before the loop is mounted: call the helper on your test context, then mount `AgentLoop` with the configuration under test and register your adapter and optional plugins. +This package gives an AgentLoop test a working service topology before the loop is mounted and gives consumer tests a structural Inbox backed by the standard session projection. ### Minimal example @@ -41,15 +41,15 @@ await mountAgentLoopTestDependencies(ctx) await ctx.plugin(AgentLoop, { agents: [] }) ``` -The helper activates the LLM, session, system-prompt, tool, and agent services in dependency order and returns before the loop is mounted. System-prompt and tool-registry configuration can be forwarded through `options`; the helper provides no test defaults beyond those the services own. +The mounting helper activates the LLM, session, system-prompt, tool, and agent services in dependency order and returns before the loop is mounted. System-prompt and tool-registry configuration can be forwarded through `options`; the helper provides no test defaults beyond those the services own. After the agent registry has registered the standard inbox projection, `createInboxFixture(ctx.sessionProjections, session)` returns an `inbox` for code under test and a separate `claim` operation for the test driver; every edit appends a durable `agent/inbox/spliced` session event. ### When to use it -Use the helper for tests whose subject is the loop: load order, retries, tool execution, or session behavior on a real prerequisite stack. Mount dependencies directly when a test probes service load order, injection failures, partial topologies, or teardown — the helper hides exactly the wiring such tests must control. +Use the mounting helper for tests whose subject is the loop: load order, retries, tool execution, or session behavior on a real prerequisite stack. Use the Inbox fixture when a consumer test needs durable queue edits without constructing the package-internal `ProjectedInbox`. Mount dependencies directly when a test probes service load order, injection failures, partial topologies, or teardown — the helper hides exactly the wiring such tests must control. ### What can go wrong -A plugin-load failure rejects the helper call; services activated earlier in the sequence remain owned by your context and unwind with it. The context owns every mounted service, so dispose it after the test. +A plugin-load failure rejects the mounting helper call; services activated earlier in the sequence remain owned by your context and unwind with it. The Inbox fixture throws when the registry does not contain the standard inbox projection. The context owns every mounted service, so dispose it after the test. ----- @@ -59,11 +59,11 @@ A plugin-load failure rejects the helper call; services activated earlier in the
Implementation internals — click to expand -This section explains the design of the helper; the observable behavior is fully covered in [Use this package](#use-this-package). +This section explains the design of the test utilities; the observable behavior is fully covered in [Use this package](#use-this-package). ### Design -The helper is one function, `mountAgentLoopTestDependencies`, that mounts five service plugins in a fixed dependency order — LLM, session, system-prompt, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. Ownership stays with the caller's context: every mounted service is context-owned, a plugin-load failure rejects the promise, and earlier services unwind with the context. The implementation lives in [`src/index.ts`](src/index.ts); the [`src/invariant.ts`](src/invariant.ts) companion declares no runtime invariant because the package owns no production event stream or mutable data — consuming test suites exercise its behavior. +`mountAgentLoopTestDependencies` mounts five service plugins in a fixed dependency order — LLM, session, system-prompt, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. `createInboxFixture` implements only the public structural Inbox operations and keeps loop-driver claiming separate; session projection replay supplies its state. Ownership stays with the caller's context and session. The implementations live in [`src/index.ts`](src/index.ts) and [`src/inbox.ts`](src/inbox.ts); the [`src/invariant.ts`](src/invariant.ts) companion declares no runtime invariant because the package owns no production event stream or mutable data — consuming test suites exercise its behavior.
@@ -85,7 +85,7 @@ Read these pages when the package-level contract is not enough. They move from t ## Model Experience -None, as this test-only composition helper neither drives nor modifies model requests. +None, as these test-only utilities neither drive nor modify model requests. #### KV Cache effect @@ -96,9 +96,10 @@ None; this package neither assembles nor sends a provider request. -These limits define what the helper does not share. They are current package constraints, not a task backlog. +These limits define what the utilities do not share. They are current package constraints, not a task backlog. - **Only the mandatory prerequisite spine is shared** — adapters, optional plugins, `AgentLoop`, agents, and context teardown remain caller-owned so scenario-specific ordering stays visible. +- **The Inbox fixture emits durable session events only** — it does not reproduce live `agent/inbox/inserted` or `agent/inbox/discarded` notifications owned by `ProjectedInbox`. ### Dev Note diff --git a/packages/test-support/agent-loop-testkit/README.zh.md b/packages/test-support/agent-loop-testkit/README.zh.md index 679a586bce..5b41a88106 100644 --- a/packages/test-support/agent-loop-testkit/README.zh.md +++ b/packages/test-support/agent-loop-testkit/README.zh.md @@ -1,5 +1,5 @@ --- -description: "为运行具体 AgentLoop 的测试挂载共享服务先决依赖,面向接线真实循环前置依赖的测试作者。" +description: "为测试 agent-loop 行为提供共享先决依赖挂载与基于会话的结构化 Inbox fixture。" kind: "package-library" --- @@ -9,7 +9,7 @@ kind: "package-library" ## 概述 -`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。当测试对象是 loop 行为而非服务接线时使用它;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 +`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。它还为消费方测试创建由会话支撑的结构化 `Inbox`,而不暴露生产环境的 `ProjectedInbox` 实现。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。当测试对象是 loop 行为而非服务接线时使用它;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-library" ## 使用本包 -本包在 loop 挂载前为 AgentLoop 测试提供可用的服务拓扑:在测试上下文上调用此辅助函数,然后用待测配置挂载 `AgentLoop`,并注册你的适配器与可选插件。 +本包在 loop 挂载前为 AgentLoop 测试提供可用的服务拓扑,并为消费方测试提供由标准会话 projection 支撑的结构化 Inbox。 ### 最小示例 @@ -41,15 +41,15 @@ await mountAgentLoopTestDependencies(ctx) await ctx.plugin(AgentLoop, { agents: [] }) ``` -该辅助函数按依赖顺序激活 LLM、会话、系统提示词、工具与 agent 服务,并在 loop 挂载前返回。系统提示词与工具注册表配置可通过 `options` 转发;除服务自有的默认值外,本辅助函数不提供测试默认值。 +挂载辅助函数按依赖顺序激活 LLM、会话、系统提示词、工具与 agent 服务,并在 loop 挂载前返回。系统提示词与工具注册表配置可通过 `options` 转发;除服务自有的默认值外,本辅助函数不提供测试默认值。agent 注册表注册标准 inbox projection 后,`createInboxFixture(ctx.sessionProjections, session)` 会返回供待测代码使用的 `inbox`,并另行返回供测试驱动使用的 `claim` 操作;每次编辑都会追加持久的 `agent/inbox/spliced` 会话事件。 ### 何时使用 -当测试对象是 loop 本身——在真实先决依赖栈上的加载顺序、重试、工具执行或会话行为——时使用此辅助函数。当测试要探测服务加载顺序、注入失败、部分拓扑或清理时,请直接挂载依赖——辅助函数隐藏的正是这类测试必须控制的接线。 +当测试对象是 loop 本身——在真实先决依赖栈上的加载顺序、重试、工具执行或会话行为——时使用挂载辅助函数。当消费方测试需要持久队列编辑但不应构造包内的 `ProjectedInbox` 时,请使用 Inbox fixture。当测试要探测服务加载顺序、注入失败、部分拓扑或清理时,请直接挂载依赖——辅助函数隐藏的正是这类测试必须控制的接线。 ### 可能出什么问题 -插件加载失败会使辅助函数调用被拒绝;顺序中较早激活的服务仍归你的上下文所有,并随上下文一起解除。上下文拥有所有已挂载服务,因此测试结束后请 dispose(资源释放)它。 +插件加载失败会使挂载辅助函数调用被拒绝;顺序中较早激活的服务仍归你的上下文所有,并随上下文一起解除。当注册表不含标准 inbox projection 时,Inbox fixture 会抛出错误。上下文拥有所有已挂载服务,因此测试结束后请 dispose(资源释放)它。 ----- @@ -59,11 +59,11 @@ await ctx.plugin(AgentLoop, { agents: [] })
实现细节——点击展开 -本节解释辅助函数的设计;可观察行为已在[使用本包](#use-this-package)中完整说明。 +本节解释测试辅助工具的设计;可观察行为已在[使用本包](#use-this-package)中完整说明。 ### 设计 -该辅助函数是单个函数 `mountAgentLoopTestDependencies`,按固定依赖顺序——LLM、会话、系统提示词、工具注册表、agent 注册表——挂载五个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。所有权留在调用方的上下文:每个已挂载服务都归上下文所有,插件加载失败会拒绝 promise,较早的服务随上下文一起解除。实现位于 [`src/index.ts`](src/index.ts);[`src/invariant.ts`](src/invariant.ts) 配套入口声明无运行时不变式,因为本包不拥有任何生产事件流或可变数据——消费它的测试套件会检验其行为。 +`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、系统提示词、工具注册表、agent 注册表——挂载五个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。`createInboxFixture` 只实现公开的结构化 Inbox 操作,并将 loop 驱动方的 claim 操作分离;会话 projection 重放提供其状态。所有权留在调用方的上下文与会话。实现位于 [`src/index.ts`](src/index.ts) 与 [`src/inbox.ts`](src/inbox.ts);[`src/invariant.ts`](src/invariant.ts) 配套入口声明无运行时不变式,因为本包不拥有任何生产事件流或可变数据——消费它的测试套件会检验其行为。
@@ -85,7 +85,7 @@ await ctx.plugin(AgentLoop, { agents: [] }) ## 模型体验 -无。该测试专用组合辅助函数既不驱动也不修改模型请求。 +无。这些测试专用辅助工具既不驱动也不修改模型请求。 #### KV Cache 影响 @@ -96,9 +96,10 @@ await ctx.plugin(AgentLoop, { agents: [] }) -这些限制说明辅助函数不共享什么。它们是当前包约束,不是任务积压。 +这些限制说明辅助工具不共享什么。它们是当前包约束,不是任务积压。 - **只共享必需的先决主干**——适配器、可选插件、`AgentLoop`、agent 与上下文清理仍由调用方负责,以使特定场景的挂载顺序清晰可见。 +- **Inbox fixture 只发出持久会话事件**——它不会复现由 `ProjectedInbox` 负责的实时 `agent/inbox/inserted` 或 `agent/inbox/discarded` 通知。 ### 开发备注 diff --git a/packages/test-support/agent-loop-testkit/package.json b/packages/test-support/agent-loop-testkit/package.json index e6a07351ef..58163093cc 100644 --- a/packages/test-support/agent-loop-testkit/package.json +++ b/packages/test-support/agent-loop-testkit/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-agent-loop-testkit", - "description": "Shared prerequisite mounting for tests that exercise the concrete agent loop", + "description": "Shared prerequisite mounting and session-backed Inbox fixtures for agent-loop tests", "version": "0.1.1-rc.2", "publishConfig": { "access": "public" diff --git a/packages/test-support/agent-loop-testkit/src/inbox.ts b/packages/test-support/agent-loop-testkit/src/inbox.ts new file mode 100644 index 0000000000..0c1fd99f1b --- /dev/null +++ b/packages/test-support/agent-loop-testkit/src/inbox.ts @@ -0,0 +1,103 @@ +import type { Inbox, InboxState, InboxTarget } from '@deepseek-ai/dsh-agent' +import type { MessageId } from '@deepseek-ai/dsh-llm' +import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' +import type SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' + +/** A structural Inbox test double and its loop-driver operation. */ +export interface InboxFixture { + /** Session-backed Inbox exposed to the code under test. */ + readonly inbox: Inbox + /** Remove the batch a test driver admits at one boundary. */ + readonly claim: (target: InboxTarget) => UserMessage[] +} + +/** + * Create a session-backed structural Inbox test double for consumer tests. + * @param projections - registry holding the standard inbox projection. + * @param session - session whose durable splices back the test double. + * @returns the structural Inbox and a separate loop-driver claim operation. + */ +export function createInboxFixture( + projections: SessionProjectionRegistry, + session: Session, +): InboxFixture { + const current = (): InboxState => { + const state = projections.stateOf(session, 'inbox') + if (state === undefined) throw new Error('test inbox requires the standard inbox projection') + return state + } + + const locate = (messageId: MessageId): { target: InboxTarget; index: number } | undefined => { + const state = current() + const turnIndex = state['next-turn'].findIndex(message => message.id === messageId) + if (turnIndex >= 0) return { target: 'next-turn', index: turnIndex } + const stepIndex = state['next-step'].findIndex(message => message.id === messageId) + return stepIndex < 0 ? undefined : { target: 'next-step', index: stepIndex } + } + + const mutate = ( + target: InboxTarget, + start: number, + deleteCount: number, + inserted: UserMessage[], + canceled: boolean, + ): UserMessage[] => { + const pending = current()[target] + const integerStart = Number.isNaN(start) ? 0 : Math.trunc(start) + const index = integerStart < 0 + ? Math.max(pending.length + integerStart, 0) + : Math.min(integerStart, pending.length) + const integerCount = Number.isNaN(deleteCount) ? 0 : Math.trunc(deleteCount) + const count = Math.min(Math.max(integerCount, 0), pending.length - index) + if (count === 0 && inserted.length === 0) return [] + const event: SessionEventMap['agent/inbox/spliced'] = { + target, + start: index, + ...(count === 0 ? {} : { removedCount: count }), + inserted, + ...(canceled && count > 0 ? { outcome: 'canceled' } : {}), + } + const removed = pending.slice(index, index + count) + session.append('agent/inbox/spliced', event) + return removed + } + + const inbox: Inbox = { + get nextTurn() { return current()['next-turn'] }, + get nextStep() { return current()['next-step'] }, + clear() { + mutate('next-step', 0, current()['next-step'].length, [], true) + mutate('next-turn', 0, current()['next-turn'].length, [], true) + }, + append(target, message) { + mutate(target, current()[target].length, 0, [message], true) + }, + prepend(target, message) { + mutate(target, 0, 0, [message], true) + }, + replace(messageId, message) { + const location = locate(messageId) + if (location === undefined) return false + mutate(location.target, location.index, 1, [message], true) + return true + }, + remove(messageId) { + const location = locate(messageId) + if (location === undefined) return false + mutate(location.target, location.index, 1, [], true) + return true + }, + splice(target, start, deleteCount, inserted) { + return mutate(target, start, deleteCount, inserted, true) + }, + } + + return { + inbox, + claim: (target) => { + const claimed = mutate('next-step', 0, current()['next-step'].length, [], false) + if (target === 'next-turn') claimed.push(...mutate('next-turn', 0, 1, [], false)) + return claimed + }, + } +} diff --git a/packages/test-support/agent-loop-testkit/src/index.ts b/packages/test-support/agent-loop-testkit/src/index.ts index 7867d00c1e..ae384f45ab 100644 --- a/packages/test-support/agent-loop-testkit/src/index.ts +++ b/packages/test-support/agent-loop-testkit/src/index.ts @@ -1,6 +1,6 @@ /** - * Shared mounting for the services required before tests load the concrete - * agent loop. The caller retains ownership of the context, loop, adapters, + * Shared service mounting and session-backed Inbox fixtures for agent-loop + * tests. Callers retain ownership of their contexts, loops, adapters, * optional plugins, and teardown. * @module @deepseek-ai/dsh-agent-loop-testkit */ @@ -15,6 +15,9 @@ import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-promp import ToolRuntime from '@deepseek-ai/dsh-tools' import type { Config as ToolRuntimeConfig } from '@deepseek-ai/dsh-tools' +export { createInboxFixture } from './inbox.ts' +export type { InboxFixture } from './inbox.ts' + /** Configuration forwarded to the prerequisite service plugins. */ export interface AgentLoopTestDependenciesOptions { /** Configuration for the system-prompt registry. */ diff --git a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts index 233900fc65..6ddf987d79 100644 --- a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts +++ b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts @@ -1,8 +1,15 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' -import { mountAgentLoopTestDependencies } from '../src/index.ts' +import { createInboxFixture, mountAgentLoopTestDependencies } from '../src/index.ts' + +function message(text: string) { + return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }) +} describe('dsh-agent-loop-testkit', () => { it('mounts a configurable prerequisite spine that can activate AgentLoop', async () => { @@ -17,4 +24,61 @@ describe('dsh-agent-loop-testkit', () => { await ctx.fiber.dispose() }) + + it('provides a session-backed structural Inbox with separate driver claims', async () => { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + const session = ctx.sessions.create(SessionId('agent-loop-testkit-inbox')) + const fixture = createInboxFixture(ctx.sessionProjections, session) + const firstTurn = message('first turn') + const secondTurn = message('second turn') + const firstStep = message('first step') + const editedTurn = message('edited turn') + const editedStep = message('edited step') + + fixture.inbox.append('next-turn', firstTurn) + fixture.inbox.prepend('next-turn', secondTurn) + fixture.inbox.append('next-step', firstStep) + expect(fixture.inbox.nextTurn).toEqual([secondTurn, firstTurn]) + expect(fixture.inbox.nextStep).toEqual([firstStep]) + + expect(fixture.inbox.replace(firstTurn.id, editedTurn)).toBe(true) + expect(fixture.inbox.replace(firstStep.id, editedStep)).toBe(true) + expect(fixture.inbox.replace(firstTurn.id, message('missing replacement'))).toBe(false) + expect(fixture.inbox.remove(firstTurn.id)).toBe(false) + expect(fixture.inbox.splice('next-turn', -1, 1, [])).toEqual([editedTurn]) + expect(fixture.inbox.remove(editedStep.id)).toBe(true) + + const claimedStep = message('claimed step') + const claimedTurn = message('claimed turn') + fixture.inbox.splice('next-step', Number.NaN, Number.NaN, [claimedStep]) + fixture.inbox.append('next-turn', claimedTurn) + expect(fixture.claim('next-step')).toEqual([claimedStep]) + expect(fixture.claim('next-turn')).toEqual([secondTurn]) + expect(fixture.inbox.nextTurn).toEqual([claimedTurn]) + + const eventCount = session.events.length + expect(fixture.inbox.splice('next-step', 100, -1, [])).toEqual([]) + expect(session.events).toHaveLength(eventCount) + + fixture.inbox.clear() + expect(fixture.inbox.nextTurn).toEqual([]) + expect(fixture.inbox.nextStep).toEqual([]) + fixture.inbox.clear() + + await ctx.fiber.dispose() + }) + + it('reports a missing standard inbox projection', async () => { + const ctx = new Context() + await ctx.plugin(SessionProjectionRegistry) + const fixture = createInboxFixture( + ctx.sessionProjections, + Session.create(SessionId('agent-loop-testkit-missing-inbox')), + ) + + expect(() => fixture.inbox.nextStep).toThrow('test inbox requires the standard inbox projection') + + await ctx.fiber.dispose() + }) }) diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index afdd1b8d40..fcd0a9f900 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -11,7 +11,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' import { ToolCallId } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' @@ -32,13 +32,12 @@ function agent(ctx: Context): Agent { const id = SessionId('todo-loader-agent') const session = Session.create(id) const value: Agent = { - id, options: {}, session, inbox: undefined as never, + id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, status: 'idle', ctx: scope.ctx, followup: () => {}, steer: () => {}, inject: () => {}, send: () => {}, cancel() {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) }) ctx.agents.register(value) return value } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b6f343d4e8..e0f7aeb5bf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -753,6 +753,9 @@ importers: '@deepseek-ai/dsh-agent-default-model': specifier: workspace:^ version: link:../../core/agent-default-model + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-agent-presets': specifier: workspace:^ version: link:../../preset/agent-presets @@ -1297,6 +1300,9 @@ importers: '@deepseek-ai/dsh-agent-default-model': specifier: workspace:^ version: link:../../core/agent-default-model + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants @@ -5424,6 +5430,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-commands': specifier: workspace:^ version: link:../../interaction/commands @@ -5455,6 +5464,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-agent-spine-demo': specifier: workspace:^ version: link:../../examples/agent-spine-demo @@ -5543,6 +5555,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-goal': specifier: workspace:^ version: link:../goal diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index b54672eb87..7bad8f02bd 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -116,6 +116,11 @@ "symbol": "LlmCallConfigAdapterDefaults", "source": "packages/llm/llm/src/call-config.ts" }, + { + "doc": "docs/subsystems/core.md", + "symbol": "Inbox", + "source": "packages/core/agent/src/runtime-types.ts" + }, { "doc": "docs/subsystems/core.md", "symbol": "InboxTarget", From fc746f7851fb1465bdd4fc761765d6a58f78d842 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 28 Aug 2026 14:49:38 +0800 Subject: [PATCH 12/26] refactor(agent-loop): own inbox projection in loop --- docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.i18n.yaml | 4 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- packages/core/agent-loop/src/agent.ts | 10 +- packages/core/agent-loop/src/inbox.ts | 68 +++++- packages/core/agent-loop/src/index.ts | 26 ++- .../tests/contract-regressions.spec.ts | 16 +- packages/core/agent-loop/tests/inbox.spec.ts | 195 +++++++++++++----- packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 3 +- packages/core/agent/README.zh.md | 3 +- packages/core/agent/package.json | 9 +- packages/core/agent/src/inbox-projection.ts | 53 ----- packages/core/agent/src/index.ts | 6 - packages/core/agent/tests/agent.spec.ts | 132 +----------- packages/core/agent/tsconfig.json | 3 - .../agent-loop-testkit/package.json | 1 + .../agent-loop-testkit/src/inbox.ts | 6 +- .../agent-loop-testkit/src/index.ts | 2 - .../tests/agent-loop-testkit.spec.ts | 13 +- .../agent-loop-testkit/tsconfig.json | 6 + pnpm-lock.yaml | 4 - 25 files changed, 281 insertions(+), 295 deletions(-) delete mode 100644 packages/core/agent/src/inbox-projection.ts diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 4ca92ba463..9af4c5b074 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 2ed8dd593e69b00d659ac71e96e856456a5e9185 -config-catalog.zh.md: dd22bea8e2f47179d9458cfdba1f74726fb78ae2 +config-catalog.md: 06d2b82a3214b8f48f674925ffda97bf56219882 +config-catalog.zh.md: f1f543e17a28c191d2ae9e58d74b112adb71c256 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 2ed8dd593e..06d2b82a32 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -111,7 +111,7 @@ export interface Config { Depends on: [`AgentOptions`](subsystems/core.md) · [`SessionId`](subsystems/core.md) -Source: [`packages/core/agent-loop/src/index.ts:310`](../packages/core/agent-loop/src/index.ts) +Source: [`packages/core/agent-loop/src/index.ts:312`](../packages/core/agent-loop/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index dd22bea8e2..f1f543e17a 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -113,7 +113,7 @@ export interface Config { 依赖:[`AgentOptions`](subsystems/core.zh.md) · [`SessionId`](subsystems/core.zh.md) -来源:[`packages/core/agent-loop/src/index.ts:310`](../packages/core/agent-loop/src/index.ts) +来源:[`packages/core/agent-loop/src/index.ts:312`](../packages/core/agent-loop/src/index.ts) diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index d474380b43..52c6d98ec0 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/event-producer-consumer.md -event-producer-consumer.md: d56e1e30b53c21b5e9415415863278335c00c209 -event-producer-consumer.zh.md: 9b9d29699b1dd8f11580ef7bb39a326b748e92e9 +event-producer-consumer.md: 086ed4e1d692b69a48da8b68d777a8411a346a94 +event-producer-consumer.zh.md: 4142e7c55e5364b4bd24ec0518edae8f67b7803a diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d56e1e30b5..086ed4e1d6 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -7,7 +7,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:238`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:240`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:92`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `remotes` | | `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:220`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:229`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 9b9d29699b..4142e7c55e 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -9,7 +9,7 @@ | 事件 | 模式 | 声明位置 | 派发方 | 监听方 | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:238`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:240`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:92`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `remotes` | | `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:220`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:229`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 7c6969afc4..121a2c5cc6 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -33,7 +33,7 @@ import { joinContextSections, renderContextSections, renderPrompt } from '@deeps 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 { ProjectedInbox } from './inbox.ts' +import { ReactLoopInbox } from './inbox.ts' import { RuntimeContextProjection } from './runtime-context.ts' import { executeToolCalls } from './tool-calls.ts' @@ -69,7 +69,7 @@ function requestProposal(header: EpochHeader): LlmCallConfig { /** Drives one session through turn and step boundaries. */ export class ReactLoopAgent implements Agent { - readonly inbox: ProjectedInbox + readonly inbox: ReactLoopInbox private phase: Phase private activityDone: Promise = Promise.resolve() @@ -93,12 +93,12 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, ) { this.dispatch = agentEvents(loopCtx, this) - this.inbox = new ProjectedInbox(loopCtx.sessionProjections, session, this.dispatch) + this.scope = createScope(loopCtx, this) + this.ctx = this.scope.ctx.extend({ agent: this }) + this.inbox = new ReactLoopInbox(this.ctx.sessionProjections, session, this.dispatch) /* v8 ignore next -- the loop registers its own turnBoundary unit, so the key is always present */ const lastTurn = this.loopCtx.sessionProjections.stateOf(session, 'turnBoundary')?.lastTurn ?? 0 this.phase = { kind: 'idle', lastTurn } - this.scope = createScope(loopCtx, this) - this.ctx = this.scope.ctx.extend({ agent: this }) this.runtimeContext = new RuntimeContextProjection(this.ctx, session) } diff --git a/packages/core/agent-loop/src/inbox.ts b/packages/core/agent-loop/src/inbox.ts index a8b4ccec8a..a040c76d4f 100644 --- a/packages/core/agent-loop/src/inbox.ts +++ b/packages/core/agent-loop/src/inbox.ts @@ -1,21 +1,78 @@ /** - * Driver-owned command facade over the durable agent inbox projection. + * Driver-owned durable agent inbox projection and command facade. * * @module @deepseek-ai/dsh-agent-loop/inbox */ import type { MessageId } from '@deepseek-ai/dsh-llm' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' import type SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' -import type { AgentEventDispatch, Inbox, InboxState, InboxTarget } from '@deepseek-ai/dsh-agent' +import type { + AgentEventDispatch, + Inbox as InboxContract, + InboxState, + InboxTarget, + InboxWireState, +} from '@deepseek-ai/dsh-agent' +import { z } from 'zod' + +/** Wire validation for pending agent input reconstructed from durable inbox splices. */ +export const inboxProjectionSchema = z.object({ + 'next-turn': z.array(z.custom()).readonly(), + 'next-step': z.array(z.custom()).readonly(), +}).readonly() + +/** Standard fold that reconstructs pending input and rejects invalid durable splice history. */ +export const inboxProjectionDefinition = { + key: 'inbox', + stateSchema: inboxProjectionSchema, + init: (): InboxState => ({ 'next-turn': [], 'next-step': [] }), + apply(state: InboxState, event) { + if (event.type !== 'agent/inbox/spliced') return state + const splice = event.data + try { + const inbox = state[splice.target] + const removedCount = splice.removedCount ?? 0 + if (!Number.isSafeInteger(splice.start) || splice.start < 0 || splice.start > inbox.length + || !Number.isSafeInteger(removedCount) || removedCount < 0 + || splice.start + removedCount > inbox.length) { + throw new Error('invalid inbox splice') + } + const next = inbox.toSpliced(splice.start, removedCount, ...splice.inserted) + const ids = new Set() + for (const message of splice.target === 'next-turn' + ? [...next, ...state['next-step']] + : [...state['next-turn'], ...next]) { + if (ids.has(message.id)) throw new Error(`message "${message.id}" is already pending`) + ids.add(message.id) + } + return splice.target === 'next-turn' + ? { 'next-turn': next, 'next-step': state['next-step'] } + : { 'next-turn': state['next-turn'], 'next-step': next } + } catch (error: unknown) { + throw new Error(`invalid persisted inbox splice at session seq ${event.seq}`, { cause: error }) + } + }, + wire: { + // The wire value is the fold state itself: every pending message already + // round-trips the session log as lossless JSON. Only the static type + // narrows to the JSON-safe projection table entry. + viewSchema: inboxProjectionSchema as unknown as z.ZodType, + view: (state: InboxState) => state as unknown as InboxWireState, + }, + stateVersion: 1, +} satisfies ProjectionDefinition<'inbox', InboxState> /** Concrete inbox implementation constructed only by ReactLoopAgent. */ -export class ProjectedInbox implements Inbox { +export class ReactLoopInbox implements InboxContract { constructor( private readonly projections: SessionProjectionRegistry, private readonly session: Session, private readonly dispatch: AgentEventDispatch, - ) {} + ) { + this.projections.register(inboxProjectionDefinition) + } /** Prompts awaiting individual turns. */ get nextTurn(): readonly UserMessage[] { @@ -125,9 +182,10 @@ export class ProjectedInbox implements Inbox { /** Read the current durable projection state. */ private current(): InboxState { const state = this.projections.stateOf(this.session, 'inbox') + /* v8 ignore next -- the constructor registers this key before any read */ if (state === undefined) { throw new Error( - `agent "${this.session.id}" cannot read inbox state: session projection "inbox" is not registered; load AgentRegistry with SessionProjectionRegistry before constructing ReactLoopAgent`, + `agent "${this.session.id}" cannot read inbox state: its projection registration is not active`, ) } return state diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 0f0f4858c7..b92be10dcc 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -33,6 +33,8 @@ import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import { ReactLoopAgent } from './agent.ts' import { DEFAULT_MAX_PARALLEL_TOOL_CALLS } from './constants.ts' +export { inboxProjectionDefinition } from './inbox.ts' + /** Fiber states that cannot own or serve a new lifecycle. */ const INACTIVE_STATES: ReadonlySet = new Set([ FiberState.UNLOADING, @@ -581,15 +583,21 @@ export class AgentLoop extends Service implements AgentFactory { const untrack = this.ownership.track(dispose) let unfollowOwner: () => Promise | void try { - unfollowOwner = ownerCtx.effect(() => () => { - // Owner disposal owns the same quiescence boundary. Its teardown skips - // unregistering this already-running owner effect from inside itself. - if (disposing !== undefined) return - abort.abort(new Error(`agent "${id}" setup aborted: owner disposed during setup`)) - return dispose(true) + unfollowOwner = ownerCtx.effect(function* () { + machine = new ReactLoopAgent(loopCtx, id, options, session) + machineReady.resolve() + yield machine.scope.rawDispose + yield () => { + // Owner disposal owns the same quiescence boundary. Its teardown skips + // unregistering this already-running owner effect from inside itself. + if (disposing !== undefined) return + abort.abort(new Error(`agent "${id}" setup aborted: owner disposed during setup`)) + return dispose(true) + } }, `agentLoop.lifecycle(${id})`) /* v8 ignore start -- ctx.effect throws only on an inactive fiber, which assertActive() above already rejected */ } catch (error: unknown) { + machineReady.resolve() untrack() callerSignal?.removeEventListener('abort', onCallerAbort) this.ownership.signal.removeEventListener('abort', onFactoryTeardown) @@ -606,8 +614,9 @@ export class AgentLoop extends Service implements AgentFactory { throw abort.signal.reason instanceof Error ? abort.signal.reason : new Error(String(abort.signal.reason)) } try { - const agent = machine = new ReactLoopAgent(loopCtx, id, options, session) - machineReady.resolve() + /* v8 ignore next -- a synchronous effect exhausts the generator before returning */ + if (machine === undefined) throw new Error(`agent "${id}" lifecycle did not construct its driver`) + const agent = machine assertLive() return { @@ -631,7 +640,6 @@ export class AgentLoop extends Service implements AgentFactory { dispose, } } catch (error: unknown) { - machineReady.resolve() void dispose() throw error } diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index c9ec773082..ec24a4386e 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -8,7 +8,6 @@ import ToolRuntime, { defineContentToolFixture, type PostToolDecision } from '@d import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' -import { ReactLoopAgent } from '../src/agent.ts' import InvariantRegistry from '@deepseek-ai/dsh-invariants' import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant' @@ -250,7 +249,11 @@ describe('abort during tool execution ends the turn', () => { ? [event.data.content] : [])) .toEqual([]) - expect(agent.inbox.nextStep.map(inboxText)) + expect(agent.session.events + .flatMap(event => event.type === 'agent/inbox/spliced' && event.data.target === 'next-step' + ? [event.data.inserted.map(inboxText)] + : []) + .at(-1)) .toEqual(['accepted result context during disposal']) expect(agent.session.events.filter(event => event.type === 'turn/start')) .toHaveLength(1) @@ -535,10 +538,11 @@ describe('turn numbering continues across seeded sessions', () => { await ctx2.plugin(AgentLoop, { agents: [] }) ctx2.llm.registerAdapter(['mock'], second) - const seeded = ctx2.sessions.create(SessionId('forked'), { seed: [...agent.session.events] }) - const forked = new ReactLoopAgent( - ctx2, SessionId('forked-agent'), { provider: 'mock', model: 'mock' }, seeded, - ) + const { agent: forked } = await ctx2.agents.create({ + sessionId: SessionId('forked'), + seed: [...agent.session.events], + agentOptions: { provider: 'mock', model: 'mock' }, + }) const turns: number[] = [] ctx2.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) }) diff --git a/packages/core/agent-loop/tests/inbox.spec.ts b/packages/core/agent-loop/tests/inbox.spec.ts index f26af08deb..c0c56c1bb2 100644 --- a/packages/core/agent-loop/tests/inbox.spec.ts +++ b/packages/core/agent-loop/tests/inbox.spec.ts @@ -1,12 +1,11 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' -import type { Agent } from '@deepseek-ai/dsh-agent' +import { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session' import type { UserMessage } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' -import { ProjectedInbox } from '../src/inbox.ts' +import { ReactLoopInbox } from '../src/inbox.ts' function stubAgent(rawId: string, overrides: Partial = {}): Agent { const id = SessionId(rawId) @@ -30,33 +29,140 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { } } -async function inboxAgent(rawId: string): Promise<{ ctx: Context; session: Session; agent: Agent }> { +async function inboxAgent(rawId: string): Promise<{ + ctx: Context + session: Session + agent: Agent + inbox: ReactLoopInbox +}> { const ctx = new Context() await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(AgentRegistry) const session = ctx.sessions.create(SessionId(rawId)) const agent = stubAgent(rawId, { ctx, session }) - Object.assign(agent, { - inbox: new ProjectedInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)), - }) - return { ctx, session, agent } + const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) + Object.assign(agent, { inbox }) + return { ctx, session, agent, inbox } } -describe('ProjectedInbox', () => { - it('reports a missing inbox projection as a composition error', async () => { - const ctx = new Context() - await ctx.plugin(SessionProjectionRegistry) - const agent = stubAgent('missing-inbox-projection', { ctx }) - const inbox = new ProjectedInbox( - ctx.sessionProjections, - agent.session, - agentEvents(ctx, agent), - ) +async function reconstructPersistedInbox( + rawId: string, + populate: (session: Session) => void, +): Promise { + const ctx = new Context() + await ctx.plugin(SessionStore) + const session = ctx.sessions.create(SessionId(rawId)) + populate(session) + await ctx.plugin(SessionProjectionRegistry) + const agent = stubAgent(rawId, { ctx, session }) + const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) + try { + void inbox.nextTurn + } catch (error: unknown) { + if (error instanceof Error) return error + throw error + } + throw new Error('persisted inbox reconstruction unexpectedly succeeded') +} - expect(() => inbox.nextTurn).toThrow( - 'agent "missing-inbox-projection" cannot read inbox state: session projection "inbox" is not registered; load AgentRegistry with SessionProjectionRegistry before constructing ReactLoopAgent', - ) +describe('ReactLoopInbox', () => { + it('registers the durable projection in its constructor', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + const session = ctx.sessions.create(SessionId('inbox-projection')) + const pending = createUserMessage({ + content: [{ type: 'text', text: 'pending' }], + source: { kind: 'user' }, + }) + session.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, inserted: [pending], + }) + const agent = stubAgent('inbox-projection', { ctx, session }) + const dispatch = agentEvents(ctx, agent) + const first = new ReactLoopInbox(ctx.sessionProjections, session, dispatch) + const second = new ReactLoopInbox(ctx.sessionProjections, session, dispatch) + + expect(first.nextTurn).toEqual([pending]) + expect(second.nextTurn).toEqual([pending]) + expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ + 'next-turn': [pending], + 'next-step': [], + }) + }) + + it('rejects invalid durable coordinates and duplicate identities during reconstruction', async () => { + const outOfRange = await reconstructPersistedInbox('invalid-inbox-range', (session) => { + session.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, removedCount: 1, inserted: [], + }) + }) + expect(outOfRange.message).toBe('invalid persisted inbox splice at session seq 0') + expect((outOfRange.cause as Error).message).toBe('invalid inbox splice') + + const pending = createUserMessage({ + content: [{ type: 'text', text: 'duplicate' }], + source: { kind: 'user' }, + }) + const duplicate = await reconstructPersistedInbox('invalid-inbox-duplicate', (session) => { + session.append('agent/inbox/spliced', { + target: 'next-turn', start: 0, inserted: [pending], + }) + session.append('agent/inbox/spliced', { + target: 'next-step', start: 0, inserted: [pending], + }) + }) + expect(duplicate.message).toBe('invalid persisted inbox splice at session seq 1') + expect((duplicate.cause as Error).message).toBe(`message "${pending.id}" is already pending`) + }) + + it('projects inherited inbox events in a forked session', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + const parent = ctx.sessions.create(SessionId('inbox-fork-parent')) + const parentAgent = stubAgent('inbox-fork-parent', { ctx, session: parent }) + const parentInbox = new ReactLoopInbox(ctx.sessionProjections, parent, agentEvents(ctx, parentAgent)) + const inherited = createUserMessage({ + content: [{ type: 'text', text: 'parent pending' }], + source: { kind: 'user' }, + }) + parentInbox.append('next-turn', inherited) + const child = ctx.sessions.fork(parent, undefined, SessionId('inbox-fork-child')) + const childAgent = stubAgent('inbox-fork-child', { ctx, session: child }) + const childInbox = new ReactLoopInbox(ctx.sessionProjections, child, agentEvents(ctx, childAgent)) + + expect(child.header.seedLength).toBe(parent.events.length) + expect(childInbox.nextTurn).toEqual([inherited]) + + const own = createUserMessage({ + content: [{ type: 'text', text: 'child pending' }], + source: { kind: 'user' }, + }) + childInbox.append('next-turn', own) + expect(childInbox.nextTurn).toEqual([inherited, own]) + + }) + + it('updates the projection cell before session observers run', async () => { + const { ctx, session, inbox } = await inboxAgent('inbox-live-projection') + const pending = createUserMessage({ + content: [{ type: 'text', text: 'direct' }], + source: { kind: 'user' }, + }) + let observed: readonly UserMessage[] | undefined + ctx.on('session/event', (subject, event) => { + if (subject === session && event.type === 'agent/inbox/spliced') { + observed = ctx.sessionProjections.stateOf(session, 'inbox')?.['next-turn'] + } + }) + + inbox.append('next-turn', pending) + + expect(observed).toEqual([pending]) + expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ + 'next-turn': [pending], 'next-step': [], + }) }) it('replaces a pending message by identity across both lists', async () => { @@ -65,7 +171,6 @@ describe('ProjectedInbox', () => { const discarded: UserMessage[] = [] ctx.on('agent/inbox/inserted', ({ message }) => void inserted.push(message)) ctx.on('agent/inbox/discarded', ({ message }) => void discarded.push(message)) - const { inbox } = agent const original = createUserMessage({ content: [{ type: 'text', text: 'original' }], source: { kind: 'user' }, @@ -82,26 +187,25 @@ describe('ProjectedInbox', () => { ...nextStep, content: [{ type: 'text', text: 'edited step' }], }) - inbox.append('next-turn', original) - inbox.append('next-step', nextStep) + agent.inbox.append('next-turn', original) + agent.inbox.append('next-step', nextStep) - expect(inbox.replace(createUserMessage({ + expect(agent.inbox.replace(createUserMessage({ content: [{ type: 'text', text: 'missing' }], source: { kind: 'user' }, }).id, replacement)).toBe(false) - expect(inbox.replace(original.id, replacement)).toBe(true) - expect(inbox.replace(nextStep.id, editedStep)).toBe(true) - expect(inbox.nextTurn).toEqual([replacement]) - expect(inbox.nextStep).toEqual([editedStep]) + expect(agent.inbox.replace(original.id, replacement)).toBe(true) + expect(agent.inbox.replace(nextStep.id, editedStep)).toBe(true) + expect(agent.inbox.nextTurn).toEqual([replacement]) + expect(agent.inbox.nextStep).toEqual([editedStep]) expect(discarded).toEqual([original, nextStep]) expect(inserted).toEqual([original, nextStep, replacement, editedStep]) - expect(() => { inbox.replace(editedStep.id, replacement) }) + expect(() => { agent.inbox.replace(editedStep.id, replacement) }) .toThrow(`message "${replacement.id}" is already pending`) }) it('normalizes splice coordinates, rejects duplicate identities, and reports missing removals', async () => { const { agent } = await inboxAgent('splice-inbox') - const { inbox } = agent const first = createUserMessage({ content: [{ type: 'text', text: 'first' }], source: { kind: 'user' }, @@ -115,30 +219,29 @@ describe('ProjectedInbox', () => { source: { kind: 'user' }, }) - inbox.splice('next-turn', Number.NaN, Number.NaN, [first, second]) - expect(inbox.nextTurn).toEqual([first, second]) - expect(inbox.splice('next-turn', -1, 1, [])).toEqual([second]) - inbox.prepend('next-turn', prefixed) - expect(inbox.nextTurn).toEqual([prefixed, first]) - expect(inbox.remove(second.id)).toBe(false) - expect(() => { inbox.append('next-step', first) }).toThrow(`message "${first.id}" is already pending`) + agent.inbox.splice('next-turn', Number.NaN, Number.NaN, [first, second]) + expect(agent.inbox.nextTurn).toEqual([first, second]) + expect(agent.inbox.splice('next-turn', -1, 1, [])).toEqual([second]) + agent.inbox.prepend('next-turn', prefixed) + expect(agent.inbox.nextTurn).toEqual([prefixed, first]) + expect(agent.inbox.remove(second.id)).toBe(false) + expect(() => { agent.inbox.append('next-step', first) }).toThrow(`message "${first.id}" is already pending`) }) it('clears both pending lists as durable cancellations', async () => { const { ctx, session, agent } = await inboxAgent('clear-inbox') const discarded: UserMessage[] = [] ctx.on('agent/inbox/discarded', ({ message }) => void discarded.push(message)) - const { inbox } = agent const nextTurn = createUserMessage({ content: [{ type: 'text', text: 'turn' }], source: { kind: 'user' } }) const nextStep = createUserMessage({ content: [{ type: 'text', text: 'step' }], source: { kind: 'user' } }) - inbox.append('next-turn', nextTurn) - inbox.append('next-step', nextStep) + agent.inbox.append('next-turn', nextTurn) + agent.inbox.append('next-step', nextStep) const beforeClear = session.events.length - inbox.clear() + agent.inbox.clear() - expect(inbox.nextTurn).toEqual([]) - expect(inbox.nextStep).toEqual([]) + expect(agent.inbox.nextTurn).toEqual([]) + expect(agent.inbox.nextStep).toEqual([]) expect(discarded).toEqual([nextStep, nextTurn]) expect(session.events.slice(beforeClear).map(event => event.type === 'agent/inbox/spliced' ? event.data @@ -147,7 +250,7 @@ describe('ProjectedInbox', () => { { target: 'next-turn', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' }, ]) - inbox.clear() + agent.inbox.clear() expect(session.events).toHaveLength(beforeClear + 2) }) }) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index b8a4979101..dcd2fd8fac 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent/README.md -README.md: fae67d0c63b902a19fe27d6ab652b04e486f8eb6 -README.zh.md: fcb09fa68d79aa5e08cadd1a036dcdfbf0721ced +README.md: ff66f47c0c748bbb12d50e16adf28865c457a1a4 +README.zh.md: 323eb771f36b38ca914647cd918144f33327ee0d diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index fae67d0c63..ff66f47c0c 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -86,7 +86,7 @@ The package is built on one separation: the public `Agent` surface and registry ### Durable inbox -`AgentRegistry` contributes the standard `inbox` session projection whenever the projection registry is composed. The registry folds durable `agent/inbox/spliced` events once and remains the sole owner of the live `{ 'next-turn', 'next-step' }` state. `Agent.inbox` exposes only the structural `Inbox` interface; dsh-agent-loop owns the package-internal `ProjectedInbox` that reads the projection. Missing projection composition fails explicitly, while reconstruction rejects unsafe or out-of-range splice coordinates and duplicate `MessageId` values across both pending lists and reports the offending event seq. +`Agent.inbox` exposes only the structural `Inbox` interface and the projection vocabulary stays in this package. dsh-agent-loop owns the package-internal `ReactLoopInbox` and the standard `inbox` projection; constructing its concrete inbox ensures that the projection registry owns one registration for the durable `agent/inbox/spliced` fold. The registry remains the sole owner of the live `{ 'next-turn', 'next-step' }` state. Reconstruction rejects unsafe or out-of-range splice coordinates and duplicate `MessageId` values across both pending lists and reports the offending event seq. `Inbox` exposes pending `nextTurn` and `nextStep` messages and mutates them through `append`, `prepend`, `replace`, `remove`, `clear`, and `splice`. Ordinary removals and `clear()` are durable cancellations. At a step boundary, the loop's internal implementation claims pending input through pure deletion splices. Live notifications are deliberately per-message and minimal: `agent/inbox/inserted { message }`, `agent/inbox/claimed { message, turn }`, and `agent/inbox/discarded { message }`. @@ -97,7 +97,6 @@ The package is built on one separation: the public `Agent` surface and registry | [`src/index.ts`](src/index.ts) | Plugin entry: `AgentRegistry`, factory slot, initiator scope, `CreateAgentOptions`/`ResumeAgentOptions` | | [`src/runtime-types.ts`](src/runtime-types.ts) | `Agent`, structural `Inbox`, `AgentStatus`, and the `agent/*` event declarations | | [`src/types.ts`](src/types.ts) | `AgentOptions`, cancellation causes, and inbox projection vocabulary | -| [`src/inbox-projection.ts`](src/inbox-projection.ts) | Standard projection over durable `agent/inbox/spliced` events | | [`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 | diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index fcb09fa68d..323eb771f3 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -86,7 +86,7 @@ await handle.agent.whenIdle() ### 持久 inbox -`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 会话投影。注册表只折叠一次持久 `agent/inbox/spliced` 事件,并继续作为实时 `{ 'next-turn', 'next-step' }` 状态的唯一所有者。`Agent.inbox` 只暴露结构化 `Inbox` 接口;dsh-agent-loop 持有读取该投影的包内部 `ProjectedInbox`。投影组合缺失时会明确失败;重建过程则会拒绝不安全或越界的 splice 坐标,以及跨两份待处理列表重复的 `MessageId`,并报告出错事件的 seq。 +`Agent.inbox` 只暴露结构化 `Inbox` 接口,投影词汇仍位于本包。dsh-agent-loop 持有包内部的 `ReactLoopInbox` 与标准 `inbox` 投影;构造具体 inbox 时会确保投影注册表为持久 `agent/inbox/spliced` fold 持有一份注册。注册表继续作为实时 `{ 'next-turn', 'next-step' }` 状态的唯一所有者。重建过程会拒绝不安全或越界的 splice 坐标,以及跨两份待处理列表重复的 `MessageId`,并报告出错事件的 seq。 `Inbox` 暴露待处理的 `nextTurn` 与 `nextStep` 消息,并通过 `append`、`prepend`、`replace`、`remove`、`clear` 与 `splice` 变更它们。普通删除和 `clear()` 都是持久取消。在步骤边界,循环的内部实现会通过纯删除 splice 领取待处理输入。实时通知刻意采用逐消息的最小载荷:`agent/inbox/inserted { message }`、`agent/inbox/claimed { message, turn }` 与 `agent/inbox/discarded { message }`。 @@ -97,7 +97,6 @@ await handle.agent.whenIdle() | [`src/index.ts`](src/index.ts) | 插件入口:`AgentRegistry`、工厂槽位、发起方作用域、`CreateAgentOptions`/`ResumeAgentOptions` | | [`src/runtime-types.ts`](src/runtime-types.ts) | `Agent`、结构化 `Inbox`、`AgentStatus` 与 `agent/*` 事件声明 | | [`src/types.ts`](src/types.ts) | `AgentOptions`、取消原因与收件箱投影词汇 | -| [`src/inbox-projection.ts`](src/inbox-projection.ts) | 持久 `agent/inbox/spliced` 事件之上的标准投影 | | [`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`:把一个选择耦合到组装与路由 | diff --git a/packages/core/agent/package.json b/packages/core/agent/package.json index 625a0e47b1..b0125d6a0c 100644 --- a/packages/core/agent/package.json +++ b/packages/core/agent/package.json @@ -44,11 +44,7 @@ "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-typert-protocol": "workspace:^", - "@deepseek-ai/cordis": "workspace:^", - "@deepseek-ai/dsh-session-projection": "workspace:^" - }, - "dependencies": { - "zod": "^4.4.3" + "@deepseek-ai/cordis": "workspace:^" }, "devDependencies": { "@deepseek-ai/dsh-invariants": "workspace:^", @@ -59,7 +55,6 @@ "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-typert-protocol": "workspace:^", "@deepseek-ai/dsh-typert-registry": "workspace:^", - "@deepseek-ai/cordis": "workspace:^", - "@deepseek-ai/dsh-session-projection": "workspace:^" + "@deepseek-ai/cordis": "workspace:^" } } diff --git a/packages/core/agent/src/inbox-projection.ts b/packages/core/agent/src/inbox-projection.ts deleted file mode 100644 index 5eba9ad87a..0000000000 --- a/packages/core/agent/src/inbox-projection.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** Inbox projection schema and its inferred wire value. */ - -import type { UserMessage } from '@deepseek-ai/dsh-llm/types' -import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' -import { z } from 'zod' -import type { InboxState, InboxWireState } from './types.ts' - -/** Wire validation for pending agent input reconstructed from durable inbox splices. */ -export const inboxProjectionSchema = z.object({ - 'next-turn': z.array(z.custom()).readonly(), - 'next-step': z.array(z.custom()).readonly(), -}).readonly() - -/** Standard fold that reconstructs pending input and rejects invalid durable splice history. */ -export const inboxProjectionDefinition = { - key: 'inbox', - stateSchema: inboxProjectionSchema, - init: (): InboxState => ({ 'next-turn': [], 'next-step': [] }), - apply(state: InboxState, event) { - if (event.type !== 'agent/inbox/spliced') return state - const splice = event.data - try { - const inbox = state[splice.target] - const removedCount = splice.removedCount ?? 0 - if (!Number.isSafeInteger(splice.start) || splice.start < 0 || splice.start > inbox.length - || !Number.isSafeInteger(removedCount) || removedCount < 0 - || splice.start + removedCount > inbox.length) { - throw new Error('invalid inbox splice') - } - const next = inbox.toSpliced(splice.start, removedCount, ...splice.inserted) - const ids = new Set() - for (const message of splice.target === 'next-turn' - ? [...next, ...state['next-step']] - : [...state['next-turn'], ...next]) { - if (ids.has(message.id)) throw new Error(`message "${message.id}" is already pending`) - ids.add(message.id) - } - return splice.target === 'next-turn' - ? { 'next-turn': next, 'next-step': state['next-step'] } - : { 'next-turn': state['next-turn'], 'next-step': next } - } catch (error: unknown) { - throw new Error(`invalid persisted inbox splice at session seq ${event.seq}`, { cause: error }) - } - }, - wire: { - // The wire value is the fold state itself: every pending message already - // round-trips the session log as lossless JSON. Only the static type - // narrows to the JSON-safe projection table entry. - viewSchema: inboxProjectionSchema as unknown as z.ZodType, - view: (state: InboxState) => state as unknown as InboxWireState, - }, - stateVersion: 1, -} satisfies ProjectionDefinition<'inbox', InboxState> diff --git a/packages/core/agent/src/index.ts b/packages/core/agent/src/index.ts index 363081ea6e..dae6b1b239 100644 --- a/packages/core/agent/src/index.ts +++ b/packages/core/agent/src/index.ts @@ -12,9 +12,6 @@ import { isPromise } from 'node:util/types' import { scopeTarget } from '@deepseek-ai/dsh-scope' import type { Scoped } from '@deepseek-ai/dsh-scope' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' -// Type-only: resolves ctx.sessionProjections for the optional Inbox projection contribution. -import type {} from '@deepseek-ai/dsh-session-projection' -import { inboxProjectionDefinition } from './inbox-projection.ts' import type { Agent } from './types.ts' import type { AgentOptions } from './runtime-types.ts' @@ -258,9 +255,6 @@ export class AgentRegistry extends Service { constructor(ctx: Context) { super(ctx, 'agents') - ctx.inject(['sessionProjections'], (projectionCtx) => { - projectionCtx.sessionProjections.register(inboxProjectionDefinition) - }) ctx.inject(['typert'], (typeCtx) => { typeCtx.typert.lookups.register('agent', { parameter: 'agent', diff --git a/packages/core/agent/tests/agent.spec.ts b/packages/core/agent/tests/agent.spec.ts index 99817fe475..f0649dd5f5 100644 --- a/packages/core/agent/tests/agent.spec.ts +++ b/packages/core/agent/tests/agent.spec.ts @@ -1,9 +1,7 @@ import { describe, expect, expectTypeOf, it } from 'vitest' import { Context, Service, symbols } from '@deepseek-ai/cordis' -import { createUserMessage } from '@deepseek-ai/dsh-llm' -import SessionStore, { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session' +import { Session, SessionId } from '@deepseek-ai/dsh-session' import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import type { @@ -40,134 +38,6 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { return agent } -async function reconstructPersistedInbox( - rawId: string, - populate: (session: Session) => void, -): Promise { - const ctx = new Context() - await ctx.plugin(SessionStore) - const session = ctx.sessions.create(SessionId(rawId)) - populate(session) - await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(AgentRegistry) - try { - ctx.sessionProjections.stateOf(session, 'inbox') - } catch (error: unknown) { - if (error instanceof Error) return error - throw error - } - throw new Error('persisted inbox reconstruction unexpectedly succeeded') -} - -describe('Inbox projection', () => { - it('rejects invalid durable coordinates and duplicate identities during reconstruction', async () => { - const outOfRange = await reconstructPersistedInbox('invalid-inbox-range', (session) => { - session.append('agent/inbox/spliced', { - target: 'next-turn', start: 0, removedCount: 1, inserted: [], - }) - }) - expect(outOfRange.message).toBe('invalid persisted inbox splice at session seq 0') - expect((outOfRange.cause as Error).message).toBe('invalid inbox splice') - - const pending = createUserMessage({ - content: [{ type: 'text', text: 'duplicate' }], - source: { kind: 'user' }, - }) - const duplicate = await reconstructPersistedInbox('invalid-inbox-duplicate', (session) => { - session.append('agent/inbox/spliced', { - target: 'next-turn', start: 0, inserted: [pending], - }) - session.append('agent/inbox/spliced', { - target: 'next-step', start: 0, inserted: [pending], - }) - }) - expect(duplicate.message).toBe('invalid persisted inbox splice at session seq 1') - expect((duplicate.cause as Error).message).toBe(`message "${pending.id}" is already pending`) - }) - - it('projects inherited inbox events in a forked session', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(AgentRegistry) - const parent = ctx.sessions.create(SessionId('inbox-fork-parent')) - const inherited = createUserMessage({ - content: [{ type: 'text', text: 'parent pending' }], - source: { kind: 'user' }, - }) - parent.append('agent/inbox/spliced', { - target: 'next-turn', start: 0, inserted: [inherited], - }) - const child = ctx.sessions.fork(parent, undefined, SessionId('inbox-fork-child')) - - expect(child.header.seedLength).toBe(parent.events.length) - expect(ctx.sessionProjections.stateOf(child, 'inbox')).toEqual({ - 'next-turn': [inherited], - 'next-step': [], - }) - - const own = createUserMessage({ - content: [{ type: 'text', text: 'child pending' }], - source: { kind: 'user' }, - }) - child.append('agent/inbox/spliced', { - target: 'next-turn', start: 1, inserted: [own], - }) - expect(ctx.sessionProjections.stateOf(child, 'inbox')?.['next-turn']).toEqual([inherited, own]) - }) - - it('registers the durable inbox projection from the Agent registry', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(SessionProjectionRegistry) - const agentFiber = ctx.plugin(AgentRegistry) - await agentFiber - const session = ctx.sessions.create(SessionId('inbox-projection')) - const pending = createUserMessage({ - content: [{ type: 'text', text: 'pending' }], - source: { kind: 'user' }, - }) - - session.append('agent/inbox/spliced', { - target: 'next-turn', start: 0, inserted: [pending], - }) - - expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ - 'next-turn': [pending], - 'next-step': [], - }) - await agentFiber.dispose() - expect(ctx.sessionProjections.snapshot(session).values).toEqual({}) - }) - - it('updates the projection cell before session observers run', async () => { - const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(AgentRegistry) - const session = ctx.sessions.create(SessionId('inbox-live-projection')) - const pending = createUserMessage({ - content: [{ type: 'text', text: 'direct' }], - source: { kind: 'user' }, - }) - let observed: readonly UserMessage[] | undefined - ctx.on('session/event', (subject, event) => { - if (subject === session && event.type === 'agent/inbox/spliced') { - observed = ctx.sessionProjections.stateOf(session, 'inbox')?.['next-turn'] - } - }) - - session.append('agent/inbox/spliced', { - target: 'next-turn', start: 0, inserted: [pending], - }) - - expect(observed).toEqual([pending]) - expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ - 'next-turn': [pending], 'next-step': [], - }) - }) -}) - describe('AgentRegistry', () => { it('contributes Agent lookup and scoped Context providers while Typert is live', async () => { const ctx = new Context() diff --git a/packages/core/agent/tsconfig.json b/packages/core/agent/tsconfig.json index 230196abac..068c1e6b8f 100644 --- a/packages/core/agent/tsconfig.json +++ b/packages/core/agent/tsconfig.json @@ -32,9 +32,6 @@ { "path": "../../runtime-diagnostics/invariants" }, - { - "path": "../../session/session-projection" - }, { "path": "../../typert/protocol" } diff --git a/packages/test-support/agent-loop-testkit/package.json b/packages/test-support/agent-loop-testkit/package.json index 2518f56133..3e8d857c58 100644 --- a/packages/test-support/agent-loop-testkit/package.json +++ b/packages/test-support/agent-loop-testkit/package.json @@ -33,6 +33,7 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", diff --git a/packages/test-support/agent-loop-testkit/src/inbox.ts b/packages/test-support/agent-loop-testkit/src/inbox.ts index 0c1fd99f1b..af0bebaf73 100644 --- a/packages/test-support/agent-loop-testkit/src/inbox.ts +++ b/packages/test-support/agent-loop-testkit/src/inbox.ts @@ -1,4 +1,5 @@ import type { Inbox, InboxState, InboxTarget } from '@deepseek-ai/dsh-agent' +import { inboxProjectionDefinition } from '@deepseek-ai/dsh-agent-loop' import type { MessageId } from '@deepseek-ai/dsh-llm' import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' import type SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -13,7 +14,7 @@ export interface InboxFixture { /** * Create a session-backed structural Inbox test double for consumer tests. - * @param projections - registry holding the standard inbox projection. + * @param projections - registry that will own the fixture's standard inbox projection registration. * @param session - session whose durable splices back the test double. * @returns the structural Inbox and a separate loop-driver claim operation. */ @@ -21,8 +22,11 @@ export function createInboxFixture( projections: SessionProjectionRegistry, session: Session, ): InboxFixture { + projections.register(inboxProjectionDefinition) + const current = (): InboxState => { const state = projections.stateOf(session, 'inbox') + /* v8 ignore next -- createInboxFixture holds the registration for the context lifetime */ if (state === undefined) throw new Error('test inbox requires the standard inbox projection') return state } diff --git a/packages/test-support/agent-loop-testkit/src/index.ts b/packages/test-support/agent-loop-testkit/src/index.ts index ae384f45ab..e6d86338f2 100644 --- a/packages/test-support/agent-loop-testkit/src/index.ts +++ b/packages/test-support/agent-loop-testkit/src/index.ts @@ -9,7 +9,6 @@ import type { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' @@ -44,7 +43,6 @@ export async function mountAgentLoopTestDependencies( ): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SystemPrompt, options.systemPrompt ?? {}) await ctx.plugin(ToolRuntime, options.tools ?? {}) await ctx.plugin(AgentRegistry) diff --git a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts index 6ddf987d79..bc71618d05 100644 --- a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts +++ b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts @@ -18,6 +18,7 @@ describe('dsh-agent-loop-testkit', () => { systemPrompt: { persona: 'Test persona.' }, tools: { mode: 'native' }, }) + await ctx.plugin(SessionProjectionRegistry) expect(renderPrompt(await ctx.systemPrompt.assemble())).toContain('Test persona.') await expect(ctx.plugin(AgentLoop, { agents: [] })).resolves.toBeDefined() @@ -28,6 +29,7 @@ describe('dsh-agent-loop-testkit', () => { it('provides a session-backed structural Inbox with separate driver claims', async () => { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) + await ctx.plugin(SessionProjectionRegistry) const session = ctx.sessions.create(SessionId('agent-loop-testkit-inbox')) const fixture = createInboxFixture(ctx.sessionProjections, session) const firstTurn = message('first turn') @@ -69,15 +71,20 @@ describe('dsh-agent-loop-testkit', () => { await ctx.fiber.dispose() }) - it('reports a missing standard inbox projection', async () => { + it('registers the standard inbox projection for a standalone fixture', async () => { const ctx = new Context() await ctx.plugin(SessionProjectionRegistry) + const session = Session.create(SessionId('agent-loop-testkit-standalone-inbox')) const fixture = createInboxFixture( ctx.sessionProjections, - Session.create(SessionId('agent-loop-testkit-missing-inbox')), + session, ) - expect(() => fixture.inbox.nextStep).toThrow('test inbox requires the standard inbox projection') + expect(fixture.inbox.nextStep).toEqual([]) + expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ + 'next-turn': [], + 'next-step': [], + }) await ctx.fiber.dispose() }) diff --git a/packages/test-support/agent-loop-testkit/tsconfig.json b/packages/test-support/agent-loop-testkit/tsconfig.json index e425e87e2e..5e898500b8 100644 --- a/packages/test-support/agent-loop-testkit/tsconfig.json +++ b/packages/test-support/agent-loop-testkit/tsconfig.json @@ -17,6 +17,9 @@ { "path": "../../core/agent" }, + { + "path": "../../core/agent-loop" + }, { "path": "../../llm/llm" }, @@ -31,6 +34,9 @@ }, { "path": "../../runtime-diagnostics/invariants" + }, + { + "path": "../../session/session-projection" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b739f10454..7bf938b332 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4233,10 +4233,6 @@ importers: version: link:../../core/system-prompt packages/core/agent: - dependencies: - zod: - specifier: ^4.4.3 - version: 4.4.3 devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ From c33fe6265e0715a1f5efe989910c1d96a9b8bbd5 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 28 Aug 2026 15:39:19 +0800 Subject: [PATCH 13/26] fix(agent-loop): restore inbox projection test wiring --- ...claimed-pre-step-inbox-lifecycle.i18n.yaml | 4 +-- ...-07-31-claimed-pre-step-inbox-lifecycle.md | 12 ++++----- ...-31-claimed-pre-step-inbox-lifecycle.zh.md | 12 ++++----- .../tests/profiles/headless/tests/harness.ts | 2 -- docs/module-graph.i18n.yaml | 4 +-- docs/module-graph.md | 17 ++++++------ docs/module-graph.zh.md | 17 ++++++------ docs/subsystems/core.i18n.yaml | 4 +-- docs/subsystems/core.md | 2 +- docs/subsystems/core.zh.md | 2 +- packages/acp/acp/tests/harness.ts | 5 ---- .../tests/compaction-loop-repro.spec.ts | 6 ----- .../tests/manual-compaction.spec.ts | 1 - .../time-context/tests/time-context.spec.ts | 1 - packages/core/agent-loop/README.i18n.yaml | 4 +-- packages/core/agent-loop/README.md | 4 +-- packages/core/agent-loop/README.zh.md | 4 +-- .../agent-loop/tests/scope-lifecycle.spec.ts | 27 +++++++++++++++++++ .../agent-team/tests/persistence.spec.ts | 2 -- .../agent-team/tests/team.spec.ts | 4 --- .../tool-agent-team/tests/tool-team.spec.ts | 2 -- packages/fs/tool-fs/tests/harness.ts | 2 -- .../tests/goal-round-driver.spec.ts | 3 --- .../tests/repeat-tool-reminder.spec.ts | 4 --- .../hooks-claude-code/tests/bridge.spec.ts | 4 --- .../hooks-claude-code/tests/coverage-cases.ts | 5 ---- .../hooks/hooks-codex/tests/bridge.spec.ts | 4 --- .../hooks/hooks-codex/tests/coverage-cases.ts | 4 --- .../tests/transport-recovery.spec.ts | 2 -- .../schedule/tests/jsonl-restart.spec.ts | 2 -- .../schedule/schedule/tests/plugin.spec.ts | 2 -- .../tests/fixtures/crash-child.ts | 2 -- .../shell/tool-bash/tests/integration.spec.ts | 3 --- .../tests/multi-subagent.spec.ts | 2 -- .../tests/subagent-fork-in-process.spec.ts | 1 - .../tests/inheritance.spec.ts | 2 -- .../tests/preset-inheritance.spec.ts | 2 -- .../tests/structured.spec.ts | 2 -- .../tests/subagent-in-process-driver.spec.ts | 2 -- .../tests/harness.ts | 2 -- .../tests/subagent-spawn-in-process.spec.ts | 3 --- .../tests/continuation-inheritance.spec.ts | 2 -- .../subagent/tests/continuation.spec.ts | 6 ----- .../tests/tool-subagent-report.spec.ts | 2 -- .../subagent/tool-subagent/tests/harness.ts | 1 - .../tests/model-selection-settings.spec.ts | 2 -- .../tool-subagent/tests/tool-subagent.spec.ts | 2 +- .../agent-loop-testkit/README.i18n.yaml | 4 +-- .../test-support/agent-loop-testkit/README.md | 12 ++++----- .../agent-loop-testkit/README.zh.md | 12 ++++----- .../agent-loop-testkit/src/index.ts | 2 ++ .../tests/agent-loop-testkit.spec.ts | 2 -- .../todo/tool-todo/tests/integration.spec.ts | 2 -- .../tool-ralph/tests/integration.spec.ts | 3 --- .../tests/integration.spec.ts | 2 -- 55 files changed, 88 insertions(+), 155 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml index a18e52843f..14efbb6ab8 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md -2026-07-31-claimed-pre-step-inbox-lifecycle.md: 2055770e9f2265f905caa25a6d9235e1e70ea1b8 -2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: 099066be3e3422a84b6116e23d8f0c6e82fe9fc1 +2026-07-31-claimed-pre-step-inbox-lifecycle.md: f6daaa97884c3d1ae6dd8cc9e300528389c834ae +2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: e6218bb9aafb62dc4299b0398ac3a40be6d89d68 diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md index 2055770e9f..f6daaa9788 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md @@ -12,19 +12,19 @@ Occurrence-local inbox wrappers also duplicated the identity already carried by ## Decision -Before every proposed step, the loop's package-internal `ProjectedInbox` atomically claims the complete batch: all `next-step` messages and, at a turn boundary, one `next-turn` message. At the initial boundary the loop first commits `turn/start`, so the claim and its single `agent/pre-step` decision have durable turn ownership. Claiming records normalized `agent/inbox/spliced` pure deletions with no outcome, emits `agent/inbox/claimed { message, turn }` once per claimed message, and returns the exclusive batch for the loop's waterfall with `{ turn, step, signal }`. +Before every proposed step, the loop's package-internal `ReactLoopInbox` atomically claims the complete batch: all `next-step` messages and, at a turn boundary, one `next-turn` message. At the initial boundary the loop first commits `turn/start`, so the claim and its single `agent/pre-step` decision have durable turn ownership. Claiming records normalized `agent/inbox/spliced` pure deletions with no outcome, emits `agent/inbox/claimed { message, turn }` once per claimed message, and returns the exclusive batch for the loop's waterfall with `{ turn, step, signal }`. `PreStepDecision` is `{ kind: 'reject' } | { kind: 'enter'; messages: UserMessage[] }`. Reject opens no step, leaves the claimed batch removed, and closes the turn as blocked without any step events. Empty entry, cancellation, and failure before `step/start` likewise close a balanced no-step turn. Enter supplies the complete batch appended as `user/message` events after `step/start`. A listener wrapping `next()` preserves downstream changes unless it intentionally replaces them, so all message rewrites settle once in the final return value. There is no `agent/prompt-prepare`, `agent/prompt-submit`, or `agent/step` extension point. -The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming records pure deletions without an outcome and emits claimed events from `ProjectedInbox`. These live events add no placement, outcome, or batch fields. +The durable inbox remains two `UserMessage[]` lists addressed by `MessageId`. `append`, `prepend`, and `splice` take a target, while `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists before committing a normalized splice. Replacement may change identity and emits the old message as discarded followed by the new message as inserted. Every insertion emits `agent/inbox/inserted { message }`; an ordinary removal records `outcome: 'canceled'` and emits `agent/inbox/discarded { message }`. Claiming records pure deletions without an outcome and emits claimed events from `ReactLoopInbox`. These live events add no placement, outcome, or batch fields. -`Agent.inbox` exposes only the structural `Inbox` interface for reading and mutating pending work; loop-only `hasPending` and claim operations are absent from that public face. dsh-agent-loop constructs one `ProjectedInbox` and uses it for both structural commands and driver operations. The concrete constructor receives `SessionProjectionRegistry` directly instead of the wider Cordis `Context`, and a missing `inbox` projection throws an explicit composition error. +`Agent.inbox` exposes only the structural `Inbox` interface for reading and mutating pending work; loop-only `hasPending` and claim operations are absent from that public face. dsh-agent-loop constructs one `ReactLoopInbox` and uses it for both structural commands and driver operations. The concrete constructor receives `SessionProjectionRegistry` directly instead of the wider Cordis `Context` and registers the standard definition on the agent scope before its first read. `AgentLoop` requires the registry service at activation, and the registry reference-counts the definition across live agent scopes. -The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. `AgentRegistry` contributes the standard `inbox` projection over the durable `agent/inbox/spliced` stream whenever the projection registry is composed; UI edits and removals route through an Inbox mutation method so the same projection records every change. When that projection reconstructs durable history, it rejects unsafe or out-of-range coordinates and duplicate `MessageId` values across both lists, and reports the offending event seq. Whole-queue control consumers use the projection change feed: the Session controller publishes the projection frame, then derives the queue replacement from the same post-fold inbox value. +The two event surfaces have separate consumers. Observers following one message use `agent/inbox/inserted`, `claimed`, and `discarded`. Each `ReactLoopInbox` contributes the standard `inbox` projection over the durable `agent/inbox/spliced` stream from its agent scope; UI edits and removals route through an Inbox mutation method so the same projection records every change. When that projection reconstructs durable history, it rejects unsafe or out-of-range coordinates and duplicate `MessageId` values across both lists, and reports the offending event seq. Whole-queue control consumers use the projection change feed: the Session controller publishes the projection frame, then derives the queue replacement from the same post-fold inbox value. Plugins that need current-step atomic rewriting return messages from `agent/pre-step`. Plugins that only need later context may mutate `agent.inbox` directly. Workspace context uses both paths: asynchronous filesystem projections stage one replaceable `next-step` item, while the next entering pre-step folds that item or a newly composed baseline into its final batch and removes the pending copy. Rejection keeps the item queued. -The archived [addressable queue occurrence decision](../../archived/feature/2026-07-29-addressable-queue-operations.md) describes the superseded occurrence-wrapper design. `MessageId` owns addressability, while `AgentRegistry` contributes `inbox` as the standard session projection over durable splices. The generic projection carrier serves that fold for live updates, history-tail reconnect baselines, and cold process-restart recovery without a live Agent mirror. +The archived [addressable queue occurrence decision](../../archived/feature/2026-07-29-addressable-queue-operations.md) describes the superseded occurrence-wrapper design. `MessageId` owns addressability, while `ReactLoopInbox` contributes `inbox` as the standard session projection over durable splices. The generic projection carrier serves that fold for live updates, history-tail reconnect baselines, and cold process-restart recovery without a live Agent mirror. ## Alternatives considered @@ -36,7 +36,7 @@ The archived [addressable queue occurrence decision](../../archived/feature/2026 ## Verification -Agent-loop coverage pins turn-start-before-claim-before-pre-step ordering, exact live event payloads, balanced no-step rejection, final-batch rewriting, input inserted after a claim, listener failure, and cancellation. Inbox and consumer tests pin pure claim deletions, canceled ordinary removals, agent-instructions staging, replacement, and same-step entry, plan/goal/hook behavior, UI cleanup, compaction, checkpointing, resumed durable projection, rejection of invalid persisted coordinates or cross-list identities, and post-fold queue replacement when the controller registers before the projection registry. Generated event and type catalogs expose only the new waterfall and payloads. +Agent-loop coverage pins turn-start-before-claim-before-pre-step ordering, exact live event payloads, balanced no-step rejection, final-batch rewriting, input inserted after a claim, listener failure, cancellation, and agent-scope projection removal after the last owner unloads. Inbox and consumer tests pin pure claim deletions, canceled ordinary removals, agent-instructions staging, replacement, and same-step entry, plan/goal/hook behavior, UI cleanup, compaction, checkpointing, resumed durable projection, rejection of invalid persisted coordinates or cross-list identities, and post-fold queue replacement when the controller registers before the projection registry. Generated event and type catalogs expose only the new waterfall and payloads. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md index 099066be3e..e6218bb9aa 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md @@ -12,19 +12,19 @@ Status: implemented ## 决策 -每个拟议步骤之前,循环包内部的 `ProjectedInbox` 会原子领取完整批次:全部 `next-step` 消息,以及轮次边界上的一条 `next-turn` 消息。在首次边界,循环会先提交 `turn/start`,使领取及其唯一一次 `agent/pre-step` 决策拥有持久轮次归属。领取会记录规范化、不带 outcome 的纯删除 `agent/inbox/spliced`,针对每条已领取消息发出一次 `agent/inbox/claimed { message, turn }`,并把独占批次返回给循环,由后者用 `{ turn, step, signal }` 等待 waterfall(瀑布式事件)。 +每个拟议步骤之前,循环包内部的 `ReactLoopInbox` 会原子领取完整批次:全部 `next-step` 消息,以及轮次边界上的一条 `next-turn` 消息。在首次边界,循环会先提交 `turn/start`,使领取及其唯一一次 `agent/pre-step` 决策拥有持久轮次归属。领取会记录规范化、不带 outcome 的纯删除 `agent/inbox/spliced`,针对每条已领取消息发出一次 `agent/inbox/claimed { message, turn }`,并把独占批次返回给循环,由后者用 `{ turn, step, signal }` 等待 waterfall(瀑布式事件)。 `PreStepDecision` 为 `{ kind: 'reject' } | { kind: 'enter'; messages: UserMessage[] }`。reject 不会打开步骤,会让已领取批次保持已删除,并将轮次关闭为 blocked,且不产生任何步骤事件。空的 enter、取消以及 `step/start` 前的失败同样会关闭一个边界平衡的无步骤轮次。enter 提供在 `step/start` 后以 `user/message` 追加的完整批次。包装 `next()` 的监听器会保留下游变更,除非有意替换,因此全部消息改写只在最终返回值中一次性结算。系统不再存在 `agent/prompt-prepare`、`agent/prompt-submit` 或 `agent/step` 扩展点。 -持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取记录不带 outcome 的纯删除,并由 `ProjectedInbox` 发出 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 +持久 inbox 仍是两份通过 `MessageId` 寻址的 `UserMessage[]` 列表。`append`、`prepend` 与 `splice` 接受 target;`replace(messageId, newMessage)` 与 `remove(messageId)` 则在提交规范化 splice 前,通过 `MessageId` 跨两份列表定位待处理消息。替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。每次插入发出 `agent/inbox/inserted { message }`;普通删除记录 `outcome: 'canceled'` 并发出 `agent/inbox/discarded { message }`。领取记录不带 outcome 的纯删除,并由 `ReactLoopInbox` 发出 claimed 事件。这些实时事件不增加 placement、outcome 或批次字段。 -`Agent.inbox` 只暴露用于读取和变更待处理工作的结构化 `Inbox` 接口;仅供循环使用的 `hasPending` 与领取操作不在该公开接口上。dsh-agent-loop 只构造一个 `ProjectedInbox`,同时用于结构化命令与驱动器操作。具体构造函数直接接收 `SessionProjectionRegistry`,而不是更宽泛的 Cordis `Context`;`inbox` 投影缺失时会抛出明确的组合错误。 +`Agent.inbox` 只暴露用于读取和变更待处理工作的结构化 `Inbox` 接口;仅供循环使用的 `hasPending` 与领取操作不在该公开接口上。dsh-agent-loop 只构造一个 `ReactLoopInbox`,同时用于结构化命令与驱动器操作。具体构造函数直接接收 `SessionProjectionRegistry`,而不是更宽泛的 Cordis `Context`,并在首次读取前从 agent 作用域注册标准定义。`AgentLoop` 激活时要求该注册表服务存在,注册表则对多个 live agent 作用域贡献的定义进行引用计数。 -两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。`AgentRegistry` 会在投影注册表已组合时,在持久 `agent/inbox/spliced` 流上贡献标准 `inbox` 投影;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。该投影重建持久历史时,会拒绝不安全或越界的坐标,以及跨两份列表重复的 `MessageId`,并报告出错事件的 seq。整体队列的 control 消费方使用投影变更流:Session controller 先发布 projection frame,再从同一份折叠后的 inbox 值派生 queue replacement。 +两类事件接口服务不同消费方。跟踪单条消息的观察方使用 `agent/inbox/inserted`、`claimed` 与 `discarded`。每个 `ReactLoopInbox` 都从其 agent 作用域在持久 `agent/inbox/spliced` 流上贡献标准 `inbox` 投影;UI 编辑与移除通过 Inbox 变更方法处理,从而让同一投影记录所有变化。该投影重建持久历史时,会拒绝不安全或越界的坐标,以及跨两份列表重复的 `MessageId`,并报告出错事件的 seq。整体队列的 control 消费方使用投影变更流:Session controller 先发布 projection frame,再从同一份折叠后的 inbox 值派生 queue replacement。 必须对当前步骤进行原子改写的插件从 `agent/pre-step` 返回消息。只需要稍后上下文的插件可以直接修改 `agent.inbox`。Workspace context 同时使用两条路径:异步文件系统投影会暂存一条可替换的 `next-step` 消息,而下一次进入步骤的 pre-step 会把该消息或新组合的基线折入最终批次,并移除仍待处理的副本。reject 会让该条目继续排队。 -已归档的[可寻址队列项决策](../../archived/feature/2026-07-29-addressable-queue-operations.md)描述了已被取代的单次出现包装层设计。`MessageId` 负责寻址,而 `AgentRegistry` 把 `inbox` 作为持久 splice 上的标准会话投影贡献给投影注册表。通用投影传输层会将该折叠结果用于实时更新、历史尾页的重连基线和冷进程重启恢复,无需 live Agent 镜像。 +已归档的[可寻址队列项决策](../../archived/feature/2026-07-29-addressable-queue-operations.md)描述了已被取代的单次出现包装层设计。`MessageId` 负责寻址,而 `ReactLoopInbox` 把 `inbox` 作为持久 splice 上的标准会话投影贡献给投影注册表。通用投影传输层会将该折叠结果用于实时更新、历史尾页的重连基线和冷进程重启恢复,无需 live Agent 镜像。 ## 曾考虑的替代方案 @@ -36,7 +36,7 @@ Status: implemented ## 验证 -agent loop(智能体循环)覆盖固定先 `turn/start`、再领取、后 pre-step 的顺序、实时事件的确切载荷、边界平衡的无步骤 reject、最终批次改写、领取后插入的输入、监听器失败与取消。Inbox 和消费方测试固定纯领取删除、普通删除的 canceled 结果、agent-instructions 的暂存、替换与同一步骤进入、plan/goal/钩子行为、UI 清理、压缩(compaction)、检查点、恢复后的持久投影、对非法持久坐标或跨列表重复标识的拒绝,以及 controller 早于投影注册表注册时仍使用折叠后队列值。生成的事件与类型目录只公开新的 waterfall 与载荷。 +agent loop(智能体循环)覆盖固定先 `turn/start`、再领取、后 pre-step 的顺序、实时事件的确切载荷、边界平衡的无步骤 reject、最终批次改写、领取后插入的输入、监听器失败、取消,以及最后一个所有者卸载后移除 agent 作用域投影。Inbox 和消费方测试固定纯领取删除、普通删除的 canceled 结果、agent-instructions 的暂存、替换与同一步骤进入、plan/goal/钩子行为、UI 清理、压缩(compaction)、检查点、恢复后的持久投影、对非法持久坐标或跨列表重复标识的拒绝,以及 controller 早于投影注册表注册时仍使用折叠后队列值。生成的事件与类型目录只公开新的 waterfall 与载荷。 ## 后果 diff --git a/apps/cli/tests/profiles/headless/tests/harness.ts b/apps/cli/tests/profiles/headless/tests/harness.ts index 495b7ebbd2..d20637eede 100644 --- a/apps/cli/tests/profiles/headless/tests/harness.ts +++ b/apps/cli/tests/profiles/headless/tests/harness.ts @@ -2,7 +2,6 @@ import { Context } from '@deepseek-ai/cordis' import type { SessionEvent } from '@deepseek-ai/dsh-session' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env' @@ -56,7 +55,6 @@ export interface CodingHarnessOptions { export async function codingHarness(workdir: string, options: CodingHarnessOptions = {}): Promise { const ctx = new Context() - await ctx.plugin(SessionProjectionRegistry) await mountAgentLoopTestDependencies(ctx, { systemPrompt: { persona: options.persona ?? '' }, }) diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index 5e74fd34c8..9f5b9bfa9e 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/module-graph.md -module-graph.md: 2191b3c2e76babc9308095cab1c567c1372b58e6 -module-graph.zh.md: d42c712332081848e271e95822a7f03401176fc6 +module-graph.md: daa8e382919419bd08798ec6a4a3f1aabc9d02c7 +module-graph.zh.md: e8906850ef2c71e74330e6c1feef87273a3fe0fc diff --git a/docs/module-graph.md b/docs/module-graph.md index 2191b3c2e7..daa8e38291 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -976,13 +976,6 @@ flowchart TD pkg_tool_terminal --> pkg_system_prompt pkg_tool_terminal --> pkg_terminal pkg_tool_terminal --> pkg_tools - pkg_agent_loop_testkit --> pkg_agent - pkg_agent_loop_testkit --> pkg_invariants - pkg_agent_loop_testkit --> pkg_llm - pkg_agent_loop_testkit --> pkg_session - pkg_agent_loop_testkit --> pkg_session_projection - pkg_agent_loop_testkit --> pkg_system_prompt - pkg_agent_loop_testkit --> pkg_tools pkg_llm_replay --> pkg_compaction pkg_llm_replay --> pkg_deepseek_llm_api_extensions pkg_llm_replay --> pkg_invariants @@ -1074,6 +1067,14 @@ flowchart TD pkg_tool_pwsh --> pkg_system_prompt pkg_tool_pwsh --> pkg_tools pkg_tool_pwsh --> pkg_user_approval + pkg_agent_loop_testkit --> pkg_agent + pkg_agent_loop_testkit --> pkg_agent_loop + pkg_agent_loop_testkit --> pkg_invariants + pkg_agent_loop_testkit --> pkg_llm + pkg_agent_loop_testkit --> pkg_session + pkg_agent_loop_testkit --> pkg_session_projection + pkg_agent_loop_testkit --> pkg_system_prompt + pkg_agent_loop_testkit --> pkg_tools pkg_webhook --> pkg_agent pkg_webhook --> pkg_agent_default_model pkg_webhook --> pkg_agent_presets @@ -1888,7 +1889,6 @@ flowchart TD | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-pwsh-persistent`](../packages/shell/tool-pwsh-persistent) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-terminal`](../packages/terminal/tool-terminal) | `terminal` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`llm-replay`](../packages/test-support/llm-replay) | `test-support` | [`compaction`](../packages/compaction/compaction), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | `llm` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | @@ -1901,6 +1901,7 @@ flowchart TD | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | | [`tool-pwsh`](../packages/shell/tool-pwsh) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | +| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`webhook`](../packages/webhook/webhook) | `webhook` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-presets`](../packages/preset/agent-presets), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index d42c712332..e8906850ef 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -978,13 +978,6 @@ flowchart TD pkg_tool_terminal --> pkg_system_prompt pkg_tool_terminal --> pkg_terminal pkg_tool_terminal --> pkg_tools - pkg_agent_loop_testkit --> pkg_agent - pkg_agent_loop_testkit --> pkg_invariants - pkg_agent_loop_testkit --> pkg_llm - pkg_agent_loop_testkit --> pkg_session - pkg_agent_loop_testkit --> pkg_session_projection - pkg_agent_loop_testkit --> pkg_system_prompt - pkg_agent_loop_testkit --> pkg_tools pkg_llm_replay --> pkg_compaction pkg_llm_replay --> pkg_deepseek_llm_api_extensions pkg_llm_replay --> pkg_invariants @@ -1076,6 +1069,14 @@ flowchart TD pkg_tool_pwsh --> pkg_system_prompt pkg_tool_pwsh --> pkg_tools pkg_tool_pwsh --> pkg_user_approval + pkg_agent_loop_testkit --> pkg_agent + pkg_agent_loop_testkit --> pkg_agent_loop + pkg_agent_loop_testkit --> pkg_invariants + pkg_agent_loop_testkit --> pkg_llm + pkg_agent_loop_testkit --> pkg_session + pkg_agent_loop_testkit --> pkg_session_projection + pkg_agent_loop_testkit --> pkg_system_prompt + pkg_agent_loop_testkit --> pkg_tools pkg_webhook --> pkg_agent pkg_webhook --> pkg_agent_default_model pkg_webhook --> pkg_agent_presets @@ -1890,7 +1891,6 @@ flowchart TD | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-pwsh-persistent`](../packages/shell/tool-pwsh-persistent) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-terminal`](../packages/terminal/tool-terminal) | `terminal` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`llm-replay`](../packages/test-support/llm-replay) | `test-support` | [`compaction`](../packages/compaction/compaction), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | `llm` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session) | @@ -1903,6 +1903,7 @@ flowchart TD | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | | [`tool-pwsh`](../packages/shell/tool-pwsh) | `shell` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | +| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`webhook`](../packages/webhook/webhook) | `webhook` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-presets`](../packages/preset/agent-presets), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`brand`](../packages/util/brand), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index fc4dfe19ed..c73275117e 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/core.md -core.md: f1e08b11ec6730960d15c64261936de9e83a5ecc -core.zh.md: 4a61f691a5578e38635fbdd700445e1f47ab4cba +core.md: 5f66abccad5ad691f855c49923a49a276c983f7d +core.zh.md: 36521157b6ac121cf0e9a4eee67706bec3a37735 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index f1e08b11ec..5f66abccad 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -234,7 +234,7 @@ interface Inbox { type InboxTarget = 'next-turn' | 'next-step' ``` -Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. The structural `Inbox` methods record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. At a step boundary, dsh-agent-loop's package-internal `ProjectedInbox` removes the proposed batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without discarded notifications, then emits per-message claimed notifications. Loop-only pending detection and claiming are not part of `Agent.inbox`. `AgentRegistry` contributes the standard `inbox` projection whenever the projection registry is composed; its cell is the sole live state and the same fold serves cold consumers. `ProjectedInbox` depends directly on that registry and reports an explicit missing-projection error when composition is broken. The fold rejects unsafe or out-of-range splice coordinates and duplicate identities across both lists, identifying malformed durable history by event seq. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. +Every pending occurrence is its `UserMessage`; `MessageId` is the sole identity. The structural `Inbox` methods record normalized durable `agent/inbox/spliced` mutations and reject duplicate pending ids. `replace(messageId, newMessage)` and `remove(messageId)` locate the pending message across both lists; replacement may change identity and emits the old message as discarded followed by the new message as inserted. Ordinary removals and `clear()` are cancellations. At a step boundary, dsh-agent-loop's package-internal `ReactLoopInbox` removes the proposed batch — all `next-step` input plus, at a turn boundary, one `next-turn` message — through pure deletion splices without discarded notifications, then emits per-message claimed notifications. Loop-only pending detection and claiming are not part of `Agent.inbox`. Each `ReactLoopInbox` constructor contributes the standard `inbox` projection from its agent scope; the registry shares that definition across agents by reference count, and its cell is the sole live state while the same fold serves cold consumers. The fold rejects unsafe or out-of-range splice coordinates and duplicate identities across both lists, identifying malformed durable history by event seq. Consumers following one message use the exact `agent/inbox/inserted`, `claimed`, and `discarded` notifications. Cancellation: diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 4a61f691a5..36521157b6 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -238,7 +238,7 @@ interface Inbox { type InboxTarget = 'next-turn' | 'next-step' ``` -每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。结构化 `Inbox` 方法会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。在步骤边界,dsh-agent-loop 包内部的 `ProjectedInbox` 会通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后逐条发出 claimed 通知。仅供循环使用的待处理检测与领取操作不属于 `Agent.inbox`。`AgentRegistry` 会在投影注册表已组合时贡献标准 `inbox` 投影;其 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。`ProjectedInbox` 直接依赖该注册表,并在组合关系损坏时报告明确的投影缺失错误。该 fold 会拒绝不安全或越界的 splice 坐标,以及跨两份列表重复的标识,并通过事件 seq 指出格式错误的持久历史。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 +每个待处理入队项就是其 `UserMessage`;`MessageId` 是唯一标识。结构化 `Inbox` 方法会记录规范化的持久 `agent/inbox/spliced` 变更,并拒绝重复的待处理 id。`replace(messageId, newMessage)` 与 `remove(messageId)` 通过 `MessageId` 跨两份列表定位待处理消息;替换可以改变标识,并先将旧消息作为 discarded 发布,再将新消息作为 inserted 发布。普通删除和 `clear()` 都表示取消。在步骤边界,dsh-agent-loop 包内部的 `ReactLoopInbox` 会通过纯删除 splice 移除拟进入步骤的批次——全部 `next-step` 输入,外加轮次边界上的一条 `next-turn` 消息——且不发出 discarded 通知,随后逐条发出 claimed 通知。仅供循环使用的待处理检测与领取操作不属于 `Agent.inbox`。每个 `ReactLoopInbox` 构造函数都从其 agent 作用域贡献标准 `inbox` 投影;注册表通过引用计数在多个 agent 之间共享该定义,其 cell 是唯一 live 状态,同一份折叠也服务于冷消费方。该 fold 会拒绝不安全或越界的 splice 坐标,以及跨两份列表重复的标识,并通过事件 seq 指出格式错误的持久历史。跟踪单条消息的消费方使用精确的 `agent/inbox/inserted`、`claimed` 与 `discarded` 通知。 取消: diff --git a/packages/acp/acp/tests/harness.ts b/packages/acp/acp/tests/harness.ts index 39b2d7e030..70e31cbbe4 100644 --- a/packages/acp/acp/tests/harness.ts +++ b/packages/acp/acp/tests/harness.ts @@ -23,7 +23,6 @@ import type { ImageAttachmentLimits, ImageAttachmentRef, SaveImageAttachment, St import { type GenerateOptions, LlmAdapter, ReasoningEffortId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import TokenMeter from '@deepseek-ai/dsh-token-meter' import * as AcpPlugin from '../src/index.ts' @@ -232,10 +231,6 @@ export async function makeBridgeHarness(options: { const ownsPersistenceRoot = options.persistenceRoot === undefined const persistenceRoot = options.persistenceRoot ?? await mkdtemp(join(tmpdir(), 'dsh-acp-test-')) await mountAgentLoopTestDependencies(ctx, { systemPrompt: { persona: options.persona ?? '' } }) - // The agent loop and the composed approval/permission services declare - // sessionProjections a required injection: mount the registry (and with it - // the loop's turnBoundary unit) before the loop activates. - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' }) await ctx.plugin(TokenMeter) if (options.attachments !== false) await ctx.plugin(MemoryAttachmentStore) 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 1dacfe2114..46d0384803 100644 --- a/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts +++ b/packages/compaction/compaction-basic/tests/compaction-loop-repro.spec.ts @@ -13,7 +13,6 @@ import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant' import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant' import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import TokenMeter from '@deepseek-ai/dsh-token-meter' import * as LlmRetry from '@deepseek-ai/dsh-llm-retry' import { Session, SessionId, type SessionEvent, type SurfaceEvent } from '@deepseek-ai/dsh-session' @@ -151,9 +150,6 @@ async function harness(toolSteps: number): Promise<{ ctx: Context; compact: Repr const ctx = new Context() await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) - // AgentLoop and TokenMeter both declare the registry as a required - // injection; mount it before either activates. - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(TokenMeter) ctx.llm.registerAdapter(['mock'], new StepwiseToolAdapter(toolSteps)) @@ -316,7 +312,6 @@ describe('context-overflow recovery across the real loop and compaction-basic', const adapter = new OverflowRecoveryAdapter(delivery) await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(TokenMeter) ctx.llm.registerAdapter(['mock'], adapter) @@ -395,7 +390,6 @@ describe('context-overflow recovery across the real loop and compaction-basic', const adapter = new OverflowRecoveryAdapter('thrown', true) await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(LlmRetry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(TokenMeter) diff --git a/packages/compaction/compaction-basic/tests/manual-compaction.spec.ts b/packages/compaction/compaction-basic/tests/manual-compaction.spec.ts index a0497f8041..6652e14fe8 100644 --- a/packages/compaction/compaction-basic/tests/manual-compaction.spec.ts +++ b/packages/compaction/compaction-basic/tests/manual-compaction.spec.ts @@ -106,7 +106,6 @@ async function loopHarness(): Promise { await ctx.plugin(AgentLoopInvariant) await ctx.plugin(CompactionInvariant) await ctx.plugin(CompactionBasicInvariant) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(TokenMeter) const adapter = new TextAdapter() diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index ba185b5e0e..7e201e1bcf 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -140,7 +140,6 @@ class ScriptedAdapter extends LlmAdapter { async function loopHarness(adapter: ScriptedAdapter, config: Config = {}): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(timeContext, config) ctx.llm.registerAdapter(['mock'], adapter) diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index b974726560..dc3e5bb068 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent-loop/README.md -README.md: 5878c92846e3808ed6702e9addf1aa7170df9bd4 -README.zh.md: 48ebd08f409afb1dcbf5b75354565bbd3fd1fb87 +README.md: 2c8a75867068a001c0f5978e201c3795359685eb +README.zh.md: e375da777161b0df6249bfb5b7df15eda0d8a140 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 5878c92846..2c8a758670 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -98,7 +98,7 @@ After `agent/request`, `ctx.llm.prepareCall()` validates adapter-owned fields an |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `AgentLoop` service, config schema, declarative agent startup, factory registration | | [`src/agent.ts`](src/agent.ts) | The concrete `ReactLoopAgent` driver: inbox, turn/step machine, cancellation | -| [`src/inbox.ts`](src/inbox.ts) | Package-internal `ProjectedInbox`: structural commands plus loop-only claim state | +| [`src/inbox.ts`](src/inbox.ts) | Package-internal `ReactLoopInbox`: durable projection, structural commands, and loop-only claim state | | [`src/tool-calls.ts`](src/tool-calls.ts) | Tool scheduling: exclusive barriers and the bounded parallel pool | | [`src/runtime-context.ts`](src/runtime-context.ts) | Per-step runtime-context snapshot handling | | [`src/constants.ts`](src/constants.ts) | `DEFAULT_MAX_PARALLEL_TOOL_CALLS` | @@ -110,7 +110,7 @@ Creation is one rollback-covered transaction: construct a private session, concr ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. Its single `ProjectedInbox` field receives `SessionProjectionRegistry` directly; a missing standard projection reports the composition failure before any inbox operation can continue. 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. `agent/pre-step` decides what enters the step; each successful model call appends one `assistant/message` anchor citing its chunk seqs, 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, and result context remain model-ordered. +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. Its `ReactLoopInbox` constructor registers the standard `inbox` projection on the agent scope, then uses that projection for structural commands and loop-only claims; registry reference counting keeps the shared key active until the last agent scope unloads. 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. `agent/pre-step` decides what enters the step; each successful model call appends one `assistant/message` anchor citing its chunk seqs, 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, and result context remain model-ordered. ### Failure and cancellation diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 48ebd08f40..e375da7771 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -98,7 +98,7 @@ const handle = await ctx.agents.create({ |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`AgentLoop` 服务、配置 schema、声明式 agent 启动、工厂注册 | | [`src/agent.ts`](src/agent.ts) | 具体 `ReactLoopAgent` 驱动器:收件箱、轮次/步骤状态机、取消 | -| [`src/inbox.ts`](src/inbox.ts) | 包内部 `ProjectedInbox`:结构化命令与仅供循环使用的领取状态 | +| [`src/inbox.ts`](src/inbox.ts) | 包内部 `ReactLoopInbox`:持久投影、结构化命令与仅供循环使用的领取状态 | | [`src/tool-calls.ts`](src/tool-calls.ts) | 工具调度:独占屏障与有界并行池 | | [`src/runtime-context.ts`](src/runtime-context.ts) | 每步骤 runtime-context 快照处理 | | [`src/constants.ts`](src/constants.ts) | `DEFAULT_MAX_PARALLEL_TOOL_CALLS` | @@ -110,7 +110,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。它唯一的 `ProjectedInbox` 字段直接接收 `SessionProjectionRegistry`;标准投影缺失时,会先报告组合错误,不让任何 inbox 操作继续。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤;每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。其 `ReactLoopInbox` 构造函数在 agent 作用域上注册标准 `inbox` 投影,随后将该投影用于结构化命令与仅供 loop 使用的领取操作;注册表引用计数会使共享 key 持续有效,直至最后一个 agent 作用域卸载。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤;每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 ### 失败与取消 diff --git a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts index 1d5821538d..a4e96d8226 100644 --- a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts @@ -196,6 +196,33 @@ describe('agent scope lifecycle', () => { expect(after.sections.find(s => s.name === 'deployment:persona')?.text).toBe('You are the deployment.') }) + it('keeps the inbox projection until the last owning agent fiber unloads', async () => { + const ctx = await harness() + let first!: Awaited> + let second!: Awaited> + const firstOwner = await ctx.plugin(Object.assign(async (inner: Context) => { + first = await inner.agents.create({ + sessionId: SessionId('projection-owner-first'), + agentOptions: { provider: 'mock', model: 'mock' }, + }) + }, { inject: ['agents'] })) + const secondOwner = await ctx.plugin(Object.assign(async (inner: Context) => { + second = await inner.agents.create({ + sessionId: SessionId('projection-owner-second'), + agentOptions: { provider: 'mock', model: 'mock' }, + }) + }, { inject: ['agents'] })) + + expect(ctx.sessionProjections.stateOf(first.agent.session, 'inbox')).toBeDefined() + await firstOwner.dispose() + expect(ctx.sessionProjections.stateOf(second.agent.session, 'inbox')).toBeDefined() + await secondOwner.dispose() + expect(ctx.sessionProjections.stateOf(second.agent.session, 'inbox')).toBeUndefined() + + await Promise.all([first.dispose(), second.dispose()]) + await ctx.fiber.dispose() + }) + it('agent.ctx listeners hear only their own agent (scoped dispatch end to end)', async () => { const ctx = await harness(new MockAdapter([textResponse('one'), textResponse('two')])) const a = ctx.agentLoop.create(SessionId('a'), { provider: 'mock', model: 'mock' }) diff --git a/packages/experimental/agent-team/tests/persistence.spec.ts b/packages/experimental/agent-team/tests/persistence.spec.ts index 88e72e5506..eacb4d2217 100644 --- a/packages/experimental/agent-team/tests/persistence.spec.ts +++ b/packages/experimental/agent-team/tests/persistence.spec.ts @@ -9,7 +9,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SqliteSessionPersistence from '@deepseek-ai/dsh-session-persistence-sqlite' import SubagentService, { seedDescriptorTurn, snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' @@ -99,7 +98,6 @@ async function stack( const ctx = new Context() contexts.add(ctx) await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await backend.mount(ctx, root) await ctx.plugin(TestSessionQuery) await ctx.plugin(AgentLoop, { agents: [] }) diff --git a/packages/experimental/agent-team/tests/team.spec.ts b/packages/experimental/agent-team/tests/team.spec.ts index 21d0e61b4a..4b52293910 100644 --- a/packages/experimental/agent-team/tests/team.spec.ts +++ b/packages/experimental/agent-team/tests/team.spec.ts @@ -8,7 +8,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { SessionId, type Session } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SubagentService from '@deepseek-ai/dsh-subagent' import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' @@ -51,7 +50,6 @@ async function setup( ) { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-')) roots.push(storageRoot) await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) @@ -159,7 +157,6 @@ describe('Team identity and provisioning', () => { it('supports direct-constructor defaults and recovers roots that already exist', async () => { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-direct-')) roots.push(storageRoot) await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) @@ -1353,7 +1350,6 @@ describe('Team mailbox and waiting', () => { it('waits for one change, supports cancellation, times out, and releases waiters on HMR disposal', async () => { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-wait-')) roots.push(storageRoot) await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) diff --git a/packages/experimental/tool-agent-team/tests/tool-team.spec.ts b/packages/experimental/tool-agent-team/tests/tool-team.spec.ts index db80af0ed2..1efc795932 100644 --- a/packages/experimental/tool-agent-team/tests/tool-team.spec.ts +++ b/packages/experimental/tool-agent-team/tests/tool-team.spec.ts @@ -9,7 +9,6 @@ import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-test import { ToolCallId } from '@deepseek-ai/dsh-llm' import { scopeOf } from '@deepseek-ai/dsh-scope' import { SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SessionQueryEngine from '@deepseek-ai/dsh-session-query' import SubagentService from '@deepseek-ai/dsh-subagent' @@ -57,7 +56,6 @@ afterEach(() => { async function setup(script: ConstructorParameters[0], legacyControl = false) { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-tool-team-')) roots.push(storageRoot) await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }) diff --git a/packages/fs/tool-fs/tests/harness.ts b/packages/fs/tool-fs/tests/harness.ts index f226e47b71..2e6dc22cf8 100644 --- a/packages/fs/tool-fs/tests/harness.ts +++ b/packages/fs/tool-fs/tests/harness.ts @@ -1,7 +1,6 @@ import { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import * as FsPolicy from '@deepseek-ai/dsh-fs-observation-policy' @@ -15,7 +14,6 @@ import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' */ export async function fsHarness(fsCwd: string, persona = ''): Promise { const ctx = new Context() - await ctx.plugin(SessionProjectionRegistry) await mountAgentLoopTestDependencies(ctx, { systemPrompt: { persona } }) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LlmDeepSeek) diff --git a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts index f92db57dbf..2a4059c2ea 100644 --- a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts +++ b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts @@ -10,7 +10,6 @@ import { createUserMessage, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import type { UserMessage } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as goalSession from '../src/index.ts' type ScriptEntry = StreamChunk[] | Error | 'hang' | ((options: GenerateOptions) => StreamChunk[]) @@ -90,7 +89,6 @@ async function harness(script: ScriptEntry[]): Promise { const ctx = new Context() contexts.push(ctx) await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(GoalService) const driver = await ctx.plugin(goalSession) await ctx.plugin(AgentLoop, { agents: [] }) @@ -217,7 +215,6 @@ describe('same-session goal driving', () => { const ctx = new Context() contexts.push(ctx) await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(GoalService) await ctx.plugin(AgentLoop, { agents: [] }) const adapter = new ScriptedAdapter([textResponse('after resume')]) diff --git a/packages/guard/repeat-tool-reminder/tests/repeat-tool-reminder.spec.ts b/packages/guard/repeat-tool-reminder/tests/repeat-tool-reminder.spec.ts index 58369c16b7..ea0f0ceef8 100644 --- a/packages/guard/repeat-tool-reminder/tests/repeat-tool-reminder.spec.ts +++ b/packages/guard/repeat-tool-reminder/tests/repeat-tool-reminder.spec.ts @@ -6,7 +6,6 @@ import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as RepeatToolGuard from '@deepseek-ai/dsh-repeat-tool-reminder' import type { Config } from '@deepseek-ai/dsh-repeat-tool-reminder' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' @@ -25,8 +24,6 @@ const testToolSignal = new AbortController().signal async function harness(config: Config = {}): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - // AgentLoop declares the registry as a required injection. - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(RepeatToolGuard, config) ctx.tools.register(defineContentToolFixture({ name: 'probe', description: 'p', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } })) @@ -373,7 +370,6 @@ describe('config validation fails loud', () => { async function spine(): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) return ctx } diff --git a/packages/hooks/hooks-claude-code/tests/bridge.spec.ts b/packages/hooks/hooks-claude-code/tests/bridge.spec.ts index af323d9b63..d80d393375 100644 --- a/packages/hooks/hooks-claude-code/tests/bridge.spec.ts +++ b/packages/hooks/hooks-claude-code/tests/bridge.spec.ts @@ -15,7 +15,6 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import { scopeTarget } from '@deepseek-ai/dsh-scope' import SubagentRuntime, { SubagentRunId } from '@deepseek-ai/dsh-subagent' import * as HooksClaude from '@deepseek-ai/dsh-hooks-claude-code' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' /** @@ -58,7 +57,6 @@ async function harnessWithFiber( ): Promise<{ ctx: Context; hooks: Fiber }> { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) @@ -356,7 +354,6 @@ describe('hooks-claude-code bridge — load resilience', () => { const adapter = new MockAdapter([textResponse('fine')]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) @@ -417,7 +414,6 @@ describe('hooks-claude-code bridge — load resilience', () => { const adapter = new MockAdapter([textResponse('ok')]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) diff --git a/packages/hooks/hooks-claude-code/tests/coverage-cases.ts b/packages/hooks/hooks-claude-code/tests/coverage-cases.ts index 4be08bb348..416010d69f 100644 --- a/packages/hooks/hooks-claude-code/tests/coverage-cases.ts +++ b/packages/hooks/hooks-claude-code/tests/coverage-cases.ts @@ -15,7 +15,6 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import { scopeTarget } from '@deepseek-ai/dsh-scope' import SubagentRuntime, { SubagentRunId } from '@deepseek-ai/dsh-subagent' import * as HooksClaude from '@deepseek-ai/dsh-hooks-claude-code' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' const testToolSignal = new AbortController().signal @@ -42,7 +41,6 @@ type HarnessOpts = { pluginRoot?: string; projectDir?: string; stderrSummaryMaxC async function harness(configPath: string, adapter: MockAdapter, opts: HarnessOpts = {}): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) if (opts.sessionRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: opts.sessionRoot }) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) @@ -370,7 +368,6 @@ export function defineCoverageCases(group: CoverageGroup): void { const adapter = new MockAdapter([textResponse('ok')]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) @@ -670,7 +667,6 @@ export function defineCoverageCases(group: CoverageGroup): void { const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) // Executor default cwd = serverDir (deliberately NOT the session cwd). await ctx.plugin(LocalSubprocessRuntime) @@ -700,7 +696,6 @@ export function defineCoverageCases(group: CoverageGroup): void { hooks(serverDir, { SubagentStop: [{ hooks: [{ type: 'command', command: 'cat > stoppayload.tmp; mv stoppayload.tmp stoppayload; pwd > stopwhere' }] }] }) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) // Executor default cwd = serverDir (deliberately NOT the child session cwd). await ctx.plugin(LocalSubprocessRuntime) diff --git a/packages/hooks/hooks-codex/tests/bridge.spec.ts b/packages/hooks/hooks-codex/tests/bridge.spec.ts index bac95b7eed..c2004b92aa 100644 --- a/packages/hooks/hooks-codex/tests/bridge.spec.ts +++ b/packages/hooks/hooks-codex/tests/bridge.spec.ts @@ -13,7 +13,6 @@ import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-test import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as HooksCodex from '@deepseek-ai/dsh-hooks-codex' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' /** @@ -43,7 +42,6 @@ function writeHooks(dir: string, hooks: unknown): void { async function harness(dir: string, adapter: MockAdapter, beforeHooks?: (ctx: Context) => void): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) @@ -184,7 +182,6 @@ describe('hooks-codex bridge', () => { const adapter = new MockAdapter([textResponse('ok')]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) @@ -208,7 +205,6 @@ describe('hooks-codex bridge', () => { writeHooks(dir, { SessionStart: [{ hooks: [{ type: 'command', command: slow }] }] }) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) diff --git a/packages/hooks/hooks-codex/tests/coverage-cases.ts b/packages/hooks/hooks-codex/tests/coverage-cases.ts index 7fed07518a..dcb5cd4443 100644 --- a/packages/hooks/hooks-codex/tests/coverage-cases.ts +++ b/packages/hooks/hooks-codex/tests/coverage-cases.ts @@ -13,7 +13,6 @@ import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-test import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as HooksCodex from '@deepseek-ai/dsh-hooks-codex' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' const testToolSignal = new AbortController().signal @@ -32,7 +31,6 @@ type HarnessOpts = { stderrSummaryMaxChars?: number; sessionRoot?: string } async function harness(configPath: string, adapter: MockAdapter, opts: HarnessOpts = {}): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) if (opts.sessionRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: opts.sessionRoot }) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) @@ -316,7 +314,6 @@ export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGro const adapter = new MockAdapter([textResponse('ok')]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) @@ -627,7 +624,6 @@ export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGro const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LocalSubprocessRuntime) await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir }) diff --git a/packages/llm/llm-retry/tests/transport-recovery.spec.ts b/packages/llm/llm-retry/tests/transport-recovery.spec.ts index 7591f8fdf2..fb830f9868 100644 --- a/packages/llm/llm-retry/tests/transport-recovery.spec.ts +++ b/packages/llm/llm-retry/tests/transport-recovery.spec.ts @@ -10,7 +10,6 @@ import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import type { MockLlmBehavior, MockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' import { SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as Retry from '../src/index.ts' let context: Context | undefined @@ -38,7 +37,6 @@ async function harness( vi.stubEnv('DEEPSEEK_API_KEY', 'mock-key') const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(LlmDeepSeek, { baseURL, streamIdleTimeoutMs: options.streamIdleTimeoutMs ?? 1_000, diff --git a/packages/schedule/schedule/tests/jsonl-restart.spec.ts b/packages/schedule/schedule/tests/jsonl-restart.spec.ts index d18e35aac9..23371feee6 100644 --- a/packages/schedule/schedule/tests/jsonl-restart.spec.ts +++ b/packages/schedule/schedule/tests/jsonl-restart.spec.ts @@ -7,7 +7,6 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { LlmAdapter, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -52,7 +51,6 @@ async function mountRuntime(root: string, adapter: RecordingAdapter): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(PersistenceProbe) ctx.on('session/flush', () => {}) await ctx.plugin(AgentLoop, { agents: [] }) diff --git a/packages/session/session-checkpoint-policy/tests/fixtures/crash-child.ts b/packages/session/session-checkpoint-policy/tests/fixtures/crash-child.ts index 37caecb8dc..83826090dd 100644 --- a/packages/session/session-checkpoint-policy/tests/fixtures/crash-child.ts +++ b/packages/session/session-checkpoint-policy/tests/fixtures/crash-child.ts @@ -2,7 +2,6 @@ import { writeFile } from 'node:fs/promises' import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { createUserMessage, ToolCallId, type GenerateOptions, LlmAdapter, type StreamChunk } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -38,7 +37,6 @@ class CrashAdapter extends LlmAdapter { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) -await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' }) await ctx.plugin(checkpointPolicy) diff --git a/packages/shell/tool-bash/tests/integration.spec.ts b/packages/shell/tool-bash/tests/integration.spec.ts index c645230ac2..78a40d6962 100644 --- a/packages/shell/tool-bash/tests/integration.spec.ts +++ b/packages/shell/tool-bash/tests/integration.spec.ts @@ -6,7 +6,6 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' @@ -27,8 +26,6 @@ import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent async function harness(adapter: MockAdapter, sessionRoot?: string, dshHome?: string) { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - // AgentLoop declares the registry as a required injection. - await ctx.plugin(SessionProjectionRegistry) if (sessionRoot !== undefined) { await ctx.plugin(JsonlSessionPersistence, { root: sessionRoot, compression: 'none' }) } diff --git a/packages/subagent/subagent-fork-in-process/tests/multi-subagent.spec.ts b/packages/subagent/subagent-fork-in-process/tests/multi-subagent.spec.ts index f14c5d001b..42e5216e47 100644 --- a/packages/subagent/subagent-fork-in-process/tests/multi-subagent.spec.ts +++ b/packages/subagent/subagent-fork-in-process/tests/multi-subagent.spec.ts @@ -9,7 +9,6 @@ import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant' import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant' import SubagentRuntime, { type SubagentStartRequest } from '@deepseek-ai/dsh-subagent' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as Spawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import * as fork from '../src/index.ts' @@ -38,7 +37,6 @@ async function setup(script: Script) { await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) await ctx.plugin(Spawn, { providerName: 'spawn' }) await ctx.plugin(fork, { providerName: 'fork' }) diff --git a/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts b/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts index 1d4a98e60e..1dea726624 100644 --- a/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts +++ b/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts @@ -45,7 +45,6 @@ async function setup(script: Script) { await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) await ctx.plugin(fork, { providerName: 'fork' }) ctx.llm.registerAdapter(['mock'], new MockAdapter(script)) diff --git a/packages/subagent/subagent-in-process-driver/tests/inheritance.spec.ts b/packages/subagent/subagent-in-process-driver/tests/inheritance.spec.ts index 4ff72cba21..aa7437be81 100644 --- a/packages/subagent/subagent-in-process-driver/tests/inheritance.spec.ts +++ b/packages/subagent/subagent-in-process-driver/tests/inheritance.spec.ts @@ -18,7 +18,6 @@ import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import * as ToolFs from '@deepseek-ai/dsh-tool-fs' import ApprovalService from '@deepseek-ai/dsh-user-approval' import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import { startInProcessRun } from '../src/index.ts' @@ -41,7 +40,6 @@ async function setupWalled(script: Script): Promise<{ ctx: Context; parent: Agen const ctx = new Context() contexts.push(ctx) await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: workspace }) await ctx.plugin(SandboxedFileSystem, { cwd: workspace }) await ctx.plugin(ToolFs) diff --git a/packages/subagent/subagent-in-process-driver/tests/preset-inheritance.spec.ts b/packages/subagent/subagent-in-process-driver/tests/preset-inheritance.spec.ts index e912c2516f..706b81b128 100644 --- a/packages/subagent/subagent-in-process-driver/tests/preset-inheritance.spec.ts +++ b/packages/subagent/subagent-in-process-driver/tests/preset-inheritance.spec.ts @@ -18,7 +18,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import AgentPresets from '@deepseek-ai/dsh-agent-presets' import { SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import { startInProcessRun } from '../src/index.ts' @@ -40,7 +39,6 @@ async function setupPresetHost(): Promise<{ ctx: Context; adapter: MockAdapter; await ctx.plugin(Loader) ctx.loader.builtins.include = Include await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(AgentPresets, { default: 'coding', roots: ROOTS, includeShippedRoot: false, includeUserRoot: false }) const adapter = new MockAdapter([textResponse('parent idle'), textResponse('child done')]) diff --git a/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts b/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts index 731ada1fd9..7cafcd8e08 100644 --- a/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts +++ b/packages/subagent/subagent-in-process-driver/tests/structured.spec.ts @@ -13,7 +13,6 @@ import SubagentRuntime, { type ResolvedSubagentStartRequest, type SubagentStartRequest, } from '@deepseek-ai/dsh-subagent' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Config as ToolConfig, ObjectJsonSchema } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture, RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' @@ -69,7 +68,6 @@ async function setup(script: Script, options: SetupOptions = {}) { } await mountInvariants(ctx) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) const disposeProvider = ctx.subagents.registerProvider({ name: 'spawn', diff --git a/packages/subagent/subagent-in-process-driver/tests/subagent-in-process-driver.spec.ts b/packages/subagent/subagent-in-process-driver/tests/subagent-in-process-driver.spec.ts index b69a549983..da43c58fb1 100644 --- a/packages/subagent/subagent-in-process-driver/tests/subagent-in-process-driver.spec.ts +++ b/packages/subagent/subagent-in-process-driver/tests/subagent-in-process-driver.spec.ts @@ -10,7 +10,6 @@ import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant' import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant' import SubagentRuntime, { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' import { maxTokensResponse, MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import { startInProcessRun } from '../src/index.ts' @@ -29,7 +28,6 @@ async function setup(script: Script, parentOptions: Partial = {}) await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) const adapter = new MockAdapter(script) ctx.llm.registerAdapter(['mock'], adapter) diff --git a/packages/subagent/subagent-spawn-in-process/tests/harness.ts b/packages/subagent/subagent-spawn-in-process/tests/harness.ts index 16e6680432..d60d8057d3 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/harness.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/harness.ts @@ -1,7 +1,6 @@ import { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env' @@ -25,7 +24,6 @@ export async function spawnHarness(workdir: string): Promise { // spawned children render it. It stays neutral for both roles; the // delegation nudge lives in the e2e's user prompt and the subagent tool's // own description. - await ctx.plugin(SessionProjectionRegistry) await mountAgentLoopTestDependencies(ctx, { systemPrompt: { persona: 'You are a coding agent. Report only when the requested work is done.' }, }) diff --git a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts index b3efa062e7..b6b64d66d6 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts @@ -39,7 +39,6 @@ async function setup(script: Script) { await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) await ctx.plugin(spawn, { providerName: 'spawn' }) ctx.llm.registerAdapter(['mock'], adapter) @@ -330,7 +329,6 @@ describe('dsh-subagent-spawn-in-process', () => { await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) const fiber = await ctx.plugin(spawn, { providerName: 'spawn' }) ctx.llm.registerAdapter(['mock'], adapter) @@ -359,7 +357,6 @@ describe('dsh-subagent-spawn-in-process', () => { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) const fiber = await ctx.plugin(spawn, { providerName: 'spawn' }) const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' }) diff --git a/packages/subagent/subagent/tests/continuation-inheritance.spec.ts b/packages/subagent/subagent/tests/continuation-inheritance.spec.ts index 97c7737ad7..41b12039f2 100644 --- a/packages/subagent/subagent/tests/continuation-inheritance.spec.ts +++ b/packages/subagent/subagent/tests/continuation-inheritance.spec.ts @@ -19,7 +19,6 @@ import SandboxPolicyService, { setSandboxMode } from '@deepseek-ai/dsh-sandbox-p import { Session, SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import ApprovalService from '@deepseek-ai/dsh-user-approval' @@ -41,7 +40,6 @@ async function setup(script: Script) { const ctx = new Context() contexts.push(ctx) await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) const root = mkdtempSync(join(tmpdir(), 'dsh-continuation-inherit-')) roots.push(root) await ctx.plugin(JsonlSessionPersistence, { root }) diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index 31b5bdbcb5..9508065197 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -9,7 +9,6 @@ import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-test import { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import * as SubagentFork from '@deepseek-ai/dsh-subagent-fork-in-process' import type { GenerateOptions, MessageId, StreamChunk } from '@deepseek-ai/dsh-llm' @@ -73,9 +72,6 @@ async function setupWith( ) { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - // The registry is a required injection of AgentLoop and SubagentRuntime - // (both register projection units on activation). - await ctx.plugin(SessionProjectionRegistry) let disposePersistence: (() => Promise) | undefined let root: string | undefined if (options.persistence !== false) { @@ -459,7 +455,6 @@ describe('SubagentRuntime.startContinuable', () => { const fresh = new Context() await mountAgentLoopTestDependencies(fresh) - await fresh.plugin(SessionProjectionRegistry) const freshPersistence = await fresh.plugin(JsonlSessionPersistence, { root: root! }) // This context opened a second handle on the same root; register it so // afterEach closes it before removing the root (even on a failure path). @@ -2517,7 +2512,6 @@ describe('continuable errors', () => { const adapter = new GatedAdapter([{ chunks: textResponse('child'), gate: hold.promise }]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) const root = mkdtempSync(join(tmpdir(), 'dsh-subagent-continuation-')) const persistenceFiber = await ctx.plugin(JsonlSessionPersistence, { root }) cleanups.push(async () => { diff --git a/packages/subagent/tool-subagent-report/tests/tool-subagent-report.spec.ts b/packages/subagent/tool-subagent-report/tests/tool-subagent-report.spec.ts index 30a5568d94..e8bb53925d 100644 --- a/packages/subagent/tool-subagent-report/tests/tool-subagent-report.spec.ts +++ b/packages/subagent/tool-subagent-report/tests/tool-subagent-report.spec.ts @@ -13,7 +13,6 @@ import { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SubagentRuntime from '@deepseek-ai/dsh-subagent' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import * as control from '@deepseek-ai/dsh-tool-subagent-control' import { textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' @@ -69,7 +68,6 @@ async function setup(options: { load?: boolean; config?: tool.Config } = {}) { const root = mkdtempSync(join(tmpdir(), 'dsh-tool-subagent-report-')) await ctx.plugin(JsonlSessionPersistence, { root }) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SubagentRuntime) await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) const fiber = options.load === false diff --git a/packages/subagent/tool-subagent/tests/harness.ts b/packages/subagent/tool-subagent/tests/harness.ts index acd1b02c7c..bda0a5ae63 100644 --- a/packages/subagent/tool-subagent/tests/harness.ts +++ b/packages/subagent/tool-subagent/tests/harness.ts @@ -50,7 +50,6 @@ export async function setup(toolConfig: SetupConfig, mockConfig: Partial { await ctx.plugin(MemorySettings) await ctx.plugin(SubagentModelSelectionConfig) await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(SubagentRuntime) await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) @@ -323,7 +322,6 @@ describe('SubagentModelSelectionConfig', () => { it('requires both the Host setting owner and a composition scope', async () => { const withoutSettings = new Context() await mountAgentLoopTestDependencies(withoutSettings) - await withoutSettings.plugin(SessionProjectionRegistry) await withoutSettings.plugin(SubagentRuntime) expect(() => { tool.apply(withoutSettings, { diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index 459cc346fc..756907924e 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -1181,7 +1181,7 @@ describe('dsh-tool-subagent continuable background mode', () => { /** Boot the real continuable stack without any model-facing follow-up adapter. */ async function continuableSetup() { - const ctx = await projectedContext() + const ctx = new Context() await mountAgentLoopTestDependencies(ctx) const root = mkdtempSync(path.join(tmpdir(), 'dsh-tool-subagent-continuable-')) roots.push(root) diff --git a/packages/test-support/agent-loop-testkit/README.i18n.yaml b/packages/test-support/agent-loop-testkit/README.i18n.yaml index 11c5a3c8e7..5b3ae21458 100644 --- a/packages/test-support/agent-loop-testkit/README.i18n.yaml +++ b/packages/test-support/agent-loop-testkit/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/test-support/agent-loop-testkit/README.md -README.md: 9a4ebbd62e7930bc5d4cbfb9acd025104e7fa85b -README.zh.md: 5b41a88106748074f0c265baaea639bdb9e73eb4 +README.md: b674df26f076425d03542108e9a8d7599aeaa1e2 +README.zh.md: 88a414360455a433165350d717c9ee59664fad88 diff --git a/packages/test-support/agent-loop-testkit/README.md b/packages/test-support/agent-loop-testkit/README.md index 9a4ebbd62e..b674df26f0 100644 --- a/packages/test-support/agent-loop-testkit/README.md +++ b/packages/test-support/agent-loop-testkit/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. It also creates a session-backed structural `Inbox` for consumer tests without exposing the production `ProjectedInbox` implementation. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. Use it when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. +`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, session-projection registry, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. It also creates a session-backed structural `Inbox` for consumer tests without exposing the production `ReactLoopInbox` implementation. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. Use it when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. ## Table of Contents @@ -41,15 +41,15 @@ await mountAgentLoopTestDependencies(ctx) await ctx.plugin(AgentLoop, { agents: [] }) ``` -The mounting helper activates the LLM, session, system-prompt, tool, and agent services in dependency order and returns before the loop is mounted. System-prompt and tool-registry configuration can be forwarded through `options`; the helper provides no test defaults beyond those the services own. After the agent registry has registered the standard inbox projection, `createInboxFixture(ctx.sessionProjections, session)` returns an `inbox` for code under test and a separate `claim` operation for the test driver; every edit appends a durable `agent/inbox/spliced` session event. +The mounting helper activates the LLM, session, session-projection, system-prompt, tool, and agent services in dependency order and returns before the loop is mounted. System-prompt and tool-registry configuration can be forwarded through `options`; the helper provides no test defaults beyond those the services own. `createInboxFixture(ctx.sessionProjections, session)` registers the standard inbox projection for the fixture, then returns an `inbox` for code under test and a separate `claim` operation for the test driver; every edit appends a durable `agent/inbox/spliced` session event. ### When to use it -Use the mounting helper for tests whose subject is the loop: load order, retries, tool execution, or session behavior on a real prerequisite stack. Use the Inbox fixture when a consumer test needs durable queue edits without constructing the package-internal `ProjectedInbox`. Mount dependencies directly when a test probes service load order, injection failures, partial topologies, or teardown — the helper hides exactly the wiring such tests must control. +Use the mounting helper for tests whose subject is the loop: load order, retries, tool execution, or session behavior on a real prerequisite stack. Use the Inbox fixture when a consumer test needs durable queue edits without constructing the package-internal `ReactLoopInbox`. Mount dependencies directly when a test probes service load order, injection failures, partial topologies, or teardown — the helper hides exactly the wiring such tests must control. ### What can go wrong -A plugin-load failure rejects the mounting helper call; services activated earlier in the sequence remain owned by your context and unwind with it. The Inbox fixture throws when the registry does not contain the standard inbox projection. The context owns every mounted service, so dispose it after the test. +A plugin-load failure rejects the mounting helper call; services activated earlier in the sequence remain owned by your context and unwind with it. The Inbox fixture requires a live session-projection registry and owns its standard inbox registration through that context. The context owns every mounted service, so dispose it after the test. ----- @@ -63,7 +63,7 @@ This section explains the design of the test utilities; the observable behavior ### Design -`mountAgentLoopTestDependencies` mounts five service plugins in a fixed dependency order — LLM, session, system-prompt, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. `createInboxFixture` implements only the public structural Inbox operations and keeps loop-driver claiming separate; session projection replay supplies its state. Ownership stays with the caller's context and session. The implementations live in [`src/index.ts`](src/index.ts) and [`src/inbox.ts`](src/inbox.ts); the [`src/invariant.ts`](src/invariant.ts) companion declares no runtime invariant because the package owns no production event stream or mutable data — consuming test suites exercise its behavior. +`mountAgentLoopTestDependencies` mounts six service plugins in a fixed dependency order — LLM, session, session-projection registry, system-prompt registry, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. `createInboxFixture` implements only the public structural Inbox operations and keeps loop-driver claiming separate; session projection replay supplies its state. Ownership stays with the caller's context and session. The implementations live in [`src/index.ts`](src/index.ts) and [`src/inbox.ts`](src/inbox.ts); the [`src/invariant.ts`](src/invariant.ts) companion declares no runtime invariant because the package owns no production event stream or mutable data — consuming test suites exercise its behavior. @@ -99,7 +99,7 @@ None; this package neither assembles nor sends a provider request. These limits define what the utilities do not share. They are current package constraints, not a task backlog. - **Only the mandatory prerequisite spine is shared** — adapters, optional plugins, `AgentLoop`, agents, and context teardown remain caller-owned so scenario-specific ordering stays visible. -- **The Inbox fixture emits durable session events only** — it does not reproduce live `agent/inbox/inserted` or `agent/inbox/discarded` notifications owned by `ProjectedInbox`. +- **The Inbox fixture emits durable session events only** — it does not reproduce live `agent/inbox/inserted` or `agent/inbox/discarded` notifications owned by `ReactLoopInbox`. ### Dev Note diff --git a/packages/test-support/agent-loop-testkit/README.zh.md b/packages/test-support/agent-loop-testkit/README.zh.md index 5b41a88106..88a4143604 100644 --- a/packages/test-support/agent-loop-testkit/README.zh.md +++ b/packages/test-support/agent-loop-testkit/README.zh.md @@ -9,7 +9,7 @@ kind: "package-library" ## 概述 -`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。它还为消费方测试创建由会话支撑的结构化 `Inbox`,而不暴露生产环境的 `ProjectedInbox` 实现。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。当测试对象是 loop 行为而非服务接线时使用它;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 +`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、会话投影注册表、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。它还为消费方测试创建由会话支撑的结构化 `Inbox`,而不暴露生产环境的 `ReactLoopInbox` 实现。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。当测试对象是 loop 行为而非服务接线时使用它;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 ## 目录 @@ -41,15 +41,15 @@ await mountAgentLoopTestDependencies(ctx) await ctx.plugin(AgentLoop, { agents: [] }) ``` -挂载辅助函数按依赖顺序激活 LLM、会话、系统提示词、工具与 agent 服务,并在 loop 挂载前返回。系统提示词与工具注册表配置可通过 `options` 转发;除服务自有的默认值外,本辅助函数不提供测试默认值。agent 注册表注册标准 inbox projection 后,`createInboxFixture(ctx.sessionProjections, session)` 会返回供待测代码使用的 `inbox`,并另行返回供测试驱动使用的 `claim` 操作;每次编辑都会追加持久的 `agent/inbox/spliced` 会话事件。 +挂载辅助函数按依赖顺序激活 LLM、会话、会话投影、系统提示词、工具与 agent 服务,并在 loop 挂载前返回。系统提示词与工具注册表配置可通过 `options` 转发;除服务自有的默认值外,本辅助函数不提供测试默认值。`createInboxFixture(ctx.sessionProjections, session)` 会为 fixture 注册标准 inbox 投影,然后返回供待测代码使用的 `inbox`,并另行返回供测试驱动使用的 `claim` 操作;每次编辑都会追加持久的 `agent/inbox/spliced` 会话事件。 ### 何时使用 -当测试对象是 loop 本身——在真实先决依赖栈上的加载顺序、重试、工具执行或会话行为——时使用挂载辅助函数。当消费方测试需要持久队列编辑但不应构造包内的 `ProjectedInbox` 时,请使用 Inbox fixture。当测试要探测服务加载顺序、注入失败、部分拓扑或清理时,请直接挂载依赖——辅助函数隐藏的正是这类测试必须控制的接线。 +当测试对象是 loop 本身——在真实先决依赖栈上的加载顺序、重试、工具执行或会话行为——时使用挂载辅助函数。当消费方测试需要持久队列编辑但不应构造包内的 `ReactLoopInbox` 时,请使用 Inbox fixture。当测试要探测服务加载顺序、注入失败、部分拓扑或清理时,请直接挂载依赖——辅助函数隐藏的正是这类测试必须控制的接线。 ### 可能出什么问题 -插件加载失败会使挂载辅助函数调用被拒绝;顺序中较早激活的服务仍归你的上下文所有,并随上下文一起解除。当注册表不含标准 inbox projection 时,Inbox fixture 会抛出错误。上下文拥有所有已挂载服务,因此测试结束后请 dispose(资源释放)它。 +插件加载失败会使挂载辅助函数调用被拒绝;顺序中较早激活的服务仍归你的上下文所有,并随上下文一起解除。Inbox fixture 要求会话投影注册表处于活跃状态,并通过该上下文持有自己的标准 inbox 注册。上下文拥有所有已挂载服务,因此测试结束后请 dispose(资源释放)它。 ----- @@ -63,7 +63,7 @@ await ctx.plugin(AgentLoop, { agents: [] }) ### 设计 -`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、系统提示词、工具注册表、agent 注册表——挂载五个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。`createInboxFixture` 只实现公开的结构化 Inbox 操作,并将 loop 驱动方的 claim 操作分离;会话 projection 重放提供其状态。所有权留在调用方的上下文与会话。实现位于 [`src/index.ts`](src/index.ts) 与 [`src/inbox.ts`](src/inbox.ts);[`src/invariant.ts`](src/invariant.ts) 配套入口声明无运行时不变式,因为本包不拥有任何生产事件流或可变数据——消费它的测试套件会检验其行为。 +`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、会话投影注册表、系统提示词注册表、工具注册表、agent 注册表——挂载六个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。`createInboxFixture` 只实现公开的结构化 Inbox 操作,并将 loop 驱动方的 claim 操作分离;会话投影重放提供其状态。所有权留在调用方的上下文与会话。实现位于 [`src/index.ts`](src/index.ts) 与 [`src/inbox.ts`](src/inbox.ts);[`src/invariant.ts`](src/invariant.ts) 配套入口声明无运行时不变式,因为本包不拥有任何生产事件流或可变数据——消费它的测试套件会检验其行为。 @@ -99,7 +99,7 @@ await ctx.plugin(AgentLoop, { agents: [] }) 这些限制说明辅助工具不共享什么。它们是当前包约束,不是任务积压。 - **只共享必需的先决主干**——适配器、可选插件、`AgentLoop`、agent 与上下文清理仍由调用方负责,以使特定场景的挂载顺序清晰可见。 -- **Inbox fixture 只发出持久会话事件**——它不会复现由 `ProjectedInbox` 负责的实时 `agent/inbox/inserted` 或 `agent/inbox/discarded` 通知。 +- **Inbox fixture 只发出持久会话事件**——它不会复现由 `ReactLoopInbox` 负责的实时 `agent/inbox/inserted` 或 `agent/inbox/discarded` 通知。 ### 开发备注 diff --git a/packages/test-support/agent-loop-testkit/src/index.ts b/packages/test-support/agent-loop-testkit/src/index.ts index e6d86338f2..ae384f45ab 100644 --- a/packages/test-support/agent-loop-testkit/src/index.ts +++ b/packages/test-support/agent-loop-testkit/src/index.ts @@ -9,6 +9,7 @@ import type { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' @@ -43,6 +44,7 @@ export async function mountAgentLoopTestDependencies( ): Promise { await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(SystemPrompt, options.systemPrompt ?? {}) await ctx.plugin(ToolRuntime, options.tools ?? {}) await ctx.plugin(AgentRegistry) diff --git a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts index bc71618d05..a839738af4 100644 --- a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts +++ b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts @@ -18,7 +18,6 @@ describe('dsh-agent-loop-testkit', () => { systemPrompt: { persona: 'Test persona.' }, tools: { mode: 'native' }, }) - await ctx.plugin(SessionProjectionRegistry) expect(renderPrompt(await ctx.systemPrompt.assemble())).toContain('Test persona.') await expect(ctx.plugin(AgentLoop, { agents: [] })).resolves.toBeDefined() @@ -29,7 +28,6 @@ describe('dsh-agent-loop-testkit', () => { it('provides a session-backed structural Inbox with separate driver claims', async () => { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) const session = ctx.sessions.create(SessionId('agent-loop-testkit-inbox')) const fixture = createInboxFixture(ctx.sessionProjections, session) const firstTurn = message('first turn') diff --git a/packages/todo/tool-todo/tests/integration.spec.ts b/packages/todo/tool-todo/tests/integration.spec.ts index 0692772ea9..264731bdbc 100644 --- a/packages/todo/tool-todo/tests/integration.spec.ts +++ b/packages/todo/tool-todo/tests/integration.spec.ts @@ -5,7 +5,6 @@ import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' @@ -18,7 +17,6 @@ import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent async function harness(adapter: MockAdapter): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(ToolTodo, { allowParallelInProgress: true }) ctx.llm.registerAdapter(['mock'], adapter) diff --git a/packages/workflow/tool-ralph/tests/integration.spec.ts b/packages/workflow/tool-ralph/tests/integration.spec.ts index 67f29d29fd..8b4d4e4e42 100644 --- a/packages/workflow/tool-ralph/tests/integration.spec.ts +++ b/packages/workflow/tool-ralph/tests/integration.spec.ts @@ -5,7 +5,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SubagentRuntime from '@deepseek-ai/dsh-subagent' import { STRUCTURED_OUTPUT_TOOL } from '@deepseek-ai/dsh-subagent-in-process-driver' import * as spawn from '@deepseek-ai/dsh-subagent-spawn-in-process' @@ -21,7 +20,6 @@ async function mountRalph(script: MockScript, config: toolRalph.Config) { const ctx = new Context() const adapter = new MockAdapter(script) await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(SubagentRuntime) await ctx.plugin(spawn, { providerName: 'spawn' }) @@ -59,7 +57,6 @@ describe('dsh-tool-ralph over the real spawn and worker-thread stack', () => { toolCallResponse('round-2', STRUCTURED_OUTPUT_TOOL, finalReport), ]) await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(SubagentRuntime) await ctx.plugin(spawn, { providerName: 'spawn' }) diff --git a/packages/workflow/workflow-worker-thread/tests/integration.spec.ts b/packages/workflow/workflow-worker-thread/tests/integration.spec.ts index 686c342ad5..33f5575693 100644 --- a/packages/workflow/workflow-worker-thread/tests/integration.spec.ts +++ b/packages/workflow/workflow-worker-thread/tests/integration.spec.ts @@ -7,7 +7,6 @@ import InvariantRegistry from '@deepseek-ai/dsh-invariants' import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant' import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SubagentRuntime from '@deepseek-ai/dsh-subagent' import * as spawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import { STRUCTURED_OUTPUT_TOOL } from '@deepseek-ai/dsh-subagent-in-process-driver' @@ -36,7 +35,6 @@ async function setup(script: Script) { const adapter = new MockAdapter(script) await mountAgentLoopTestDependencies(ctx) await mountInvariants(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(SubagentRuntime) await ctx.plugin(spawn, { providerName: 'spawn' }) From d776df110652de11b661144842e21b8e8548a45a Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 28 Aug 2026 16:07:55 +0800 Subject: [PATCH 14/26] test(agent-loop): exclude unreachable teardown paths --- packages/core/agent-loop/src/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index b92be10dcc..18a3edc665 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -564,7 +564,9 @@ export class AgentLoop extends Service implements AgentFactory { // Disposal IS a disposed-cause cancel followed by quiescence. New work // sent after this point is the sender's bug — the registries are about // to drop the agent, so nothing should still hold it. + /* v8 ignore next -- Cordis effect teardown waits for synchronous setup before observing the machine slot. */ if (machine === undefined) await machineReady.promise + /* v8 ignore next -- setup failure untracks this disposer before resolving without a machine. */ if (machine !== undefined) { machine.cancel({ kind: 'disposed' }) await machine.whenIdle() From 2aeb9920ee40323fb1e36fb699955dd409bed81f Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 31 Aug 2026 10:58:17 +0800 Subject: [PATCH 15/26] test(agent-loop): remove duplicated Inbox fixture --- apps/cli/package.json | 1 + apps/cli/tests/fixtures/dsh-badge/snapshot.ts | 3 +- packages/api/session-controller/package.json | 1 + .../commands-queue-attachment.host.spec.ts | 23 ++-- .../tests/control-jobs.host.spec.ts | 20 ++- .../tests/control-queue.host.spec.ts | 25 ++-- .../tests/session-projections.host.spec.ts | 33 ++--- packages/bundle/headless/package.json | 1 + .../bundle/headless/tests/headless.spec.ts | 33 ++--- .../tests/agent-instructions.spec.ts | 38 +++--- .../time-context/tests/time-context.spec.ts | 4 +- packages/context/tmux-context/package.json | 1 + .../tmux-context/tests/tmux-context.spec.ts | 3 +- packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 4 +- packages/core/agent-loop/README.zh.md | 4 +- packages/core/agent-loop/src/inbox.ts | 8 +- packages/core/agent-loop/src/index.ts | 2 +- packages/core/agent-loop/tests/inbox.spec.ts | 12 +- packages/e2b/e2b/package.json | 1 + packages/e2b/e2b/tests/composition.e2e.ts | 3 +- .../e2b/e2b/tests/fixtures/composition/bin.ts | 14 ++- .../feedback/command-feedback/package.json | 1 + .../tests/command-feedback.spec.ts | 3 +- .../tests/loader-composition.spec.ts | 3 +- .../fs/tool-str-replace-editor/package.json | 1 + .../tests/tools.spec.ts | 3 +- packages/goal/command-goal/package.json | 1 + .../command-goal/tests/command-goal.spec.ts | 11 +- packages/goal/goal/package.json | 1 + packages/goal/goal/tests/goal.spec.ts | 9 +- packages/goal/goal/tests/projection.spec.ts | 8 +- .../goal/tool-goal/tests/tool-goal.spec.ts | 23 ++-- packages/jobs/jobs-local/package.json | 1 + packages/jobs/jobs-local/tests/jobs.spec.ts | 5 +- .../schedule/schedule/tests/runtime.spec.ts | 3 +- .../schedule/schedule/tests/tools.spec.ts | 3 +- .../shell/tool-bash-persistent/package.json | 1 + .../tests/loader-composition.spec.ts | 3 +- .../tool-bash-persistent/tests/tools.spec.ts | 3 +- .../shell/tool-pwsh-persistent/package.json | 1 + .../tests/loader-composition.spec.ts | 3 +- .../tool-pwsh-persistent/tests/tools.spec.ts | 3 +- packages/skill/tool-skill/package.json | 1 + .../skill/tool-skill/tests/tool-skill.spec.ts | 5 +- packages/terminal/terminal-bash/package.json | 1 + .../terminal-bash/tests/index.spec.ts | 7 +- .../terminal-bash/tests/local.spec.ts | 3 +- packages/terminal/terminal/package.json | 1 + .../terminal/terminal/tests/service.spec.ts | 3 +- packages/terminal/tool-terminal/package.json | 1 + .../tests/loader-composition.spec.ts | 3 +- .../tool-terminal/tests/tools.spec.ts | 3 +- .../agent-loop-testkit/README.i18n.yaml | 4 +- .../test-support/agent-loop-testkit/README.md | 29 +++-- .../agent-loop-testkit/README.zh.md | 29 +++-- .../agent-loop-testkit/package.json | 2 +- .../agent-loop-testkit/src/inbox.ts | 114 +++--------------- .../agent-loop-testkit/src/index.ts | 8 +- .../tests/agent-loop-testkit.spec.ts | 79 ++---------- .../tests/loader-composition.spec.ts | 3 +- pnpm-lock.yaml | 48 ++++++++ 62 files changed, 346 insertions(+), 326 deletions(-) diff --git a/apps/cli/package.json b/apps/cli/package.json index 8f82b8fdf7..8ec6036784 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -99,6 +99,7 @@ "@agentclientprotocol/sdk": "1.4.0", "@deepseek-ai/dsh-acp": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-agent-spine-demo": "workspace:^", "@deepseek-ai/dsh-attachment-local": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", diff --git a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts index d6a2f62918..4c2331ed0b 100644 --- a/apps/cli/tests/fixtures/dsh-badge/snapshot.ts +++ b/apps/cli/tests/fixtures/dsh-badge/snapshot.ts @@ -5,6 +5,7 @@ import { boot, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot' import { SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-skill' import type {} from '@deepseek-ai/dsh-tools' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const overlayPath = process.argv[2] if (overlayPath === undefined) throw new Error('dsh-badge snapshot requires an overlay path') @@ -23,7 +24,7 @@ try { id: agentId, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', send: () => {}, followup: () => {}, diff --git a/packages/api/session-controller/package.json b/packages/api/session-controller/package.json index 1eac7ad34b..72b77e28fd 100644 --- a/packages/api/session-controller/package.json +++ b/packages/api/session-controller/package.json @@ -113,6 +113,7 @@ "@deepseek-ai/cordis": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-default-model": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-agent-presets": "workspace:^", "@deepseek-ai/dsh-api-gateway": "workspace:^", 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 079860a4ee..c3391e9dba 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 @@ -1,5 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import type { Agent, Inbox, ModelSelectionRef } from '@deepseek-ai/dsh-agent' import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -10,7 +10,8 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it, vi } from 'vitest' import { ApiSessionAgentController } from '../src/agent.ts' import { SessionCommandController } from '../src/commands.ts' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts' async function commandHarness(): Promise<{ @@ -28,17 +29,23 @@ async function commandHarness(): Promise<{ const session = ctx.sessions.create(SessionId('commands-session'), { meta: { cwd: '/workspace' } }) const steer = vi.fn() const cancel = vi.fn() - const agent = { + const agent: Agent = { id: session.id, + options: {}, session, - inbox: undefined as never, + inbox: unsupportedInbox(), status: 'running', ctx, - steer, + send: () => {}, followup: vi.fn(), + steer, + inject: () => {}, cancel, - } as unknown as Agent - Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox }) + runMaintenance: task => task(new AbortController().signal), + whenIdle: () => Promise.resolve(), + } + const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) + Object.assign(agent, { inbox }) ctx.agents.register(agent) ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never) ctx.provide('agentDefaultModel', { @@ -55,7 +62,7 @@ async function commandHarness(): Promise<{ serializeImageAdmission: (_agent: Agent, operation: () => Promise) => operation(), composeAgent: () => Promise.resolve({ setup: () => {} }), } as unknown as ApiSessionAgentController - return { ctx, controller: new SessionCommandController(ctx, agents, '/workspace'), agent, inbox: agent.inbox, steer, cancel } + return { ctx, controller: new SessionCommandController(ctx, agents, '/workspace'), agent, inbox, steer, cancel } } async function expectFailure(operation: Promise, code: string): Promise { diff --git a/packages/api/session-controller/tests/control-jobs.host.spec.ts b/packages/api/session-controller/tests/control-jobs.host.spec.ts index 45cc2187c3..d14c1e5795 100644 --- a/packages/api/session-controller/tests/control-jobs.host.spec.ts +++ b/packages/api/session-controller/tests/control-jobs.host.spec.ts @@ -1,5 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import type { JobOutcome } from '@deepseek-ai/dsh-jobs' import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local' @@ -9,6 +9,8 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { SessionControlController } from '../src/control.ts' import type { SessionControlFrame } from '../src/types.ts' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' type BaselineFrame = Extract type JobFrame = Extract @@ -44,13 +46,23 @@ async function harness(withJobs: boolean): Promise<{ ctx.jobs.attachController('session-controller-test') } const session = ctx.sessions.create() - const agent = { + const agent: Agent = { id: session.id, + options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx, - } as unknown as Agent + send: () => {}, + followup: () => {}, + steer: () => {}, + inject: () => {}, + cancel: () => {}, + runMaintenance: task => task(new AbortController().signal), + whenIdle: () => Promise.resolve(), + } + const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) + Object.assign(agent, { inbox }) ctx.agents.register(agent) const control = new SessionControlController(ctx) await new Promise(resolve => setTimeout(resolve, 0)) diff --git a/packages/api/session-controller/tests/control-queue.host.spec.ts b/packages/api/session-controller/tests/control-queue.host.spec.ts index 0a2e813822..27ec5eef1d 100644 --- a/packages/api/session-controller/tests/control-queue.host.spec.ts +++ b/packages/api/session-controller/tests/control-queue.host.spec.ts @@ -1,5 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import type { Agent, Inbox } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' @@ -7,7 +7,8 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { SessionControlController } from '../src/control.ts' import type { SessionControlFrame } from '../src/types.ts' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' async function harness(): Promise<{ ctx: Context @@ -21,10 +22,15 @@ async function harness(): Promise<{ await ctx.plugin(AgentRegistry) await ctx.plugin(SessionProjectionRegistry) const session = ctx.sessions.create(SessionId('queue-session')) - const agent = { id: session.id, session, inbox: undefined as never, status: 'running', ctx } as unknown as Agent - Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox }) + const agent: Agent = { + id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'running', ctx, + send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, + runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), + } + const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) + Object.assign(agent, { inbox }) ctx.agents.register(agent) - return { ctx, control: new SessionControlController(ctx), agent, inbox: agent.inbox } + return { ctx, control: new SessionControlController(ctx), agent, inbox } } function message(text: string, source: 'user' | 'plugin' = 'user') { @@ -90,8 +96,13 @@ describe('Session control queue projection', () => { const control = new SessionControlController(ctx) await ctx.plugin(SessionProjectionRegistry) const session = ctx.sessions.create(SessionId('late-projection-queue')) - const agent = { id: session.id, session, inbox: undefined as never, status: 'running', ctx } as unknown as Agent - Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox }) + const agent: Agent = { + id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'running', ctx, + send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, + runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), + } + const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) + Object.assign(agent, { inbox }) ctx.agents.register(agent) const abort = new AbortController() const iterator = control.control(abort.signal)[Symbol.asyncIterator]() diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index bfe4089711..093eb8aae3 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -13,7 +13,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { z } from 'zod' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import { AttachmentStore } from '@deepseek-ai/dsh-attachment' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-presets' import type { Agent } from '@deepseek-ai/dsh-agent' @@ -27,7 +27,8 @@ import Storage from '@deepseek-ai/dsh-storage' import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' import * as StorageJson from '@deepseek-ai/dsh-storage-json' import type { SessionControlFrame, SessionFollowFrame } from '@deepseek-ai/dsh-api-session-controller/types' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' import { createSessionTestRemote, testSessionPersistence, type TestSessionRemote } from './test-remote.ts' declare module '@deepseek-ai/dsh-session-projection/types' { @@ -119,23 +120,25 @@ async function harness(withRegistry: boolean): Promise<{ await ctx.plugin(AgentRegistry) if (withRegistry) await ctx.plugin(SessionProjectionRegistry) const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) - const agent = { - id: session.id, - session, - inbox: { nextTurn: [], nextStep: [] } as never, - status: 'idle', - ctx, - } as unknown as Agent - const fixture = withRegistry ? createInboxFixture(ctx.sessionProjections, session) : undefined - if (fixture !== undefined) Object.assign(agent, { inbox: fixture.inbox }) + if (!withRegistry) { + return { + ctx, + session, + claim: () => { throw new Error('inbox is unavailable without the projection registry') }, + } + } + const agent: Agent = { + id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx, + send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, + runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), + } + const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) + Object.assign(agent, { inbox }) ctx.agents.register(agent) return { ctx, session, - claim: (target) => { - if (fixture === undefined) throw new Error('inbox fixture is unavailable without the projection registry') - return fixture.claim(target) - }, + claim: target => inbox.claim(target, 0), } } diff --git a/packages/bundle/headless/package.json b/packages/bundle/headless/package.json index 6d5b530aa6..be00e88708 100644 --- a/packages/bundle/headless/package.json +++ b/packages/bundle/headless/package.json @@ -62,6 +62,7 @@ "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-default-model": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index 6fcd318fa9..29c7625c06 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -2,14 +2,15 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import type { Agent, AgentHandle, CreateAgentOptions } from '@deepseek-ai/dsh-agent' import AgentDefaultModelConfig from '@deepseek-ai/dsh-agent-default-model' import { createAssistantMessage } from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' import { apply, Config, internals } from '../src/index.ts' const originalInternals = { ...internals } @@ -69,30 +70,34 @@ async function bench(script: Script): Promise<{ ...options.meta === undefined ? {} : { meta: options.meta }, }) let idle = Promise.resolve() - const agent = {} as Agent - const agentCtx = ownerCtx.extend({ agent }) - const inbox = createInboxFixture(ctx.sessionProjections, session) - Object.assign(agent, { + const agent: Agent = { id: session.id, options: options.agentOptions ?? {}, session, - inbox: inbox.inbox, + inbox: unsupportedInbox(), status: 'idle', - ctx: agentCtx, + ctx: ownerCtx, cancel: () => {}, runMaintenance: () => Promise.reject(new Error('not used')), send: () => {}, + followup: () => { throw new Error('scripted Agent Inbox is not initialized') }, + steer: () => {}, + inject: () => {}, + whenIdle: () => idle, + } + const agentCtx = ownerCtx.extend({ agent }) + const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) + Object.assign(agent, { + inbox, + ctx: agentCtx, followup: (message: UserMessage) => { - inbox.inbox.append('next-turn', message) - const claimed = inbox.claim('next-turn') + inbox.append('next-turn', message) + const claimed = inbox.claim('next-turn', 1) const [prompt] = claimed if (prompt === undefined || claimed.length !== 1) throw new Error('scripted Agent expected one claimed prompt') idle = Promise.resolve().then(() => script.afterPrompt(session, prompt)) }, - steer: () => {}, - inject: () => {}, - whenIdle: () => idle, - } satisfies Partial) + }) await options.setup?.(agentCtx) script.before?.(session) ctx.agents.register(agent) diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index b79545505a..3676d37c1a 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -43,7 +43,8 @@ import { import { resolveConfig } from '../src/config.ts' import { candidateScopeKey, renderInstructionChanges, renderWorkspaceInstructionSet, USER_GLOBAL_DIRECTORY, USER_GLOBAL_FILE } from '../src/render.ts' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' -import { createInboxFixture, type InboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' /** Per-candidate reconciliation scope key: directory paired with the file name. */ const sk = (directory: string, candidateName: string): string => candidateScopeKey(directory, candidateName) @@ -53,14 +54,10 @@ const isolatedInboxCtx = new Context() await isolatedInboxCtx.plugin(SessionStore) await isolatedInboxCtx.plugin(SessionProjectionRegistry) await isolatedInboxCtx.plugin(AgentRegistry) -const inboxFixtures = new WeakMap() let nextStubSession = 1 -/** Test-driver operations for one structural agent inbox. */ -function inboxFixture(agent: Agent): InboxFixture { - const fixture = inboxFixtures.get(agent) - if (fixture === undefined) throw new Error('agent inbox fixture is unavailable') - return fixture +interface TestAgent extends Agent { + readonly inbox: ReactLoopInbox } async function tempRepo(): Promise { @@ -201,7 +198,7 @@ async function mountFileToolsAndWorkspaceContext(ctx: Context, config: workspace return mountWorkspaceContextPlugin(ctx, config) } -function stubAgent(cwd?: string, seed: SessionEvent[] = []): Agent { +function stubAgent(cwd?: string, seed: SessionEvent[] = []): TestAgent { const id = SessionId(`agent-instructions-${String(nextStubSession++)}`) const agentCtx = isolatedInboxCtx const session = agentCtx.sessions.create(id, { @@ -213,7 +210,7 @@ function stubAgent(cwd?: string, seed: SessionEvent[] = []): Agent { id: SessionId('a1'), options: {}, session, - inbox: undefined as never, + inbox: unsupportedInbox(), status: 'idle', send: () => {}, followup: () => {}, @@ -223,10 +220,9 @@ function stubAgent(cwd?: string, seed: SessionEvent[] = []): Agent { runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - const fixture = createInboxFixture(agentCtx.sessionProjections, session) - Object.assign(agent, { inbox: fixture.inbox }) - inboxFixtures.set(agent, fixture) - return agent + return Object.assign(agent, { + inbox: new ReactLoopInbox(agentCtx.sessionProjections, session, agentEvents(agentCtx, agent)), + }) } function stubToolExecution( @@ -274,10 +270,10 @@ function baselineEvents(agent: Agent): SessionEvent[] { && event.data.source.baseline === true) } -async function appendAdditionalContexts(ctx: Context, agent: Agent): Promise { +async function appendAdditionalContexts(ctx: Context, agent: TestAgent): Promise { await syncedWorkspaceContext(ctx, agent) let lastSeq: number | undefined - for (const claimed of inboxFixture(agent).claim('next-step')) { + for (const claimed of agent.inbox.claim('next-step', 1)) { if (claimed.source.kind !== 'agent-instructions') continue const event = agent.session.append('user/message', claimed, { surfaceOp: 'append' }) ctx.emit('session/event', agent.session, event) @@ -288,14 +284,14 @@ async function appendAdditionalContexts(ctx: Context, agent: Agent): Promise() -async function composeBaselinePrefix(ctx: Context, agent: Agent): Promise { +async function composeBaselinePrefix(ctx: Context, agent: TestAgent): Promise { const signal = new AbortController().signal await agentEvents(ctx, agent).waterfall( 'agent/pre-step', { messages: [], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter' as const, messages: [] }), ) - const claimed = inboxFixture(agent).claim('next-step') + const claimed = agent.inbox.claim('next-step', 1) const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 2, signal }, @@ -1408,7 +1404,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(ctx, { dshHome: home, maxBytes: 65536 }) const resumed = stubAgent(root, [...original.session.events]) agentEvents(ctx, resumed).emit('agent/session-start', { source: 'resume' }) - const claimed = inboxFixture(resumed).claim('next-step') + const claimed = resumed.inbox.claim('next-step', 1) const decision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(1000) }, @@ -1454,7 +1450,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(ctx, { dshHome: home, maxBytes: 65536 }) const resumed = stubAgent(root, [...original.session.events]) agentEvents(ctx, resumed).emit('agent/session-start', { source: 'resume' }) - const staleClaim = inboxFixture(resumed).claim('next-step') + const staleClaim = resumed.inbox.claim('next-step', 1) const staleDecision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', { messages: staleClaim, turn: 1, step: 1, signal: AbortSignal.timeout(1000) }, @@ -1507,7 +1503,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(resumedCtx, { dshHome: home, maxBytes }) const resumed = stubAgent(root, [...original.session.events]) agentEvents(resumedCtx, resumed).emit('agent/session-start', { source: 'resume' }) - const claimed = inboxFixture(resumed).claim('next-step') + const claimed = resumed.inbox.claim('next-step', 1) const decision = await agentEvents(resumedCtx, resumed).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(1000) }, @@ -4662,7 +4658,7 @@ describe('workspace context inbox synchronization', () => { await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) const agent = stubAgent(join(root, 'pkg')) await syncedWorkspaceContext(ctx, agent) - const claimed = inboxFixture(agent).claim('next-step') + const claimed = agent.inbox.claim('next-step', 1) await write(join(root, 'pkg/AGENTS.md'), 'new claimed rule with more detail') const downstream = { kind: 'enter' as const, messages: claimed } diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index 7e201e1bcf..51ae467fb7 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -8,7 +8,7 @@ import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' -import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import { unsupportedInbox, mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import * as timeContext from '@deepseek-ai/dsh-time-context' import type { Config } from '@deepseek-ai/dsh-time-context' @@ -42,7 +42,7 @@ function sessionAgent(session: Session, id = 'agent'): Agent { id: SessionId(id), options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'running', ctx: new Context(), send: () => {}, diff --git a/packages/context/tmux-context/package.json b/packages/context/tmux-context/package.json index b90a6aa230..d6113b4cbc 100644 --- a/packages/context/tmux-context/package.json +++ b/packages/context/tmux-context/package.json @@ -45,6 +45,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-shell": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", diff --git a/packages/context/tmux-context/tests/tmux-context.spec.ts b/packages/context/tmux-context/tests/tmux-context.spec.ts index 302830bfa3..6935fe39c5 100644 --- a/packages/context/tmux-context/tests/tmux-context.spec.ts +++ b/packages/context/tmux-context/tests/tmux-context.spec.ts @@ -8,6 +8,7 @@ import { ShellExecutor } from '@deepseek-ai/dsh-shell' import type { ShellExecRequest, ShellExecSpec, ShellProcess, ShellRunResult } from '@deepseek-ai/dsh-shell' import * as tmuxContext from '@deepseek-ai/dsh-tmux-context' import type { Config } from '@deepseek-ai/dsh-tmux-context' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const SIGNAL = new AbortController().signal @@ -98,7 +99,7 @@ function sessionAgent(session: Session, id = 'agent'): Agent { id: SessionId(id), options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'running', ctx: new Context(), send: () => {}, diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index dc3e5bb068..5c8125a46d 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent-loop/README.md -README.md: 2c8a75867068a001c0f5978e201c3795359685eb -README.zh.md: e375da777161b0df6249bfb5b7df15eda0d8a140 +README.md: bf3da4edc65aae498775feb119fb8ed1c704da31 +README.zh.md: 5861335b9e1c13c57a135889f7854cad97c6c3d0 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 2c8a758670..bf3da4edc6 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -98,7 +98,7 @@ After `agent/request`, `ctx.llm.prepareCall()` validates adapter-owned fields an |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `AgentLoop` service, config schema, declarative agent startup, factory registration | | [`src/agent.ts`](src/agent.ts) | The concrete `ReactLoopAgent` driver: inbox, turn/step machine, cancellation | -| [`src/inbox.ts`](src/inbox.ts) | Package-internal `ReactLoopInbox`: durable projection, structural commands, and loop-only claim state | +| [`src/inbox.ts`](src/inbox.ts) | Exported `ReactLoopInbox`: durable projection, structural commands, and loop-only claim state | | [`src/tool-calls.ts`](src/tool-calls.ts) | Tool scheduling: exclusive barriers and the bounded parallel pool | | [`src/runtime-context.ts`](src/runtime-context.ts) | Per-step runtime-context snapshot handling | | [`src/constants.ts`](src/constants.ts) | `DEFAULT_MAX_PARALLEL_TOOL_CALLS` | @@ -110,7 +110,7 @@ Creation is one rollback-covered transaction: construct a private session, concr ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. Its `ReactLoopInbox` constructor registers the standard `inbox` projection on the agent scope, then uses that projection for structural commands and loop-only claims; registry reference counting keeps the shared key active until the last agent scope unloads. 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. `agent/pre-step` decides what enters the step; each successful model call appends one `assistant/message` anchor citing its chunk seqs, 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, and result context remain model-ordered. +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. Its `ReactLoopInbox` constructor registers the standard `inbox` projection on the agent scope, then uses that projection for structural commands and loop-only claims; focused consumer tests construct the exported class to exercise the same implementation. Registry reference counting keeps the shared key active until the last agent scope unloads. At a turn boundary the driver opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. `agent/pre-step` decides what enters the step; each successful model call appends one `assistant/message` anchor citing its chunk seqs, 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, and result context remain model-ordered. ### Failure and cancellation diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index e375da7771..5861335b9e 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -98,7 +98,7 @@ const handle = await ctx.agents.create({ |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`AgentLoop` 服务、配置 schema、声明式 agent 启动、工厂注册 | | [`src/agent.ts`](src/agent.ts) | 具体 `ReactLoopAgent` 驱动器:收件箱、轮次/步骤状态机、取消 | -| [`src/inbox.ts`](src/inbox.ts) | 包内部 `ReactLoopInbox`:持久投影、结构化命令与仅供循环使用的领取状态 | +| [`src/inbox.ts`](src/inbox.ts) | 导出的 `ReactLoopInbox`:持久投影、结构化命令与仅供循环使用的领取状态 | | [`src/tool-calls.ts`](src/tool-calls.ts) | 工具调度:独占屏障与有界并行池 | | [`src/runtime-context.ts`](src/runtime-context.ts) | 每步骤 runtime-context 快照处理 | | [`src/constants.ts`](src/constants.ts) | `DEFAULT_MAX_PARALLEL_TOOL_CALLS` | @@ -110,7 +110,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。其 `ReactLoopInbox` 构造函数在 agent 作用域上注册标准 `inbox` 投影,随后将该投影用于结构化命令与仅供 loop 使用的领取操作;注册表引用计数会使共享 key 持续有效,直至最后一个 agent 作用域卸载。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤;每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。其 `ReactLoopInbox` 构造函数在 agent 作用域上注册标准 `inbox` 投影,随后将该投影用于结构化命令与仅供 loop 使用的领取操作;聚焦消费方的测试会构造这个导出的类,以运行同一份实现。注册表引用计数会使共享 key 持续有效,直至最后一个 agent 作用域卸载。在轮次边界,驱动器先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤;每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 ### 失败与取消 diff --git a/packages/core/agent-loop/src/inbox.ts b/packages/core/agent-loop/src/inbox.ts index a040c76d4f..db89cd3072 100644 --- a/packages/core/agent-loop/src/inbox.ts +++ b/packages/core/agent-loop/src/inbox.ts @@ -64,7 +64,13 @@ export const inboxProjectionDefinition = { stateVersion: 1, } satisfies ProjectionDefinition<'inbox', InboxState> -/** Concrete inbox implementation constructed only by ReactLoopAgent. */ +/** + * Driver-owned durable Inbox implementation used by ReactLoopAgent and focused + * provider tests. + * @param projections - registry that owns the standard Inbox projection. + * @param session - session whose durable events store pending input. + * @param dispatch - agent-scoped notifications for Inbox lifecycle events. + */ export class ReactLoopInbox implements InboxContract { constructor( private readonly projections: SessionProjectionRegistry, diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 18a3edc665..2fd525bd04 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -33,7 +33,7 @@ import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import { ReactLoopAgent } from './agent.ts' import { DEFAULT_MAX_PARALLEL_TOOL_CALLS } from './constants.ts' -export { inboxProjectionDefinition } from './inbox.ts' +export { ReactLoopInbox, inboxProjectionDefinition } from './inbox.ts' /** Fiber states that cannot own or serve a new lifecycle. */ const INACTIVE_STATES: ReadonlySet = new Set([ diff --git a/packages/core/agent-loop/tests/inbox.spec.ts b/packages/core/agent-loop/tests/inbox.spec.ts index c0c56c1bb2..74fb85c7ff 100644 --- a/packages/core/agent-loop/tests/inbox.spec.ts +++ b/packages/core/agent-loop/tests/inbox.spec.ts @@ -7,6 +7,16 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { ReactLoopInbox } from '../src/inbox.ts' +function unsupportedInbox(): Agent['inbox'] { + const rejectMutation = (): never => { + throw new Error('this test Agent does not support Inbox mutations') + } + return { + nextTurn: [], nextStep: [], clear: rejectMutation, append: rejectMutation, + prepend: rejectMutation, replace: rejectMutation, remove: rejectMutation, splice: rejectMutation, + } +} + function stubAgent(rawId: string, overrides: Partial = {}): Agent { const id = SessionId(rawId) const session = overrides.session ?? Session.create(id) @@ -15,7 +25,7 @@ function stubAgent(rawId: string, overrides: Partial = {}): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx, send: () => {}, diff --git a/packages/e2b/e2b/package.json b/packages/e2b/e2b/package.json index a94691bbfe..fbbceb2a80 100644 --- a/packages/e2b/e2b/package.json +++ b/packages/e2b/e2b/package.json @@ -41,6 +41,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-app-boot": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", "@deepseek-ai/dsh-fs-e2b": "workspace:^", diff --git a/packages/e2b/e2b/tests/composition.e2e.ts b/packages/e2b/e2b/tests/composition.e2e.ts index 28a45fbc45..de6f192bf3 100644 --- a/packages/e2b/e2b/tests/composition.e2e.ts +++ b/packages/e2b/e2b/tests/composition.e2e.ts @@ -16,6 +16,7 @@ import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { Session, SessionId } from '@deepseek-ai/dsh-session' import E2BSubprocessRuntime from '@deepseek-ai/dsh-subprocess-e2b' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const fixtureRoot = fileURLToPath(new URL('./fixtures/composition/', import.meta.url)) const binScript = join(fixtureRoot, 'bin.ts') @@ -86,7 +87,7 @@ describe.skipIf(!process.env.E2B_API_KEY)('E2B live Loader composition', () => { id: ownerId, options: {}, session: ownerSession, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx, send() {}, diff --git a/packages/e2b/e2b/tests/fixtures/composition/bin.ts b/packages/e2b/e2b/tests/fixtures/composition/bin.ts index 78f3d8e84c..d762a2dda7 100644 --- a/packages/e2b/e2b/tests/fixtures/composition/bin.ts +++ b/packages/e2b/e2b/tests/fixtures/composition/bin.ts @@ -15,11 +15,23 @@ const ctx = await boot('e2b-composition', resolve(configPath)) const ownerFiber = ctx.plugin(() => {}) const ownerId = SessionId('e2b-live-owner') const session = Session.create(ownerId) +const unsupportedInboxMutation = (): never => { + throw new Error('the E2B composition owner does not support Inbox mutations') +} const owner: Agent = { id: ownerId, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: { + nextTurn: [], + nextStep: [], + clear: unsupportedInboxMutation, + append: unsupportedInboxMutation, + prepend: unsupportedInboxMutation, + replace: unsupportedInboxMutation, + remove: unsupportedInboxMutation, + splice: unsupportedInboxMutation, + }, status: 'idle', ctx: ownerFiber.ctx, send() {}, diff --git a/packages/feedback/command-feedback/package.json b/packages/feedback/command-feedback/package.json index dac634d5a6..9ac617ad10 100644 --- a/packages/feedback/command-feedback/package.json +++ b/packages/feedback/command-feedback/package.json @@ -43,6 +43,7 @@ "@deepseek-ai/cordis-plugin-include": "workspace:^", "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", diff --git a/packages/feedback/command-feedback/tests/command-feedback.spec.ts b/packages/feedback/command-feedback/tests/command-feedback.spec.ts index c04877e2f5..c6a5627dce 100644 --- a/packages/feedback/command-feedback/tests/command-feedback.spec.ts +++ b/packages/feedback/command-feedback/tests/command-feedback.spec.ts @@ -7,6 +7,7 @@ import CommandRuntime from '@deepseek-ai/dsh-commands' import SessionStore, { foldSurface, Session, SessionId } from '@deepseek-ai/dsh-session' import { SessionTelemetryBackend, type SessionTelemetrySharingStatus } from '@deepseek-ai/dsh-session-telemetry' import * as commandFeedback from '@deepseek-ai/dsh-command-feedback' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const { USER_ID, getOrCreateAnonymousUserId } = vi.hoisted(() => { const USER_ID = '01234567-89ab-4cde-8f01-23456789abcd' @@ -48,7 +49,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } id: session.id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), ctx: new Context(), get status() { return status }, send: () => {}, diff --git a/packages/feedback/command-feedback/tests/loader-composition.spec.ts b/packages/feedback/command-feedback/tests/loader-composition.spec.ts index c6a4125dc6..e40b7346e8 100644 --- a/packages/feedback/command-feedback/tests/loader-composition.spec.ts +++ b/packages/feedback/command-feedback/tests/loader-composition.spec.ts @@ -12,6 +12,7 @@ import CommandRuntime from '@deepseek-ai/dsh-commands' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import * as CommandFeedback from '@deepseek-ai/dsh-command-feedback' import { getOrCreateAnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' let root: string | undefined let context: Context | undefined @@ -34,7 +35,7 @@ function agent(ctx: Context): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), ctx: scope.ctx, get status() { return status }, send: () => {}, diff --git a/packages/fs/tool-str-replace-editor/package.json b/packages/fs/tool-str-replace-editor/package.json index c97dd886af..6f27bea02d 100644 --- a/packages/fs/tool-str-replace-editor/package.json +++ b/packages/fs/tool-str-replace-editor/package.json @@ -43,6 +43,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-fs": "workspace:^", "@deepseek-ai/dsh-fs-local": "workspace:^", "@deepseek-ai/dsh-fs-observation-policy": "workspace:^", 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 7cc021b6b7..28eac70167 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -16,6 +16,7 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import * as ToolStrReplaceEditor from '@deepseek-ai/dsh-tool-str-replace-editor' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const contexts: Context[] = [] const roots: string[] = [] @@ -34,7 +35,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, send: () => {}, diff --git a/packages/goal/command-goal/package.json b/packages/goal/command-goal/package.json index cdc6dec77f..31bfa7939e 100644 --- a/packages/goal/command-goal/package.json +++ b/packages/goal/command-goal/package.json @@ -41,6 +41,7 @@ "devDependencies": { "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-goal": "workspace:^", diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 88bf09674c..944be2688e 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import GoalService from '@deepseek-ai/dsh-goal' @@ -9,7 +9,8 @@ import type { GoalRef } from '@deepseek-ai/dsh-goal' import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as commandGoal from '@deepseek-ai/dsh-command-goal' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' interface Harness { readonly ctx: Context @@ -27,7 +28,7 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } id: session.id, options: {}, session, - inbox: undefined as never, + inbox: unsupportedInbox(), ctx: new Context(), get status() { return status }, send: () => {}, @@ -38,7 +39,9 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox }) + Object.assign(agent, { + inbox: new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)), + }) return { agent, session } } diff --git a/packages/goal/goal/package.json b/packages/goal/goal/package.json index 401aedf655..cced515e57 100644 --- a/packages/goal/goal/package.json +++ b/packages/goal/goal/package.json @@ -69,6 +69,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-agent-spine-demo": "workspace:^", "@deepseek-ai/dsh-bash-local": "workspace:^", diff --git a/packages/goal/goal/tests/goal.spec.ts b/packages/goal/goal/tests/goal.spec.ts index cf9ef86927..b77579ed3e 100644 --- a/packages/goal/goal/tests/goal.spec.ts +++ b/packages/goal/goal/tests/goal.spec.ts @@ -12,7 +12,8 @@ import GoalService, { foldGoal, } from '@deepseek-ai/dsh-goal' import type { GoalChangeMeta, GoalRef, GoalSnapshotChangeMeta } from '@deepseek-ai/dsh-goal' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' interface StubAgent { agent: Agent @@ -48,7 +49,7 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent id, options: {}, session, - inbox: undefined as never, + inbox: unsupportedInbox(), ctx: agentCtx, status: 'idle', send: () => {}, @@ -59,7 +60,9 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { inbox: createInboxFixture(agentCtx.sessionProjections, session).inbox }) + Object.assign(agent, { + inbox: new ReactLoopInbox(agentCtx.sessionProjections, session, agentEvents(agentCtx, agent)), + }) const stub = { agent, session, diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index b4c835bccf..c33b4f8baa 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -13,12 +13,12 @@ import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' -import type { UserMessage } from '@deepseek-ai/dsh-session' import SessionStore from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import GoalService, { GoalId, applyGoalProjection, foldGoal, goalProjectionDefinition } from '@deepseek-ai/dsh-goal' import type { GoalProjection, GoalProjectionState, GoalRef } from '@deepseek-ai/dsh-goal' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' interface Bench { ctx: Context @@ -35,15 +35,13 @@ function liveAgent(ctx: Context, session: Session): Agent { id: session.id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), ctx, get status() { return status }, send: () => {}, followup: () => {}, steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }), - inject(input: UserMessage) { - this.inbox.append('next-step', input) - }, + inject: () => { throw new Error('goal projection tests do not inject model context') }, cancel() {}, runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index 3b6bd9ed11..76f90acea6 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -15,13 +15,15 @@ import ToolRuntime from '@deepseek-ai/dsh-tools' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' import * as toolGoal from '@deepseek-ai/dsh-tool-goal' -import { createInboxFixture, type InboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const testToolSignal = new AbortController().signal interface StubAgent { readonly agent: Agent readonly session: Session + readonly inbox: ReactLoopInbox setStatus(status: AgentStatus): void } @@ -29,14 +31,6 @@ const isolatedInboxCtx = new Context() await isolatedInboxCtx.plugin(SessionStore) await isolatedInboxCtx.plugin(SessionProjectionRegistry) await isolatedInboxCtx.plugin(AgentRegistry) -const inboxFixtures = new WeakMap() - -/** Test-driver operations for one structural agent inbox. */ -function inboxFixture(agent: Agent): InboxFixture { - const fixture = inboxFixtures.get(agent) - if (fixture === undefined) throw new Error('agent inbox fixture is unavailable') - return fixture -} /** Build one registry-compatible live agent whose injections enter the durable inbox. */ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): StubAgent { @@ -52,7 +46,7 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St id: session.id, options: {}, session, - inbox: undefined as never, + inbox: unsupportedInbox(), get status() { return status }, ctx: agentCtx, send: () => {}, @@ -65,10 +59,9 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - const fixture = createInboxFixture(agentCtx.sessionProjections, session) - Object.assign(agent, { inbox: fixture.inbox }) - inboxFixtures.set(agent, fixture) - return { agent, session, setStatus(value) { status = value } } + const inbox = new ReactLoopInbox(agentCtx.sessionProjections, session, agentEvents(agentCtx, agent)) + Object.assign(agent, { inbox }) + return { agent, session, inbox, setStatus(value) { status = value } } } /** Open one message-triggered turn with its accepted model-visible input. */ @@ -81,7 +74,7 @@ function openTurn(stub: StubAgent, source: MessageSource, text = 'prompt'): numb source, }) stub.agent.inbox.append('next-turn', message) - const claimed = inboxFixture(stub.agent).claim('next-turn') + const claimed = stub.inbox.claim('next-turn', turn) if (claimed.length === 0) throw new Error('expected queued turn input') stub.session.append('turn/start', { turn }) for (const admitted of claimed) { diff --git a/packages/jobs/jobs-local/package.json b/packages/jobs/jobs-local/package.json index 02b00e36e1..8b275a4327 100644 --- a/packages/jobs/jobs-local/package.json +++ b/packages/jobs/jobs-local/package.json @@ -46,6 +46,7 @@ "@deepseek-ai/cordis-plugin-include": "workspace:^", "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-brand": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", diff --git a/packages/jobs/jobs-local/tests/jobs.spec.ts b/packages/jobs/jobs-local/tests/jobs.spec.ts index df035ac948..14f4ecd847 100644 --- a/packages/jobs/jobs-local/tests/jobs.spec.ts +++ b/packages/jobs/jobs-local/tests/jobs.spec.ts @@ -8,6 +8,7 @@ import type { ScopeKey } from '@deepseek-ai/dsh-scope' import { JobId } from '@deepseek-ai/dsh-jobs' import type { JobHooks, JobKind, JobOutcome, JobSnapshot, JobStart } from '@deepseek-ai/dsh-jobs' import LocalJobRegistry, { type Config as JobsConfig } from '@deepseek-ai/dsh-jobs-local' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' declare module '@deepseek-ai/dsh-jobs' { interface JobKindMap { @@ -34,7 +35,7 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle' as const, ctx: agentCtx, send: () => {}, @@ -44,7 +45,7 @@ function stubAgent(ctx: Context, rawId: string, presetScope?: ScopeKey): Agent { cancel() {}, runMaintenance: (job: (signal: AbortSignal) => Promise) => job(new AbortController().signal), whenIdle() { return Promise.resolve() }, - } + } satisfies Agent agentScopeDisposers.set(agent, async () => { await scopeFiber.dispose() }) return agent } diff --git a/packages/schedule/schedule/tests/runtime.spec.ts b/packages/schedule/schedule/tests/runtime.spec.ts index f3a9c3e058..7dc495766b 100644 --- a/packages/schedule/schedule/tests/runtime.spec.ts +++ b/packages/schedule/schedule/tests/runtime.spec.ts @@ -11,6 +11,7 @@ import { foldScheduleEvents, } from '../src/domain.ts' import { MAX_TIMER_DELAY_MS, ScheduleRuntime } from '../src/runtime.ts' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const contexts: Context[] = [] const runtimes: ScheduleRuntime[] = [] @@ -61,7 +62,7 @@ async function harness(): Promise { id: session.id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx: new Context(), send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {}, diff --git a/packages/schedule/schedule/tests/tools.spec.ts b/packages/schedule/schedule/tests/tools.spec.ts index b4dd2c6eda..bd76c87bfe 100644 --- a/packages/schedule/schedule/tests/tools.spec.ts +++ b/packages/schedule/schedule/tests/tools.spec.ts @@ -10,6 +10,7 @@ import ToolRuntime from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' import { registerScheduleTools } from '../src/tools.ts' import { runScheduleTransaction } from '../src/transaction.ts' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const signal = new AbortController().signal const contexts: Context[] = [] @@ -28,7 +29,7 @@ function stubAgent(ctx: Context, id: string): Agent { id: session.id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx: new Context(), send(_message: UserMessage, _target: InboxTarget, _wakeup: boolean) {}, diff --git a/packages/shell/tool-bash-persistent/package.json b/packages/shell/tool-bash-persistent/package.json index d72697c5f2..598a11033b 100644 --- a/packages/shell/tool-bash-persistent/package.json +++ b/packages/shell/tool-bash-persistent/package.json @@ -45,6 +45,7 @@ "@deepseek-ai/cordis-plugin-include": "workspace:^", "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-terminal": "workspace:^", 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 053eb78e0f..bdb9654cb6 100644 --- a/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/loader-composition.spec.ts @@ -20,6 +20,7 @@ import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import * as ToolBashPersistent from '@deepseek-ai/dsh-tool-bash-persistent' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' let root: string | undefined let context: Context | undefined @@ -45,7 +46,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, send: () => {}, diff --git a/packages/shell/tool-bash-persistent/tests/tools.spec.ts b/packages/shell/tool-bash-persistent/tests/tools.spec.ts index d5f1aeaccf..617ac76e2f 100644 --- a/packages/shell/tool-bash-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/tools.spec.ts @@ -18,6 +18,7 @@ import type { import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import * as ToolBashPersistent from '@deepseek-ai/dsh-tool-bash-persistent' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const contexts: Context[] = [] let callNumber = 0 @@ -39,7 +40,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, send: () => {}, diff --git a/packages/shell/tool-pwsh-persistent/package.json b/packages/shell/tool-pwsh-persistent/package.json index 2c7519147d..0631e540ab 100644 --- a/packages/shell/tool-pwsh-persistent/package.json +++ b/packages/shell/tool-pwsh-persistent/package.json @@ -45,6 +45,7 @@ "@deepseek-ai/cordis-plugin-include": "workspace:^", "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-terminal": "workspace:^", 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 070d165095..9b6b042f81 100644 --- a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts @@ -22,6 +22,7 @@ import { resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local/src/resolve.ts' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry from '@deepseek-ai/dsh-tools' import * as ToolPwshPersistent from '@deepseek-ai/dsh-tool-pwsh-persistent' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const hasPwsh = spawnSync( resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'], @@ -52,7 +53,7 @@ function agent(ctx: Context, cwd: string): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, send: () => {}, diff --git a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts index 99c5937352..212149dee7 100644 --- a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts @@ -18,6 +18,7 @@ import type { import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry from '@deepseek-ai/dsh-tools' import * as ToolPwshPersistent from '@deepseek-ai/dsh-tool-pwsh-persistent' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const contexts: Context[] = [] let callNumber = 0 @@ -39,7 +40,7 @@ function agent(ctx: Context, cwd: string | undefined): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, send: () => {}, diff --git a/packages/skill/tool-skill/package.json b/packages/skill/tool-skill/package.json index e2823175d4..fd9d4bf28e 100644 --- a/packages/skill/tool-skill/package.json +++ b/packages/skill/tool-skill/package.json @@ -44,6 +44,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-scope": "workspace:^", diff --git a/packages/skill/tool-skill/tests/tool-skill.spec.ts b/packages/skill/tool-skill/tests/tool-skill.spec.ts index b3b85906db..08afba6480 100644 --- a/packages/skill/tool-skill/tests/tool-skill.spec.ts +++ b/packages/skill/tool-skill/tests/tool-skill.spec.ts @@ -12,6 +12,7 @@ import AgentRegistry, { agentEvents, type Agent, type PreStepDecision } from '@d import SkillRegistry from '@deepseek-ai/dsh-skill' import * as SkillFileSystem from '@deepseek-ai/dsh-skill-filesystem' import * as toolSkill from '@deepseek-ai/dsh-tool-skill' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const testToolSignal = new AbortController().signal @@ -44,7 +45,7 @@ function agentForCwd(cwd: string): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', send: () => {}, followup: () => {}, @@ -62,7 +63,7 @@ function sessionAgent(session: Session, id = 'tool-skill-agent'): Agent { id: SessionId(id), options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'running', ctx: new Context(), send: () => {}, diff --git a/packages/terminal/terminal-bash/package.json b/packages/terminal/terminal-bash/package.json index 5a21cb370a..1ff3f240b8 100644 --- a/packages/terminal/terminal-bash/package.json +++ b/packages/terminal/terminal-bash/package.json @@ -49,6 +49,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-terminal": "workspace:^", "@deepseek-ai/dsh-sandbox": "workspace:^", diff --git a/packages/terminal/terminal-bash/tests/index.spec.ts b/packages/terminal/terminal-bash/tests/index.spec.ts index d044db37fb..9605ece597 100644 --- a/packages/terminal/terminal-bash/tests/index.spec.ts +++ b/packages/terminal/terminal-bash/tests/index.spec.ts @@ -23,6 +23,7 @@ import type { SubprocessTerminalHandle, SubprocessTerminalSpawnSpec, } from '@deepseek-ai/dsh-subprocess' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' class EmptySandbox extends SandboxProvider { confine(_argv: readonly string[], _policy: SandboxPolicy): ConfinedArgv { @@ -52,7 +53,7 @@ function agent(ctx: Context, cwd?: string): Agent { const id = SessionId('agent') const session = Session.create(id, undefined, { version: 0, id, createdAt: 0, ...cwd === undefined ? {} : { cwd } }) const agent: Agent = { - id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, + id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx, send: () => {}, @@ -592,7 +593,7 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { - id: session.id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, + id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: ownerFiber.ctx, send: () => {}, @@ -642,7 +643,7 @@ describe('terminal-bash plugin shape', () => { const session = ctx.sessions.create(SessionId('pending-mode-owner')) const ownerFiber = await ctx.plugin(() => {}) const owner: Agent = { - id: session.id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, + id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: ownerFiber.ctx, send: () => {}, diff --git a/packages/terminal/terminal-bash/tests/local.spec.ts b/packages/terminal/terminal-bash/tests/local.spec.ts index d6744362b5..6b897dab60 100644 --- a/packages/terminal/terminal-bash/tests/local.spec.ts +++ b/packages/terminal/terminal-bash/tests/local.spec.ts @@ -16,6 +16,7 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import { resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local/src/resolve.ts' import * as ptyLocal from '@deepseek-ai/dsh-terminal-bash' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const roots: string[] = [] const contexts: Context[] = [] @@ -39,7 +40,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { const scope = ctx.plugin(() => {}) const session = Session.create(id) const agent: Agent = { - id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, + id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, send: () => {}, diff --git a/packages/terminal/terminal/package.json b/packages/terminal/terminal/package.json index aed22656b7..3dc758f6b1 100644 --- a/packages/terminal/terminal/package.json +++ b/packages/terminal/terminal/package.json @@ -39,6 +39,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-brand": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index 2dddafcea3..c5c552d18f 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -14,6 +14,7 @@ import type { TerminalSessionStatus, TerminalSignal, } from '@deepseek-ai/dsh-terminal' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' const agentScopeDisposers = new WeakMap Promise>() const ptyServiceDisposers = new WeakMap Promise>() @@ -26,7 +27,7 @@ function stubAgent(ctx: Context, rawId: string): Agent { id, options: {}, session, - inbox: { nextTurn: [], nextStep: [] } as never, + inbox: unsupportedInbox(), status: 'idle', ctx: scopeFiber.ctx, send: () => {}, diff --git a/packages/terminal/tool-terminal/package.json b/packages/terminal/tool-terminal/package.json index e76ec91aa7..a222efe1ee 100644 --- a/packages/terminal/tool-terminal/package.json +++ b/packages/terminal/tool-terminal/package.json @@ -49,6 +49,7 @@ "@deepseek-ai/cordis-plugin-include": "workspace:^", "@deepseek-ai/cordis-plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-terminal": "workspace:^", diff --git a/packages/terminal/tool-terminal/tests/loader-composition.spec.ts b/packages/terminal/tool-terminal/tests/loader-composition.spec.ts index 557511c629..c6f8f494de 100644 --- a/packages/terminal/tool-terminal/tests/loader-composition.spec.ts +++ b/packages/terminal/tool-terminal/tests/loader-composition.spec.ts @@ -20,6 +20,7 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as TerminalLocal from '@deepseek-ai/dsh-terminal-bash' import * as ToolPty from '@deepseek-ai/dsh-tool-terminal' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' let root: string | undefined let context: Context | undefined @@ -42,7 +43,7 @@ function agent(ctx: Context): Agent { const id = SessionId('pty-loader-agent') const session = Session.create(id) const value: Agent = { - id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, + id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, send: () => {}, diff --git a/packages/terminal/tool-terminal/tests/tools.spec.ts b/packages/terminal/tool-terminal/tests/tools.spec.ts index 43ca33a03b..8c0c7f6292 100644 --- a/packages/terminal/tool-terminal/tests/tools.spec.ts +++ b/packages/terminal/tool-terminal/tests/tools.spec.ts @@ -12,13 +12,14 @@ import type { TerminalBackend, TerminalBackendSession, TerminalSendOperation, Te import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local' import * as ToolTasks from '@deepseek-ai/dsh-tool-jobs' import * as ToolPty from '@deepseek-ai/dsh-tool-terminal' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' function fakeAgent(ctx: Context, rawId: string): Agent { const scope = ctx.plugin(() => {}) const id = SessionId(rawId) const session = Session.create(id) const agent: Agent = { - id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, + id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, send: () => {}, diff --git a/packages/test-support/agent-loop-testkit/README.i18n.yaml b/packages/test-support/agent-loop-testkit/README.i18n.yaml index 5b3ae21458..0ba8206a30 100644 --- a/packages/test-support/agent-loop-testkit/README.i18n.yaml +++ b/packages/test-support/agent-loop-testkit/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/test-support/agent-loop-testkit/README.md -README.md: b674df26f076425d03542108e9a8d7599aeaa1e2 -README.zh.md: 88a414360455a433165350d717c9ee59664fad88 +README.md: 9e863fb8b75fcacf8c1f6a1d447c5b8717532bec +README.zh.md: 6233995ad215b806ac955acbdbc5bb4714fd14f0 diff --git a/packages/test-support/agent-loop-testkit/README.md b/packages/test-support/agent-loop-testkit/README.md index b674df26f0..9e863fb8b7 100644 --- a/packages/test-support/agent-loop-testkit/README.md +++ b/packages/test-support/agent-loop-testkit/README.md @@ -1,5 +1,5 @@ --- -description: "Shared prerequisite mounting and session-backed structural Inbox fixtures for tests that exercise agent-loop behavior." +description: "Prerequisite mounting and fail-fast Inbox stubs for Agent and agent-loop tests." kind: "package-library" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, session-projection registry, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. It also creates a session-backed structural `Inbox` for consumer tests without exposing the production `ReactLoopInbox` implementation. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. Use it when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. +`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, session-projection registry, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. It also provides a fail-fast unsupported Inbox placeholder for Agent stubs whose tests do not exercise pending input. Use the package when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. ## Table of Contents @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -This package gives an AgentLoop test a working service topology before the loop is mounted and gives consumer tests a structural Inbox backed by the standard session projection. +This package gives an AgentLoop test a working service topology before the loop is mounted. ### Minimal example @@ -41,15 +41,28 @@ await mountAgentLoopTestDependencies(ctx) await ctx.plugin(AgentLoop, { agents: [] }) ``` -The mounting helper activates the LLM, session, session-projection, system-prompt, tool, and agent services in dependency order and returns before the loop is mounted. System-prompt and tool-registry configuration can be forwarded through `options`; the helper provides no test defaults beyond those the services own. `createInboxFixture(ctx.sessionProjections, session)` registers the standard inbox projection for the fixture, then returns an `inbox` for code under test and a separate `claim` operation for the test driver; every edit appends a durable `agent/inbox/spliced` session event. +The mounting helper activates the LLM, session, session-projection, system-prompt, tool, and agent services in dependency order and returns before the loop is mounted. System-prompt and tool-registry configuration can be forwarded through `options`; the helper provides no test defaults beyond those the services own. + +### Stub an Agent outside Inbox tests + +Use `unsupportedInbox()` only when the test subject does not exercise pending Agent input. It exposes empty pending lists and throws on every mutation, so an unexpected Inbox dependency fails at its first write. Tests that exercise Inbox behavior construct `ReactLoopInbox` from `@deepseek-ai/dsh-agent-loop` instead. + +```ts +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' + +const agent = { + // ... + inbox: unsupportedInbox(), +} +``` ### When to use it -Use the mounting helper for tests whose subject is the loop: load order, retries, tool execution, or session behavior on a real prerequisite stack. Use the Inbox fixture when a consumer test needs durable queue edits without constructing the package-internal `ReactLoopInbox`. Mount dependencies directly when a test probes service load order, injection failures, partial topologies, or teardown — the helper hides exactly the wiring such tests must control. +Use the mounting helper for tests whose subject is the loop: load order, retries, tool execution, or session behavior on a real prerequisite stack. Mount dependencies directly when a test probes service load order, injection failures, partial topologies, or teardown — the helper hides exactly the wiring such tests must control. ### What can go wrong -A plugin-load failure rejects the mounting helper call; services activated earlier in the sequence remain owned by your context and unwind with it. The Inbox fixture requires a live session-projection registry and owns its standard inbox registration through that context. The context owns every mounted service, so dispose it after the test. +A plugin-load failure rejects the mounting helper call; services activated earlier in the sequence remain owned by your context and unwind with it. The context owns every mounted service, so dispose it after the test. ----- @@ -63,7 +76,7 @@ This section explains the design of the test utilities; the observable behavior ### Design -`mountAgentLoopTestDependencies` mounts six service plugins in a fixed dependency order — LLM, session, session-projection registry, system-prompt registry, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. `createInboxFixture` implements only the public structural Inbox operations and keeps loop-driver claiming separate; session projection replay supplies its state. Ownership stays with the caller's context and session. The implementations live in [`src/index.ts`](src/index.ts) and [`src/inbox.ts`](src/inbox.ts); the [`src/invariant.ts`](src/invariant.ts) companion declares no runtime invariant because the package owns no production event stream or mutable data — consuming test suites exercise its behavior. +`mountAgentLoopTestDependencies` mounts six service plugins in a fixed dependency order — LLM, session, session-projection registry, system-prompt registry, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. [`src/inbox.ts`](src/inbox.ts) provides only the fail-fast unsupported placeholder; it does not reproduce the concrete Inbox algorithm. The mounting implementation lives in [`src/index.ts`](src/index.ts); the [`src/invariant.ts`](src/invariant.ts) companion declares no runtime invariant because the package owns no production event stream or mutable data. @@ -99,7 +112,7 @@ None; this package neither assembles nor sends a provider request. These limits define what the utilities do not share. They are current package constraints, not a task backlog. - **Only the mandatory prerequisite spine is shared** — adapters, optional plugins, `AgentLoop`, agents, and context teardown remain caller-owned so scenario-specific ordering stays visible. -- **The Inbox fixture emits durable session events only** — it does not reproduce live `agent/inbox/inserted` or `agent/inbox/discarded` notifications owned by `ReactLoopInbox`. +- **The unsupported Inbox accepts no mutations** — use the concrete `ReactLoopInbox` whenever pending input is part of the test subject. ### Dev Note diff --git a/packages/test-support/agent-loop-testkit/README.zh.md b/packages/test-support/agent-loop-testkit/README.zh.md index 88a4143604..6233995ad2 100644 --- a/packages/test-support/agent-loop-testkit/README.zh.md +++ b/packages/test-support/agent-loop-testkit/README.zh.md @@ -1,5 +1,5 @@ --- -description: "为测试 agent-loop 行为提供共享先决依赖挂载与基于会话的结构化 Inbox fixture。" +description: "为 Agent 与 agent-loop 测试提供先决依赖挂载和快速失败的 Inbox 桩。" kind: "package-library" --- @@ -9,7 +9,7 @@ kind: "package-library" ## 概述 -`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、会话投影注册表、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。它还为消费方测试创建由会话支撑的结构化 `Inbox`,而不暴露生产环境的 `ReactLoopInbox` 实现。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。当测试对象是 loop 行为而非服务接线时使用它;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 +`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、会话投影注册表、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。它还为不测试待处理输入的 Agent 桩提供一个快速失败且不支持操作的 Inbox 占位值。当测试对象是 loop 行为而非服务接线时使用本包;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-library" ## 使用本包 -本包在 loop 挂载前为 AgentLoop 测试提供可用的服务拓扑,并为消费方测试提供由标准会话 projection 支撑的结构化 Inbox。 +本包在 loop 挂载前为 AgentLoop 测试提供可用的服务拓扑。 ### 最小示例 @@ -41,15 +41,28 @@ await mountAgentLoopTestDependencies(ctx) await ctx.plugin(AgentLoop, { agents: [] }) ``` -挂载辅助函数按依赖顺序激活 LLM、会话、会话投影、系统提示词、工具与 agent 服务,并在 loop 挂载前返回。系统提示词与工具注册表配置可通过 `options` 转发;除服务自有的默认值外,本辅助函数不提供测试默认值。`createInboxFixture(ctx.sessionProjections, session)` 会为 fixture 注册标准 inbox 投影,然后返回供待测代码使用的 `inbox`,并另行返回供测试驱动使用的 `claim` 操作;每次编辑都会追加持久的 `agent/inbox/spliced` 会话事件。 +挂载辅助函数按依赖顺序激活 LLM、会话、会话投影、系统提示词、工具与 agent 服务,并在 loop 挂载前返回。系统提示词与工具注册表配置可通过 `options` 转发;除服务自有的默认值外,本辅助函数不提供测试默认值。 + +### 在 Inbox 测试之外为 Agent 提供桩 + +仅当测试对象不涉及待处理的 Agent 输入时才使用 `unsupportedInbox()`。它公开空的待处理列表,并在每次变更时抛错,因此意外的 Inbox 依赖会在首次写入时失败。测试 Inbox 行为时,应改为从 `@deepseek-ai/dsh-agent-loop` 构造 `ReactLoopInbox`。 + +```ts +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' + +const agent = { + // ... + inbox: unsupportedInbox(), +} +``` ### 何时使用 -当测试对象是 loop 本身——在真实先决依赖栈上的加载顺序、重试、工具执行或会话行为——时使用挂载辅助函数。当消费方测试需要持久队列编辑但不应构造包内的 `ReactLoopInbox` 时,请使用 Inbox fixture。当测试要探测服务加载顺序、注入失败、部分拓扑或清理时,请直接挂载依赖——辅助函数隐藏的正是这类测试必须控制的接线。 +当测试对象是 loop 本身——在真实先决依赖栈上的加载顺序、重试、工具执行或会话行为——时使用挂载辅助函数。当测试要探测服务加载顺序、注入失败、部分拓扑或清理时,请直接挂载依赖——辅助函数隐藏的正是这类测试必须控制的接线。 ### 可能出什么问题 -插件加载失败会使挂载辅助函数调用被拒绝;顺序中较早激活的服务仍归你的上下文所有,并随上下文一起解除。Inbox fixture 要求会话投影注册表处于活跃状态,并通过该上下文持有自己的标准 inbox 注册。上下文拥有所有已挂载服务,因此测试结束后请 dispose(资源释放)它。 +插件加载失败会使挂载辅助函数调用被拒绝;顺序中较早激活的服务仍归你的上下文所有,并随上下文一起解除。上下文拥有所有已挂载服务,因此测试结束后请 dispose(资源释放)它。 ----- @@ -63,7 +76,7 @@ await ctx.plugin(AgentLoop, { agents: [] }) ### 设计 -`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、会话投影注册表、系统提示词注册表、工具注册表、agent 注册表——挂载六个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。`createInboxFixture` 只实现公开的结构化 Inbox 操作,并将 loop 驱动方的 claim 操作分离;会话投影重放提供其状态。所有权留在调用方的上下文与会话。实现位于 [`src/index.ts`](src/index.ts) 与 [`src/inbox.ts`](src/inbox.ts);[`src/invariant.ts`](src/invariant.ts) 配套入口声明无运行时不变式,因为本包不拥有任何生产事件流或可变数据——消费它的测试套件会检验其行为。 +`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、会话投影注册表、系统提示词注册表、工具注册表、agent 注册表——挂载六个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。[`src/inbox.ts`](src/inbox.ts) 只提供快速失败且不支持操作的占位值,不会重现具体 Inbox 算法。挂载实现位于 [`src/index.ts`](src/index.ts);[`src/invariant.ts`](src/invariant.ts) 配套入口声明无运行时不变式,因为本包不拥有任何生产事件流或可变数据。 @@ -99,7 +112,7 @@ await ctx.plugin(AgentLoop, { agents: [] }) 这些限制说明辅助工具不共享什么。它们是当前包约束,不是任务积压。 - **只共享必需的先决主干**——适配器、可选插件、`AgentLoop`、agent 与上下文清理仍由调用方负责,以使特定场景的挂载顺序清晰可见。 -- **Inbox fixture 只发出持久会话事件**——它不会复现由 `ReactLoopInbox` 负责的实时 `agent/inbox/inserted` 或 `agent/inbox/discarded` 通知。 +- **不支持操作的 Inbox 不接受变更**——只要待处理输入属于测试对象,就应使用具体 `ReactLoopInbox`。 ### 开发备注 diff --git a/packages/test-support/agent-loop-testkit/package.json b/packages/test-support/agent-loop-testkit/package.json index 3e8d857c58..5ed10b75d9 100644 --- a/packages/test-support/agent-loop-testkit/package.json +++ b/packages/test-support/agent-loop-testkit/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-agent-loop-testkit", - "description": "Shared prerequisite mounting and session-backed Inbox fixtures for agent-loop tests", + "description": "Prerequisite mounting and fail-fast Inbox stubs for Agent and agent-loop tests", "version": "0.1.2-alpha.1", "publishConfig": { "access": "public" diff --git a/packages/test-support/agent-loop-testkit/src/inbox.ts b/packages/test-support/agent-loop-testkit/src/inbox.ts index af0bebaf73..2535fbd76a 100644 --- a/packages/test-support/agent-loop-testkit/src/inbox.ts +++ b/packages/test-support/agent-loop-testkit/src/inbox.ts @@ -1,107 +1,21 @@ -import type { Inbox, InboxState, InboxTarget } from '@deepseek-ai/dsh-agent' -import { inboxProjectionDefinition } from '@deepseek-ai/dsh-agent-loop' -import type { MessageId } from '@deepseek-ai/dsh-llm' -import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' -import type SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' - -/** A structural Inbox test double and its loop-driver operation. */ -export interface InboxFixture { - /** Session-backed Inbox exposed to the code under test. */ - readonly inbox: Inbox - /** Remove the batch a test driver admits at one boundary. */ - readonly claim: (target: InboxTarget) => UserMessage[] -} +import type { Inbox } from '@deepseek-ai/dsh-agent' /** - * Create a session-backed structural Inbox test double for consumer tests. - * @param projections - registry that will own the fixture's standard inbox projection registration. - * @param session - session whose durable splices back the test double. - * @returns the structural Inbox and a separate loop-driver claim operation. + * Create an unsupported Inbox placeholder for Agent stubs whose tests do not exercise Inbox behavior. + * @returns an Inbox whose pending lists are empty and whose mutation methods throw. */ -export function createInboxFixture( - projections: SessionProjectionRegistry, - session: Session, -): InboxFixture { - projections.register(inboxProjectionDefinition) - - const current = (): InboxState => { - const state = projections.stateOf(session, 'inbox') - /* v8 ignore next -- createInboxFixture holds the registration for the context lifetime */ - if (state === undefined) throw new Error('test inbox requires the standard inbox projection') - return state +export function unsupportedInbox(): Inbox { + const rejectMutation = (): never => { + throw new Error('this test Agent does not support Inbox mutations') } - - const locate = (messageId: MessageId): { target: InboxTarget; index: number } | undefined => { - const state = current() - const turnIndex = state['next-turn'].findIndex(message => message.id === messageId) - if (turnIndex >= 0) return { target: 'next-turn', index: turnIndex } - const stepIndex = state['next-step'].findIndex(message => message.id === messageId) - return stepIndex < 0 ? undefined : { target: 'next-step', index: stepIndex } - } - - const mutate = ( - target: InboxTarget, - start: number, - deleteCount: number, - inserted: UserMessage[], - canceled: boolean, - ): UserMessage[] => { - const pending = current()[target] - const integerStart = Number.isNaN(start) ? 0 : Math.trunc(start) - const index = integerStart < 0 - ? Math.max(pending.length + integerStart, 0) - : Math.min(integerStart, pending.length) - const integerCount = Number.isNaN(deleteCount) ? 0 : Math.trunc(deleteCount) - const count = Math.min(Math.max(integerCount, 0), pending.length - index) - if (count === 0 && inserted.length === 0) return [] - const event: SessionEventMap['agent/inbox/spliced'] = { - target, - start: index, - ...(count === 0 ? {} : { removedCount: count }), - inserted, - ...(canceled && count > 0 ? { outcome: 'canceled' } : {}), - } - const removed = pending.slice(index, index + count) - session.append('agent/inbox/spliced', event) - return removed - } - - const inbox: Inbox = { - get nextTurn() { return current()['next-turn'] }, - get nextStep() { return current()['next-step'] }, - clear() { - mutate('next-step', 0, current()['next-step'].length, [], true) - mutate('next-turn', 0, current()['next-turn'].length, [], true) - }, - append(target, message) { - mutate(target, current()[target].length, 0, [message], true) - }, - prepend(target, message) { - mutate(target, 0, 0, [message], true) - }, - replace(messageId, message) { - const location = locate(messageId) - if (location === undefined) return false - mutate(location.target, location.index, 1, [message], true) - return true - }, - remove(messageId) { - const location = locate(messageId) - if (location === undefined) return false - mutate(location.target, location.index, 1, [], true) - return true - }, - splice(target, start, deleteCount, inserted) { - return mutate(target, start, deleteCount, inserted, true) - }, - } - return { - inbox, - claim: (target) => { - const claimed = mutate('next-step', 0, current()['next-step'].length, [], false) - if (target === 'next-turn') claimed.push(...mutate('next-turn', 0, 1, [], false)) - return claimed - }, + nextTurn: [], + nextStep: [], + clear: rejectMutation, + append: rejectMutation, + prepend: rejectMutation, + replace: rejectMutation, + remove: rejectMutation, + splice: rejectMutation, } } diff --git a/packages/test-support/agent-loop-testkit/src/index.ts b/packages/test-support/agent-loop-testkit/src/index.ts index ae384f45ab..9de89c7583 100644 --- a/packages/test-support/agent-loop-testkit/src/index.ts +++ b/packages/test-support/agent-loop-testkit/src/index.ts @@ -1,7 +1,6 @@ /** - * Shared service mounting and session-backed Inbox fixtures for agent-loop - * tests. Callers retain ownership of their contexts, loops, adapters, - * optional plugins, and teardown. + * Shared service mounting for agent-loop tests. Callers retain ownership of + * their contexts, loops, adapters, optional plugins, and teardown. * @module @deepseek-ai/dsh-agent-loop-testkit */ @@ -15,8 +14,7 @@ import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-promp import ToolRuntime from '@deepseek-ai/dsh-tools' import type { Config as ToolRuntimeConfig } from '@deepseek-ai/dsh-tools' -export { createInboxFixture } from './inbox.ts' -export type { InboxFixture } from './inbox.ts' +export { unsupportedInbox } from './inbox.ts' /** Configuration forwarded to the prerequisite service plugins. */ export interface AgentLoopTestDependenciesOptions { diff --git a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts index a839738af4..1ac958e3af 100644 --- a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts +++ b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts @@ -1,17 +1,18 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import { createUserMessage } from '@deepseek-ai/dsh-llm' -import { Session, SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' -import { createInboxFixture, mountAgentLoopTestDependencies } from '../src/index.ts' - -function message(text: string) { - return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }) -} +import { unsupportedInbox, mountAgentLoopTestDependencies } from '../src/index.ts' describe('dsh-agent-loop-testkit', () => { + it('rejects mutations through an unsupported Agent stub Inbox', () => { + const inbox = unsupportedInbox() + + expect(inbox.nextTurn).toEqual([]) + expect(inbox.nextStep).toEqual([]) + expect(() => { inbox.clear() }).toThrow('this test Agent does not support Inbox mutations') + }) + it('mounts a configurable prerequisite spine that can activate AgentLoop', async () => { const ctx = new Context() await mountAgentLoopTestDependencies(ctx, { @@ -24,66 +25,4 @@ describe('dsh-agent-loop-testkit', () => { await ctx.fiber.dispose() }) - - it('provides a session-backed structural Inbox with separate driver claims', async () => { - const ctx = new Context() - await mountAgentLoopTestDependencies(ctx) - const session = ctx.sessions.create(SessionId('agent-loop-testkit-inbox')) - const fixture = createInboxFixture(ctx.sessionProjections, session) - const firstTurn = message('first turn') - const secondTurn = message('second turn') - const firstStep = message('first step') - const editedTurn = message('edited turn') - const editedStep = message('edited step') - - fixture.inbox.append('next-turn', firstTurn) - fixture.inbox.prepend('next-turn', secondTurn) - fixture.inbox.append('next-step', firstStep) - expect(fixture.inbox.nextTurn).toEqual([secondTurn, firstTurn]) - expect(fixture.inbox.nextStep).toEqual([firstStep]) - - expect(fixture.inbox.replace(firstTurn.id, editedTurn)).toBe(true) - expect(fixture.inbox.replace(firstStep.id, editedStep)).toBe(true) - expect(fixture.inbox.replace(firstTurn.id, message('missing replacement'))).toBe(false) - expect(fixture.inbox.remove(firstTurn.id)).toBe(false) - expect(fixture.inbox.splice('next-turn', -1, 1, [])).toEqual([editedTurn]) - expect(fixture.inbox.remove(editedStep.id)).toBe(true) - - const claimedStep = message('claimed step') - const claimedTurn = message('claimed turn') - fixture.inbox.splice('next-step', Number.NaN, Number.NaN, [claimedStep]) - fixture.inbox.append('next-turn', claimedTurn) - expect(fixture.claim('next-step')).toEqual([claimedStep]) - expect(fixture.claim('next-turn')).toEqual([secondTurn]) - expect(fixture.inbox.nextTurn).toEqual([claimedTurn]) - - const eventCount = session.events.length - expect(fixture.inbox.splice('next-step', 100, -1, [])).toEqual([]) - expect(session.events).toHaveLength(eventCount) - - fixture.inbox.clear() - expect(fixture.inbox.nextTurn).toEqual([]) - expect(fixture.inbox.nextStep).toEqual([]) - fixture.inbox.clear() - - await ctx.fiber.dispose() - }) - - it('registers the standard inbox projection for a standalone fixture', async () => { - const ctx = new Context() - await ctx.plugin(SessionProjectionRegistry) - const session = Session.create(SessionId('agent-loop-testkit-standalone-inbox')) - const fixture = createInboxFixture( - ctx.sessionProjections, - session, - ) - - expect(fixture.inbox.nextStep).toEqual([]) - expect(ctx.sessionProjections.snapshot(session).values.inbox).toEqual({ - 'next-turn': [], - 'next-step': [], - }) - - await ctx.fiber.dispose() - }) }) diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index 8bb65b5b8b..fd152ab96c 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -17,6 +17,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' +import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' let root: string | undefined let context: Context | undefined @@ -33,7 +34,7 @@ function agent(ctx: Context): Agent { const id = SessionId('todo-loader-agent') const session = Session.create(id) const value: Agent = { - id, options: {}, session, inbox: { nextTurn: [], nextStep: [] } as never, + id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx: scope.ctx, followup: () => {}, steer: () => {}, inject: () => {}, send: () => {}, cancel() {}, runMaintenance: task => task(new AbortController().signal), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f3ded35ae3..79f5ed48a1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -343,6 +343,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../packages/core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../packages/test-support/agent-loop-testkit '@deepseek-ai/dsh-agent-spine-demo': specifier: workspace:^ version: link:../../packages/examples/agent-spine-demo @@ -756,6 +759,9 @@ importers: '@deepseek-ai/dsh-agent-default-model': specifier: workspace:^ version: link:../../core/agent-default-model + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:^ + version: link:../../core/agent-loop '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:^ version: link:../../test-support/agent-loop-testkit @@ -1330,6 +1336,9 @@ importers: '@deepseek-ai/dsh-agent-default-model': specifier: workspace:^ version: link:../../core/agent-default-model + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:^ + version: link:../../core/agent-loop '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:^ version: link:../../test-support/agent-loop-testkit @@ -4270,6 +4279,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants @@ -4580,6 +4592,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-app-boot': specifier: workspace:^ version: link:../../boot/app-boot @@ -5317,6 +5332,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-anonymous-user-id': specifier: workspace:^ version: link:../../identity/anonymous-user-id @@ -5586,6 +5604,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-fs': specifier: workspace:^ version: link:../fs @@ -5634,6 +5655,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:^ + version: link:../../core/agent-loop '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:^ version: link:../../test-support/agent-loop-testkit @@ -5671,6 +5695,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:^ + version: link:../../core/agent-loop '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:^ version: link:../../test-support/agent-loop-testkit @@ -6320,6 +6347,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-brand': specifier: workspace:^ version: link:../../util/brand @@ -8104,6 +8134,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants @@ -8226,6 +8259,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants @@ -8337,6 +8373,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants @@ -9217,6 +9256,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-brand': specifier: workspace:^ version: link:../../util/brand @@ -9248,6 +9290,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants @@ -9288,6 +9333,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:^ version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../test-support/agent-loop-testkit '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../runtime-diagnostics/invariants From 8e1c47f82f19941743064feccf54ee34ad1637b6 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 31 Aug 2026 16:36:23 +0800 Subject: [PATCH 16/26] test(sdk): avoid duplicate projection registry --- packages/sdk/server/tests/built-scope-carrier.e2e.ts | 3 --- packages/sdk/server/tests/plugin-apply.spec.ts | 2 -- packages/sdk/server/tests/server.spec.ts | 2 -- 3 files changed, 7 deletions(-) diff --git a/packages/sdk/server/tests/built-scope-carrier.e2e.ts b/packages/sdk/server/tests/built-scope-carrier.e2e.ts index 803198ab32..e55bf76bb2 100644 --- a/packages/sdk/server/tests/built-scope-carrier.e2e.ts +++ b/packages/sdk/server/tests/built-scope-carrier.e2e.ts @@ -28,7 +28,6 @@ const [ { Context }, { default: AgentLoop }, { mountAgentLoopTestDependencies }, - { default: SessionProjectionRegistry }, { default: SubagentRuntime }, { default: JsonlSessionPersistence }, { HarnessSdkJsonRpcServer }, @@ -37,7 +36,6 @@ const [ load("vendor/cordis/lib/index.js"), load("packages/core/agent-loop/lib/index.js"), load("packages/test-support/agent-loop-testkit/lib/index.js"), - load("packages/session/session-projection/lib/index.js"), load("packages/subagent/subagent/lib/index.js"), load("packages/session/session-persistence-jsonl/lib/index.js"), load("packages/sdk/server/lib/index.js"), @@ -48,7 +46,6 @@ const storageRoot = await mkdtemp(join(tmpdir(), "jsonrpc-built-scope-")); const ctx = new Context(); try { await mountAgentLoopTestDependencies(ctx); - await ctx.plugin(SessionProjectionRegistry); await ctx.plugin(AgentLoop, { agents: [] }); await ctx.plugin(SubagentRuntime); await ctx.plugin(JsonlSessionPersistence, { root: storageRoot }); diff --git a/packages/sdk/server/tests/plugin-apply.spec.ts b/packages/sdk/server/tests/plugin-apply.spec.ts index 8190a25eb3..e51324c019 100644 --- a/packages/sdk/server/tests/plugin-apply.spec.ts +++ b/packages/sdk/server/tests/plugin-apply.spec.ts @@ -11,7 +11,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { LlmAdapter } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import * as jsonrpc from '../src/index.ts' @@ -77,7 +76,6 @@ async function mountPlugin( ): Promise { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(JsonlSessionPersistence, { root: storageDir }) await new Promise(resolve => setTimeout(resolve, 50)) diff --git a/packages/sdk/server/tests/server.spec.ts b/packages/sdk/server/tests/server.spec.ts index ac3af4f47b..d0bb7e1c8d 100644 --- a/packages/sdk/server/tests/server.spec.ts +++ b/packages/sdk/server/tests/server.spec.ts @@ -12,7 +12,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import SubagentRuntime, { type SubagentResult, type SubagentRunEndInfo } from '@deepseek-ai/dsh-subagent' @@ -65,7 +64,6 @@ async function mockCompletionServer(): Promise<{ url: string; requests: unknown[ async function makeHarness(storageDir: string) { const ctx = new Context() await mountAgentLoopTestDependencies(ctx) - await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(SubagentRuntime) await ctx.plugin(JsonlSessionPersistence, { root: storageDir }) From 3f0b7779e6a10e9e876d8eb1b9ab69bc8a66ea24 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Tue, 1 Sep 2026 11:23:15 +0800 Subject: [PATCH 17/26] test(headless): derive captured session length --- packages/bundle/headless/tests/headless.spec.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index 29ee8e1343..84ed8466cb 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -323,16 +323,20 @@ describe('headless runner', () => { }) it('fails when an event below the captured Session length cannot be read', async () => { + let capturedLength = 0 const test = await bench({ afterPrompt(session, message) { appendTurn(session, 1, message, 'unreachable', true) + capturedLength = session.seq Object.defineProperty(session, 'eventAt', { value: () => undefined }) }, }) - expect(await test.run()).toMatchObject({ + const result = await test.run() + expect(capturedLength).toBeGreaterThan(0) + expect(result).toMatchObject({ code: 1, out: '', - err: 'dsh: headless summary cannot read seq 0 below captured length 7\n', + err: `dsh: headless summary cannot read seq 0 below captured length ${String(capturedLength)}\n`, }) await test.ctx.fiber.dispose() }) From a96ec3dbd696b5588827461e4ff8a578992cc555 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Tue, 1 Sep 2026 20:18:04 +0800 Subject: [PATCH 18/26] test(agent-loop): keep inbox internals private --- docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.i18n.yaml | 4 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- .../commands-queue-attachment.host.spec.ts | 10 +- .../tests/control-jobs.host.spec.ts | 5 +- .../tests/control-queue.host.spec.ts | 17 +-- .../tests/session-projections.host.spec.ts | 14 +- .../bundle/headless/tests/headless.spec.ts | 25 ++-- .../tests/agent-instructions.spec.ts | 39 +++-- packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 4 +- packages/core/agent-loop/README.zh.md | 4 +- packages/core/agent-loop/src/index.ts | 2 - .../command-goal/tests/command-goal.spec.ts | 11 +- packages/goal/goal/tests/goal.spec.ts | 9 +- .../goal/tool-goal/tests/tool-goal.spec.ts | 20 +-- .../agent-loop-testkit/README.i18n.yaml | 4 +- .../test-support/agent-loop-testkit/README.md | 22 +-- .../agent-loop-testkit/README.zh.md | 22 +-- .../agent-loop-testkit/package.json | 5 +- .../agent-loop-testkit/src/inbox.ts | 133 +++++++++++++++++- .../agent-loop-testkit/src/index.ts | 11 +- .../tests/agent-loop-testkit.spec.ts | 57 +++++++- pnpm-lock.yaml | 4 + 27 files changed, 319 insertions(+), 119 deletions(-) diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 90c1f5a898..3989c90eb9 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 12e50800ac32604088f3b0922c1006b0d050daf3 -config-catalog.zh.md: bb39c05f512011be6cd639f5b7938aebf939223a +config-catalog.md: 85aead7a93bd8dff0da4eb4f0e6b6b348d9616b9 +config-catalog.zh.md: f91ebc6c46989cbf98d2a773f6f2873539ad6351 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 12e50800ac..85aead7a93 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -111,7 +111,7 @@ export interface Config { Depends on: [`AgentOptions`](subsystems/core.md) · [`SessionId`](subsystems/core.md) -Source: [`packages/core/agent-loop/src/index.ts:313`](../packages/core/agent-loop/src/index.ts) +Source: [`packages/core/agent-loop/src/index.ts:311`](../packages/core/agent-loop/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index bb39c05f51..f91ebc6c46 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -113,7 +113,7 @@ export interface Config { 依赖:[`AgentOptions`](subsystems/core.zh.md) · [`SessionId`](subsystems/core.zh.md) -来源:[`packages/core/agent-loop/src/index.ts:313`](../packages/core/agent-loop/src/index.ts) +来源:[`packages/core/agent-loop/src/index.ts:311`](../packages/core/agent-loop/src/index.ts) diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index 5fff379418..894b0155c0 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/event-producer-consumer.md -event-producer-consumer.md: 676d7e5db42e1db96bc6e15563e443bb3d676d8e -event-producer-consumer.zh.md: c42529a9f35dca9475ad44a8eefd7d83dbab5a97 +event-producer-consumer.md: a47c1df5aca5cc79cfda6cffde53e860a88b784b +event-producer-consumer.zh.md: 5baa32146e24b8b155ccb2692282846b63f37937 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 676d7e5db4..a47c1df5ac 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -7,7 +7,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:241`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:239`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:80`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `remotes` | | `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:220`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:229`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index c42529a9f3..5baa32146e 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -9,7 +9,7 @@ | 事件 | 模式 | 声明位置 | 派发方 | 监听方 | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:241`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:239`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:80`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `remotes` | | `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:220`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:229`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | 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 f8b2d850d5..4bc7f068a7 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 @@ -1,5 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, Inbox, ModelSelectionRef } from '@deepseek-ai/dsh-agent' import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -10,8 +10,7 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it, vi } from 'vitest' import { ApiSessionAgentController } from '../src/agent.ts' import { SessionCommandController } from '../src/commands.ts' -import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts' async function commandHarness(): Promise<{ @@ -27,13 +26,14 @@ async function commandHarness(): Promise<{ await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) const session = ctx.sessions.create(SessionId('commands-session'), { meta: { cwd: '/workspace' } }) + const { inbox } = createInboxFixture(ctx.sessionProjections, session) const steer = vi.fn() const cancel = vi.fn() const agent: Agent = { id: session.id, options: {}, session, - inbox: unsupportedInbox(), + inbox, status: 'running', ctx, send: () => {}, @@ -44,8 +44,6 @@ async function commandHarness(): Promise<{ runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) - Object.assign(agent, { inbox }) ctx.agents.register(agent) ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never) ctx.provide('agentDefaultModel', { diff --git a/packages/api/session-controller/tests/control-jobs.host.spec.ts b/packages/api/session-controller/tests/control-jobs.host.spec.ts index 04acff8465..b51d364044 100644 --- a/packages/api/session-controller/tests/control-jobs.host.spec.ts +++ b/packages/api/session-controller/tests/control-jobs.host.spec.ts @@ -1,5 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import type { JobOutcome } from '@deepseek-ai/dsh-jobs' import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local' @@ -9,7 +9,6 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { SessionControlController } from '../src/control.ts' import type { SessionControlFrame } from '../src/types.ts' -import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' type BaselineFrame = Extract @@ -60,8 +59,6 @@ async function harness(withJobs: boolean): Promise<{ runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) - Object.assign(agent, { inbox }) ctx.agents.register(agent) const control = new SessionControlController(ctx) await new Promise(resolve => setTimeout(resolve, 0)) diff --git a/packages/api/session-controller/tests/control-queue.host.spec.ts b/packages/api/session-controller/tests/control-queue.host.spec.ts index 226ed9fdb7..4a2eeeac20 100644 --- a/packages/api/session-controller/tests/control-queue.host.spec.ts +++ b/packages/api/session-controller/tests/control-queue.host.spec.ts @@ -1,5 +1,5 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, Inbox } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' @@ -7,8 +7,7 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it } from 'vitest' import { SessionControlController } from '../src/control.ts' import type { SessionControlFrame } from '../src/types.ts' -import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' async function harness(): Promise<{ ctx: Context @@ -21,13 +20,12 @@ async function harness(): Promise<{ await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) const session = ctx.sessions.create(SessionId('queue-session')) + const { inbox } = createInboxFixture(ctx.sessionProjections, session) const agent: Agent = { - id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'running', ctx, + id: session.id, options: {}, session, inbox, status: 'running', ctx, send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) - Object.assign(agent, { inbox }) ctx.agents.register(agent) return { ctx, control: new SessionControlController(ctx), agent, inbox } } @@ -95,20 +93,19 @@ describe('Session control queue projection', () => { await ctx.plugin(AgentRegistry) const control = new SessionControlController(ctx) const session = ctx.sessions.create(SessionId('late-projection-queue')) + const { inbox } = createInboxFixture(ctx.sessionProjections, session) const agent: Agent = { - id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'running', ctx, + id: session.id, options: {}, session, inbox, status: 'running', ctx, send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) - Object.assign(agent, { inbox }) ctx.agents.register(agent) const abort = new AbortController() const iterator = control.control(abort.signal)[Symbol.asyncIterator]() await iterator.next() const pending = message('late projection') - agent.inbox.append('next-turn', pending) + inbox.append('next-turn', pending) await expect(iterator.next()).resolves.toMatchObject({ value: { diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index f7d952623d..e0e0907edd 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -13,10 +13,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { z } from 'zod' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import type { Agent } from '@deepseek-ai/dsh-agent' import { AttachmentStore } from '@deepseek-ai/dsh-attachment' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-presets' -import type { Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, UserMessage } from '@deepseek-ai/dsh-session' @@ -27,8 +27,7 @@ import Storage from '@deepseek-ai/dsh-storage' import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' import * as StorageJson from '@deepseek-ai/dsh-storage-json' import type { SessionControlFrame, SessionFollowFrame } from '@deepseek-ai/dsh-api-session-controller/types' -import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { createSessionTestRemote, testSessionPersistence, type TestSessionRemote } from './test-remote.ts' declare module '@deepseek-ai/dsh-session-projection/types' { @@ -127,18 +126,17 @@ async function harness(withRegistry: boolean): Promise<{ claim: () => { throw new Error('inbox is unavailable without the projection registry') }, } } + const fixture = createInboxFixture(ctx.sessionProjections, session) const agent: Agent = { - id: session.id, options: {}, session, inbox: unsupportedInbox(), status: 'idle', ctx, + id: session.id, options: {}, session, inbox: fixture.inbox, status: 'idle', ctx, send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) - Object.assign(agent, { inbox }) ctx.agents.register(agent) return { ctx, session, - claim: target => inbox.claim(target, 0), + claim: fixture.claim, } } diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index 84ed8466cb..46fb2617b7 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -2,15 +2,14 @@ import { afterEach, describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentHandle, CreateAgentOptions } from '@deepseek-ai/dsh-agent' import AgentDefaultModelConfig from '@deepseek-ai/dsh-agent-default-model' import { createAssistantMessage } from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' -import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { apply, Config, internals } from '../src/index.ts' const originalInternals = { ...internals } @@ -69,34 +68,32 @@ async function bench(script: Script): Promise<{ const session = ctx.sessions.create(options.sessionId, { ...options.meta === undefined ? {} : { meta: options.meta }, }) + const fixture = createInboxFixture(ctx.sessionProjections, session) let idle = Promise.resolve() const agent: Agent = { id: session.id, options: options.agentOptions ?? {}, session, - inbox: unsupportedInbox(), + inbox: fixture.inbox, status: 'idle', ctx: ownerCtx, cancel: () => {}, runMaintenance: () => Promise.reject(new Error('not used')), send: () => {}, - followup: () => { throw new Error('scripted Agent Inbox is not initialized') }, + followup: (message: UserMessage) => { + fixture.inbox.append('next-turn', message) + const claimed = fixture.claim('next-turn') + const [prompt] = claimed + if (prompt === undefined || claimed.length !== 1) throw new Error('scripted Agent expected one claimed prompt') + idle = Promise.resolve().then(() => script.afterPrompt(session, prompt)) + }, steer: () => {}, inject: () => {}, whenIdle: () => idle, } const agentCtx = ownerCtx.extend({ agent }) - const inbox = new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)) Object.assign(agent, { - inbox, ctx: agentCtx, - followup: (message: UserMessage) => { - inbox.append('next-turn', message) - const claimed = inbox.claim('next-turn', 1) - const [prompt] = claimed - if (prompt === undefined || claimed.length !== 1) throw new Error('scripted Agent expected one claimed prompt') - idle = Promise.resolve().then(() => script.afterPrompt(session, prompt)) - }, }) await options.setup?.(agentCtx) script.before?.(session) diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index a43d598c13..937e8b37df 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -8,7 +8,7 @@ import * as workspaceContext from '@deepseek-ai/dsh-agent-instructions' import LlmRuntime, { createUserMessage, ToolCallId, type Message, type StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' -import AgentLoop, { ReactLoopInbox, turnBoundaryProjectionDefinition } from '@deepseek-ai/dsh-agent-loop' +import AgentLoop, { turnBoundaryProjectionDefinition } from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { FileSystem, FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs' import type { @@ -43,7 +43,10 @@ import { import { resolveConfig } from '../src/config.ts' import { candidateScopeKey, renderInstructionChanges, renderWorkspaceInstructionSet, USER_GLOBAL_DIRECTORY, USER_GLOBAL_FILE } from '../src/render.ts' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { + createInboxFixture, + type InboxFixture, +} from '@deepseek-ai/dsh-agent-loop-testkit' /** Per-candidate reconciliation scope key: directory paired with the file name. */ const sk = (directory: string, candidateName: string): string => candidateScopeKey(directory, candidateName) @@ -55,8 +58,14 @@ await isolatedInboxCtx.plugin(SessionProjectionRegistry) await isolatedInboxCtx.plugin(AgentRegistry) let nextStubSession = 1 -interface TestAgent extends Agent { - readonly inbox: ReactLoopInbox +type TestAgent = Agent +const inboxFixtures = new WeakMap() + +/** Return the loop-driver operations paired with one structural test Agent. */ +function inboxFixture(agent: Agent): InboxFixture { + const fixture = inboxFixtures.get(agent) + if (fixture === undefined) throw new Error('agent Inbox fixture is unavailable') + return fixture } const requestTimeoutMs = process.platform === 'win32' ? 5_000 : 1_000 @@ -205,12 +214,13 @@ function stubAgent(cwd?: string, seed: readonly SessionEvent[] = []): TestAgent seed, ...cwd === undefined ? {} : { meta: { createdAt: 0, cwd } }, }) - const agent: Agent = { + const fixture = createInboxFixture(agentCtx.sessionProjections, session) + const agent: TestAgent = { ctx: agentCtx, id: SessionId('a1'), options: {}, session, - inbox: unsupportedInbox(), + inbox: fixture.inbox, status: 'idle', send: () => {}, followup: () => {}, @@ -220,9 +230,8 @@ function stubAgent(cwd?: string, seed: readonly SessionEvent[] = []): TestAgent runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), } - return Object.assign(agent, { - inbox: new ReactLoopInbox(agentCtx.sessionProjections, session, agentEvents(agentCtx, agent)), - }) + inboxFixtures.set(agent, fixture) + return agent } function stubToolExecution( @@ -273,7 +282,7 @@ function baselineEvents(agent: Agent): SessionEvent[] { async function appendAdditionalContexts(ctx: Context, agent: TestAgent): Promise { await syncedWorkspaceContext(ctx, agent) let lastSeq: number | undefined - for (const claimed of agent.inbox.claim('next-step', 1)) { + for (const claimed of inboxFixture(agent).claim('next-step')) { if (claimed.source.kind !== 'agent-instructions') continue const event = agent.session.append('user/message', claimed, { surfaceOp: 'append' }) ctx.emit('session/event', agent.session, event) @@ -291,7 +300,7 @@ async function composeBaselinePrefix(ctx: Context, agent: TestAgent): Promise Promise.resolve({ kind: 'enter' as const, messages: [] }), ) - const claimed = agent.inbox.claim('next-step', 1) + const claimed = inboxFixture(agent).claim('next-step') const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 2, signal }, @@ -1404,7 +1413,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(ctx, { dshHome: home, maxBytes: 65536 }) const resumed = stubAgent(root, original.session.snapshotEvents()) agentEvents(ctx, resumed).emit('agent/session-start', { source: 'resume' }) - const claimed = resumed.inbox.claim('next-step', 1) + const claimed = inboxFixture(resumed).claim('next-step') const decision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, @@ -1450,7 +1459,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(ctx, { dshHome: home, maxBytes: 65536 }) const resumed = stubAgent(root, original.session.snapshotEvents()) agentEvents(ctx, resumed).emit('agent/session-start', { source: 'resume' }) - const staleClaim = resumed.inbox.claim('next-step', 1) + const staleClaim = inboxFixture(resumed).claim('next-step') const staleDecision = await agentEvents(ctx, resumed).waterfall( 'agent/pre-step', { messages: staleClaim, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, @@ -1503,7 +1512,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(resumedCtx, { dshHome: home, maxBytes }) const resumed = stubAgent(root, original.session.snapshotEvents()) agentEvents(resumedCtx, resumed).emit('agent/session-start', { source: 'resume' }) - const claimed = resumed.inbox.claim('next-step', 1) + const claimed = inboxFixture(resumed).claim('next-step') const decision = await agentEvents(resumedCtx, resumed).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 1, signal: AbortSignal.timeout(requestTimeoutMs) }, @@ -4658,7 +4667,7 @@ describe('workspace context inbox synchronization', () => { await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) const agent = stubAgent(join(root, 'pkg')) await syncedWorkspaceContext(ctx, agent) - const claimed = agent.inbox.claim('next-step', 1) + const claimed = inboxFixture(agent).claim('next-step') await write(join(root, 'pkg/AGENTS.md'), 'new claimed rule with more detail') const downstream = { kind: 'enter' as const, messages: claimed } diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 2262efcd82..571232e93b 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/agent-loop/README.md -README.md: 4466fb4ff074e1266b4ee1cd1ef427f8192de1e3 -README.zh.md: 50259f1fa553deb9ffcb63edc2ce0cf85e4474ba +README.md: e6fb94a51200b37af559b516e60acda512859ad6 +README.zh.md: 8048691399b849d05534db5d64f232c7c282aa25 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 4466fb4ff0..e6fb94a512 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -98,7 +98,7 @@ After `agent/request`, `ctx.llm.prepareCall()` validates adapter-owned fields an |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `AgentLoop` service, config schema, declarative agent startup, factory registration | | [`src/agent.ts`](src/agent.ts) | The concrete `ReactLoopAgent` driver: inbox, turn/step machine, cancellation | -| [`src/inbox.ts`](src/inbox.ts) | Exported `ReactLoopInbox`: durable projection, structural commands, and loop-only claim state | +| [`src/inbox.ts`](src/inbox.ts) | Package-internal `ReactLoopInbox`: durable projection, structural commands, and loop-only claim state | | [`src/tool-calls.ts`](src/tool-calls.ts) | Tool scheduling: exclusive barriers and the bounded parallel pool | | [`src/runtime-context.ts`](src/runtime-context.ts) | Per-step runtime-context snapshot handling | | [`src/constants.ts`](src/constants.ts) | `DEFAULT_MAX_PARALLEL_TOOL_CALLS` | @@ -110,7 +110,7 @@ Creation is one rollback-covered transaction: construct a private session, concr ### Turn and step flow -The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. Its `ReactLoopInbox` constructor registers the standard `inbox` projection on the agent scope, then uses that projection for structural commands and loop-only claims; focused consumer tests construct the exported class to exercise the same implementation. Registry reference counting keeps the shared key active until the last agent scope unloads. At a turn boundary the driver opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. `agent/pre-step` decides what enters the step. An entered decision appends its complete `user/message` batch before the driver can claim again, while a rejected decision appends none. Each successful model call appends one `assistant/message` anchor citing its chunk seqs, 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, and result context remain model-ordered. +The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. Its package-internal `ReactLoopInbox` constructor registers the standard `inbox` projection on the agent scope, then uses that projection for structural commands and loop-only claims. Registry reference counting keeps the shared key active until the last agent scope unloads. At a turn boundary the driver opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. `agent/pre-step` decides what enters the step. An entered decision appends its complete `user/message` batch before the driver can claim again, while a rejected decision appends none. Each successful model call appends one `assistant/message` anchor citing its chunk seqs, 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, and result context remain model-ordered. ### Failure and cancellation diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 50259f1fa5..8048691399 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -98,7 +98,7 @@ const handle = await ctx.agents.create({ |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`AgentLoop` 服务、配置 schema、声明式 agent 启动、工厂注册 | | [`src/agent.ts`](src/agent.ts) | 具体 `ReactLoopAgent` 驱动器:收件箱、轮次/步骤状态机、取消 | -| [`src/inbox.ts`](src/inbox.ts) | 导出的 `ReactLoopInbox`:持久投影、结构化命令与仅供循环使用的领取状态 | +| [`src/inbox.ts`](src/inbox.ts) | 包内部的 `ReactLoopInbox`:持久投影、结构化命令与仅供循环使用的领取状态 | | [`src/tool-calls.ts`](src/tool-calls.ts) | 工具调度:独占屏障与有界并行池 | | [`src/runtime-context.ts`](src/runtime-context.ts) | 每步骤 runtime-context 快照处理 | | [`src/constants.ts`](src/constants.ts) | `DEFAULT_MAX_PARALLEL_TOOL_CALLS` | @@ -110,7 +110,7 @@ const handle = await ctx.agents.create({ ### 轮次与步骤流程 -驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。其 `ReactLoopInbox` 构造函数在 agent 作用域上注册标准 `inbox` 投影,随后将该投影用于结构化命令与仅供 loop 使用的领取操作;聚焦消费方的测试会构造这个导出的类,以运行同一份实现。注册表引用计数会使共享 key 持续有效,直至最后一个 agent 作用域卸载。在轮次边界,驱动器先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤。进入步骤的决定会在驱动器再次领取消息前追加完整的 `user/message` 批次,被拒绝的决定则不追加任何消息。每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 +驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。其包内部 `ReactLoopInbox` 构造函数在 agent 作用域上注册标准 `inbox` 投影,随后将该投影用于结构化命令与仅供 loop 使用的领取操作。注册表引用计数会使共享 key 持续有效,直至最后一个 agent 作用域卸载。在轮次边界,驱动器先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤。进入步骤的决定会在驱动器再次领取消息前追加完整的 `user/message` 批次,被拒绝的决定则不追加任何消息。每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。 ### 失败与取消 diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 88c1e48dcd..20beb22ad6 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -34,8 +34,6 @@ import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import { ReactLoopAgent } from './agent.ts' import { DEFAULT_MAX_PARALLEL_TOOL_CALLS } from './constants.ts' -export { ReactLoopInbox, inboxProjectionDefinition } from './inbox.ts' - /** Fiber states that cannot own or serve a new lifecycle. */ const INACTIVE_STATES: ReadonlySet = new Set([ FiberState.UNLOADING, diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 82db3b4fb5..7132d27d72 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import GoalService from '@deepseek-ai/dsh-goal' @@ -9,8 +9,7 @@ import type { GoalRef } from '@deepseek-ai/dsh-goal' import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as commandGoal from '@deepseek-ai/dsh-command-goal' -import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' interface Harness { readonly ctx: Context @@ -23,12 +22,13 @@ interface Harness { function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } { // Store-created: the command executor durably logs lifecycle events on it. const session = ctx.sessions.create(SessionId(id)) + const { inbox } = createInboxFixture(ctx.sessionProjections, session) let status: AgentStatus = 'idle' const agent: Agent = { id: session.id, options: {}, session, - inbox: unsupportedInbox(), + inbox, ctx: new Context(), get status() { return status }, send: () => {}, @@ -39,9 +39,6 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { - inbox: new ReactLoopInbox(ctx.sessionProjections, session, agentEvents(ctx, agent)), - }) return { agent, session } } diff --git a/packages/goal/goal/tests/goal.spec.ts b/packages/goal/goal/tests/goal.spec.ts index 4387aa0bbc..e33be74014 100644 --- a/packages/goal/goal/tests/goal.spec.ts +++ b/packages/goal/goal/tests/goal.spec.ts @@ -12,8 +12,7 @@ import GoalService, { foldGoal, } from '@deepseek-ai/dsh-goal' import type { GoalChangeMeta, GoalRef, GoalSnapshotChangeMeta } from '@deepseek-ai/dsh-goal' -import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' interface StubAgent { agent: Agent @@ -45,11 +44,12 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent if (suppliedCtx === undefined) { agentCtx.sessions.enter(session) } + const { inbox } = createInboxFixture(agentCtx.sessionProjections, session) const agent: Agent = { id, options: {}, session, - inbox: unsupportedInbox(), + inbox, ctx: agentCtx, status: 'idle', send: () => {}, @@ -60,9 +60,6 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - Object.assign(agent, { - inbox: new ReactLoopInbox(agentCtx.sessionProjections, session, agentEvents(agentCtx, agent)), - }) const stub = { agent, session, diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index 970a809ef3..a94143a563 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent' -import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' +import type { Agent, AgentStatus, Inbox } from '@deepseek-ai/dsh-agent' import { turnBoundaryProjectionDefinition } from '@deepseek-ai/dsh-agent-loop' import GoalService, { GoalId } from '@deepseek-ai/dsh-goal' import type { GoalRef } from '@deepseek-ai/dsh-goal' @@ -14,15 +14,18 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' import * as toolGoal from '@deepseek-ai/dsh-tool-goal' -import { ReactLoopInbox } from '@deepseek-ai/dsh-agent-loop' -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { + createInboxFixture, + type InboxFixture, +} from '@deepseek-ai/dsh-agent-loop-testkit' const testToolSignal = new AbortController().signal interface StubAgent { readonly agent: Agent readonly session: Session - readonly inbox: ReactLoopInbox + readonly inbox: Inbox + readonly fixture: InboxFixture setStatus(status: AgentStatus): void } @@ -40,12 +43,13 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St if (suppliedCtx === undefined) { if (agentCtx.sessions.get(session.id) !== session) agentCtx.sessions.enter(session) } + const fixture = createInboxFixture(agentCtx.sessionProjections, session) let status: AgentStatus = 'running' const agent: Agent = { id: session.id, options: {}, session, - inbox: unsupportedInbox(), + inbox: fixture.inbox, get status() { return status }, ctx: agentCtx, send: () => {}, @@ -58,9 +62,7 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - const inbox = new ReactLoopInbox(agentCtx.sessionProjections, session, agentEvents(agentCtx, agent)) - Object.assign(agent, { inbox }) - return { agent, session, inbox, setStatus(value) { status = value } } + return { agent, session, inbox: fixture.inbox, fixture, setStatus(value) { status = value } } } /** Open one message-triggered turn with its accepted model-visible input. */ @@ -73,7 +75,7 @@ function openTurn(stub: StubAgent, source: MessageSource, text = 'prompt'): numb source, }) stub.agent.inbox.append('next-turn', message) - const claimed = stub.inbox.claim('next-turn', turn) + const claimed = stub.fixture.claim('next-turn') if (claimed.length === 0) throw new Error('expected queued turn input') stub.session.append('turn/start', { turn }) for (const admitted of claimed) { diff --git a/packages/test-support/agent-loop-testkit/README.i18n.yaml b/packages/test-support/agent-loop-testkit/README.i18n.yaml index c42ef60861..21902118b0 100644 --- a/packages/test-support/agent-loop-testkit/README.i18n.yaml +++ b/packages/test-support/agent-loop-testkit/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/test-support/agent-loop-testkit/README.md -README.md: 8aaa982f780ceca2502395ffc7dbbbc82e7695fb -README.zh.md: ded8c9a4f60a5d1b8a32c4e8edbe6d292d5ef8f3 +README.md: 1bc4e31ac62c7a7de28f32c230bc7db97e47917e +README.zh.md: 41345f9ab3a55efb022957afe9d310aafac40514 diff --git a/packages/test-support/agent-loop-testkit/README.md b/packages/test-support/agent-loop-testkit/README.md index 8aaa982f78..1bc4e31ac6 100644 --- a/packages/test-support/agent-loop-testkit/README.md +++ b/packages/test-support/agent-loop-testkit/README.md @@ -1,5 +1,5 @@ --- -description: "Prerequisite mounting and fail-fast Inbox stubs for Agent and agent-loop tests." +description: "Prerequisite mounting, session-backed structural Inbox fixtures, and fail-fast Inbox stubs for agent-loop tests." kind: "package-library" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, session-projection registry, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. It also provides a fail-fast unsupported Inbox placeholder for Agent stubs whose tests do not exercise pending input. Use the package when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. +`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, session-projection registry, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. It also provides a session-backed structural Inbox fixture for consumer tests and a fail-fast unsupported Inbox placeholder for stubs whose tests do not exercise pending input. Use the package when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. ## Table of Contents @@ -43,16 +43,20 @@ await ctx.plugin(AgentLoop, { agents: [] }) The mounting helper activates the LLM, session, session-projection, system-prompt, tool, and agent services in dependency order and returns before the loop is mounted. System-prompt and tool-registry configuration can be forwarded through `options`; the helper provides no test defaults beyond those the services own. -### Stub an Agent outside Inbox tests +### Build structural Agent stubs -Use `unsupportedInbox()` only when the test subject does not exercise pending Agent input. It exposes empty pending lists and throws on every mutation, so an unexpected Inbox dependency fails at its first write. Tests that exercise Inbox behavior construct `ReactLoopInbox` from `@deepseek-ai/dsh-agent-loop` instead. +Use `createInboxFixture(ctx.sessionProjections, session)` when pending input belongs to the test. It returns an `inbox` for the Agent literal and a separate `claim` operation for the test driver. Create the fixture before the Agent literal so the object satisfies the required structural interface from construction onward. Use `unsupportedInbox()` only when the test subject does not exercise pending Agent input; it exposes empty pending lists and throws on every mutation, so an unexpected Inbox dependency fails at its first write. ```ts -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +declare const ctx: import('@deepseek-ai/cordis').Context +declare const session: Parameters[1] + +const fixture = createInboxFixture(ctx.sessionProjections, session) const agent = { // ... - inbox: unsupportedInbox(), + inbox: fixture.inbox, } ``` @@ -76,7 +80,7 @@ This section explains the design of the test utilities; the observable behavior ### Design -`mountAgentLoopTestDependencies` mounts six service plugins in a fixed dependency order — LLM, session, session-projection registry, system-prompt registry, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. [`src/inbox.ts`](src/inbox.ts) provides only the fail-fast unsupported placeholder; it does not reproduce the concrete Inbox algorithm. The mounting implementation lives in [`src/index.ts`](src/index.ts). No companion is published because this test-support package owns no production event stream or mutable data; consuming test suites exercise its behavior. +`mountAgentLoopTestDependencies` mounts six service plugins in a fixed dependency order — LLM, session, session-projection registry, system-prompt registry, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. [`src/inbox.ts`](src/inbox.ts) owns a test-only projection definition for the public durable Inbox event and state contract, the structural command facade and driver claim operation, and the fail-fast unsupported placeholder. It does not import the package-internal loop implementation. The mounting implementation lives in [`src/index.ts`](src/index.ts). No companion is published because this test-support package owns no production event stream or mutable data; consuming test suites exercise its behavior. @@ -112,7 +116,9 @@ None; this package neither assembles nor sends a provider request. These limits define what the utilities do not share. They are current package constraints, not a task backlog. - **Only the mandatory prerequisite spine is shared** — adapters, optional plugins, `AgentLoop`, agents, and context teardown remain caller-owned so scenario-specific ordering stays visible. -- **The unsupported Inbox accepts no mutations** — use the concrete `ReactLoopInbox` whenever pending input is part of the test subject. +- **The structural fixture emits durable session events only** — it does not reproduce live `agent/inbox/inserted`, `agent/inbox/claimed`, or `agent/inbox/discarded` notifications owned by the loop implementation. +- **The structural fixture accepts trusted test events** — it does not repeat the production provider's persisted-splice validation; focused `agent-loop` tests own invalid-history coverage. +- **The unsupported Inbox accepts no mutations** — use `createInboxFixture()` whenever pending input is part of the test subject. ### Dev Note diff --git a/packages/test-support/agent-loop-testkit/README.zh.md b/packages/test-support/agent-loop-testkit/README.zh.md index ded8c9a4f6..41345f9ab3 100644 --- a/packages/test-support/agent-loop-testkit/README.zh.md +++ b/packages/test-support/agent-loop-testkit/README.zh.md @@ -1,5 +1,5 @@ --- -description: "为 Agent 与 agent-loop 测试提供先决依赖挂载和快速失败的 Inbox 桩。" +description: "为 agent-loop 测试提供先决依赖挂载、基于会话的结构化 Inbox fixture 和快速失败的 Inbox 桩。" kind: "package-library" --- @@ -9,7 +9,7 @@ kind: "package-library" ## 概述 -`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、会话投影注册表、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。它还为不测试待处理输入的 Agent 桩提供一个快速失败且不支持操作的 Inbox 占位值。当测试对象是 loop 行为而非服务接线时使用本包;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 +`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、会话投影注册表、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。它还为消费方测试提供基于会话的结构化 Inbox fixture,并为不测试待处理输入的桩提供一个快速失败且不支持操作的 Inbox 占位值。当测试对象是 loop 行为而非服务接线时使用本包;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 ## 目录 @@ -43,16 +43,20 @@ await ctx.plugin(AgentLoop, { agents: [] }) 挂载辅助函数按依赖顺序激活 LLM、会话、会话投影、系统提示词、工具与 agent 服务,并在 loop 挂载前返回。系统提示词与工具注册表配置可通过 `options` 转发;除服务自有的默认值外,本辅助函数不提供测试默认值。 -### 在 Inbox 测试之外为 Agent 提供桩 +### 构造结构化 Agent 桩 -仅当测试对象不涉及待处理的 Agent 输入时才使用 `unsupportedInbox()`。它公开空的待处理列表,并在每次变更时抛错,因此意外的 Inbox 依赖会在首次写入时失败。测试 Inbox 行为时,应改为从 `@deepseek-ai/dsh-agent-loop` 构造 `ReactLoopInbox`。 +当待处理输入属于测试对象时,使用 `createInboxFixture(ctx.sessionProjections, session)`。它会返回供 Agent 对象字面量使用的 `inbox`,以及供测试驱动使用的独立 `claim` 操作。应先创建 fixture,再构造 Agent 对象字面量,使对象从构造开始就满足必需的结构化接口。仅当测试对象不涉及待处理的 Agent 输入时才使用 `unsupportedInbox()`;它公开空的待处理列表,并在每次变更时抛错,因此意外的 Inbox 依赖会在首次写入时失败。 ```ts -import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +declare const ctx: import('@deepseek-ai/cordis').Context +declare const session: Parameters[1] + +const fixture = createInboxFixture(ctx.sessionProjections, session) const agent = { // ... - inbox: unsupportedInbox(), + inbox: fixture.inbox, } ``` @@ -76,7 +80,7 @@ const agent = { ### 设计 -`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、会话投影注册表、系统提示词注册表、工具注册表、agent 注册表——挂载六个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。[`src/inbox.ts`](src/inbox.ts) 只提供快速失败且不支持操作的占位值,不会重现具体 Inbox 算法。挂载实现位于 [`src/index.ts`](src/index.ts)。本测试支持包不持有任何生产事件流或可变数据,因此不发布伴生入口;消费它的测试套件会直接检验其行为。 +`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、会话投影注册表、系统提示词注册表、工具注册表、agent 注册表——挂载六个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。[`src/inbox.ts`](src/inbox.ts) 持有针对公开持久 Inbox 事件与状态约定的测试专用投影定义、结构化命令 facade、驱动方 claim 操作,以及快速失败且不支持操作的占位值。它不会导入包内部的 loop 实现。挂载实现位于 [`src/index.ts`](src/index.ts)。本测试支持包不持有任何生产事件流或可变数据,因此不发布伴生入口;消费它的测试套件会直接检验其行为。 @@ -112,7 +116,9 @@ const agent = { 这些限制说明辅助工具不共享什么。它们是当前包约束,不是任务积压。 - **只共享必需的先决主干**——适配器、可选插件、`AgentLoop`、agent 与上下文清理仍由调用方负责,以使特定场景的挂载顺序清晰可见。 -- **不支持操作的 Inbox 不接受变更**——只要待处理输入属于测试对象,就应使用具体 `ReactLoopInbox`。 +- **结构化 fixture 只发出持久会话事件**——它不会复现由 loop 实现持有的实时 `agent/inbox/inserted`、`agent/inbox/claimed` 或 `agent/inbox/discarded` 通知。 +- **结构化 fixture 接受受信的测试事件**——它不会重复生产 provider 的持久 splice 校验;无效历史覆盖由聚焦的 `agent-loop` 测试持有。 +- **不支持操作的 Inbox 不接受变更**——只要待处理输入属于测试对象,就应使用 `createInboxFixture()`。 ### 开发备注 diff --git a/packages/test-support/agent-loop-testkit/package.json b/packages/test-support/agent-loop-testkit/package.json index 34c34c9dad..89a5cec445 100644 --- a/packages/test-support/agent-loop-testkit/package.json +++ b/packages/test-support/agent-loop-testkit/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-agent-loop-testkit", - "description": "Prerequisite mounting and fail-fast Inbox stubs for Agent and agent-loop tests", + "description": "Prerequisite mounting and session-backed Inbox fixtures for agent-loop tests", "version": "0.1.2-alpha.3", "publishConfig": { "access": "public" @@ -35,6 +35,9 @@ "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/cordis": "workspace:^" }, + "dependencies": { + "zod": "^4.4.3" + }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", diff --git a/packages/test-support/agent-loop-testkit/src/inbox.ts b/packages/test-support/agent-loop-testkit/src/inbox.ts index 2535fbd76a..6a50d1b5df 100644 --- a/packages/test-support/agent-loop-testkit/src/inbox.ts +++ b/packages/test-support/agent-loop-testkit/src/inbox.ts @@ -1,4 +1,135 @@ -import type { Inbox } from '@deepseek-ai/dsh-agent' +import type { Inbox, InboxState, InboxTarget, InboxWireState } from '@deepseek-ai/dsh-agent' +import type { MessageId } from '@deepseek-ai/dsh-llm' +import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' +import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' +import type SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import { z } from 'zod' + +const testInboxProjectionSchema = z.object({ + 'next-turn': z.array(z.custom()).readonly(), + 'next-step': z.array(z.custom()).readonly(), +}).readonly() + +/** Test-only registration for the public durable Inbox event and state contract. */ +const testInboxProjectionDefinition = { + key: 'inbox', + stateSchema: testInboxProjectionSchema, + init: (): InboxState => ({ 'next-turn': [], 'next-step': [] }), + apply(state: InboxState, event) { + if (event.type !== 'agent/inbox/spliced') return state + const { target, start, removedCount = 0, inserted } = event.data + const next = [...state[target]] + next.splice(start, removedCount, ...inserted) + return { ...state, [target]: next } + }, + wire: { + viewSchema: testInboxProjectionSchema as unknown as z.ZodType, + view: (state: InboxState) => state as unknown as InboxWireState, + }, + stateVersion: 1, +} satisfies ProjectionDefinition<'inbox', InboxState> + +/** A structural Inbox test double and its loop-driver operation. */ +export interface InboxFixture { + /** Session-backed Inbox exposed to the code under test. */ + readonly inbox: Inbox + /** Remove the batch a test driver admits at one boundary. */ + readonly claim: (target: InboxTarget) => UserMessage[] +} + +/** + * Create a session-backed structural Inbox test double for consumer tests. + * @param projections - registry that owns the fixture's test projection registration. + * @param session - session whose durable splices back the test double. + * @returns the structural Inbox and a separate loop-driver claim operation. + */ +export function createInboxFixture( + projections: SessionProjectionRegistry, + session: Session, +): InboxFixture { + projections.register(testInboxProjectionDefinition) + + const current = (): InboxState => { + const state = projections.stateOf(session, 'inbox') + /* v8 ignore next -- createInboxFixture holds the registration for the context lifetime */ + if (state === undefined) throw new Error('test inbox projection registration is not active') + return state + } + + const locate = (messageId: MessageId): { target: InboxTarget; index: number } | undefined => { + const state = current() + const turnIndex = state['next-turn'].findIndex(message => message.id === messageId) + if (turnIndex >= 0) return { target: 'next-turn', index: turnIndex } + const stepIndex = state['next-step'].findIndex(message => message.id === messageId) + return stepIndex < 0 ? undefined : { target: 'next-step', index: stepIndex } + } + + const mutate = ( + target: InboxTarget, + start: number, + deleteCount: number, + inserted: UserMessage[], + canceled: boolean, + ): UserMessage[] => { + const pending = current()[target] + const integerStart = Number.isNaN(start) ? 0 : Math.trunc(start) + const index = integerStart < 0 + ? Math.max(pending.length + integerStart, 0) + : Math.min(integerStart, pending.length) + const integerCount = Number.isNaN(deleteCount) ? 0 : Math.trunc(deleteCount) + const count = Math.min(Math.max(integerCount, 0), pending.length - index) + if (count === 0 && inserted.length === 0) return [] + const event: SessionEventMap['agent/inbox/spliced'] = { + target, + start: index, + ...(count === 0 ? {} : { removedCount: count }), + inserted, + ...(canceled && count > 0 ? { outcome: 'canceled' } : {}), + } + const removed = pending.slice(index, index + count) + session.append('agent/inbox/spliced', event) + return removed + } + + const inbox: Inbox = { + get nextTurn() { return current()['next-turn'] }, + get nextStep() { return current()['next-step'] }, + clear() { + mutate('next-step', 0, current()['next-step'].length, [], true) + mutate('next-turn', 0, current()['next-turn'].length, [], true) + }, + append(target, message) { + mutate(target, current()[target].length, 0, [message], true) + }, + prepend(target, message) { + mutate(target, 0, 0, [message], true) + }, + replace(messageId, message) { + const location = locate(messageId) + if (location === undefined) return false + mutate(location.target, location.index, 1, [message], true) + return true + }, + remove(messageId) { + const location = locate(messageId) + if (location === undefined) return false + mutate(location.target, location.index, 1, [], true) + return true + }, + splice(target, start, deleteCount, inserted) { + return mutate(target, start, deleteCount, inserted, true) + }, + } + + return { + inbox, + claim: (target) => { + const claimed = mutate('next-step', 0, current()['next-step'].length, [], false) + if (target === 'next-turn') claimed.push(...mutate('next-turn', 0, 1, [], false)) + return claimed + }, + } +} /** * Create an unsupported Inbox placeholder for Agent stubs whose tests do not exercise Inbox behavior. diff --git a/packages/test-support/agent-loop-testkit/src/index.ts b/packages/test-support/agent-loop-testkit/src/index.ts index 9de89c7583..cde26ba7ee 100644 --- a/packages/test-support/agent-loop-testkit/src/index.ts +++ b/packages/test-support/agent-loop-testkit/src/index.ts @@ -1,6 +1,7 @@ /** - * Shared service mounting for agent-loop tests. Callers retain ownership of - * their contexts, loops, adapters, optional plugins, and teardown. + * Shared service mounting and session-backed Inbox fixtures for agent-loop + * tests. Callers retain ownership of their contexts, loops, adapters, + * optional plugins, and teardown. * @module @deepseek-ai/dsh-agent-loop-testkit */ @@ -14,7 +15,11 @@ import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-promp import ToolRuntime from '@deepseek-ai/dsh-tools' import type { Config as ToolRuntimeConfig } from '@deepseek-ai/dsh-tools' -export { unsupportedInbox } from './inbox.ts' +export { + createInboxFixture, + unsupportedInbox, + type InboxFixture, +} from './inbox.ts' /** Configuration forwarded to the prerequisite service plugins. */ export interface AgentLoopTestDependenciesOptions { diff --git a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts index 1ac958e3af..b13ab29717 100644 --- a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts +++ b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts @@ -1,8 +1,19 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' -import { unsupportedInbox, mountAgentLoopTestDependencies } from '../src/index.ts' +import { + createInboxFixture, + mountAgentLoopTestDependencies, + unsupportedInbox, +} from '../src/index.ts' + +function message(text: string) { + return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }) +} describe('dsh-agent-loop-testkit', () => { it('rejects mutations through an unsupported Agent stub Inbox', () => { @@ -25,4 +36,48 @@ describe('dsh-agent-loop-testkit', () => { await ctx.fiber.dispose() }) + + it('provides a session-backed structural Inbox with separate driver claims', async () => { + const ctx = new Context() + await ctx.plugin(SessionProjectionRegistry) + const session = Session.create(SessionId('agent-loop-testkit-inbox')) + const fixture = createInboxFixture(ctx.sessionProjections, session) + const firstTurn = message('first turn') + const secondTurn = message('second turn') + const firstStep = message('first step') + const editedTurn = message('edited turn') + const editedStep = message('edited step') + + fixture.inbox.append('next-turn', firstTurn) + fixture.inbox.prepend('next-turn', secondTurn) + fixture.inbox.append('next-step', firstStep) + expect(fixture.inbox.nextTurn).toEqual([secondTurn, firstTurn]) + expect(fixture.inbox.nextStep).toEqual([firstStep]) + + expect(fixture.inbox.replace(firstTurn.id, editedTurn)).toBe(true) + expect(fixture.inbox.replace(firstStep.id, editedStep)).toBe(true) + expect(fixture.inbox.replace(firstTurn.id, message('missing replacement'))).toBe(false) + expect(fixture.inbox.remove(firstTurn.id)).toBe(false) + expect(fixture.inbox.splice('next-turn', -1, 1, [])).toEqual([editedTurn]) + expect(fixture.inbox.remove(editedStep.id)).toBe(true) + + const claimedStep = message('claimed step') + const claimedTurn = message('claimed turn') + fixture.inbox.splice('next-step', Number.NaN, Number.NaN, [claimedStep]) + fixture.inbox.append('next-turn', claimedTurn) + expect(fixture.claim('next-step')).toEqual([claimedStep]) + expect(fixture.claim('next-turn')).toEqual([secondTurn]) + expect(fixture.inbox.nextTurn).toEqual([claimedTurn]) + + const eventCount = session.snapshotEvents().length + expect(fixture.inbox.splice('next-step', 100, -1, [])).toEqual([]) + expect(session.snapshotEvents()).toHaveLength(eventCount) + + fixture.inbox.clear() + expect(fixture.inbox.nextTurn).toEqual([]) + expect(fixture.inbox.nextStep).toEqual([]) + fixture.inbox.clear() + + await ctx.fiber.dispose() + }) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2202aa8730..7f1d7f2ea9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8919,6 +8919,10 @@ importers: version: link:../../core/tools packages/test-support/agent-loop-testkit: + dependencies: + zod: + specifier: ^4.4.3 + version: 4.4.3 devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ From dc160810da8b0cd5865471e006ff9a1fdbf1e2c6 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Tue, 1 Sep 2026 21:39:10 +0800 Subject: [PATCH 19/26] test(agent-loop): use production inbox harness --- ...claimed-pre-step-inbox-lifecycle.i18n.yaml | 4 +- ...-07-31-claimed-pre-step-inbox-lifecycle.md | 2 +- ...-31-claimed-pre-step-inbox-lifecycle.zh.md | 2 +- .../commands-queue-attachment.host.spec.ts | 4 +- .../tests/control-queue.host.spec.ts | 51 ++++--- .../tests/session-projections.host.spec.ts | 41 +++--- .../bundle/headless/tests/headless.spec.ts | 10 +- .../tests/agent-instructions.spec.ts | 76 +++++------ .../command-goal/tests/command-goal.spec.ts | 4 +- packages/goal/goal/tests/goal.spec.ts | 4 +- .../goal/tool-goal/tests/tool-goal.spec.ts | 16 +-- .../agent-loop-testkit/README.i18n.yaml | 4 +- .../test-support/agent-loop-testkit/README.md | 67 +++++----- .../agent-loop-testkit/README.zh.md | 65 ++++----- .../agent-loop-testkit/package.json | 7 +- .../agent-loop-testkit/src/inbox.ts | 126 ++++-------------- .../agent-loop-testkit/src/index.ts | 55 ++++++-- .../tests/agent-loop-testkit.spec.ts | 95 ++++++++----- pnpm-lock.yaml | 4 - 19 files changed, 312 insertions(+), 325 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml index 14efbb6ab8..1b529c379b 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md -2026-07-31-claimed-pre-step-inbox-lifecycle.md: f6daaa97884c3d1ae6dd8cc9e300528389c834ae -2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: e6218bb9aafb62dc4299b0398ac3a40be6d89d68 +2026-07-31-claimed-pre-step-inbox-lifecycle.md: 737e3835263a3215a0fd2e52dad4ee05402bd888 +2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md: ecb731df663e0d48b374a3118d7db7f6a34bfc18 diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md index f6daaa9788..737e383526 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.md @@ -36,7 +36,7 @@ The archived [addressable queue occurrence decision](../../archived/feature/2026 ## Verification -Agent-loop coverage pins turn-start-before-claim-before-pre-step ordering, exact live event payloads, balanced no-step rejection, final-batch rewriting, input inserted after a claim, listener failure, cancellation, and agent-scope projection removal after the last owner unloads. Inbox and consumer tests pin pure claim deletions, canceled ordinary removals, agent-instructions staging, replacement, and same-step entry, plan/goal/hook behavior, UI cleanup, compaction, checkpointing, resumed durable projection, rejection of invalid persisted coordinates or cross-list identities, and post-fold queue replacement when the controller registers before the projection registry. Generated event and type catalogs expose only the new waterfall and payloads. +Agent-loop coverage pins turn-start-before-claim-before-pre-step ordering, exact live event payloads, balanced no-step rejection, final-batch rewriting, input inserted after a claim, listener failure, cancellation, and agent-scope projection removal after the last owner unloads. Inbox and consumer tests pin pure claim deletions, canceled ordinary removals, agent-instructions staging, replacement, and same-step entry, plan/goal/hook behavior, UI cleanup, compaction, checkpointing, resumed durable projection, rejection of invalid persisted coordinates or cross-list identities, and post-fold queue replacement when the controller registers before the projection registry. Consumer-domain tests use a process-local Inbox stub only when durability is outside the test subject; claiming, durable projection, recovery, validation, and live-notification tests create Agents through the production AgentLoop test harness, so test support never reimplements the projection. Generated event and type catalogs expose only the new waterfall and payloads. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md index e6218bb9aa..ecb731df66 100644 --- a/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-31-claimed-pre-step-inbox-lifecycle.zh.md @@ -36,7 +36,7 @@ Status: implemented ## 验证 -agent loop(智能体循环)覆盖固定先 `turn/start`、再领取、后 pre-step 的顺序、实时事件的确切载荷、边界平衡的无步骤 reject、最终批次改写、领取后插入的输入、监听器失败、取消,以及最后一个所有者卸载后移除 agent 作用域投影。Inbox 和消费方测试固定纯领取删除、普通删除的 canceled 结果、agent-instructions 的暂存、替换与同一步骤进入、plan/goal/钩子行为、UI 清理、压缩(compaction)、检查点、恢复后的持久投影、对非法持久坐标或跨列表重复标识的拒绝,以及 controller 早于投影注册表注册时仍使用折叠后队列值。生成的事件与类型目录只公开新的 waterfall 与载荷。 +agent loop(智能体循环)覆盖固定先 `turn/start`、再领取、后 pre-step 的顺序、实时事件的确切载荷、边界平衡的无步骤 reject、最终批次改写、领取后插入的输入、监听器失败、取消,以及最后一个所有者卸载后移除 agent 作用域投影。Inbox 和消费方测试固定纯领取删除、普通删除的 canceled 结果、agent-instructions 的暂存、替换与同一步骤进入、plan/goal/钩子行为、UI 清理、压缩(compaction)、检查点、恢复后的持久投影、对非法持久坐标或跨列表重复标识的拒绝,以及 controller 早于投影注册表注册时仍使用折叠后队列值。只有当持久性不属于测试对象时,消费方领域测试才使用进程内 Inbox 桩;领取、持久投影、恢复、校验与实时通知测试通过生产 AgentLoop 测试 harness 创建 Agent,因此测试支持代码不会重新实现该投影。生成的事件与类型目录只公开新的 waterfall 与载荷。 ## 后果 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 4bc7f068a7..23a366ec70 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 @@ -10,7 +10,7 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { describe, expect, it, vi } from 'vitest' import { ApiSessionAgentController } from '../src/agent.ts' import { SessionCommandController } from '../src/commands.ts' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts' async function commandHarness(): Promise<{ @@ -26,7 +26,7 @@ async function commandHarness(): Promise<{ await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) const session = ctx.sessions.create(SessionId('commands-session'), { meta: { cwd: '/workspace' } }) - const { inbox } = createInboxFixture(ctx.sessionProjections, session) + const inbox = createInboxStub() const steer = vi.fn() const cancel = vi.fn() const agent: Agent = { diff --git a/packages/api/session-controller/tests/control-queue.host.spec.ts b/packages/api/session-controller/tests/control-queue.host.spec.ts index 4a2eeeac20..ed2b2dd5fd 100644 --- a/packages/api/session-controller/tests/control-queue.host.spec.ts +++ b/packages/api/session-controller/tests/control-queue.host.spec.ts @@ -1,13 +1,20 @@ import { Context } from '@deepseek-ai/cordis' -import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, Inbox } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' -import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' -import { describe, expect, it } from 'vitest' +import { SessionId } from '@deepseek-ai/dsh-session' +import { afterEach, describe, expect, it } from 'vitest' import { SessionControlController } from '../src/control.ts' import type { SessionControlFrame } from '../src/types.ts' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { + mountAgentLoopTestDependencies, + mountAgentLoopTestHarness, +} from '@deepseek-ai/dsh-agent-loop-testkit' + +const ownedContexts = new Set() +afterEach(async () => { + await Promise.all([...ownedContexts].map(ctx => ctx.fiber.dispose())) + ownedContexts.clear() +}) async function harness(): Promise<{ ctx: Context @@ -16,18 +23,11 @@ async function harness(): Promise<{ inbox: Inbox }> { const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(AgentRegistry) - const session = ctx.sessions.create(SessionId('queue-session')) - const { inbox } = createInboxFixture(ctx.sessionProjections, session) - const agent: Agent = { - id: session.id, options: {}, session, inbox, status: 'running', ctx, - send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, - runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), - } - ctx.agents.register(agent) - return { ctx, control: new SessionControlController(ctx), agent, inbox } + ownedContexts.add(ctx) + await mountAgentLoopTestDependencies(ctx) + const loop = await mountAgentLoopTestHarness(ctx) + const agent = loop.create(SessionId('queue-session')) + return { ctx, control: new SessionControlController(ctx), agent, inbox: agent.inbox } } function message(text: string, source: 'user' | 'plugin' = 'user') { @@ -88,18 +88,12 @@ describe('Session control queue projection', () => { it('derives queue replacements from the completed projection regardless of registration order', async () => { const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(SessionProjectionRegistry) - await ctx.plugin(AgentRegistry) + ownedContexts.add(ctx) + await mountAgentLoopTestDependencies(ctx) + const loop = await mountAgentLoopTestHarness(ctx) const control = new SessionControlController(ctx) - const session = ctx.sessions.create(SessionId('late-projection-queue')) - const { inbox } = createInboxFixture(ctx.sessionProjections, session) - const agent: Agent = { - id: session.id, options: {}, session, inbox, status: 'running', ctx, - send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, - runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), - } - ctx.agents.register(agent) + const agent = loop.create(SessionId('late-projection-queue')) + const { inbox } = agent const abort = new AbortController() const iterator = control.control(abort.signal)[Symbol.asyncIterator]() await iterator.next() @@ -190,6 +184,7 @@ describe('Session control queue projection', () => { inbox.append('next-turn', second) const queues: Extract[] = [] + ownedContexts.delete(ctx) await ctx.fiber.dispose() for (;;) { const next = await iterator.next() diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index e0e0907edd..4968fb726a 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -7,14 +7,13 @@ * pushed through the control stream. */ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { z } from 'zod' import AgentRegistry from '@deepseek-ai/dsh-agent' -import type { Agent } from '@deepseek-ai/dsh-agent' import { AttachmentStore } from '@deepseek-ai/dsh-attachment' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-presets' import { createUserMessage } from '@deepseek-ai/dsh-llm' @@ -27,9 +26,19 @@ import Storage from '@deepseek-ai/dsh-storage' import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' import * as StorageJson from '@deepseek-ai/dsh-storage-json' import type { SessionControlFrame, SessionFollowFrame } from '@deepseek-ai/dsh-api-session-controller/types' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { + mountAgentLoopTestDependencies, + mountAgentLoopTestHarness, +} from '@deepseek-ai/dsh-agent-loop-testkit' import { createSessionTestRemote, testSessionPersistence, type TestSessionRemote } from './test-remote.ts' +const ownedContexts = new Set() +afterEach(async () => { + await Promise.all([...ownedContexts].map(ctx => ctx.fiber.dispose())) + ownedContexts.clear() +}) +let nextHarnessSession = 1 + declare module '@deepseek-ai/dsh-session-projection/types' { interface SessionProjectionStateMap { 'test/last-user': LastUserState @@ -115,28 +124,28 @@ async function harness(withRegistry: boolean): Promise<{ readonly claim: (target: 'next-turn' | 'next-step') => UserMessage[] }> { const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(AgentRegistry) - if (withRegistry) await ctx.plugin(SessionProjectionRegistry) - const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) + ownedContexts.add(ctx) if (!withRegistry) { + await ctx.plugin(SessionStore) + await ctx.plugin(AgentRegistry) + const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) return { ctx, session, claim: () => { throw new Error('inbox is unavailable without the projection registry') }, } } - const fixture = createInboxFixture(ctx.sessionProjections, session) - const agent: Agent = { - id: session.id, options: {}, session, inbox: fixture.inbox, status: 'idle', ctx, - send: () => {}, followup: () => {}, steer: () => {}, inject: () => {}, cancel: () => {}, - runMaintenance: task => task(new AbortController().signal), whenIdle: () => Promise.resolve(), - } - ctx.agents.register(agent) + await mountAgentLoopTestDependencies(ctx) + const loop = await mountAgentLoopTestHarness(ctx) + const agent = loop.create( + SessionId(`session-projections-${String(nextHarnessSession++)}`), + {}, + { cwd: '/workspace' }, + ) return { ctx, - session, - claim: fixture.claim, + session: agent.session, + claim: target => loop.claim(agent, target, 1), } } diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index 46fb2617b7..9330b1372d 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -9,7 +9,7 @@ import { createAssistantMessage } from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' import { apply, Config, internals } from '../src/index.ts' const originalInternals = { ...internals } @@ -68,21 +68,21 @@ async function bench(script: Script): Promise<{ const session = ctx.sessions.create(options.sessionId, { ...options.meta === undefined ? {} : { meta: options.meta }, }) - const fixture = createInboxFixture(ctx.sessionProjections, session) + const inbox = createInboxStub() let idle = Promise.resolve() const agent: Agent = { id: session.id, options: options.agentOptions ?? {}, session, - inbox: fixture.inbox, + inbox, status: 'idle', ctx: ownerCtx, cancel: () => {}, runMaintenance: () => Promise.reject(new Error('not used')), send: () => {}, followup: (message: UserMessage) => { - fixture.inbox.append('next-turn', message) - const claimed = fixture.claim('next-turn') + inbox.append('next-turn', message) + const claimed = inbox.splice('next-turn', 0, 1, []) const [prompt] = claimed if (prompt === undefined || claimed.length !== 1) throw new Error('scripted Agent expected one claimed prompt') idle = Promise.resolve().then(() => script.afterPrompt(session, prompt)) diff --git a/packages/context/agent-instructions/tests/agent-instructions.spec.ts b/packages/context/agent-instructions/tests/agent-instructions.spec.ts index 937e8b37df..2ea3866ecc 100644 --- a/packages/context/agent-instructions/tests/agent-instructions.spec.ts +++ b/packages/context/agent-instructions/tests/agent-instructions.spec.ts @@ -1,12 +1,12 @@ import { chmod, mkdtemp, mkdir, rm, stat, symlink, utimes, writeFile } from 'node:fs/promises' import { dirname, isAbsolute, join, relative, resolve } from 'node:path' import { tmpdir } from 'node:os' -import { describe, expect, it, vi } from 'vitest' +import { afterAll, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import * as workspaceContext from '@deepseek-ai/dsh-agent-instructions' import LlmRuntime, { createUserMessage, ToolCallId, type Message, type StreamChunk } from '@deepseek-ai/dsh-llm' -import SessionStore, { SessionId, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' +import SessionStore, { SessionId, type SessionEvent, type SurfaceIntent, type UserMessage } from '@deepseek-ai/dsh-session' import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop, { turnBoundaryProjectionDefinition } from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -44,8 +44,8 @@ import { resolveConfig } from '../src/config.ts' import { candidateScopeKey, renderInstructionChanges, renderWorkspaceInstructionSet, USER_GLOBAL_DIRECTORY, USER_GLOBAL_FILE } from '../src/render.ts' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import { - createInboxFixture, - type InboxFixture, + mountAgentLoopTestDependencies, + mountAgentLoopTestHarness, } from '@deepseek-ai/dsh-agent-loop-testkit' /** Per-candidate reconciliation scope key: directory paired with the file name. */ @@ -53,19 +53,16 @@ const sk = (directory: string, candidateName: string): string => candidateScopeK const testToolSignal = new AbortController().signal const isolatedInboxCtx = new Context() -await isolatedInboxCtx.plugin(SessionStore) -await isolatedInboxCtx.plugin(SessionProjectionRegistry) -await isolatedInboxCtx.plugin(AgentRegistry) +await mountAgentLoopTestDependencies(isolatedInboxCtx) +const isolatedAgentLoop = await mountAgentLoopTestHarness(isolatedInboxCtx) let nextStubSession = 1 +afterAll(() => isolatedInboxCtx.fiber.dispose()) type TestAgent = Agent -const inboxFixtures = new WeakMap() -/** Return the loop-driver operations paired with one structural test Agent. */ -function inboxFixture(agent: Agent): InboxFixture { - const fixture = inboxFixtures.get(agent) - if (fixture === undefined) throw new Error('agent Inbox fixture is unavailable') - return fixture +/** Admit one test Agent's pending input through the production loop driver. */ +function claimInbox(agent: Agent, target: 'next-turn' | 'next-step'): UserMessage[] { + return isolatedAgentLoop.claim(agent, target, 1) } const requestTimeoutMs = process.platform === 'win32' ? 5_000 : 1_000 @@ -209,28 +206,27 @@ async function mountFileToolsAndWorkspaceContext(ctx: Context, config: workspace function stubAgent(cwd?: string, seed: readonly SessionEvent[] = []): TestAgent { const id = SessionId(`agent-instructions-${String(nextStubSession++)}`) - const agentCtx = isolatedInboxCtx - const session = agentCtx.sessions.create(id, { - seed, - ...cwd === undefined ? {} : { meta: { createdAt: 0, cwd } }, - }) - const fixture = createInboxFixture(agentCtx.sessionProjections, session) - const agent: TestAgent = { - ctx: agentCtx, - id: SessionId('a1'), - options: {}, - session, - inbox: fixture.inbox, - status: 'idle', - send: () => {}, - followup: () => {}, - steer: () => {}, - inject: () => { throw new Error('agent-instructions must append directly to the open step') }, - cancel() {}, - runMaintenance: task => task(new AbortController().signal), - whenIdle: () => Promise.resolve(), + const agent = isolatedAgentLoop.create( + id, + {}, + cwd === undefined ? {} : { cwd }, + ) + const append = agent.session.append.bind(agent.session) as unknown as ( + type: SessionEvent['type'], + data: SessionEvent['data'], + opts?: Partial, + ) => SessionEvent + for (const event of seed) { + if ('surfaceOp' in event || 'sourceEventSeqs' in event) { + append(event.type, event.data, { + ...event.surfaceOp === undefined ? {} : { surfaceOp: event.surfaceOp }, + ...event.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: event.sourceEventSeqs }, + }) + } else { + append(event.type, event.data) + } } - inboxFixtures.set(agent, fixture) + if (seed.at(-1)?.type !== 'session/end-seed') agent.session.append('session/end-seed', {}) return agent } @@ -282,7 +278,7 @@ function baselineEvents(agent: Agent): SessionEvent[] { async function appendAdditionalContexts(ctx: Context, agent: TestAgent): Promise { await syncedWorkspaceContext(ctx, agent) let lastSeq: number | undefined - for (const claimed of inboxFixture(agent).claim('next-step')) { + for (const claimed of claimInbox(agent, 'next-step')) { if (claimed.source.kind !== 'agent-instructions') continue const event = agent.session.append('user/message', claimed, { surfaceOp: 'append' }) ctx.emit('session/event', agent.session, event) @@ -300,7 +296,7 @@ async function composeBaselinePrefix(ctx: Context, agent: TestAgent): Promise Promise.resolve({ kind: 'enter' as const, messages: [] }), ) - const claimed = inboxFixture(agent).claim('next-step') + const claimed = claimInbox(agent, 'next-step') const decision = await agentEvents(ctx, agent).waterfall( 'agent/pre-step', { messages: claimed, turn: 1, step: 2, signal }, @@ -1413,7 +1409,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(ctx, { dshHome: home, maxBytes: 65536 }) const resumed = stubAgent(root, original.session.snapshotEvents()) agentEvents(ctx, resumed).emit('agent/session-start', { source: 'resume' }) - const claimed = inboxFixture(resumed).claim('next-step') + 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) }, @@ -1459,7 +1455,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(ctx, { dshHome: home, maxBytes: 65536 }) const resumed = stubAgent(root, original.session.snapshotEvents()) agentEvents(ctx, resumed).emit('agent/session-start', { source: 'resume' }) - const staleClaim = inboxFixture(resumed).claim('next-step') + 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) }, @@ -1512,7 +1508,7 @@ describe('workspace context request injection', () => { await mountWorkspaceContextPlugin(resumedCtx, { dshHome: home, maxBytes }) const resumed = stubAgent(root, original.session.snapshotEvents()) agentEvents(resumedCtx, resumed).emit('agent/session-start', { source: 'resume' }) - const claimed = inboxFixture(resumed).claim('next-step') + 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) }, @@ -4667,7 +4663,7 @@ describe('workspace context inbox synchronization', () => { await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) const agent = stubAgent(join(root, 'pkg')) await syncedWorkspaceContext(ctx, agent) - const claimed = inboxFixture(agent).claim('next-step') + const claimed = claimInbox(agent, 'next-step') await write(join(root, 'pkg/AGENTS.md'), 'new claimed rule with more detail') const downstream = { kind: 'enter' as const, messages: claimed } diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 7132d27d72..3158326eb3 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -9,7 +9,7 @@ import type { GoalRef } from '@deepseek-ai/dsh-goal' import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as commandGoal from '@deepseek-ai/dsh-command-goal' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' interface Harness { readonly ctx: Context @@ -22,7 +22,7 @@ interface Harness { function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } { // Store-created: the command executor durably logs lifecycle events on it. const session = ctx.sessions.create(SessionId(id)) - const { inbox } = createInboxFixture(ctx.sessionProjections, session) + const inbox = createInboxStub() let status: AgentStatus = 'idle' const agent: Agent = { id: session.id, diff --git a/packages/goal/goal/tests/goal.spec.ts b/packages/goal/goal/tests/goal.spec.ts index e33be74014..f3a415ff02 100644 --- a/packages/goal/goal/tests/goal.spec.ts +++ b/packages/goal/goal/tests/goal.spec.ts @@ -12,7 +12,7 @@ import GoalService, { foldGoal, } from '@deepseek-ai/dsh-goal' import type { GoalChangeMeta, GoalRef, GoalSnapshotChangeMeta } from '@deepseek-ai/dsh-goal' -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' interface StubAgent { agent: Agent @@ -44,7 +44,7 @@ function stubAgentForSession(session: Session, suppliedCtx?: Context): StubAgent if (suppliedCtx === undefined) { agentCtx.sessions.enter(session) } - const { inbox } = createInboxFixture(agentCtx.sessionProjections, session) + const inbox = createInboxStub() const agent: Agent = { id, options: {}, diff --git a/packages/goal/tool-goal/tests/tool-goal.spec.ts b/packages/goal/tool-goal/tests/tool-goal.spec.ts index a94143a563..6c75f7ed8f 100644 --- a/packages/goal/tool-goal/tests/tool-goal.spec.ts +++ b/packages/goal/tool-goal/tests/tool-goal.spec.ts @@ -14,10 +14,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' import * as toolGoal from '@deepseek-ai/dsh-tool-goal' -import { - createInboxFixture, - type InboxFixture, -} from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' const testToolSignal = new AbortController().signal @@ -25,7 +22,6 @@ interface StubAgent { readonly agent: Agent readonly session: Session readonly inbox: Inbox - readonly fixture: InboxFixture setStatus(status: AgentStatus): void } @@ -34,7 +30,7 @@ await isolatedInboxCtx.plugin(SessionStore) await isolatedInboxCtx.plugin(SessionProjectionRegistry) await isolatedInboxCtx.plugin(AgentRegistry) -/** Build one registry-compatible live agent whose injections enter the durable inbox. */ +/** Build one registry-compatible live agent whose injections enter its test Inbox. */ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): StubAgent { const agentCtx = suppliedCtx ?? isolatedInboxCtx const session = supplied ?? (suppliedCtx === undefined @@ -43,13 +39,13 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St if (suppliedCtx === undefined) { if (agentCtx.sessions.get(session.id) !== session) agentCtx.sessions.enter(session) } - const fixture = createInboxFixture(agentCtx.sessionProjections, session) + const inbox = createInboxStub() let status: AgentStatus = 'running' const agent: Agent = { id: session.id, options: {}, session, - inbox: fixture.inbox, + inbox, get status() { return status }, ctx: agentCtx, send: () => {}, @@ -62,7 +58,7 @@ function stubAgent(rawId: string, supplied?: Session, suppliedCtx?: Context): St runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - return { agent, session, inbox: fixture.inbox, fixture, setStatus(value) { status = value } } + return { agent, session, inbox, setStatus(value) { status = value } } } /** Open one message-triggered turn with its accepted model-visible input. */ @@ -75,7 +71,7 @@ function openTurn(stub: StubAgent, source: MessageSource, text = 'prompt'): numb source, }) stub.agent.inbox.append('next-turn', message) - const claimed = stub.fixture.claim('next-turn') + const claimed = stub.inbox.splice('next-turn', 0, 1, []) if (claimed.length === 0) throw new Error('expected queued turn input') stub.session.append('turn/start', { turn }) for (const admitted of claimed) { diff --git a/packages/test-support/agent-loop-testkit/README.i18n.yaml b/packages/test-support/agent-loop-testkit/README.i18n.yaml index 21902118b0..b20f520958 100644 --- a/packages/test-support/agent-loop-testkit/README.i18n.yaml +++ b/packages/test-support/agent-loop-testkit/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/test-support/agent-loop-testkit/README.md -README.md: 1bc4e31ac62c7a7de28f32c230bc7db97e47917e -README.zh.md: 41345f9ab3a55efb022957afe9d310aafac40514 +README.md: cb71e8cda9560dd432fa818e210df58c33c0fb9d +README.zh.md: c93ae5ccf020650b00379c12515c431933359168 diff --git a/packages/test-support/agent-loop-testkit/README.md b/packages/test-support/agent-loop-testkit/README.md index 1bc4e31ac6..cb71e8cda9 100644 --- a/packages/test-support/agent-loop-testkit/README.md +++ b/packages/test-support/agent-loop-testkit/README.md @@ -1,5 +1,5 @@ --- -description: "Prerequisite mounting, session-backed structural Inbox fixtures, and fail-fast Inbox stubs for agent-loop tests." +description: "Prerequisite mounting, production AgentLoop drivers, and explicit Inbox stubs for agent-loop tests." kind: "package-library" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, session-projection registry, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. The loop itself, adapters, optional plugins, agents, and teardown stay in the test's hands, so each scenario keeps its own load order and topology. It also provides a session-backed structural Inbox fixture for consumer tests and a fail-fast unsupported Inbox placeholder for stubs whose tests do not exercise pending input. Use the package when a test's subject is loop behavior rather than service wiring; tests that probe injection failures or partial topologies mount their dependencies directly. It registers no model-facing behavior of its own. +`dsh-agent-loop-testkit` mounts the standard prerequisite services a test needs before loading the concrete `AgentLoop` — the LLM runtime, session store, session-projection registry, system-prompt registry, tool registry, and agent registry — in dependency order, with one call. A second helper mounts the production loop and returns a narrow driver for creating real Agents and claiming their real Inbox input. Consumer tests that need only the public queue operations can instead use an explicitly process-local Inbox stub, while tests with no pending-input behavior can use a fail-fast unsupported Inbox. Adapters, optional plugins, load order, and teardown stay in the test's hands. The package registers no model-facing behavior of its own. ## Table of Contents @@ -25,48 +25,54 @@ English | [中文](README.zh.md) ## Use this package -This package gives an AgentLoop test a working service topology before the loop is mounted. +This package gives an AgentLoop test a working service topology and keeps the choice between production Inbox behavior and a structural stub explicit. -### Minimal example +### Drive a production Agent + +Use `mountAgentLoopTestHarness()` when the test covers durable Inbox events, projection recovery or validation, live Inbox notifications, or loop-driver claims. Mount any load-order-sensitive consumers after the prerequisites and before creating the Agent. The context owns the loop and every Agent returned by the harness. ```ts import { Context } from '@deepseek-ai/cordis' -import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import { SessionId, type UserMessage } from '@deepseek-ai/dsh-session' +import { + mountAgentLoopTestDependencies, + mountAgentLoopTestHarness, +} from '@deepseek-ai/dsh-agent-loop-testkit' const ctx = new Context() await mountAgentLoopTestDependencies(ctx) -// Register the test adapter and any optional plugins here. -await ctx.plugin(AgentLoop, { agents: [] }) +// Register the test adapter and any load-order-sensitive plugins here. +const harness = await mountAgentLoopTestHarness(ctx) +const agent = harness.create(SessionId('test-agent')) +declare const message: UserMessage + +agent.inbox.append('next-turn', message) +const admitted = harness.claim(agent, 'next-turn', 1) ``` -The mounting helper activates the LLM, session, session-projection, system-prompt, tool, and agent services in dependency order and returns before the loop is mounted. System-prompt and tool-registry configuration can be forwarded through `options`; the helper provides no test defaults beyond those the services own. +The dependency helper forwards system-prompt and tool-registry configuration through `options` and provides no test defaults beyond those services' own defaults. A plugin-load failure rejects the helper call; services activated earlier in the sequence remain context-owned and unwind when the context is disposed. -### Build structural Agent stubs +### Build a structural Agent stub -Use `createInboxFixture(ctx.sessionProjections, session)` when pending input belongs to the test. It returns an `inbox` for the Agent literal and a separate `claim` operation for the test driver. Create the fixture before the Agent literal so the object satisfies the required structural interface from construction onward. Use `unsupportedInbox()` only when the test subject does not exercise pending Agent input; it exposes empty pending lists and throws on every mutation, so an unexpected Inbox dependency fails at its first write. +Use `createInboxStub()` when the test subject needs mutable pending lists but does not exercise durability, projection validation, live Inbox notifications, or the driver's claim policy. The stub implements the public queue operations with two process-local arrays and never writes to a Session. Use `unsupportedInbox()` when the test subject must not touch pending input; every mutation throws at the first unexpected dependency. ```ts -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' -declare const ctx: import('@deepseek-ai/cordis').Context -declare const session: Parameters[1] - -const fixture = createInboxFixture(ctx.sessionProjections, session) const agent = { // ... - inbox: fixture.inbox, + inbox: createInboxStub(), } ``` ### When to use it -Use the mounting helper for tests whose subject is the loop: load order, retries, tool execution, or session behavior on a real prerequisite stack. Mount dependencies directly when a test probes service load order, injection failures, partial topologies, or teardown — the helper hides exactly the wiring such tests must control. +Use the dependency and loop helpers for tests whose subject is production loop or durable Inbox behavior. Use the structural stub for consumer-domain tests that only need queue editing. Mount dependencies directly when a test probes service injection failures or partial topologies, because the helper hides exactly the wiring those tests must control. ### What can go wrong -A plugin-load failure rejects the mounting helper call; services activated earlier in the sequence remain owned by your context and unwind with it. The context owns every mounted service, so dispose it after the test. +The harness mounts no LLM adapter. Register an adapter before sending work that would start a model request. Dispose the owning context after every test so Agents reach quiescence and their scoped registrations unwind. ----- @@ -80,7 +86,7 @@ This section explains the design of the test utilities; the observable behavior ### Design -`mountAgentLoopTestDependencies` mounts six service plugins in a fixed dependency order — LLM, session, session-projection registry, system-prompt registry, tool registry, then agent registry — and deliberately stops before `AgentLoop` itself, so the caller controls loop load order and the topology under test. [`src/inbox.ts`](src/inbox.ts) owns a test-only projection definition for the public durable Inbox event and state contract, the structural command facade and driver claim operation, and the fail-fast unsupported placeholder. It does not import the package-internal loop implementation. The mounting implementation lives in [`src/index.ts`](src/index.ts). No companion is published because this test-support package owns no production event stream or mutable data; consuming test suites exercise its behavior. +`mountAgentLoopTestDependencies` mounts six service plugins in a fixed dependency order — LLM, session, session-projection registry, system-prompt registry, tool registry, then agent registry — and stops before `AgentLoop`, so the caller controls loop load order. `mountAgentLoopTestHarness` mounts the public production plugin, creates Agents through its service, and exposes the production driver's claim operation without exporting the loop's concrete Inbox class or projection definition. [`src/inbox.ts`](src/inbox.ts) contains only the process-local mutable stub and the fail-fast unsupported placeholder; it owns no projection or durable event implementation. The mounting and driver implementation lives in [`src/index.ts`](src/index.ts). No invariant companion is published because the package owns only test helpers and has no independent production observations that can diverge. @@ -89,11 +95,11 @@ This section explains the design of the test utilities; the observable behavior ## Further Exploration -Read these pages when the package-level contract is not enough. They move from the loop to the services the helper mounts and the tests that use it. +Read these pages when the package-level behavior is not enough. They move from the loop to the services the helper mounts and the tests that use it. -- [Agent loop package](../../core/agent-loop/README.md) — the concrete loop this helper prepares tests for. -- [Session package](../../core/session/README.md) — the session store the helper mounts. -- [LLM package](../../llm/llm/README.md) — the LLM runtime and adapter contract the helper mounts. +- [Agent loop package](../../core/agent-loop/README.md) — the concrete loop this helper mounts for production behavior. +- [Session package](../../core/session/README.md) — the durable event log used by production Inbox behavior. +- [LLM package](../../llm/llm/README.md) — the LLM runtime and adapter interface the helper prepares. - [Testing policy](../../../docs/testing.md) — the coverage tiers these tests serve. - [Test-support group map](../README.md) — sibling harnesses and support packages. @@ -102,23 +108,22 @@ Read these pages when the package-level contract is not enough. They move from t ## Model Experience -None, as these test-only utilities neither drive nor modify model requests. +None, as these test-only utilities neither assemble nor modify model requests. #### KV Cache effect -None; this package neither assembles nor sends a provider request. +None; the package itself sends no provider request. ## Known Limitations and Deferred Work - These limits define what the utilities do not share. They are current package constraints, not a task backlog. -- **Only the mandatory prerequisite spine is shared** — adapters, optional plugins, `AgentLoop`, agents, and context teardown remain caller-owned so scenario-specific ordering stays visible. -- **The structural fixture emits durable session events only** — it does not reproduce live `agent/inbox/inserted`, `agent/inbox/claimed`, or `agent/inbox/discarded` notifications owned by the loop implementation. -- **The structural fixture accepts trusted test events** — it does not repeat the production provider's persisted-splice validation; focused `agent-loop` tests own invalid-history coverage. -- **The unsupported Inbox accepts no mutations** — use `createInboxFixture()` whenever pending input is part of the test subject. +- **Only the mandatory prerequisite spine is shared** — adapters, optional plugins, scenario-specific load order, and context teardown remain caller-owned. +- **The production harness has no adapter default** — tests that start the loop must register the route they exercise. +- **The mutable Inbox stub is process-local only** — use a harness-created Agent whenever durable events, projection recovery or validation, live notifications, or claim policy matter. +- **The unsupported Inbox accepts no mutations** — use the mutable stub or a harness-created Agent whenever pending input is part of the test subject. ### Dev Note diff --git a/packages/test-support/agent-loop-testkit/README.zh.md b/packages/test-support/agent-loop-testkit/README.zh.md index 41345f9ab3..c93ae5ccf0 100644 --- a/packages/test-support/agent-loop-testkit/README.zh.md +++ b/packages/test-support/agent-loop-testkit/README.zh.md @@ -1,5 +1,5 @@ --- -description: "为 agent-loop 测试提供先决依赖挂载、基于会话的结构化 Inbox fixture 和快速失败的 Inbox 桩。" +description: "为 agent-loop 测试提供先决依赖挂载、生产 AgentLoop 驱动与职责明确的 Inbox 桩。" kind: "package-library" --- @@ -9,7 +9,7 @@ kind: "package-library" ## 概述 -`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的全部标准先决服务——LLM(大语言模型)运行时、会话存储、会话投影注册表、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。loop 本身、适配器、可选插件、agent 与清理仍由测试掌控,因此每个场景都保持自己的加载顺序与拓扑。它还为消费方测试提供基于会话的结构化 Inbox fixture,并为不测试待处理输入的桩提供一个快速失败且不支持操作的 Inbox 占位值。当测试对象是 loop 行为而非服务接线时使用本包;针对注入失败或部分拓扑的测试会直接挂载其依赖。它自身不注册任何模型可见行为。 +`dsh-agent-loop-testkit` 为测试在加载具体 `AgentLoop` 之前所需的标准先决服务——LLM(大语言模型)运行时、会话存储、会话投影注册表、系统提示词注册表、工具注册表与 agent(智能体)注册表——按依赖顺序一键挂载。另一个辅助函数会挂载生产 loop,并返回一个精简驱动,用于创建真实 Agent 和通过真实 Inbox 认领输入。只需要公开队列操作的消费方测试可以改用明确标记为进程内实现的 Inbox 桩;不涉及待处理输入的测试则可以使用快速失败且不支持操作的 Inbox。适配器、可选插件、加载顺序与清理由测试掌控。本包自身不注册任何模型可见行为。 ## 目录 @@ -25,48 +25,54 @@ kind: "package-library" ## 使用本包 -本包在 loop 挂载前为 AgentLoop 测试提供可用的服务拓扑。 +本包为 AgentLoop 测试提供可用的服务拓扑,并要求测试明确选择生产 Inbox 行为或结构化桩。 -### 最小示例 +### 驱动生产 Agent + +当测试覆盖持久 Inbox 事件、投影恢复或校验、实时 Inbox 通知,或 loop 驱动的认领策略时,使用 `mountAgentLoopTestHarness()`。应在挂载先决依赖后、创建 Agent 前挂载所有对加载顺序敏感的消费方。上下文拥有 loop 以及该 harness 返回的每个 Agent。 ```ts import { Context } from '@deepseek-ai/cordis' -import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import { SessionId, type UserMessage } from '@deepseek-ai/dsh-session' +import { + mountAgentLoopTestDependencies, + mountAgentLoopTestHarness, +} from '@deepseek-ai/dsh-agent-loop-testkit' const ctx = new Context() await mountAgentLoopTestDependencies(ctx) -// Register the test adapter and any optional plugins here. -await ctx.plugin(AgentLoop, { agents: [] }) +// Register the test adapter and any load-order-sensitive plugins here. +const harness = await mountAgentLoopTestHarness(ctx) +const agent = harness.create(SessionId('test-agent')) +declare const message: UserMessage + +agent.inbox.append('next-turn', message) +const admitted = harness.claim(agent, 'next-turn', 1) ``` -挂载辅助函数按依赖顺序激活 LLM、会话、会话投影、系统提示词、工具与 agent 服务,并在 loop 挂载前返回。系统提示词与工具注册表配置可通过 `options` 转发;除服务自有的默认值外,本辅助函数不提供测试默认值。 +依赖辅助函数通过 `options` 转发系统提示词与工具注册表配置,除这些服务自有的默认值外不提供测试默认值。插件加载失败会使辅助函数调用被拒绝;顺序中较早激活的服务仍归上下文所有,并在上下文释放时一并解除。 ### 构造结构化 Agent 桩 -当待处理输入属于测试对象时,使用 `createInboxFixture(ctx.sessionProjections, session)`。它会返回供 Agent 对象字面量使用的 `inbox`,以及供测试驱动使用的独立 `claim` 操作。应先创建 fixture,再构造 Agent 对象字面量,使对象从构造开始就满足必需的结构化接口。仅当测试对象不涉及待处理的 Agent 输入时才使用 `unsupportedInbox()`;它公开空的待处理列表,并在每次变更时抛错,因此意外的 Inbox 依赖会在首次写入时失败。 +当测试对象需要可变的待处理列表,但不测试持久性、投影校验、实时 Inbox 通知或驱动的认领策略时,使用 `createInboxStub()`。该桩通过两个进程内数组实现公开队列操作,且绝不会写入 Session。当测试对象不应访问待处理输入时,使用 `unsupportedInbox()`;每次变更都会在首个意外依赖处抛错。 ```ts -import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit' -declare const ctx: import('@deepseek-ai/cordis').Context -declare const session: Parameters[1] - -const fixture = createInboxFixture(ctx.sessionProjections, session) const agent = { // ... - inbox: fixture.inbox, + inbox: createInboxStub(), } ``` ### 何时使用 -当测试对象是 loop 本身——在真实先决依赖栈上的加载顺序、重试、工具执行或会话行为——时使用挂载辅助函数。当测试要探测服务加载顺序、注入失败、部分拓扑或清理时,请直接挂载依赖——辅助函数隐藏的正是这类测试必须控制的接线。 +当测试对象是生产 loop 或持久 Inbox 行为时,使用依赖与 loop 辅助函数。只需要编辑队列的消费方领域测试使用结构化桩。当测试探测服务注入失败或部分拓扑时,请直接挂载依赖,因为辅助函数隐藏的正是这类测试必须控制的接线。 ### 可能出什么问题 -插件加载失败会使挂载辅助函数调用被拒绝;顺序中较早激活的服务仍归你的上下文所有,并随上下文一起解除。上下文拥有所有已挂载服务,因此测试结束后请 dispose(资源释放)它。 +harness 不会挂载任何 LLM 适配器。若测试发送的任务会启动模型请求,请先注册被测路由的适配器。每个测试结束后都应释放所属上下文,使 Agent 达到静止状态并解除其作用域注册。 ----- @@ -80,7 +86,7 @@ const agent = { ### 设计 -`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、会话投影注册表、系统提示词注册表、工具注册表、agent 注册表——挂载六个服务插件,并刻意在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序与待测拓扑。[`src/inbox.ts`](src/inbox.ts) 持有针对公开持久 Inbox 事件与状态约定的测试专用投影定义、结构化命令 facade、驱动方 claim 操作,以及快速失败且不支持操作的占位值。它不会导入包内部的 loop 实现。挂载实现位于 [`src/index.ts`](src/index.ts)。本测试支持包不持有任何生产事件流或可变数据,因此不发布伴生入口;消费它的测试套件会直接检验其行为。 +`mountAgentLoopTestDependencies` 按固定依赖顺序——LLM、会话、会话投影注册表、系统提示词注册表、工具注册表、agent 注册表——挂载六个服务插件,并在 `AgentLoop` 之前停下,使调用方控制 loop 加载顺序。`mountAgentLoopTestHarness` 挂载公开的生产插件,通过其服务创建 Agent,并公开生产驱动的认领操作,而不导出 loop 的具体 Inbox 类或投影定义。[`src/inbox.ts`](src/inbox.ts) 仅包含进程内可变桩和快速失败且不支持操作的占位值;它不持有投影或持久事件实现。挂载与驱动实现位于 [`src/index.ts`](src/index.ts)。本包不发布 invariant companion,因为它只持有测试辅助工具,不存在可能相互偏离的独立生产观测。 @@ -89,11 +95,11 @@ const agent = { ## 进一步探索 -当包级约定不够用时阅读以下页面。它们从 loop 逐步进入辅助函数挂载的服务以及使用它的测试。 +当包级行为不够用时阅读以下页面。它们从 loop 逐步进入辅助函数挂载的服务以及使用它的测试。 -- [Agent loop 包](../../core/agent-loop/README.zh.md)——本辅助函数为之准备测试的具体 loop。 -- [会话包](../../core/session/README.zh.md)——辅助函数挂载的会话存储。 -- [LLM 包](../../llm/llm/README.zh.md)——辅助函数挂载的 LLM 运行时与适配器约定。 +- [Agent loop 包](../../core/agent-loop/README.zh.md)——本辅助函数为生产行为挂载的具体 loop。 +- [会话包](../../core/session/README.zh.md)——生产 Inbox 行为使用的持久事件日志。 +- [LLM 包](../../llm/llm/README.zh.md)——本辅助函数准备的 LLM 运行时与适配器接口。 - [测试策略](../../../docs/testing.zh.md)——这些测试所服务的覆盖层级。 - [test-support 组地图](../README.zh.md)——兄弟 harness 与支持包。 @@ -102,23 +108,22 @@ const agent = { ## 模型体验 -无。这些测试专用辅助工具既不驱动也不修改模型请求。 +无。这些测试专用辅助工具既不组装也不修改模型请求。 #### KV Cache 影响 -无;本包既不组装也不发送提供方请求。 +无;本包自身不发送提供方请求。 ## 已知限制与延期工作 - 这些限制说明辅助工具不共享什么。它们是当前包约束,不是任务积压。 -- **只共享必需的先决主干**——适配器、可选插件、`AgentLoop`、agent 与上下文清理仍由调用方负责,以使特定场景的挂载顺序清晰可见。 -- **结构化 fixture 只发出持久会话事件**——它不会复现由 loop 实现持有的实时 `agent/inbox/inserted`、`agent/inbox/claimed` 或 `agent/inbox/discarded` 通知。 -- **结构化 fixture 接受受信的测试事件**——它不会重复生产 provider 的持久 splice 校验;无效历史覆盖由聚焦的 `agent-loop` 测试持有。 -- **不支持操作的 Inbox 不接受变更**——只要待处理输入属于测试对象,就应使用 `createInboxFixture()`。 +- **只共享必需的先决主干**——适配器、可选插件、场景特定的加载顺序与上下文清理仍由调用方负责。 +- **生产 harness 没有适配器默认值**——启动 loop 的测试必须注册其实际使用的路由。 +- **可变 Inbox 桩仅存在于进程内**——只要持久事件、投影恢复或校验、实时通知或认领策略属于测试对象,就应使用 harness 创建的 Agent。 +- **不支持操作的 Inbox 不接受变更**——只要待处理输入属于测试对象,就应使用可变桩或 harness 创建的 Agent。 ### 开发备注 diff --git a/packages/test-support/agent-loop-testkit/package.json b/packages/test-support/agent-loop-testkit/package.json index 89a5cec445..67f4695fb8 100644 --- a/packages/test-support/agent-loop-testkit/package.json +++ b/packages/test-support/agent-loop-testkit/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-agent-loop-testkit", - "description": "Prerequisite mounting and session-backed Inbox fixtures for agent-loop tests", + "description": "Prerequisite mounting, production AgentLoop drivers, and Inbox stubs for tests", "version": "0.1.2-alpha.3", "publishConfig": { "access": "public" @@ -28,6 +28,7 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-projection": "workspace:^", @@ -35,9 +36,7 @@ "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/cordis": "workspace:^" }, - "dependencies": { - "zod": "^4.4.3" - }, + "dependencies": {}, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", diff --git a/packages/test-support/agent-loop-testkit/src/inbox.ts b/packages/test-support/agent-loop-testkit/src/inbox.ts index 6a50d1b5df..dbb1dbff57 100644 --- a/packages/test-support/agent-loop-testkit/src/inbox.ts +++ b/packages/test-support/agent-loop-testkit/src/inbox.ts @@ -1,132 +1,54 @@ -import type { Inbox, InboxState, InboxTarget, InboxWireState } from '@deepseek-ai/dsh-agent' +import type { Inbox, InboxTarget } from '@deepseek-ai/dsh-agent' import type { MessageId } from '@deepseek-ai/dsh-llm' -import type { Session, SessionEventMap, UserMessage } from '@deepseek-ai/dsh-session' -import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' -import type SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' -import { z } from 'zod' - -const testInboxProjectionSchema = z.object({ - 'next-turn': z.array(z.custom()).readonly(), - 'next-step': z.array(z.custom()).readonly(), -}).readonly() - -/** Test-only registration for the public durable Inbox event and state contract. */ -const testInboxProjectionDefinition = { - key: 'inbox', - stateSchema: testInboxProjectionSchema, - init: (): InboxState => ({ 'next-turn': [], 'next-step': [] }), - apply(state: InboxState, event) { - if (event.type !== 'agent/inbox/spliced') return state - const { target, start, removedCount = 0, inserted } = event.data - const next = [...state[target]] - next.splice(start, removedCount, ...inserted) - return { ...state, [target]: next } - }, - wire: { - viewSchema: testInboxProjectionSchema as unknown as z.ZodType, - view: (state: InboxState) => state as unknown as InboxWireState, - }, - stateVersion: 1, -} satisfies ProjectionDefinition<'inbox', InboxState> - -/** A structural Inbox test double and its loop-driver operation. */ -export interface InboxFixture { - /** Session-backed Inbox exposed to the code under test. */ - readonly inbox: Inbox - /** Remove the batch a test driver admits at one boundary. */ - readonly claim: (target: InboxTarget) => UserMessage[] -} +import type { UserMessage } from '@deepseek-ai/dsh-session' /** - * Create a session-backed structural Inbox test double for consumer tests. - * @param projections - registry that owns the fixture's test projection registration. - * @param session - session whose durable splices back the test double. - * @returns the structural Inbox and a separate loop-driver claim operation. + * Create a mutable in-memory Inbox stub for tests that exercise only the public + * queue operations. Durable events, projection validation, and live Inbox + * notifications require a real Agent created by the AgentLoop test harness. + * @returns an Inbox backed by two process-local arrays. */ -export function createInboxFixture( - projections: SessionProjectionRegistry, - session: Session, -): InboxFixture { - projections.register(testInboxProjectionDefinition) - - const current = (): InboxState => { - const state = projections.stateOf(session, 'inbox') - /* v8 ignore next -- createInboxFixture holds the registration for the context lifetime */ - if (state === undefined) throw new Error('test inbox projection registration is not active') - return state +export function createInboxStub(): Inbox { + const pending: Record = { + 'next-turn': [], + 'next-step': [], } const locate = (messageId: MessageId): { target: InboxTarget; index: number } | undefined => { - const state = current() - const turnIndex = state['next-turn'].findIndex(message => message.id === messageId) - if (turnIndex >= 0) return { target: 'next-turn', index: turnIndex } - const stepIndex = state['next-step'].findIndex(message => message.id === messageId) - return stepIndex < 0 ? undefined : { target: 'next-step', index: stepIndex } - } - - const mutate = ( - target: InboxTarget, - start: number, - deleteCount: number, - inserted: UserMessage[], - canceled: boolean, - ): UserMessage[] => { - const pending = current()[target] - const integerStart = Number.isNaN(start) ? 0 : Math.trunc(start) - const index = integerStart < 0 - ? Math.max(pending.length + integerStart, 0) - : Math.min(integerStart, pending.length) - const integerCount = Number.isNaN(deleteCount) ? 0 : Math.trunc(deleteCount) - const count = Math.min(Math.max(integerCount, 0), pending.length - index) - if (count === 0 && inserted.length === 0) return [] - const event: SessionEventMap['agent/inbox/spliced'] = { - target, - start: index, - ...(count === 0 ? {} : { removedCount: count }), - inserted, - ...(canceled && count > 0 ? { outcome: 'canceled' } : {}), + for (const target of ['next-turn', 'next-step'] as const) { + const index = pending[target].findIndex(message => message.id === messageId) + if (index >= 0) return { target, index } } - const removed = pending.slice(index, index + count) - session.append('agent/inbox/spliced', event) - return removed + return undefined } - const inbox: Inbox = { - get nextTurn() { return current()['next-turn'] }, - get nextStep() { return current()['next-step'] }, + return { + get nextTurn() { return pending['next-turn'] }, + get nextStep() { return pending['next-step'] }, clear() { - mutate('next-step', 0, current()['next-step'].length, [], true) - mutate('next-turn', 0, current()['next-turn'].length, [], true) + pending['next-step'].splice(0) + pending['next-turn'].splice(0) }, append(target, message) { - mutate(target, current()[target].length, 0, [message], true) + pending[target].push(message) }, prepend(target, message) { - mutate(target, 0, 0, [message], true) + pending[target].unshift(message) }, replace(messageId, message) { const location = locate(messageId) if (location === undefined) return false - mutate(location.target, location.index, 1, [message], true) + pending[location.target].splice(location.index, 1, message) return true }, remove(messageId) { const location = locate(messageId) if (location === undefined) return false - mutate(location.target, location.index, 1, [], true) + pending[location.target].splice(location.index, 1) return true }, splice(target, start, deleteCount, inserted) { - return mutate(target, start, deleteCount, inserted, true) - }, - } - - return { - inbox, - claim: (target) => { - const claimed = mutate('next-step', 0, current()['next-step'].length, [], false) - if (target === 'next-turn') claimed.push(...mutate('next-turn', 0, 1, [], false)) - return claimed + return pending[target].splice(start, deleteCount, ...inserted) }, } } diff --git a/packages/test-support/agent-loop-testkit/src/index.ts b/packages/test-support/agent-loop-testkit/src/index.ts index cde26ba7ee..d90043c70c 100644 --- a/packages/test-support/agent-loop-testkit/src/index.ts +++ b/packages/test-support/agent-loop-testkit/src/index.ts @@ -1,25 +1,48 @@ /** - * Shared service mounting and session-backed Inbox fixtures for agent-loop - * tests. Callers retain ownership of their contexts, loops, adapters, - * optional plugins, and teardown. + * Shared service mounting, real AgentLoop drivers, and structural Inbox stubs + * for agent-loop tests. Callers retain ownership of their contexts, adapters, + * optional plugins, agents, and teardown. * @module @deepseek-ai/dsh-agent-loop-testkit */ import type { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' +import type { Agent, AgentOptions, Inbox, InboxTarget } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' import LlmRuntime from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' +import type { SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import type { Config as ToolRuntimeConfig } from '@deepseek-ai/dsh-tools' -export { - createInboxFixture, - unsupportedInbox, - type InboxFixture, -} from './inbox.ts' +export { createInboxStub, unsupportedInbox } from './inbox.ts' + +interface DriverInbox extends Inbox { + claim(target: InboxTarget, turn: number): UserMessage[] +} + +/** Test driver for production Agents created by a mounted AgentLoop. */ +export interface AgentLoopTestHarness { + /** + * Create a production Agent and fresh Session owned by the harness context. + * @param id - shared Agent and Session identity. + * @param options - concrete loop options. + * @param meta - optional fresh-session workspace metadata. + * @returns the published production Agent. + */ + create(id: SessionId, options?: AgentOptions, meta?: Pick): Agent + /** + * Admit pending messages through the production loop driver's claim operation. + * @param agent - Agent returned by this harness's `create` method. + * @param target - boundary whose pending input is admitted. + * @param turn - turn that owns the admitted messages. + * @returns next-step messages followed by one next-turn message when requested. + */ + claim(agent: Agent, target: InboxTarget, turn: number): UserMessage[] +} /** Configuration forwarded to the prerequisite service plugins. */ export interface AgentLoopTestDependenciesOptions { @@ -52,3 +75,19 @@ export async function mountAgentLoopTestDependencies( await ctx.plugin(ToolRuntime, options.tools ?? {}) await ctx.plugin(AgentRegistry) } + +/** + * Mount the production AgentLoop and expose its narrow test-driver operations. + * Mount {@link mountAgentLoopTestDependencies} and any load-order-sensitive + * consumers before calling this helper. The context owns the loop and every + * Agent returned by the harness. + * @param ctx - test context with the AgentLoop prerequisite services active. + * @returns a driver that creates production Agents and claims their real Inbox. + */ +export async function mountAgentLoopTestHarness(ctx: Context): Promise { + await ctx.plugin(AgentLoop, { agents: [] }) + return { + create: (id, options = {}, meta = {}) => ctx.agentLoop.create(id, options, meta), + claim: (agent, target, turn) => (agent.inbox as DriverInbox).claim(target, turn), + } +} diff --git a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts index b13ab29717..b6186d0544 100644 --- a/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts +++ b/packages/test-support/agent-loop-testkit/tests/agent-loop-testkit.spec.ts @@ -1,13 +1,12 @@ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' import { - createInboxFixture, + createInboxStub, mountAgentLoopTestDependencies, + mountAgentLoopTestHarness, unsupportedInbox, } from '../src/index.ts' @@ -24,7 +23,7 @@ describe('dsh-agent-loop-testkit', () => { expect(() => { inbox.clear() }).toThrow('this test Agent does not support Inbox mutations') }) - it('mounts a configurable prerequisite spine that can activate AgentLoop', async () => { + it('mounts a configurable prerequisite spine and the production AgentLoop', async () => { const ctx = new Context() await mountAgentLoopTestDependencies(ctx, { systemPrompt: { persona: 'Test persona.' }, @@ -32,51 +31,77 @@ describe('dsh-agent-loop-testkit', () => { }) expect(renderPrompt(await ctx.systemPrompt.assemble())).toContain('Test persona.') - await expect(ctx.plugin(AgentLoop, { agents: [] })).resolves.toBeDefined() + await expect(mountAgentLoopTestHarness(ctx)).resolves.toBeDefined() await ctx.fiber.dispose() }) - it('provides a session-backed structural Inbox with separate driver claims', async () => { - const ctx = new Context() - await ctx.plugin(SessionProjectionRegistry) - const session = Session.create(SessionId('agent-loop-testkit-inbox')) - const fixture = createInboxFixture(ctx.sessionProjections, session) + it('provides a mutable in-memory Inbox stub for structural Agent tests', () => { + const inbox = createInboxStub() const firstTurn = message('first turn') const secondTurn = message('second turn') const firstStep = message('first step') const editedTurn = message('edited turn') const editedStep = message('edited step') - fixture.inbox.append('next-turn', firstTurn) - fixture.inbox.prepend('next-turn', secondTurn) - fixture.inbox.append('next-step', firstStep) - expect(fixture.inbox.nextTurn).toEqual([secondTurn, firstTurn]) - expect(fixture.inbox.nextStep).toEqual([firstStep]) + inbox.append('next-turn', firstTurn) + inbox.prepend('next-turn', secondTurn) + inbox.append('next-step', firstStep) + expect(inbox.nextTurn).toEqual([secondTurn, firstTurn]) + expect(inbox.nextStep).toEqual([firstStep]) - expect(fixture.inbox.replace(firstTurn.id, editedTurn)).toBe(true) - expect(fixture.inbox.replace(firstStep.id, editedStep)).toBe(true) - expect(fixture.inbox.replace(firstTurn.id, message('missing replacement'))).toBe(false) - expect(fixture.inbox.remove(firstTurn.id)).toBe(false) - expect(fixture.inbox.splice('next-turn', -1, 1, [])).toEqual([editedTurn]) - expect(fixture.inbox.remove(editedStep.id)).toBe(true) + expect(inbox.replace(firstTurn.id, editedTurn)).toBe(true) + expect(inbox.replace(firstStep.id, editedStep)).toBe(true) + expect(inbox.replace(firstTurn.id, message('missing replacement'))).toBe(false) + expect(inbox.remove(firstTurn.id)).toBe(false) + expect(inbox.splice('next-turn', -1, 1, [])).toEqual([editedTurn]) + expect(inbox.remove(editedStep.id)).toBe(true) - const claimedStep = message('claimed step') - const claimedTurn = message('claimed turn') - fixture.inbox.splice('next-step', Number.NaN, Number.NaN, [claimedStep]) - fixture.inbox.append('next-turn', claimedTurn) - expect(fixture.claim('next-step')).toEqual([claimedStep]) - expect(fixture.claim('next-turn')).toEqual([secondTurn]) - expect(fixture.inbox.nextTurn).toEqual([claimedTurn]) + inbox.clear() + expect(inbox.nextTurn).toEqual([]) + expect(inbox.nextStep).toEqual([]) + }) - const eventCount = session.snapshotEvents().length - expect(fixture.inbox.splice('next-step', 100, -1, [])).toEqual([]) - expect(session.snapshotEvents()).toHaveLength(eventCount) + it('drives durable Inbox behavior through a production Agent', async () => { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + const harness = await mountAgentLoopTestHarness(ctx) + const agent = harness.create(SessionId('agent-loop-testkit-inbox')) + const turn = message('turn') + const step = message('step') + const inserted: string[] = [] + const claimed: Array<{ id: string; turn: number }> = [] + ctx.on('agent/inbox/inserted', ({ agent: subject, message: pending }) => { + if (subject === agent) inserted.push(pending.id) + }) + ctx.on('agent/inbox/claimed', ({ agent: subject, message: pending, turn: ownerTurn }) => { + if (subject === agent) claimed.push({ id: pending.id, turn: ownerTurn }) + }) - fixture.inbox.clear() - expect(fixture.inbox.nextTurn).toEqual([]) - expect(fixture.inbox.nextStep).toEqual([]) - fixture.inbox.clear() + agent.inbox.append('next-turn', turn) + agent.inbox.append('next-step', step) + + expect(inserted).toEqual([turn.id, step.id]) + expect(() => { agent.inbox.append('next-step', turn) }).toThrow(`message "${turn.id}" is already pending`) + const invalid = Session.create(SessionId('invalid-persisted-inbox'), [{ + type: 'agent/inbox/spliced', + seq: 0, + time: 1, + data: { target: 'next-turn', start: 99, inserted: [] }, + }]) + expect(() => ctx.sessionProjections.stateOf(invalid, 'inbox')) + .toThrow(/invalid persisted inbox splice/) + expect(harness.claim(agent, 'next-turn', 3)).toEqual([step, turn]) + expect(claimed).toEqual([ + { id: step.id, turn: 3 }, + { id: turn.id, turn: 3 }, + ]) + expect(agent.session.snapshotEvents().map(event => event.type)).toEqual([ + 'agent/inbox/spliced', + 'agent/inbox/spliced', + 'agent/inbox/spliced', + 'agent/inbox/spliced', + ]) await ctx.fiber.dispose() }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7f1d7f2ea9..2202aa8730 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8919,10 +8919,6 @@ importers: version: link:../../core/tools packages/test-support/agent-loop-testkit: - dependencies: - zod: - specifier: ^4.4.3 - version: 4.4.3 devDependencies: '@deepseek-ai/cordis': specifier: workspace:^ From 6f4b38ea2e8ac74d20a9a8a437e0db7e77349d4a Mon Sep 17 00:00:00 2001 From: _Kerman Date: Tue, 1 Sep 2026 21:50:28 +0800 Subject: [PATCH 20/26] docs: refresh agent loop testkit graph --- docs/module-graph.i18n.yaml | 4 ++-- docs/module-graph.md | 15 ++++++++------- docs/module-graph.zh.md | 15 ++++++++------- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index dec5cfb323..f2ec41f83a 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/module-graph.md -module-graph.md: 3f089e3e3d618377522d927845fccbf7548c64bc -module-graph.zh.md: 04c2f2a35b01434a6e622d92ead8b9ce55b9cfec +module-graph.md: bd597fed0a4f2aa2b883f72822dbd59398f1422e +module-graph.zh.md: e732988c84a1b61f4086f8cb54112484a22c4a02 diff --git a/docs/module-graph.md b/docs/module-graph.md index 3f089e3e3d..bd597fed0a 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -854,12 +854,6 @@ flowchart TD pkg_tool_terminal --> pkg_system_prompt pkg_tool_terminal --> pkg_terminal pkg_tool_terminal --> pkg_tools - pkg_agent_loop_testkit --> pkg_agent - pkg_agent_loop_testkit --> pkg_llm - pkg_agent_loop_testkit --> pkg_session - pkg_agent_loop_testkit --> pkg_session_projection - pkg_agent_loop_testkit --> pkg_system_prompt - pkg_agent_loop_testkit --> pkg_tools pkg_llm_replay --> pkg_compaction pkg_llm_replay --> pkg_deepseek_llm_api_extensions pkg_llm_replay --> pkg_llm @@ -933,6 +927,13 @@ flowchart TD pkg_tool_pwsh --> pkg_system_prompt pkg_tool_pwsh --> pkg_tools pkg_tool_pwsh --> pkg_user_approval + pkg_agent_loop_testkit --> pkg_agent + pkg_agent_loop_testkit --> pkg_agent_loop + pkg_agent_loop_testkit --> pkg_llm + pkg_agent_loop_testkit --> pkg_session + pkg_agent_loop_testkit --> pkg_session_projection + pkg_agent_loop_testkit --> pkg_system_prompt + pkg_agent_loop_testkit --> pkg_tools pkg_webhook --> pkg_agent pkg_webhook --> pkg_agent_default_model pkg_webhook --> pkg_agent_presets @@ -1351,7 +1352,6 @@ flowchart TD | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-pwsh-persistent`](../packages/shell/tool-pwsh-persistent) | `shell` | [`agent`](../packages/core/agent), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-terminal`](../packages/terminal/tool-terminal) | `terminal` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`llm-replay`](../packages/test-support/llm-replay) | `test-support` | [`compaction`](../packages/compaction/compaction), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | `llm` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`session`](../packages/core/session) | @@ -1364,6 +1364,7 @@ flowchart TD | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-presets`](../packages/preset/agent-presets), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | | [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | | [`tool-pwsh`](../packages/shell/tool-pwsh) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | +| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`webhook`](../packages/webhook/webhook) | `webhook` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-presets`](../packages/preset/agent-presets), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 04c2f2a35b..e732988c84 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -856,12 +856,6 @@ flowchart TD pkg_tool_terminal --> pkg_system_prompt pkg_tool_terminal --> pkg_terminal pkg_tool_terminal --> pkg_tools - pkg_agent_loop_testkit --> pkg_agent - pkg_agent_loop_testkit --> pkg_llm - pkg_agent_loop_testkit --> pkg_session - pkg_agent_loop_testkit --> pkg_session_projection - pkg_agent_loop_testkit --> pkg_system_prompt - pkg_agent_loop_testkit --> pkg_tools pkg_llm_replay --> pkg_compaction pkg_llm_replay --> pkg_deepseek_llm_api_extensions pkg_llm_replay --> pkg_llm @@ -935,6 +929,13 @@ flowchart TD pkg_tool_pwsh --> pkg_system_prompt pkg_tool_pwsh --> pkg_tools pkg_tool_pwsh --> pkg_user_approval + pkg_agent_loop_testkit --> pkg_agent + pkg_agent_loop_testkit --> pkg_agent_loop + pkg_agent_loop_testkit --> pkg_llm + pkg_agent_loop_testkit --> pkg_session + pkg_agent_loop_testkit --> pkg_session_projection + pkg_agent_loop_testkit --> pkg_system_prompt + pkg_agent_loop_testkit --> pkg_tools pkg_webhook --> pkg_agent pkg_webhook --> pkg_agent_default_model pkg_webhook --> pkg_agent_presets @@ -1353,7 +1354,6 @@ flowchart TD | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-pwsh-persistent`](../packages/shell/tool-pwsh-persistent) | `shell` | [`agent`](../packages/core/agent), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-terminal`](../packages/terminal/tool-terminal) | `terminal` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) | -| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`llm-replay`](../packages/test-support/llm-replay) | `test-support` | [`compaction`](../packages/compaction/compaction), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tool-workflow`](../packages/workflow/tool-workflow) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | `llm` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`session`](../packages/core/session) | @@ -1366,6 +1366,7 @@ flowchart TD | [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-presets`](../packages/preset/agent-presets), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) | | [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | | [`tool-pwsh`](../packages/shell/tool-pwsh) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval) | +| [`agent-loop-testkit`](../packages/test-support/agent-loop-testkit) | `test-support` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`webhook`](../packages/webhook/webhook) | `webhook` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-presets`](../packages/preset/agent-presets), [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-presets`](../packages/preset/agent-presets), [`attachment`](../packages/attachment/attachment), [`invariants`](../packages/runtime-diagnostics/invariants), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval), [`util-time`](../packages/util/time) | | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) | From c3447a2c15e4cf71cb0a94eb89462eda0a9f7420 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Tue, 1 Sep 2026 22:00:59 +0800 Subject: [PATCH 21/26] test(headless): cover pre-turn inbox events --- .../bundle/headless/tests/headless.spec.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index 9330b1372d..61a2b98f45 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -143,6 +143,25 @@ describe('headless runner', () => { await test.ctx.fiber.dispose() }) + it('ignores durable inbox events before the first owned turn', async () => { + const test = await bench({ + afterPrompt(session, message) { + session.append('agent/inbox/spliced', { + target: 'next-turn', + start: 0, + inserted: [message], + }) + appendTurn(session, 1, message, 'answer after inbox activity', true) + }, + }) + expect(await test.run()).toMatchObject({ + code: 0, + out: 'answer after inbox activity\n', + err: '', + }) + await test.ctx.fiber.dispose() + }) + it('waits for asynchronously appended events instead of racing Agent idleness', async () => { const test = await bench({ afterPrompt: async (session, message) => { From 8fa72e3d6011068b654091993fe43a1eeaac0bc4 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 2 Sep 2026 11:26:45 +0800 Subject: [PATCH 22/26] fix(chat): settle scroll sample before resize follow --- ...r-scroll-attribution-observed-top-ledger.i18n.yaml | 4 ++-- ...6-reader-scroll-attribution-observed-top-ledger.md | 8 +++++--- ...eader-scroll-attribution-observed-top-ledger.zh.md | 8 +++++--- packages/client/ui-chat/README.i18n.yaml | 4 ++-- packages/client/ui-chat/README.md | 2 +- packages/client/ui-chat/README.zh.md | 2 +- packages/client/ui-chat/src/client/chat/ChatView.tsx | 10 +++++++++- .../client/ui-chat/tests/chat-view.client.spec.tsx | 11 +++++++++-- 8 files changed, 34 insertions(+), 15 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.i18n.yaml index 841f1c8442..ad58c45ddb 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md -2026-08-06-reader-scroll-attribution-observed-top-ledger.md: b55bbc39f6e1f24bb7751b7743da23736abbd06b -2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md: e38ead6c9b80e41b37556172bd6c1f411858b6ed +2026-08-06-reader-scroll-attribution-observed-top-ledger.md: d948996b10f200f7dcf5da597b0bf80b40bd801f +2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md: 9659930a2d3571d03f4d3b02d58ea78929dcf3c6 diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md index b55bbc39f6..d948996b10 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md +++ b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md @@ -10,7 +10,7 @@ ChatView's bottom-follow recognized only wheel/trackpad gestures as reader input ## Decision -Reader input is no longer identified by device. ChatView keeps an observed-top ledger (`observedTopRef`): the last `scrollTop` either delivered on the main thread or written by the component, recorded synchronously at every programmatic write site — bottom follow, open restore, prepend anchoring, resize follow, and scroll delivery itself. When a scroll event arrives, a position that deviates from `min(ledger, floor)` by more than half a pixel is reader input; a position on the ledger (a delayed programmatic delivery) or exactly on the shrunken floor (a browser clamp after content shrank) preserves the current ownership state. Ownership then changes only through reader input under the existing threshold rule: within `FOLLOW_THRESHOLD` of the floor re-pins, beyond it releases follow and shows Back to bottom. The wheel listener and its epoch bookkeeping are deleted; the component listens to `scroll` alone, so wheel, touch, scrollbar, keyboard, and any future input source are covered by one rule. +Reader input is no longer identified by device. ChatView keeps an observed-top ledger (`observedTopRef`): the last `scrollTop` either delivered on the main thread or written by the component, recorded synchronously at every programmatic write site — bottom follow, open restore, prepend anchoring, resize follow, and scroll delivery itself. When a scroll event arrives, a position that deviates from `min(ledger, floor)` by more than half a pixel is reader input; a position on the ledger (a delayed programmatic delivery) or exactly on the shrunken floor (a browser clamp after content shrank) preserves the current ownership state. Ownership then changes only through reader input under the existing threshold rule: within `FOLLOW_THRESHOLD` of the floor re-pins, beyond it releases follow and shows Back to bottom. Raw scroll events only schedule a sample, capped at one per 500 ms and finalized by `scrollend`. A `ResizeObserver` notification first flushes any pending sample against the resized floor; only the resulting ownership may follow the new floor. The wheel listener and its epoch bookkeeping are deleted; the component listens to `scroll` alone, so wheel, touch, scrollbar, keyboard, and any future input source are covered by one rule. ## Contract change: coalesced shrink-plus-regrow clamps @@ -18,7 +18,7 @@ A shrink clamp whose layout regrows within the same rendering update before the ## Testing -Unit specs in `packages/client/ui-chat/tests/chat-view.client.spec.tsx` pin the ledger contract directly: a `readerScroll` helper delivers a position the component never wrote, programmatic deliveries land on the ledger, and the stream-finalization shrink clamp keeps following. Two scenarios in `apps/web/tests/chat-scroll-contract.e2e.ts` extend the [browser e2e lane](../testing/2026-07-24-web-gui-browser-e2e-lane.md): keyboard paging over a settled transcript and a touch-style momentum fling against paced streaming, both red under the wheel-only implementation and green under the ledger. +Unit specs in `packages/client/ui-chat/tests/chat-view.client.spec.tsx` pin the ledger contract directly: a `readerScroll` helper delivers a position the component never wrote, programmatic deliveries land on the ledger, the stream-finalization shrink clamp keeps following, and a resize settles queued programmatic and reader deliveries before choosing whether to follow. Two scenarios in `apps/web/tests/chat-scroll-contract.e2e.ts` extend the [browser e2e lane](../testing/2026-07-24-web-gui-browser-e2e-lane.md): keyboard paging over a settled transcript and a touch-style momentum fling against paced streaming, both red under the wheel-only implementation and green under the ledger. The lane's Chromium cannot synthesize any non-wheel device scrolling, which bounds what the e2e can drive for real: `Input.synthesizeScrollGesture` with a touch source and hand-rolled `Input.dispatchTouchEvent` sequences deliver DOM events but never move a scroller (headless and headed-under-Xvfb alike); the `default` gesture source synthesizes wheel events; and compositor scrollbars ignore synthetic mouse input entirely, with a gutter visible only when `--hide-scrollbars` is removed. Keyboard is the one working non-wheel primitive, so it carries the real-input-pipeline proof, and the fling scenario replays touch's signature — per-frame decaying displacements the component never authored — through the scrollport directly. @@ -30,8 +30,10 @@ The lane's Chromium cannot synthesize any non-wheel device scrolling, which boun **Absorb the coalesced shrink-plus-regrow clamp with heuristics.** Floor-mismatch grace windows or deferred rAF re-checks could keep the raced clamp from reading as the reader. Rejected: streaming rewrites the floor at chunk pace (24 ms) against ~16 ms frames, so any grace window either swallows genuine touch input during streaming — reopening the bug this change fixes — or is too short to cover the race it targets. The mis-attribution is accepted and recoverable instead. +**Drop resize follow while a scroll sample is pending.** Rejected: a delayed programmatic scroll delivery can still be queued when streaming or a tool disclosure raises the floor. Ignoring that resize can leave a pinned reader one content increment above the tail; settling the sample first distinguishes it from a queued reader move without removing throttling. + **Drive real touch and scrollbar devices in e2e.** Rejected by the environment, not by preference: every synthesis path (CDP touch gestures, touch event sequences, synthetic mouse on classic scrollbars, headed under Xvfb) was probed and cannot scroll; the details live in Testing above. ## Consequences -Every reader input owns bottom-follow uniformly, with less code: the wheel listener, its epoch counter, and the pre-input baseline bookkeeping are gone, and attribution rides state the component already maintained. The sticky-composer note's layout, wheel chaining, and prepend-anchoring decisions are untouched and remain authoritative; its wheel-only input rule is superseded by this note. The cost is the contract change above — a coalesced non-React shrink-plus-regrow clamp now pauses follow until the reader returns to the floor or presses Back to bottom — traded for touch, scrollbar, and keyboard correctness during streaming. The e2e lane gains non-wheel coverage only within what its browser can synthesize; if gesture synthesis starts working in a future Chromium, the fling emulation can be replaced by real touch strokes without changing the asserted contract. +Every reader input owns bottom-follow uniformly, with less code: the wheel listener, its epoch counter, and the pre-input baseline bookkeeping are gone, and attribution rides state the component already maintained. A content resize may advance one throttled sample, making the changed floor an explicit ownership decision point. The sticky-composer note's layout, wheel chaining, and prepend-anchoring decisions are untouched and remain authoritative; its wheel-only input rule is superseded by this note. The cost is the contract change above — a coalesced non-React shrink-plus-regrow clamp now pauses follow until the reader returns to the floor or presses Back to bottom — traded for touch, scrollbar, and keyboard correctness during streaming. The e2e lane gains non-wheel coverage only within what its browser can synthesize; if gesture synthesis starts working in a future Chromium, the fling emulation can be replaced by real touch strokes without changing the asserted contract. diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md index e38ead6c9b..9659930a2d 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md @@ -10,7 +10,7 @@ ChatView 的贴底跟随此前只把滚轮/触控板手势识别为读者输 ## 决策 -读者输入不再依据设备来识别。ChatView 维护一份 observed-top ledger(`observedTopRef`):即最近一次由主线程交付、或由组件自身写入的 `scrollTop`,并在每一个程序化写入点(贴底跟随、打开时恢复、前置锚定、尺寸变化跟随以及滚动交付本身)同步记录。滚动事件到达时,偏离 `min(ledger, floor)` 超过半像素的位置即为读者输入;落在 ledger 上的位置(迟到的程序化交付),或恰好落在收缩后底部上的位置(内容收缩后的浏览器钳制),则维持当前的所有权状态。此后所有权只经由读者输入、按既有阈值规则变化:位置距底部在 `FOLLOW_THRESHOLD` 以内则重新贴底,超出则释放跟随并显示「回到底部」。滚轮监听器及其 epoch 簿记已删除;组件只监听 `scroll`,因此滚轮、触控、滚动条、键盘以及未来任何输入来源都由同一条规则覆盖。 +读者输入不再依据设备来识别。ChatView 维护一份 observed-top ledger(`observedTopRef`):即最近一次由主线程交付、或由组件自身写入的 `scrollTop`,并在每一个程序化写入点(贴底跟随、打开时恢复、前置锚定、尺寸变化跟随以及滚动交付本身)同步记录。滚动事件到达时,偏离 `min(ledger, floor)` 超过半像素的位置即为读者输入;落在 ledger 上的位置(迟到的程序化交付),或恰好落在收缩后底部上的位置(内容收缩后的浏览器钳制),则维持当前的所有权状态。此后所有权只经由读者输入、按既有阈值规则变化:位置距底部在 `FOLLOW_THRESHOLD` 以内则重新贴底,超出则释放跟随并显示「回到底部」。原始 `scroll` 事件只安排采样,采样频率上限为每 500 ms 一次,并由 `scrollend` 完成最终采样。`ResizeObserver` 通知会先根据尺寸变化后的底部刷新任何待处理采样;只有结算后的所有权才能跟随新底部。滚轮监听器及其 epoch 簿记已删除;组件只监听 `scroll`,因此滚轮、触控、滚动条、键盘以及未来任何输入来源都由同一条规则覆盖。 ## 约定变更:收缩与重新增长被合并的钳制 @@ -18,7 +18,7 @@ ChatView 的贴底跟随此前只把滚轮/触控板手势识别为读者输 ## 测试 -`packages/client/ui-chat/tests/chat-view.client.spec.tsx` 中的单元测试直接钉住 ledger 约定:`readerScroll` 辅助函数交付一个组件从未写入过的位置,程序化交付落在 ledger 上,流收尾阶段的收缩钳制保持跟随。`apps/web/tests/chat-scroll-contract.e2e.ts` 中的两个场景扩展了[浏览器 e2e 车道](../testing/2026-07-24-web-gui-browser-e2e-lane.zh.md):在已停稳的 transcript 上做键盘翻页,以及对着按节奏推进的流式输出做一次触控式惯性快滑(momentum fling);两者在仅认滚轮的实现下均为红、在 ledger 下均为绿。 +`packages/client/ui-chat/tests/chat-view.client.spec.tsx` 中的单元测试直接钉住 ledger 约定:`readerScroll` 辅助函数交付一个组件从未写入过的位置,程序化交付落在 ledger 上,流收尾阶段的收缩钳制保持跟随,而尺寸变化会在决定是否跟随前先结算排队中的程序化交付和读者交付。`apps/web/tests/chat-scroll-contract.e2e.ts` 中的两个场景扩展了[浏览器 e2e 车道](../testing/2026-07-24-web-gui-browser-e2e-lane.zh.md):在已停稳的 transcript 上做键盘翻页,以及对着按节奏推进的流式输出做一次触控式惯性快滑(momentum fling);两者在仅认滚轮的实现下均为红、在 ledger 下均为绿。 该车道的 Chromium 无法合成任何非滚轮的设备滚动,这限定了 e2e 能真实驱动的范围:触控来源的 `Input.synthesizeScrollGesture` 与手工构造的 `Input.dispatchTouchEvent` 序列都能交付 DOM 事件,却从不移动滚动容器(无头模式与 Xvfb 下的有头模式皆然);`default` 手势来源合成的是滚轮事件;合成器滚动条则完全无视合成的鼠标输入,且只有移除 `--hide-scrollbars` 后才能看到滚动条槽。键盘是唯一可用的非滚轮原语,因此由它承担真实输入流水线的证明;快滑场景则把触控的特征(组件从未写入过的逐帧衰减位移)直接回放进滚动容器。 @@ -30,8 +30,10 @@ ChatView 的贴底跟随此前只把滚轮/触控板手势识别为读者输 **用启发式吸收收缩与重新增长被合并的钳制。** 针对底部失配的宽限窗口,或推迟到 rAF 的复查,本可让这种竞态下的钳制不被判读为读者。否决:流式输出以分片节奏(24 ms)改写底部,而帧间隔约 16 ms,因此任何宽限窗口要么会在流式输出期间吞掉真实的触控输入(重新打开本次变更所修复的缺陷),要么短到盖不住它想针对的竞态。转而接受这一误归因,它是可恢复的。 +**有滚动采样待处理时放弃尺寸变化跟随。** 否决:当流式输出或 Tool 披露抬高底部时,延迟的程序化滚动交付可能仍在排队。忽略这次尺寸变化会让已贴底的读者停在尾部上方一段内容处;先结算采样既可以把它与排队中的读者移动区分开,又无需移除节流。 + **在 e2e 中驱动真实的触控与滚动条设备。** 否决来自环境,而非偏好取舍:每条合成路径(CDP 触控手势、触控事件序列、经典滚动条上的合成鼠标、Xvfb 下的有头模式)都逐一试过,均无法滚动;细节见上文「测试」一节。 ## 后果 -每种读者输入现在都以同一方式拥有贴底跟随,而代码更少:滚轮监听器、它的 epoch 计数器以及输入前基线簿记均已移除,归因搭载在组件本就维护的状态之上。sticky-composer 笔记中的布局、滚轮链式处理与前置锚定决策原样保留,仍为权威;其窄范围的输入来源规则由本笔记取代。代价就是上文的约定变更:一次收缩与重新增长被合并的非 React 钳制现在会暂停跟随,直到读者回到底部或按下「回到底部」;以此换来流式输出期间触控、滚动条与键盘的正确性。e2e 车道获得的非滚轮覆盖仅限其浏览器能够合成的范围;若手势合成在未来某个 Chromium 版本中开始可用,可以在不改变所断言约定的前提下,把快滑模拟替换为真实的触控划动。 +每种读者输入现在都以同一方式拥有贴底跟随,而代码更少:滚轮监听器、它的 epoch 计数器以及输入前基线簿记均已移除,归因搭载在组件本就维护的状态之上。一次内容尺寸变化可以提前执行一次被节流的采样,使变化后的底部成为明确的所有权决策点。sticky-composer 笔记中的布局、滚轮链式处理与前置锚定决策原样保留,仍为权威;其窄范围的输入来源规则由本笔记取代。代价就是上文的约定变更:一次收缩与重新增长被合并的非 React 钳制现在会暂停跟随,直到读者回到底部或按下「回到底部」;以此换来流式输出期间触控、滚动条与键盘的正确性。e2e 车道获得的非滚轮覆盖仅限其浏览器能够合成的范围;若手势合成在未来某个 Chromium 版本中开始可用,可以在不改变所断言约定的前提下,把快滑模拟替换为真实的触控划动。 diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 8183f95981..7d3a1e034f 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md -README.md: 79214bf2feb8384cecbb152aa31af162dc6dfdde -README.zh.md: 674959e1974c74abba75f179eff50fe8488458fc +README.md: 1bdb036a7f1ce35970f3010bcec7d2bdef973545 +README.zh.md: c7270071dbb2b3a82343f84890c5eb28e1096169 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 79214bf2fe..1bdb036a7f 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -46,7 +46,7 @@ Settings → General exposes a persisted `Normal` / `Compact` conversation-displ ## Scroll ownership -Chat restores semantic anchors across history prepend and renderer remounts. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer ([loaded-Turn navigation](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.md)). +Chat restores semantic anchors across history prepend and renderer remounts. Raw scroll events are throttled; a content resize first settles any queued sample against the new floor, then `ResizeObserver` follows only while the observed-top ledger still assigns bottom ownership. Pinned resize follow selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer ([reader scroll attribution](../../../.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md), [loaded-Turn navigation](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.md)). ----- diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 674959e197..c7270071db 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -46,7 +46,7 @@ Chat 会为每个非空的初始或恢复请求、显式消息序列起点或真 ## 滚动归属 -Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载 Turn;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃 Turn。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内([已加载 Turn 导航](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.zh.md))。 +Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点。原始滚动事件会被节流;内容尺寸变化会先根据新底部结算任何待处理采样,然后 `ResizeObserver` 仅在 observed-top ledger 仍将底部归给跟随时追随它。已贴底的尺寸变化跟随无需读取行几何就选中最后一个已加载 Turn。读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃 Turn。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内([读者滚动归因](../../../.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md)、[已加载 Turn 导航](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.zh.md))。 ----- diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 403eecd96f..296c7073ad 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -309,6 +309,7 @@ export function ChatView({ const [atBottom, setAtBottom] = useState(() => chatScroll.read() === null) const atBottomRef = useRef(atBottom) const scrollSamplePendingRef = useRef(false) + const flushScrollSampleRef = useRef<(() => void) | null>(null) const [, setScrollSampleTick] = useState(0) const [activeTurn, setActiveTurn] = useState( () => turnNavigationItems.at(-1)?.turn ?? null, @@ -599,12 +600,14 @@ export function ChatView({ scrollSamplePendingRef.current = true sampleTimer ??= window.setTimeout(sample, SCROLL_SAMPLE_INTERVAL_MS) } + flushScrollSampleRef.current = sample el.addEventListener('scroll', onScroll, { passive: true }) el.addEventListener('scrollend', sample, { passive: true }) return () => { el.removeEventListener('scroll', onScroll) el.removeEventListener('scrollend', sample) if (sampleTimer !== undefined) window.clearTimeout(sampleTimer) + if (flushScrollSampleRef.current === sample) flushScrollSampleRef.current = null scrollSamplePendingRef.current = false } }, []) @@ -613,7 +616,12 @@ export function ChatView({ // initializer a function initial value would need never exists. const followRef = useRef<(() => void) | null>(null) followRef.current = () => { - if (scrollSamplePendingRef.current) return + // A resize changes the floor used for ownership. Settle a queued scroll + // against that geometry before deciding whether the new floor may follow. + if (scrollSamplePendingRef.current) { + flushScrollSampleRef.current?.() + return + } const local = listRef.current if (local !== null && atBottomRef.current) { const el = scrollerOf(local) diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 9e0818f37c..96cbbf9dbe 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -2343,7 +2343,7 @@ describe('ChatView', () => { expect(view.getByLabelText('回到底部')).toBeTruthy() }) - it('one ResizeObserver owns pinned dynamic-height follow and ignores growth while away', () => { + it('one ResizeObserver settles scroll ownership before following dynamic-height growth', () => { let notify: (() => void) | undefined const observe = vi.fn() class ResizeObserverStub { @@ -2363,13 +2363,20 @@ describe('ChatView', () => { scroller.scrollTop = 700 fireEvent.scroll(scroller) fireEvent(scroller, new Event('scrollend')) + // A delayed programmatic delivery may still be queued when the floor + // grows. The resize must settle it before preserving pinned ownership. + fireEvent.scroll(scroller) Object.defineProperty(scroller, 'scrollHeight', { value: 1_200, writable: true }) act(() => { notify?.() }) expect(scroller.scrollTop).toBe(1_200) - readerScroll(scroller, 200) + // A queued reader movement must win the same decision instead of being + // mistaken for a programmatic delivery and pulled to the new floor. + scroller.scrollTop = 200 + fireEvent.scroll(scroller) Object.defineProperty(scroller, 'scrollHeight', { value: 1_400, writable: true }) act(() => { notify?.() }) expect(scroller.scrollTop).toBe(200) + expect(view.getByLabelText('回到底部')).toBeTruthy() expect(observe).toHaveBeenCalledTimes(1) }) From c8f76ca39976472301cd482f91f8ad582b3b94cb Mon Sep 17 00:00:00 2001 From: _Kerman Date: Wed, 2 Sep 2026 11:36:46 +0800 Subject: [PATCH 23/26] chore: remove unrelated changes from Inbox PR --- ...r-scroll-attribution-observed-top-ledger.i18n.yaml | 4 ++-- ...6-reader-scroll-attribution-observed-top-ledger.md | 8 +++----- ...eader-scroll-attribution-observed-top-ledger.zh.md | 8 +++----- apps/cli/tests/profiles/headless/tests/ptc.e2e.ts | 2 +- packages/client/ui-chat/README.i18n.yaml | 4 ++-- packages/client/ui-chat/README.md | 2 +- packages/client/ui-chat/README.zh.md | 2 +- packages/client/ui-chat/src/client/chat/ChatView.tsx | 10 +--------- .../client/ui-chat/tests/chat-view.client.spec.tsx | 11 ++--------- 9 files changed, 16 insertions(+), 35 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.i18n.yaml index ad58c45ddb..841f1c8442 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md -2026-08-06-reader-scroll-attribution-observed-top-ledger.md: d948996b10f200f7dcf5da597b0bf80b40bd801f -2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md: 9659930a2d3571d03f4d3b02d58ea78929dcf3c6 +2026-08-06-reader-scroll-attribution-observed-top-ledger.md: b55bbc39f6e1f24bb7751b7743da23736abbd06b +2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md: e38ead6c9b80e41b37556172bd6c1f411858b6ed diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md index d948996b10..b55bbc39f6 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md +++ b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md @@ -10,7 +10,7 @@ ChatView's bottom-follow recognized only wheel/trackpad gestures as reader input ## Decision -Reader input is no longer identified by device. ChatView keeps an observed-top ledger (`observedTopRef`): the last `scrollTop` either delivered on the main thread or written by the component, recorded synchronously at every programmatic write site — bottom follow, open restore, prepend anchoring, resize follow, and scroll delivery itself. When a scroll event arrives, a position that deviates from `min(ledger, floor)` by more than half a pixel is reader input; a position on the ledger (a delayed programmatic delivery) or exactly on the shrunken floor (a browser clamp after content shrank) preserves the current ownership state. Ownership then changes only through reader input under the existing threshold rule: within `FOLLOW_THRESHOLD` of the floor re-pins, beyond it releases follow and shows Back to bottom. Raw scroll events only schedule a sample, capped at one per 500 ms and finalized by `scrollend`. A `ResizeObserver` notification first flushes any pending sample against the resized floor; only the resulting ownership may follow the new floor. The wheel listener and its epoch bookkeeping are deleted; the component listens to `scroll` alone, so wheel, touch, scrollbar, keyboard, and any future input source are covered by one rule. +Reader input is no longer identified by device. ChatView keeps an observed-top ledger (`observedTopRef`): the last `scrollTop` either delivered on the main thread or written by the component, recorded synchronously at every programmatic write site — bottom follow, open restore, prepend anchoring, resize follow, and scroll delivery itself. When a scroll event arrives, a position that deviates from `min(ledger, floor)` by more than half a pixel is reader input; a position on the ledger (a delayed programmatic delivery) or exactly on the shrunken floor (a browser clamp after content shrank) preserves the current ownership state. Ownership then changes only through reader input under the existing threshold rule: within `FOLLOW_THRESHOLD` of the floor re-pins, beyond it releases follow and shows Back to bottom. The wheel listener and its epoch bookkeeping are deleted; the component listens to `scroll` alone, so wheel, touch, scrollbar, keyboard, and any future input source are covered by one rule. ## Contract change: coalesced shrink-plus-regrow clamps @@ -18,7 +18,7 @@ A shrink clamp whose layout regrows within the same rendering update before the ## Testing -Unit specs in `packages/client/ui-chat/tests/chat-view.client.spec.tsx` pin the ledger contract directly: a `readerScroll` helper delivers a position the component never wrote, programmatic deliveries land on the ledger, the stream-finalization shrink clamp keeps following, and a resize settles queued programmatic and reader deliveries before choosing whether to follow. Two scenarios in `apps/web/tests/chat-scroll-contract.e2e.ts` extend the [browser e2e lane](../testing/2026-07-24-web-gui-browser-e2e-lane.md): keyboard paging over a settled transcript and a touch-style momentum fling against paced streaming, both red under the wheel-only implementation and green under the ledger. +Unit specs in `packages/client/ui-chat/tests/chat-view.client.spec.tsx` pin the ledger contract directly: a `readerScroll` helper delivers a position the component never wrote, programmatic deliveries land on the ledger, and the stream-finalization shrink clamp keeps following. Two scenarios in `apps/web/tests/chat-scroll-contract.e2e.ts` extend the [browser e2e lane](../testing/2026-07-24-web-gui-browser-e2e-lane.md): keyboard paging over a settled transcript and a touch-style momentum fling against paced streaming, both red under the wheel-only implementation and green under the ledger. The lane's Chromium cannot synthesize any non-wheel device scrolling, which bounds what the e2e can drive for real: `Input.synthesizeScrollGesture` with a touch source and hand-rolled `Input.dispatchTouchEvent` sequences deliver DOM events but never move a scroller (headless and headed-under-Xvfb alike); the `default` gesture source synthesizes wheel events; and compositor scrollbars ignore synthetic mouse input entirely, with a gutter visible only when `--hide-scrollbars` is removed. Keyboard is the one working non-wheel primitive, so it carries the real-input-pipeline proof, and the fling scenario replays touch's signature — per-frame decaying displacements the component never authored — through the scrollport directly. @@ -30,10 +30,8 @@ The lane's Chromium cannot synthesize any non-wheel device scrolling, which boun **Absorb the coalesced shrink-plus-regrow clamp with heuristics.** Floor-mismatch grace windows or deferred rAF re-checks could keep the raced clamp from reading as the reader. Rejected: streaming rewrites the floor at chunk pace (24 ms) against ~16 ms frames, so any grace window either swallows genuine touch input during streaming — reopening the bug this change fixes — or is too short to cover the race it targets. The mis-attribution is accepted and recoverable instead. -**Drop resize follow while a scroll sample is pending.** Rejected: a delayed programmatic scroll delivery can still be queued when streaming or a tool disclosure raises the floor. Ignoring that resize can leave a pinned reader one content increment above the tail; settling the sample first distinguishes it from a queued reader move without removing throttling. - **Drive real touch and scrollbar devices in e2e.** Rejected by the environment, not by preference: every synthesis path (CDP touch gestures, touch event sequences, synthetic mouse on classic scrollbars, headed under Xvfb) was probed and cannot scroll; the details live in Testing above. ## Consequences -Every reader input owns bottom-follow uniformly, with less code: the wheel listener, its epoch counter, and the pre-input baseline bookkeeping are gone, and attribution rides state the component already maintained. A content resize may advance one throttled sample, making the changed floor an explicit ownership decision point. The sticky-composer note's layout, wheel chaining, and prepend-anchoring decisions are untouched and remain authoritative; its wheel-only input rule is superseded by this note. The cost is the contract change above — a coalesced non-React shrink-plus-regrow clamp now pauses follow until the reader returns to the floor or presses Back to bottom — traded for touch, scrollbar, and keyboard correctness during streaming. The e2e lane gains non-wheel coverage only within what its browser can synthesize; if gesture synthesis starts working in a future Chromium, the fling emulation can be replaced by real touch strokes without changing the asserted contract. +Every reader input owns bottom-follow uniformly, with less code: the wheel listener, its epoch counter, and the pre-input baseline bookkeeping are gone, and attribution rides state the component already maintained. The sticky-composer note's layout, wheel chaining, and prepend-anchoring decisions are untouched and remain authoritative; its wheel-only input rule is superseded by this note. The cost is the contract change above — a coalesced non-React shrink-plus-regrow clamp now pauses follow until the reader returns to the floor or presses Back to bottom — traded for touch, scrollbar, and keyboard correctness during streaming. The e2e lane gains non-wheel coverage only within what its browser can synthesize; if gesture synthesis starts working in a future Chromium, the fling emulation can be replaced by real touch strokes without changing the asserted contract. diff --git a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md index 9659930a2d..e38ead6c9b 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md @@ -10,7 +10,7 @@ ChatView 的贴底跟随此前只把滚轮/触控板手势识别为读者输 ## 决策 -读者输入不再依据设备来识别。ChatView 维护一份 observed-top ledger(`observedTopRef`):即最近一次由主线程交付、或由组件自身写入的 `scrollTop`,并在每一个程序化写入点(贴底跟随、打开时恢复、前置锚定、尺寸变化跟随以及滚动交付本身)同步记录。滚动事件到达时,偏离 `min(ledger, floor)` 超过半像素的位置即为读者输入;落在 ledger 上的位置(迟到的程序化交付),或恰好落在收缩后底部上的位置(内容收缩后的浏览器钳制),则维持当前的所有权状态。此后所有权只经由读者输入、按既有阈值规则变化:位置距底部在 `FOLLOW_THRESHOLD` 以内则重新贴底,超出则释放跟随并显示「回到底部」。原始 `scroll` 事件只安排采样,采样频率上限为每 500 ms 一次,并由 `scrollend` 完成最终采样。`ResizeObserver` 通知会先根据尺寸变化后的底部刷新任何待处理采样;只有结算后的所有权才能跟随新底部。滚轮监听器及其 epoch 簿记已删除;组件只监听 `scroll`,因此滚轮、触控、滚动条、键盘以及未来任何输入来源都由同一条规则覆盖。 +读者输入不再依据设备来识别。ChatView 维护一份 observed-top ledger(`observedTopRef`):即最近一次由主线程交付、或由组件自身写入的 `scrollTop`,并在每一个程序化写入点(贴底跟随、打开时恢复、前置锚定、尺寸变化跟随以及滚动交付本身)同步记录。滚动事件到达时,偏离 `min(ledger, floor)` 超过半像素的位置即为读者输入;落在 ledger 上的位置(迟到的程序化交付),或恰好落在收缩后底部上的位置(内容收缩后的浏览器钳制),则维持当前的所有权状态。此后所有权只经由读者输入、按既有阈值规则变化:位置距底部在 `FOLLOW_THRESHOLD` 以内则重新贴底,超出则释放跟随并显示「回到底部」。滚轮监听器及其 epoch 簿记已删除;组件只监听 `scroll`,因此滚轮、触控、滚动条、键盘以及未来任何输入来源都由同一条规则覆盖。 ## 约定变更:收缩与重新增长被合并的钳制 @@ -18,7 +18,7 @@ ChatView 的贴底跟随此前只把滚轮/触控板手势识别为读者输 ## 测试 -`packages/client/ui-chat/tests/chat-view.client.spec.tsx` 中的单元测试直接钉住 ledger 约定:`readerScroll` 辅助函数交付一个组件从未写入过的位置,程序化交付落在 ledger 上,流收尾阶段的收缩钳制保持跟随,而尺寸变化会在决定是否跟随前先结算排队中的程序化交付和读者交付。`apps/web/tests/chat-scroll-contract.e2e.ts` 中的两个场景扩展了[浏览器 e2e 车道](../testing/2026-07-24-web-gui-browser-e2e-lane.zh.md):在已停稳的 transcript 上做键盘翻页,以及对着按节奏推进的流式输出做一次触控式惯性快滑(momentum fling);两者在仅认滚轮的实现下均为红、在 ledger 下均为绿。 +`packages/client/ui-chat/tests/chat-view.client.spec.tsx` 中的单元测试直接钉住 ledger 约定:`readerScroll` 辅助函数交付一个组件从未写入过的位置,程序化交付落在 ledger 上,流收尾阶段的收缩钳制保持跟随。`apps/web/tests/chat-scroll-contract.e2e.ts` 中的两个场景扩展了[浏览器 e2e 车道](../testing/2026-07-24-web-gui-browser-e2e-lane.zh.md):在已停稳的 transcript 上做键盘翻页,以及对着按节奏推进的流式输出做一次触控式惯性快滑(momentum fling);两者在仅认滚轮的实现下均为红、在 ledger 下均为绿。 该车道的 Chromium 无法合成任何非滚轮的设备滚动,这限定了 e2e 能真实驱动的范围:触控来源的 `Input.synthesizeScrollGesture` 与手工构造的 `Input.dispatchTouchEvent` 序列都能交付 DOM 事件,却从不移动滚动容器(无头模式与 Xvfb 下的有头模式皆然);`default` 手势来源合成的是滚轮事件;合成器滚动条则完全无视合成的鼠标输入,且只有移除 `--hide-scrollbars` 后才能看到滚动条槽。键盘是唯一可用的非滚轮原语,因此由它承担真实输入流水线的证明;快滑场景则把触控的特征(组件从未写入过的逐帧衰减位移)直接回放进滚动容器。 @@ -30,10 +30,8 @@ ChatView 的贴底跟随此前只把滚轮/触控板手势识别为读者输 **用启发式吸收收缩与重新增长被合并的钳制。** 针对底部失配的宽限窗口,或推迟到 rAF 的复查,本可让这种竞态下的钳制不被判读为读者。否决:流式输出以分片节奏(24 ms)改写底部,而帧间隔约 16 ms,因此任何宽限窗口要么会在流式输出期间吞掉真实的触控输入(重新打开本次变更所修复的缺陷),要么短到盖不住它想针对的竞态。转而接受这一误归因,它是可恢复的。 -**有滚动采样待处理时放弃尺寸变化跟随。** 否决:当流式输出或 Tool 披露抬高底部时,延迟的程序化滚动交付可能仍在排队。忽略这次尺寸变化会让已贴底的读者停在尾部上方一段内容处;先结算采样既可以把它与排队中的读者移动区分开,又无需移除节流。 - **在 e2e 中驱动真实的触控与滚动条设备。** 否决来自环境,而非偏好取舍:每条合成路径(CDP 触控手势、触控事件序列、经典滚动条上的合成鼠标、Xvfb 下的有头模式)都逐一试过,均无法滚动;细节见上文「测试」一节。 ## 后果 -每种读者输入现在都以同一方式拥有贴底跟随,而代码更少:滚轮监听器、它的 epoch 计数器以及输入前基线簿记均已移除,归因搭载在组件本就维护的状态之上。一次内容尺寸变化可以提前执行一次被节流的采样,使变化后的底部成为明确的所有权决策点。sticky-composer 笔记中的布局、滚轮链式处理与前置锚定决策原样保留,仍为权威;其窄范围的输入来源规则由本笔记取代。代价就是上文的约定变更:一次收缩与重新增长被合并的非 React 钳制现在会暂停跟随,直到读者回到底部或按下「回到底部」;以此换来流式输出期间触控、滚动条与键盘的正确性。e2e 车道获得的非滚轮覆盖仅限其浏览器能够合成的范围;若手势合成在未来某个 Chromium 版本中开始可用,可以在不改变所断言约定的前提下,把快滑模拟替换为真实的触控划动。 +每种读者输入现在都以同一方式拥有贴底跟随,而代码更少:滚轮监听器、它的 epoch 计数器以及输入前基线簿记均已移除,归因搭载在组件本就维护的状态之上。sticky-composer 笔记中的布局、滚轮链式处理与前置锚定决策原样保留,仍为权威;其窄范围的输入来源规则由本笔记取代。代价就是上文的约定变更:一次收缩与重新增长被合并的非 React 钳制现在会暂停跟随,直到读者回到底部或按下「回到底部」;以此换来流式输出期间触控、滚动条与键盘的正确性。e2e 车道获得的非滚轮覆盖仅限其浏览器能够合成的范围;若手势合成在未来某个 Chromium 版本中开始可用,可以在不改变所断言约定的前提下,把快滑模拟替换为真实的触控划动。 diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index 98c55f58f9..8ee3affb8a 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -6,13 +6,13 @@ import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, ToolCallId, HarnessError } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { RUN_CODE_NAME, defineTool } from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 7d3a1e034f..8183f95981 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md -README.md: 1bdb036a7f1ce35970f3010bcec7d2bdef973545 -README.zh.md: c7270071dbb2b3a82343f84890c5eb28e1096169 +README.md: 79214bf2feb8384cecbb152aa31af162dc6dfdde +README.zh.md: 674959e1974c74abba75f179eff50fe8488458fc diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 1bdb036a7f..79214bf2fe 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -46,7 +46,7 @@ Settings → General exposes a persisted `Normal` / `Compact` conversation-displ ## Scroll ownership -Chat restores semantic anchors across history prepend and renderer remounts. Raw scroll events are throttled; a content resize first settles any queued sample against the new floor, then `ResizeObserver` follows only while the observed-top ledger still assigns bottom ownership. Pinned resize follow selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer ([reader scroll attribution](../../../.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.md), [loaded-Turn navigation](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.md)). +Chat restores semantic anchors across history prepend and renderer remounts. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer ([loaded-Turn navigation](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.md)). ----- diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index c7270071db..674959e197 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -46,7 +46,7 @@ Chat 会为每个非空的初始或恢复请求、显式消息序列起点或真 ## 滚动归属 -Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点。原始滚动事件会被节流;内容尺寸变化会先根据新底部结算任何待处理采样,然后 `ResizeObserver` 仅在 observed-top ledger 仍将底部归给跟随时追随它。已贴底的尺寸变化跟随无需读取行几何就选中最后一个已加载 Turn。读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃 Turn。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内([读者滚动归因](../../../.agents/notes/implemented/bug-fix/2026-08-06-reader-scroll-attribution-observed-top-ledger.zh.md)、[已加载 Turn 导航](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.zh.md))。 +Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载 Turn;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃 Turn。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内([已加载 Turn 导航](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.zh.md))。 ----- diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 296c7073ad..403eecd96f 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -309,7 +309,6 @@ export function ChatView({ const [atBottom, setAtBottom] = useState(() => chatScroll.read() === null) const atBottomRef = useRef(atBottom) const scrollSamplePendingRef = useRef(false) - const flushScrollSampleRef = useRef<(() => void) | null>(null) const [, setScrollSampleTick] = useState(0) const [activeTurn, setActiveTurn] = useState( () => turnNavigationItems.at(-1)?.turn ?? null, @@ -600,14 +599,12 @@ export function ChatView({ scrollSamplePendingRef.current = true sampleTimer ??= window.setTimeout(sample, SCROLL_SAMPLE_INTERVAL_MS) } - flushScrollSampleRef.current = sample el.addEventListener('scroll', onScroll, { passive: true }) el.addEventListener('scrollend', sample, { passive: true }) return () => { el.removeEventListener('scroll', onScroll) el.removeEventListener('scrollend', sample) if (sampleTimer !== undefined) window.clearTimeout(sampleTimer) - if (flushScrollSampleRef.current === sample) flushScrollSampleRef.current = null scrollSamplePendingRef.current = false } }, []) @@ -616,12 +613,7 @@ export function ChatView({ // initializer a function initial value would need never exists. const followRef = useRef<(() => void) | null>(null) followRef.current = () => { - // A resize changes the floor used for ownership. Settle a queued scroll - // against that geometry before deciding whether the new floor may follow. - if (scrollSamplePendingRef.current) { - flushScrollSampleRef.current?.() - return - } + if (scrollSamplePendingRef.current) return const local = listRef.current if (local !== null && atBottomRef.current) { const el = scrollerOf(local) diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 96cbbf9dbe..9e0818f37c 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -2343,7 +2343,7 @@ describe('ChatView', () => { expect(view.getByLabelText('回到底部')).toBeTruthy() }) - it('one ResizeObserver settles scroll ownership before following dynamic-height growth', () => { + it('one ResizeObserver owns pinned dynamic-height follow and ignores growth while away', () => { let notify: (() => void) | undefined const observe = vi.fn() class ResizeObserverStub { @@ -2363,20 +2363,13 @@ describe('ChatView', () => { scroller.scrollTop = 700 fireEvent.scroll(scroller) fireEvent(scroller, new Event('scrollend')) - // A delayed programmatic delivery may still be queued when the floor - // grows. The resize must settle it before preserving pinned ownership. - fireEvent.scroll(scroller) Object.defineProperty(scroller, 'scrollHeight', { value: 1_200, writable: true }) act(() => { notify?.() }) expect(scroller.scrollTop).toBe(1_200) - // A queued reader movement must win the same decision instead of being - // mistaken for a programmatic delivery and pulled to the new floor. - scroller.scrollTop = 200 - fireEvent.scroll(scroller) + readerScroll(scroller, 200) Object.defineProperty(scroller, 'scrollHeight', { value: 1_400, writable: true }) act(() => { notify?.() }) expect(scroller.scrollTop).toBe(200) - expect(view.getByLabelText('回到底部')).toBeTruthy() expect(observe).toHaveBeenCalledTimes(1) }) From 753effe602b5c49598843614d1caa33b6689dbf3 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 7 Sep 2026 20:52:06 +0800 Subject: [PATCH 24/26] fix(bench): rely on testkit session projection mounting mountAgentLoopTestDependencies registers SessionProjectionRegistry, so benchmark workers must not mount it again before resuming agents. --- benchmarks/agent-continuation/agent-continuation.worker.ts | 2 -- benchmarks/session-open/session-open.worker.ts | 6 ++++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/benchmarks/agent-continuation/agent-continuation.worker.ts b/benchmarks/agent-continuation/agent-continuation.worker.ts index 7e676e9971..91faa5f347 100644 --- a/benchmarks/agent-continuation/agent-continuation.worker.ts +++ b/benchmarks/agent-continuation/agent-continuation.worker.ts @@ -10,7 +10,6 @@ import { createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, LlmResolvedModelInfo, StreamChunk } from '@deepseek-ai/dsh-llm' import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' -import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { defineContentToolFixture } from '@deepseek-ai/dsh-tools' import { assertBuiltBenchmarkRuntime } from '../support/built-worker.ts' import { PARENT_ID, response, resultText, syntheticHistory, TIME_ZERO, WORKLOAD } from './workload.ts' @@ -82,7 +81,6 @@ async function measure(root: string, scenario: string): Promise { const ctx = new Context() - await ctx.plugin(SessionProjectionRegistry) const agentScenario = scenario === 'agent-resume' if (agentScenario) await mountAgentLoopTestDependencies(ctx) - else await ctx.plugin(SessionStore) + else { + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SessionStore) + } await installProjectionSet(ctx, agentScenario) await ctx.plugin(JsonlSessionPersistence, { root, compression: 'zstd' }) let history: SessionHistoryController | undefined From 68643a07f966c02f495ee3ddc3309a5f9d9c9e3d Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 7 Sep 2026 20:52:09 +0800 Subject: [PATCH 25/26] docs(session-controller): unwrap zh readme paragraph --- packages/api/session-controller/README.zh.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index b6d2f56f7d..a9c53d3737 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -27,9 +27,7 @@ kind: "package-reference" 每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。queue 变更与取消要求 live 状态;模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。prompt 准入从注入的 [`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。 -Client adapter 提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend`、`append` 与 `settle-assistant` 变更,并通过 tail page 修复重连或 seq 缺口。向后分页有两个动词:`loadOlder()` 拉一页 50 条 message,而 `loadThrough(seq)`——轮次跳转加载器——按 200 条 message 一页循环拉取直到窗口覆盖目标 seq,重复调用会下调共享目标,遇到无进展的页即停止,忙碌状态复用同一个 `loadingOlder` 快照位。Web adapter 显式选择接收无 cursor 的 Assistant frame:每个 opening 携带活跃 attempt 的 `startedAfterSeq`、`nextIndex` 与紧凑 stream,每个 stream member 都成为排在持久 cursor 之间的 Client-only `assistant/live-chunk` 条目。Host 会随该 baseline 捕获 follower 本地到达序号,并抑制该 cut 及之前的 buffered frame;replacement Agent 可以从 revision 一重新开始。活跃 opening 之后到达的持久 `assistant/message` 或 `assistant/attempt` 只有在其 seq 晚于 `startedAfterSeq` 且 Turn 与 Step 匹配时才会保持暂存;匹配的 end type、seq 与 index 会发布一个具名 settlement delta,删除该 attempt 的瞬态 row、加入持久条目,并保留同一步骤中更早的 retry。已知 attempt 的 revision、密集 index 或 settlement 缺口会重新打开 follow;若 controller 错过 start,则忽略 unknown-attempt frame,并正常发布其持久 settlement。Abandoned end 会发布不含持久条目的 settlement delta,使瞬态 row 立即退出。持久缺口修复 page 不携带 Assistant baseline,因此 held notification 会重新打开 follow 一次,以取得配对的 page 与 baseline。每条历史 record 只覆盖自身的 event seq。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 queue、jobs 和 projection 状态,而不会把瞬态值当作 durable event。 -每次 inbox 变更时,Host 会先发布 projection frame,再从同一份已校验的折叠后值派生 queue replacement,因此监听器注册顺序不会产生陈旧的 queue frame。 -Client Agent context 提供独立 [`fileUpload`](../../client/file-upload/README.zh.md) 服务使用的身份;Session 对象提供生命周期、prompt、queue 与历史操作,不提供文件传输。 +Client adapter 提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend`、`append` 与 `settle-assistant` 变更,并通过 tail page 修复重连或 seq 缺口。向后分页有两个动词:`loadOlder()` 拉一页 50 条 message,而 `loadThrough(seq)`——轮次跳转加载器——按 200 条 message 一页循环拉取直到窗口覆盖目标 seq,重复调用会下调共享目标,遇到无进展的页即停止,忙碌状态复用同一个 `loadingOlder` 快照位。Web adapter 显式选择接收无 cursor 的 Assistant frame:每个 opening 携带活跃 attempt 的 `startedAfterSeq`、`nextIndex` 与紧凑 stream,每个 stream member 都成为排在持久 cursor 之间的 Client-only `assistant/live-chunk` 条目。Host 会随该 baseline 捕获 follower 本地到达序号,并抑制该 cut 及之前的 buffered frame;replacement Agent 可以从 revision 一重新开始。活跃 opening 之后到达的持久 `assistant/message` 或 `assistant/attempt` 只有在其 seq 晚于 `startedAfterSeq` 且 Turn 与 Step 匹配时才会保持暂存;匹配的 end type、seq 与 index 会发布一个具名 settlement delta,删除该 attempt 的瞬态 row、加入持久条目,并保留同一步骤中更早的 retry。已知 attempt 的 revision、密集 index 或 settlement 缺口会重新打开 follow;若 controller 错过 start,则忽略 unknown-attempt frame,并正常发布其持久 settlement。Abandoned end 会发布不含持久条目的 settlement delta,使瞬态 row 立即退出。持久缺口修复 page 不携带 Assistant baseline,因此 held notification 会重新打开 follow 一次,以取得配对的 page 与 baseline。每条历史 record 只覆盖自身的 event seq。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 queue、jobs 和 projection 状态,而不会把瞬态值当作 durable event。每次 inbox 变更时,Host 会先发布 projection frame,再从同一份已校验的折叠后值派生 queue replacement,因此监听器注册顺序不会产生陈旧的 queue frame。Client Agent context 提供独立 [`fileUpload`](../../client/file-upload/README.zh.md) 服务使用的身份;Session 对象提供生命周期、prompt、queue 与历史操作,不提供文件传输。 Session 对象还承载本地提交回显:`session.beginSubmission` 在调用方序列化与 prompt 之前,同步把一条回显写入 `SessionSnapshot.pendingSubmissions`,会话 UI 因此能在点击提交的当帧显示消息。回显按顺序存放图片预览与持久文件引用。Session 根据当前运行状态与请求的投递模式推导其 `transcript`、`queued` 或 `steering` 位置,并在序列化期间保留该位置。prompt 的 `requestId` 是关联标识:Host 把它回显为 durable user source 的 `rpcId`,queue occurrence 也把它投影为 `SessionQueuedItem.rpcId`。回显在观察到其 durable event 或 queue occurrence 后延迟一个动画帧退休,带标识的 prompt 失败或被放弃时立即退休,销毁时按 failed 退休。每次退休恰好触发一次 `onRetire`;observed 退休还会携带有序的持久附件引用,让 composer 释放成功卡片并保留失败草稿。回显只存在于 Client 内存;刷新与重连只从 durable event 重建会话。 From dbb9db5f343235a818062d67b192a65bdfe94e1b Mon Sep 17 00:00:00 2001 From: _Kerman Date: Mon, 7 Sep 2026 21:05:29 +0800 Subject: [PATCH 26/26] docs(session-controller): refresh translation pairing record --- packages/api/session-controller/README.i18n.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 97ab3b2b6b..981e5f12ca 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -3,4 +3,4 @@ # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/session-controller/README.md README.md: 6b56c4976b5ca66fbdbdb274bdf5bf8f38d52b1d -README.zh.md: b6d2f56f7daa87fc48be0db0fb18159dfc5c02bc +README.zh.md: a9c53d37371e3280c5bc0ae21a93a511036a810d