diff --git a/AGENTS.md b/AGENTS.md index 2cd72aff60..02615f53b4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md -This is the monorepo of the DeepSeek Harness group; it hosts **DeepSeek Harness SDK**, a plugin-based SDK for building agent harnesses. The codebase is built on the vendored Cordis framework, microkernel-style: **everything is a plugin**. Read [docs/architecture.md](docs/architecture.md) before changing `packages/`; the documentation standard is [docs/AGENTS.md](docs/AGENTS.md). +This is the DeepSeek Harness group's monorepo; it hosts **DeepSeek Harness SDK**, a plugin-based SDK for building agent harnesses. The codebase is built on the vendored Cordis framework, microkernel-style: **everything is a plugin**. Read [docs/architecture.md](docs/architecture.md) before changing `packages/`; the documentation standard is [docs/AGENTS.md](docs/AGENTS.md). ## Pre-release stance: foundation over blast radius @@ -19,11 +19,13 @@ packages/ Harness packages at packages///, all named @deepseek-ai compact/ compaction seam + basic backend subagent/ subagent seam + spawn/fork/ACP backends + delegation tool todo/ the todo_write tool + guard/ loop-hygiene plugins + cordis/ self-referential toolset: the agent inspects/mounts plugins in its own runtime hooks/ Claude Code / Codex hook bridges + shared wire-protocol library session-persistence/ persistence seam + JSONL/SQLite backends - ui/ ACP bridge + app-boot glue + the stdio/ACP app bins - support/ dev/test infrastructure: invariants, llm-replay, subagent-mock - util/ zero-dependency utilities (Branded) + ui/ ACP bridge, app-boot glue, stdio/ACP app bins, user-interaction seam, ask-user tool + support/ dev/test infrastructure packages + util/ zero-dependency utilities examples/ Runnable demos: thin cordis.yml leaves over the app packages (see examples/AGENTS.md) docs/ architecture, generated catalogs, RFCs, postmortems, cookbook (see docs/AGENTS.md) scripts/ repo gates and generators @@ -47,6 +49,7 @@ pnpm run hygiene # knip + publint + workspace constraints + NodeNext cons pnpm run doc-sync # all documentation gates; see the doc-sync script in package.json pnpm run demo:echo # mock-model REPL, no key needed pnpm run demo:repl # real REPL coding agent (needs DEEPSEEK_API_KEY) +pnpm run demo:cordis # self-referential demo: the agent modifies its own runtime (needs key) pnpm run demo:acp # ACP server agent (needs DEEPSEEK_API_KEY) ``` @@ -69,7 +72,7 @@ printf '%s\n' "$out" | grep -q '\[tool call\] echo({"text":"ci smoke"})' printf '%s\n' "$out" | grep -q '\[tool result\] ECHO: CI SMOKE' ls .sessions/_no-cwd/main-session-*.jsonl >/dev/null rm -rf .sessions -pnpm exec vitest run --config vitest.e2e.config.ts packages/ui/stdio-agent/tests/built-bin.e2e.ts packages/ui/acp-agent/tests/built-bin.e2e.ts +pnpm exec vitest run --config vitest.e2e.config.ts packages/ui/stdio-agent/tests/built-bin.e2e.ts packages/ui/acp-agent/tests/built-bin.e2e.ts packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts ``` `test:coverage`, not `test`, is the gating run ([why](docs/testing.md)); a sign-off counts only for commands actually run. diff --git a/docs/architecture.md b/docs/architecture.md index b668edfefd..9407460651 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,14 +1,14 @@ # DeepSeek Harness Architecture -The **DeepSeek Harness SDK** is an SDK for building agent harnesses using the Cordis framework. The governing principle is simple: **everything is a plugin**. For example, the shipped agent loop is just one plugin in the default bundle, not a privileged kernel. +The **DeepSeek Harness SDK** is an SDK for building agent harnesses on the Cordis framework. The governing principle is simple: **everything is a plugin**. The shipped agent loop is one plugin in the default bundle, not a privileged kernel. -Read this page as the system map before changing `packages/`. It explains how the runtime is shaped, how the default loop moves work, where state lives, and where extensions attach. Type shapes live in [core-data-structures/](core-data-structures/core.md); exact event and service signatures live in the generated [events](cordis-catalog/events.md) and [services](cordis-catalog/services.md) catalogs; package contracts live in the [package map](../packages/README.md); rationale lives in the [RFCs](rfc/README.md). If Cordis itself is new to you, start with the [Cordis primer](cordis-primer.md). +Read this page as the system map before changing `packages/`. It explains how the runtime is shaped, how the default loop moves work, where state lives, and where extensions attach. Type shapes live in [core-data-structures/](core-data-structures/core.md); exact event and service signatures live in the generated [events](cordis-catalog/events.md) and [services](cordis-catalog/services.md) catalogs; package contracts live in the [package map](../packages/README.md); rationale lives in the [RFCs](rfc/README.md). New to Cordis? Start with the [Cordis primer](cordis-primer.md). ## System Shape A running harness is one Cordis context. Packages contribute service keys, typed events, and disposable registrations to that context. Services are the stable call surfaces (`ctx.llm`, `ctx.tools`, `ctx.sessions`); events are interception and notification points (`agent/request`, `tools/pre-execute`, `session/event`); registrations install prompt sections, tool schemas, providers, adapters, and listeners. -The default distribution is a composition, not a hierarchy. `packages/core/` is a repository grouping for the default agent spine; capability seams around it are equally first-class plugins from a Cordis perspective. +The default distribution is a composition, not a hierarchy. `packages/core/` is a repository grouping for the default agent spine; capability seams around it are equally first-class plugins. ### Default Service Spine @@ -40,7 +40,7 @@ Events are the harness extension API. Each service owns the vocabulary for the b ### Event Domains -Use the event domain to decide where new behavior belongs: +Pick the event domain for new behavior: - **Session events** are durable, replayable facts. Turn and step boundaries, user input, assistant output, tool calls, tool results, steering, compaction records, and tool-owned durable facts append to the session log and flow through `session/event`. - **Agent events** are live runtime surfaces. They carry the live `Agent` handle for status, diagnostics, prompt admission, call-config shaping, result validation, and continuation policy. @@ -48,11 +48,11 @@ Use the event domain to decide where new behavior belongs: ### Interception Semantics -Waterfall events behave like around-middleware: a listener delegates by calling `next()` and vetoes or takes over by returning without it. The full rule lives in [Cordis waterfall semantics](cordis-primer.md#cordis-waterfall-semantics). +Waterfall events behave like around-middleware: a listener delegates by calling `next()`; returning without it vetoes or takes over. Full rule: [Cordis waterfall semantics](cordis-primer.md#cordis-waterfall-semantics). ## Default Loop Lifecycle -The shipped loop drains queued work, assembles a request, streams a model answer, executes tools, decides whether to continue, and checkpoints durable state. The important architecture is where it pauses: each pause is a documented service call or event seam that another plugin can program against. +The shipped loop drains queued work, assembles a request, streams a model answer, executes tools, decides whether to continue, and checkpoints durable state. The important architecture is where it pauses: each pause is a documented service call or event seam other plugins program against. A **session** is one agent's append-only event log. A **turn** drains one queued batch and runs until the model stops asking for tools and no plugin requests continuation. A **step** is one model request plus the tool executions caused by that response. In the flow below ([sequence companion](agent-lifecycle.md)), quoted names are durable session events and event names are extension seams. @@ -71,6 +71,7 @@ forever: STEP loop: drain steering assemble system prompt and tool schemas + agent/session-prefix (first step) agent/pre-step 'step/start' snapshot the derived messages (the reconstruction boundary) @@ -80,7 +81,7 @@ forever: 'assistant/message' each tool call: 'tool/call' - tools/pre-execute -> dispatch -> tools/post-execute + tools/pre-execute -> tools/execute -> tools/post-execute 'tool/result' append post-tool context and steering 'step/end' @@ -90,7 +91,7 @@ forever: checkpoint persistence and notify idle/running status ``` -Prompt assembly is single-path: `renderPrompt(assemble({ agent }))` IS the system prompt sent to the model. Plugins contribute ordered sections (static or computed from the per-call `AssembleContext`), tool schemas, and named variables interpolated as `{{name}}` at render — strictly, so an unknown or valueless reference fails the turn instead of shipping a hole. `dsh-system-prompt` itself owns the openers — the static `harness:identity` section (order −100) and the deployment's persona (order 0, from its `persona` config, shared by every agent in the context) — while the shipped loop registers the `model`/`cwd` variables; prompt-fact ownership is pinned by the [prompt-variables RFC](rfc/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md). +Prompt assembly is single-path: `renderPrompt(assemble({ agent }))` IS the system prompt sent to the model. Plugins contribute ordered sections (static or computed from the per-call `AssembleContext`), tool schemas, and named variables interpolated as `{{name}}` at render — strictly, so an unknown or valueless reference fails the turn instead of shipping a hole. `dsh-system-prompt` owns the openers — the static `harness:identity` section (order −100) and the deployment's persona (order 0, its `persona` config, shared context-wide) — while the shipped loop registers the `model`/`cwd` variables; prompt-fact ownership is pinned by the [prompt-variables RFC](rfc/implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md). Post-tool context lands after all tool results so tool-call/result adjacency stays stable. Steering drains between steps; leftover steering after a turn is re-queued as ordinary input. @@ -114,7 +115,7 @@ Every live agent owns a scope context, `agent.ctx` ([`dsh-scope`](../packages/co The session log is the source of truth. `deriveMessages()` projects session events into the `Message[]` sent to the model; raw `assistant/chunk` events stay in the log for replay and UI fidelity. Replay, fork, resume, transcript rendering, telemetry, and persistence all derive from the same event stream. -**Model-visible ⟺ logged**: the log reconstructs every request — messages at `step/start`, headers by folding `request/header` — and dev invariants assert this ([reconstructability RFC](rfc/implemented/architecture/2026-07-05-reconstructable-requests.md)). +**Model-visible ⟺ logged**: the log reconstructs every request — messages at `step/start` fronted by the header's session prefix, headers by folding `request/header` — and dev invariants assert this ([reconstructability RFC](rfc/implemented/architecture/2026-07-05-reconstructable-requests.md)). Durability is a plugin concern. Persistence backends buffer synchronous `session/event` notifications and the loop awaits a turn-end checkpoint before moving on. The `SessionPersistence` seam stores `SessionEvent` directly, with metadata in `SessionHeader`; JSONL and SQLite share one contract suite. @@ -128,7 +129,7 @@ Streaming is a raw chunk protocol (`block-start` through `finish`) with `BlockAs ### Capability Pattern -A swappable capability usually splits into **interface / implementation / consumer**: the interface owns the `ctx` key and vocabulary; an implementation registers a backend; a consumer exposes model-facing behavior through `ctx.tools` or prompt assembly. The bash trio is the reference shape, and the [capability seam graph](capability-seams.md) shows the current package families. +A swappable capability usually splits into **interface / implementation / consumer**: the interface owns the `ctx` key and vocabulary; an implementation registers a backend; a consumer exposes model-facing behavior through `ctx.tools` or prompt assembly. The bash trio is the reference shape, and the [capability seam graph](capability-seams.md) shows the package families. Some seams bend the template deliberately. LLM keeps interface and consumer vocabulary together because adapters are the implementations. Filesystem adds policy as event gates around provider primitives. Web is one service with search and fetch provider registries, so provider swaps do not rename model tools. Subagents use a named provider registry because multiple delegation backends can coexist; `spawn` starts fresh, `fork` seeds from the parent's completed-turn prefix, and ACP can drive an out-of-process child ([subagent.md](core-data-structures/subagent.md)). @@ -147,6 +148,7 @@ New behavior should attach to a documented seam; changing the shipped loop requi | Add command execution | implement and register a `ctx.bash` backend | | Add filesystem access or policy | implement a `ctx.fs` provider or listen on `fs/*` policy events | | Intercept prompts, requests, tool use, or continuation | listen on the relevant `agent/*` or `tools/*` waterfall | +| Add a session-stable request prefix outside history | compose it on `agent/session-prefix`, once per loop instance; logged on the request header | | Add UI or editor integration | drive `ctx.agents` and render from `session/event` | | Add durable session state | add a `SessionEventMap` member and render/replay from the log | | Fork a live session | use `ctx.sessions.fork(source, boundary?, childSessionId?)` | diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 339954c00f..a0bfba136a 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -30,11 +30,15 @@ flowchart LR pkg_tool_fs["tool-fs"] pkg_tool_web["tool-web"] svc_tools["ctx.tools
Tool registry and execution waterfall"] + pkg_tool_ask_user["tool-ask-user"] pkg_tool_bash["tool-bash"] + pkg_tool_cordis["tool-cordis"] pkg_tool_subagent["tool-subagent"] pkg_tool_todo["tool-todo"] - svc_agents["ctx.agents
Agent registry"] + pkg_user_interaction["user-interaction"] + svc_userInteraction["ctx.userInteraction
Human question/answer seam"] pkg_stdio_agent["stdio-agent"] + svc_agents["ctx.agents
Agent registry"] svc_agentLoop["ctx.agentLoop
Concrete loop driver"] pkg_agent_core["agent-core"] pkg_bash["bash"] @@ -44,6 +48,7 @@ flowchart LR pkg_hooks_codex["hooks-codex"] pkg_code_runtime["code-runtime"] svc_codeRuntime["ctx.codeRuntime
Code-execution seam"] + pkg_code_runtime_worker["code-runtime-worker"] pkg_fs["fs"] svc_fs["ctx.fs
Filesystem provider seam"] pkg_fs_local["fs-local"] @@ -62,11 +67,13 @@ flowchart LR pkg_web_search_perplexity["web-search-perplexity"] pkg_web_search_deepseek["web-search-deepseek"] pkg_web_fetch_local["web-fetch-local"] + pkg_acp --> svc_userInteraction pkg_agent --> svc_agents pkg_agent_loop --> svc_agentLoop pkg_bash --> svc_bash pkg_bash_local --> svc_bash pkg_code_runtime --> svc_codeRuntime + pkg_code_runtime_worker --> svc_codeRuntime pkg_compact --> svc_compact pkg_compact_basic --> svc_compact pkg_fs --> svc_fs @@ -79,6 +86,7 @@ flowchart LR pkg_session_persistence --> svc_sessionPersistence pkg_session_persistence_jsonl --> svc_sessionPersistence pkg_session_persistence_sqlite --> svc_sessionPersistence + pkg_stdio_agent --> svc_userInteraction pkg_subagent --> svc_subagents pkg_subagent_acp --> svc_subagents pkg_subagent_fork --> svc_subagents @@ -86,6 +94,7 @@ flowchart LR pkg_subagent_spawn --> svc_subagents pkg_system_prompt --> svc_systemPrompt pkg_tools --> svc_tools + pkg_user_interaction --> svc_userInteraction pkg_web --> svc_web pkg_web_fetch_local --> svc_web pkg_web_search_deepseek --> svc_web @@ -118,11 +127,16 @@ flowchart LR svc_systemPrompt --> pkg_tools svc_tools --> pkg_acp svc_tools --> pkg_agent_loop + svc_tools --> pkg_tool_ask_user svc_tools --> pkg_tool_bash + svc_tools --> pkg_tool_cordis svc_tools --> pkg_tool_fs svc_tools --> pkg_tool_subagent svc_tools --> pkg_tool_todo svc_tools --> pkg_tool_web + svc_userInteraction --> pkg_acp + svc_userInteraction --> pkg_stdio_agent + svc_userInteraction --> pkg_tool_ask_user svc_web --> pkg_tool_web svc_fs -. event gate .-> pkg_fs_policy ``` @@ -133,11 +147,12 @@ flowchart LR | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`session-persistence`](../packages/session-persistence/session-persistence), [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`invariants`](../packages/support/invariants) | - | Owns append-only Session instances and emits the durable session event feed. | | `ctx.sessionPersistence` | `seam` | [`session-persistence`](../packages/session-persistence/session-persistence) | [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session-persistence/session-persistence-sqlite) | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/ui/acp) | - | Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time. | | `ctx.systemPrompt` | `core` | [`system-prompt`](../packages/core/system-prompt) | - | [`agent-loop`](../packages/core/agent-loop), [`tools`](../packages/core/tools), [`tool-fs`](../packages/fs/tool-fs), [`tool-web`](../packages/web/tool-web) | - | Collects prompt sections and model-facing tool schemas for each step. | -| `ctx.tools` | `core` | [`tools`](../packages/core/tools) | - | [`agent-loop`](../packages/core/agent-loop), [`tool-bash`](../packages/bash/tool-bash), [`tool-fs`](../packages/fs/tool-fs), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-todo`](../packages/todo/tool-todo), [`tool-web`](../packages/web/tool-web), [`acp`](../packages/ui/acp) | - | Registers tool definitions, exposes schemas to the prompt, and routes calls through tools/pre-execute and tools/post-execute. | +| `ctx.tools` | `core` | [`tools`](../packages/core/tools) | - | [`agent-loop`](../packages/core/agent-loop), [`tool-ask-user`](../packages/ui/tool-ask-user), [`tool-bash`](../packages/bash/tool-bash), [`tool-cordis`](../packages/cordis/tool-cordis), [`tool-fs`](../packages/fs/tool-fs), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-todo`](../packages/todo/tool-todo), [`tool-web`](../packages/web/tool-web), [`acp`](../packages/ui/acp) | - | Registers tool definitions, exposes schemas to the prompt, and routes calls through tools/pre-execute and tools/post-execute. | +| `ctx.userInteraction` | `seam` | [`user-interaction`](../packages/ui/user-interaction) | [`stdio-agent`](../packages/ui/stdio-agent), [`acp`](../packages/ui/acp) | [`tool-ask-user`](../packages/ui/tool-ask-user), [`stdio-agent`](../packages/ui/stdio-agent), [`acp`](../packages/ui/acp) | - | UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise. | | `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/ui/acp), [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`stdio-agent`](../packages/ui/stdio-agent), [`invariants`](../packages/support/invariants) | - | Owns live Agent handles and the create/resume factory seam. | | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`agent-core`](../packages/core/agent-core) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. | | `ctx.bash` | `seam` | [`bash`](../packages/bash/bash) | [`bash-local`](../packages/bash/bash-local) | [`tool-bash`](../packages/bash/tool-bash), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | - | The model-facing bash tools and hook bridges consume this seam; sandboxed or remote executors can replace bash-local. | -| `ctx.codeRuntime` | `seam` | [`code-runtime`](../packages/code-runtime/code-runtime) | - | - | - | Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the Code Mode RFC specifies the worker-thread backend and the tool-registry consumer). | +| `ctx.codeRuntime` | `seam` | [`code-runtime`](../packages/code-runtime/code-runtime) | [`code-runtime-worker`](../packages/code-runtime/code-runtime-worker) | - | - | Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the Code Mode RFC specifies the worker-thread backend and the tool-registry consumer). | | `ctx.fs` | `seam` | [`fs`](../packages/fs/fs) | [`fs-local`](../packages/fs/fs-local) | [`tool-fs`](../packages/fs/tool-fs) | [`fs-policy`](../packages/fs/fs-policy) | tool-fs executes read/write/edit through ctx.fs; fs-policy contributes observed-state checks through the fs/* event gate. | | `ctx.compact` | `seam` | [`compact`](../packages/compact/compact) | [`compact-basic`](../packages/compact/compact-basic) | [`compact-basic`](../packages/compact/compact-basic) | - | The basic backend currently consumes the pre-step event directly; a model-facing compact tool remains deferred. | | `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn`](../packages/subagent/subagent-spawn), [`subagent-fork`](../packages/subagent/subagent-fork), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-mock`](../packages/support/subagent-mock) | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Providers implement transports; tool-subagent exposes one configured provider as a model-facing tool name. | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7aed35bd4d..73f1ef7050 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -11,7 +11,7 @@ A `Requires:` line lists the service keys the plugin `inject`s: its `cordis.yml` ## `@deepseek-ai/dsh-acp` -Requires: `agents` · `sessions` · `sessionPersistence` · `tools` +Requires: `agents` · `sessions` · `sessionPersistence` · `tools` · `userInteraction` ```ts config-catalog /** Plugin config: the agent template ACP sessions are created from. */ @@ -31,7 +31,7 @@ export interface AcpConfig { Depends on: `Stream` (`@agentclientprotocol/sdk`) -Source: [`packages/ui/acp/src/index.ts:115`](../packages/ui/acp/src/index.ts) +Source: [`packages/ui/acp/src/index.ts:236`](../packages/ui/acp/src/index.ts) ## `@deepseek-ai/dsh-acp-agent` @@ -56,7 +56,7 @@ export interface Config { } ``` -Source: [`packages/ui/acp-agent/src/index.ts:49`](../packages/ui/acp-agent/src/index.ts) +Source: [`packages/ui/acp-agent/src/index.ts:50`](../packages/ui/acp-agent/src/index.ts) ## `@deepseek-ai/dsh-agent-core` @@ -139,7 +139,43 @@ export interface Config { } ``` -Source: [`packages/bash/bash-local/src/index.ts:28`](../packages/bash/bash-local/src/index.ts) +Source: [`packages/bash/bash-local/src/index.ts:29`](../packages/bash/bash-local/src/index.ts) + +## `@deepseek-ai/dsh-code-runtime-worker` + +```ts config-catalog +/** Plugin config: every execution cap, changeable from `cordis.yml` (no hardcoded tunables). */ +export interface Config { + /** + * Busy-time budget in milliseconds: the run fails with kind `'timeout'` + * once the worker's MEASURED event-loop active time + * (`worker.performance.eventLoopUtilization()`) exceeds this. Metering + * measured busy time — not wall time, not host-side pending-call + * bookkeeping — is what makes the budget both fair (a program awaiting a + * slow tool accrues nothing) and ungameable (a hot loop accrues whether + * or not a decoy dispatch is in flight). + */ + computeMs?: number + /** + * Wall-clock ceiling in milliseconds; never pauses for anything. The + * backstop for what busy-time cannot see (a program awaiting a promise + * nobody will resolve). + */ + maxWallMs?: number + /** Shared byte budget for captured log text (console + raw stream writes), truncation marked in-band. */ + maxLogBytes?: number + /** + * Byte cap for the completion value, measured by its real cross-boundary + * size (string bytes, or structured-clone wire size); an oversized or + * non-cloneable value crosses as a capped string rendering. + */ + maxValueBytes?: number + /** The worker's max old-generation heap in MiB (`resourceLimits`); overflow kills the worker, surfacing as kind `'worker-exit'`. */ + maxOldGenerationSizeMb?: number +} +``` + +Source: [`packages/code-runtime/code-runtime-worker/src/index.ts:29`](../packages/code-runtime/code-runtime-worker/src/index.ts) ## `@deepseek-ai/dsh-compact-basic` @@ -353,6 +389,38 @@ export interface Config { Source: [`packages/support/llm-replay/src/index.ts:429`](../packages/support/llm-replay/src/index.ts) +## `@deepseek-ai/dsh-repeat-tool-guard` + +```ts config-catalog +/** + * Plugin config, validated by the same-named schemastery schema plus the + * load-time checks in `apply` (misconfiguration fails loud: an empty + * `thresholds` list, a non-integer, a value below 2, or a duplicate throws at + * plugin load, never a silent fall-back). `include`/`exclude` entries are + * `*`-wildcard predicates over tool names at call time, not references to + * registry entries — a pattern matching no currently registered tool is valid + * (`exclude: [mcp_*]` must stay legal in a deployment that loads no MCP tools). + */ +export interface Config { + /** Consecutive-repeat counts that trigger a reminder (default `[3, 5, 8]`). */ + thresholds?: number[] + /** Tool-name patterns to track; empty means every tool is tracked. */ + include?: string[] + /** Tool-name patterns transparent to the chain (neither count nor reset). */ + exclude?: string[] + /** + * Maximum characters of canonical arguments quoted in the DETAILED reminder + * (default 500). Large payloads (a `write` body, a long command) would + * otherwise ride into the next request unbounded — precisely in a loop + * scenario; the cap bounds the reminder, never the detection (the chain key + * always compares the FULL canonical string). + */ + argumentsPreviewChars?: number +} +``` + +Source: [`packages/guard/repeat-tool-guard/src/index.ts:55`](../packages/guard/repeat-tool-guard/src/index.ts) + ## `@deepseek-ai/dsh-session-persistence-jsonl` Requires: `sessions` @@ -437,7 +505,7 @@ export interface Config { } ``` -Source: [`packages/ui/stdio-agent/src/index.ts:60`](../packages/ui/stdio-agent/src/index.ts) +Source: [`packages/ui/stdio-agent/src/index.ts:62`](../packages/ui/stdio-agent/src/index.ts) ## `@deepseek-ai/dsh-subagent-acp` @@ -605,6 +673,24 @@ export interface Config { Source: [`packages/core/system-prompt/src/index.ts:220`](../packages/core/system-prompt/src/index.ts) +## `@deepseek-ai/dsh-tool-cordis` + +Requires: `tools` + +```ts config-catalog +/** Config for the tool-cordis plugin: the sandbox evaluation bound. */ +export interface Config { + /** + * Milliseconds the SYNCHRONOUS portion of mount code may run in the vm + * before evaluation is aborted (default 5000). An async body escapes this + * bound — see docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md for the trust stance. + */ + vmTimeoutMs?: number +} +``` + +Source: [`packages/cordis/tool-cordis/src/index.ts:53`](../packages/cordis/tool-cordis/src/index.ts) + ## `@deepseek-ai/dsh-tool-fs` Requires: `tools` · `fs` · `systemPrompt` @@ -690,7 +776,7 @@ Source: [`packages/subagent/tool-subagent/src/index.ts:44`](../packages/subagent Requires: `tools` · `web` · `systemPrompt` ```ts config-catalog -/** Plugin config: which web tools to register, and the `web_search` source cap. */ +/** Plugin config: which web tools to register, the source cap, and per-tool budgets. */ export interface Config { /** Register `web_search`. Defaults to true. */ search?: boolean @@ -698,10 +784,14 @@ export interface Config { fetch?: boolean /** Upper bound on sources returned by one `web_search` call. */ searchMaxResults?: number + /** Cooperative timeout budget (ms) for `web_fetch`. Defaults to 30000. */ + fetchTimeoutMs?: number + /** Cooperative timeout budget (ms) for `web_search`. Defaults to 30000. */ + searchTimeoutMs?: number } ``` -Source: [`packages/web/tool-web/src/index.ts:37`](../packages/web/tool-web/src/index.ts) +Source: [`packages/web/tool-web/src/index.ts:40`](../packages/web/tool-web/src/index.ts) ## `@deepseek-ai/dsh-web` @@ -825,9 +915,12 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-llm` ([`packages/llm/llm/src/index.ts`](../packages/llm/llm/src/index.ts)) - `@deepseek-ai/dsh-session` ([`packages/core/session/src/index.ts`](../packages/core/session/src/index.ts)) - `@deepseek-ai/dsh-subagent` ([`packages/subagent/subagent/src/index.ts`](../packages/subagent/subagent/src/index.ts)) +- `@deepseek-ai/dsh-timeout-policy` — requires `tools` ([`packages/timeout/timeout-policy/src/index.ts`](../packages/timeout/timeout-policy/src/index.ts)) +- `@deepseek-ai/dsh-tool-ask-user` — requires `tools` · `userInteraction` ([`packages/ui/tool-ask-user/src/index.ts`](../packages/ui/tool-ask-user/src/index.ts)) - `@deepseek-ai/dsh-tool-bash` — requires `tools` · `bash` · `systemPrompt` ([`packages/bash/tool-bash/src/index.ts`](../packages/bash/tool-bash/src/index.ts)) - `@deepseek-ai/dsh-tool-todo` — requires `tools` ([`packages/todo/tool-todo/src/index.ts`](../packages/todo/tool-todo/src/index.ts)) - `@deepseek-ai/dsh-tools` — requires `systemPrompt` ([`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts)) +- `@deepseek-ai/dsh-user-interaction` ([`packages/ui/user-interaction/src/index.ts`](../packages/ui/user-interaction/src/index.ts)) ## Seam packages (not directly loadable) @@ -849,3 +942,4 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. - `@deepseek-ai/dsh-hook-protocol` ([`packages/hooks/hook-protocol/src/index.ts`](../packages/hooks/hook-protocol/src/index.ts)) - `@deepseek-ai/dsh-scope` ([`packages/core/scope/src/index.ts`](../packages/core/scope/src/index.ts)) - `@deepseek-ai/dsh-subagent-inprocess` ([`packages/subagent/subagent-inprocess/src/index.ts`](../packages/subagent/subagent-inprocess/src/index.ts)) +- `@deepseek-ai/dsh-timeout` ([`packages/util/timeout/src/index.ts`](../packages/util/timeout/src/index.ts)) diff --git a/docs/cordis-catalog/events.md b/docs/cordis-catalog/events.md index 798b38b02f..5113ac0ee6 100644 --- a/docs/cordis-catalog/events.md +++ b/docs/cordis-catalog/events.md @@ -23,7 +23,7 @@ An agent was registered in the AgentRegistry and is ready to receive messages. Types: [Agent](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:286`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:287`](../../packages/core/agent/src/types.ts) ### `agent/disposed` — emit @@ -35,7 +35,7 @@ An agent was disposed and removed from the registry; its fiber and any in-flight Types: [Agent](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:298`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:299`](../../packages/core/agent/src/types.ts) ### `agent/error` — emit @@ -47,21 +47,21 @@ A step or turn errored. The loop reports a failure here (plus the logger) even w Types: [Agent](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:492`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:553`](../../packages/core/agent/src/types.ts) ### `agent/pre-step` — serial Awaited pre-step surface-mutation checkpoint, fired once per step AFTER `turn/start` (and after the prior step closed) but BEFORE this step's `step/start` — so anything a listener appends lands OUTSIDE the step, between `turn/start`/`step/end` and the upcoming `step/start`. `step` is the number of the step about to start. The loop awaits `ctx.serial('agent/pre-step', …)` after assembling the system prompt, then opens the step and derives the request history ONCE from whatever the surface now holds. This is where compaction belongs: it mutates the session surface in place (shadowing an older range with a summary node) with its log-only `compact/*` records cleanly outside any step, and the single subsequent derive reflects the mutation — so there is no double-derive and no listener can see (or be expected to act on) an assembled `messages` array that does not exist yet. -Serial (awaited in registration order), not a waterfall: a listener mutates the surface as a side effect; there is nothing to transform, but the loop must wait for the mutation to complete before opening the step and deriving. Cordis `serial` bails early if a listener returns a bail value; this event is typed and documented as `void`, so listeners must not return a semantic veto value. `fullSystemPrompt` is the assembled prompt a listener needs to measure pressure (the system prompt counts toward the budget). `signal` cancels any in-flight work a listener starts (e.g. a summarization model call). Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): a listener registered through `agent.ctx` fires only for that agent's dispatches; a listener on a plain plugin context fires for every agent. The dispatch `this` is the scope carrier (`Scoped`), built by the emitting side via `scopeTarget`/`agentEvents`. +Serial (awaited in registration order), not a waterfall: a listener mutates the surface as a side effect; there is nothing to transform, but the loop must wait for the mutation to complete before opening the step and deriving. Cordis `serial` bails early if a listener returns a bail value; this event is typed and documented as `void`, so listeners must not return a semantic veto value. `fullSystemPrompt` is the assembled prompt a listener needs to measure pressure (the system prompt counts toward the budget), and `sessionPrefix` is the instance's composed agent/session-prefix product for the same reason — every request carries it in front of the derived history, and it is composed BEFORE this seam fires precisely so a pressure gate counts the prefix the request will actually send (never a stale logged one). `signal` cancels any in-flight work a listener starts (e.g. a summarization model call). Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): a listener registered through `agent.ctx` fires only for that agent's dispatches; a listener on a plain plugin context fires for every agent. The dispatch `this` is the scope carrier (`Scoped`), built by the emitting side via `scopeTarget`/`agentEvents`. ```ts cordis-catalog -'agent/pre-step'(this: Scoped, agent: Agent, turn: number, step: number, fullSystemPrompt: string, signal: AbortSignal): Promise | void +'agent/pre-step'(this: Scoped, agent: Agent, turn: number, step: number, fullSystemPrompt: string, sessionPrefix: readonly Message[], signal: AbortSignal): Promise | void ``` -Types: [Agent](../core-data-structures/core.md) +Types: [Agent](../core-data-structures/core.md) · [Message](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:396`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:404`](../../packages/core/agent/src/types.ts) ### `agent/prompt-submit` — waterfall @@ -73,7 +73,7 @@ Waterfall: decide what happens to ONE drained queued message before it becomes a Types: [Agent](../core-data-structures/core.md) · [ContentBlock](../core-data-structures/core.md) · [MessageSource](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:414`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:422`](../../packages/core/agent/src/types.ts) ### `agent/queued` — emit @@ -85,11 +85,11 @@ A message entered the agent's inbox (queued or steering). `source` is the resolv Types: [Agent](../core-data-structures/core.md) · [ContentBlock](../core-data-structures/core.md) · [MessageSource](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:326`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:327`](../../packages/core/agent/src/types.ts) ### `agent/request` — waterfall -Waterfall: shape the step's call configuration — model switching, sampling overrides — by returning a replacement LlmCallConfig (the frozen seed is the config the loop would otherwise use). Config is ALL a listener shapes here: every request is a pure function of the session log (the reconstructability RFC), so model-visible content flows through the log channels — `inject()`, steering, prompt-submit `additionalContext`, prompt sections via `system-prompt/assemble` — never through request mutation, and the loop records whatever config the request actually uses as a `request/header*` event before dispatch. The step's messages are already snapshotted when this fires (the `step/start` boundary): an `inject()` from a listener here lands in the log but joins the NEXT request. For surface mutation that must precede the snapshot (compaction), use agent/pre-step. Call `next()` to delegate, or return an LlmCallConfig without it to short-circuit. +Waterfall: shape the step's call configuration — model switching, sampling overrides — by returning a replacement LlmCallConfig (the frozen seed is the config the loop would otherwise use). Config is ALL a listener shapes here: every request is a pure function of the session log (the reconstructability RFC), so model-visible content flows through the log channels — `inject()`, steering, prompt-submit `additionalContext`, prompt sections via `system-prompt/assemble`, or the header-logged session prefix via agent/session-prefix — never through request mutation, and the loop records whatever config the request actually uses as a `request/header*` event before dispatch. The step's messages are already snapshotted when this fires (the `step/start` boundary): an `inject()` from a listener here lands in the log but joins the NEXT request. For surface mutation that must precede the snapshot (compaction), use agent/pre-step. Call `next()` to delegate, or return an LlmCallConfig without it to short-circuit. ```ts cordis-catalog 'agent/request'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, next: () => Promise): Promise @@ -97,7 +97,23 @@ Waterfall: shape the step's call configuration — model switching, sampling ove Types: [Agent](../core-data-structures/core.md) · [LlmCallConfig](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:442`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:451`](../../packages/core/agent/src/types.ts) + +### `agent/session-prefix` — waterfall + +Waterfall: compose the SESSION PREFIX — request-only messages placed in front of the ENTIRE derived history (directly after the provider's system slot) on every request this loop instance sends. Fired ONCE per loop instance, lazily before its first step's agent/pre-step seam — BEFORE the pre-step so a token-pressure gate (compaction) counts the prefix this instance will actually send, never a previous instance's logged one. The composed result is deep-frozen, recorded as `EpochHeader.messagePrefix` on the instance's anchoring `'initial'`/`'resume'` header snapshot, and reused verbatim for every subsequent request — never recomputed mid-session, so the provider prefix cache holds by construction (a process restart or `ctx.agents.resume()` is a new instance: it recomposes, and any drift lands attributably on the `'resume'` snapshot). Composition runs outside the step, before the boundary snapshot: a composing listener's session append joins the CURRENT request's derived history. A composition interrupted by a cancel/dispose landing inside the waterfall is discarded — never cached, logged, or sent — and the next turn recomposes under a live signal, so an abort-aware listener's degraded fallback cannot leak into later requests. + +This is the home for session-stable openers the model must always see but that must NOT become durable history — a skills catalog, an AGENTS.md digest, a workspace baseline: `Session.deriveMessages()` never returns the prefix, and the header events are its only durable record, so the request stays reconstructable from the log. Content that CHANGES mid-session belongs in the append-only history channels instead — `agent.inject()`, a `tools/post-execute` decision's `additionalContext`, prompt-submit `additionalContext` — each a durable `context/message` paid once and prefix-cached thereafter. + +The seed is a frozen empty list; a contributing listener returns a NEW array — never an in-place push. The canonical contribution is a PREPEND, `[mine, ...await next()]`: the waterfall unwinds innermost-first (the LAST-registered listener's `next()` resolves first), so prepending yields registration order on the wire, and every plugin using it composes deterministically. The append form `[...await next(), mine]` is legal but places a contribution AFTER every later-registered plugin's — reverse registration order when all contributors append. Call `next()` to delegate, or return a list without it to short-circuit. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): a listener registered through `agent.ctx` fires only for that agent's dispatches; a listener on a plain plugin context fires for every agent. The dispatch `this` is the scope carrier (`Scoped`), built by the emitting side via `scopeTarget`/`agentEvents`. + +```ts cordis-catalog +'agent/session-prefix'(this: Scoped, agent: Agent, prefix: Message[], signal: AbortSignal, next: () => Promise): Promise +``` + +Types: [Agent](../core-data-structures/core.md) · [Message](../core-data-structures/core.md) + +Source: [`packages/core/agent/src/types.ts:503`](../../packages/core/agent/src/types.ts) ### `agent/session-start` — emit @@ -109,7 +125,7 @@ The agent's session lifecycle began, fired once before its first turn. `source` Types: [Agent](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:346`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:347`](../../packages/core/agent/src/types.ts) ### `agent/status` — emit @@ -121,7 +137,7 @@ Agent status changed (`idle` ⇄ `running`, or → `disposed`). Drive lifecycle Types: [Agent](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:312`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:313`](../../packages/core/agent/src/types.ts) ### `agent/step-result` — waterfall @@ -133,7 +149,7 @@ Waterfall: post-process the assembled assistant Message before tool dispatch (va Types: [Agent](../core-data-structures/core.md) · [Message](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:457`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:518`](../../packages/core/agent/src/types.ts) ### `agent/turn-continuation` — waterfall @@ -145,7 +161,7 @@ Waterfall: override the turn-continuation decision via a typed ContinuationDecis Types: [Agent](../core-data-structures/core.md) -Source: [`packages/core/agent/src/types.ts:475`](../../packages/core/agent/src/types.ts) +Source: [`packages/core/agent/src/types.ts:536`](../../packages/core/agent/src/types.ts) ## `fs/*` @@ -307,11 +323,23 @@ A tool was registered or unregistered, or a scoped restriction changed (the avai 'tools/change'(): void ``` -Source: [`packages/core/tools/src/index.ts:112`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:137`](../../packages/core/tools/src/index.ts) + +### `tools/execute` — waterfall + +Around-dispatch waterfall wrapping the registry's core tool dispatch, between the `tools/pre-execute` gate and the `tools/post-execute` seam. A listener receives `(exec, next)`: call `next()` to delegate to dispatch (returning its ToolExecutionResult, optionally wrapped), or return a replacement result without calling `next()` to short-circuit dispatch. The base `next()` IS the dispatch-with-normalization thunk — a thrown tool (or unknown tool) is already normalized to an `isError` result by the time a listener's `await next()` returns, so a wrapper never sees a raw throw from the tool body. This is the seam a timeout/retry/metrics plugin wraps: it can mutate `exec` (e.g. replace `exec.signal` with a per-call deadline) BEFORE `next()` and inspect the result AFTER. (Cordis `next()` ignores any passed arguments and re-invokes downstream with the shared payload, so a wrapper mutates `exec` in place rather than passing a new object to `next()`.) Multiple listeners compose by registration order — an outer one wraps the inner ones plus dispatch. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): the carrier is keyed by `exec.agent` — a listener registered through `agent.ctx` wraps only that agent's calls; a plain plugin listener wraps every call (including agent-less ones, which dispatch subject-less). + +```ts cordis-catalog +'tools/execute'(this: Scoped, exec: ToolExecution, next: () => Promise): Promise +``` + +Types: [ToolExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) + +Source: [`packages/core/tools/src/index.ts:107`](../../packages/core/tools/src/index.ts) ### `tools/post-execute` — waterfall -Waterfall AFTER a tool runs — where hook plugins inspect the result and accept it (optionally REPLACING the model-facing content, and/or attaching `additionalContext` for the next request) or block it with corrective `feedback` (Claude Code's `PostToolUse`). Listeners receive `(exec, result, next)`: call `next()` to delegate to the default (accept unchanged), or return a PostToolDecision to override. The core tool dispatch sits between the two waterfalls as plain code, all inside `execute`'s outer try/catch (and the tool body keeps its own inner try/catch, so a thrown tool still reaches `post-execute` as an `isError` result). Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): the carrier is keyed by `exec.agent` — a listener registered through `agent.ctx` fires only for that agent's calls; a plain plugin listener fires for every call (including agent-less ones, which dispatch subject-less). +Waterfall AFTER a tool runs — where hook plugins inspect the result and accept it (optionally REPLACING the model-facing content, and/or attaching `additionalContext` for the next request) or block it with corrective `feedback` (Claude Code's `PostToolUse`). Listeners receive `(exec, result, next)`: call `next()` to delegate to the default (accept unchanged), or return a PostToolDecision to override. Core tool dispatch runs earlier as the base `next()` of the `tools/execute` waterfall, all inside `execute`'s outer try/catch (and the tool body keeps its own inner try/catch, so a thrown tool still reaches `post-execute` as an `isError` result). Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): the carrier is keyed by `exec.agent` — a listener registered through `agent.ctx` fires only for that agent's calls; a plain plugin listener fires for every call (including agent-less ones, which dispatch subject-less). ```ts cordis-catalog 'tools/post-execute'(this: Scoped, exec: ToolExecution, result: ToolExecutionResult, next: () => Promise): Promise @@ -319,7 +347,7 @@ Waterfall AFTER a tool runs — where hook plugins inspect the result and accept Types: [ToolExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:102`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:127`](../../packages/core/tools/src/index.ts) ### `tools/pre-execute` — waterfall @@ -331,7 +359,7 @@ Waterfall BEFORE a tool runs — the gate where sandbox, permission, and hook pl Types: [ToolExecution](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:82`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:83`](../../packages/core/tools/src/index.ts) ## Inherited events (cordis core + loader/hmr/timer) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 783ef7c83e..b8a398029a 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -98,11 +98,13 @@ Implementations MUST honor: - **Blocking**: no compaction begins while another is in progress for the same session. The recommended mechanism is the log-recorded lock — append `compact/start` before the slow work and `compact/end` after (even on failure) — so the lock is visible to replay and crash recovery. ```ts cordis-catalog -abstract compactIfNeeded( agent: CompactAgentContext, fullSystemPrompt: string, signal: AbortSignal, ): Promise +abstract compactIfNeeded( agent: CompactAgentContext, fullSystemPrompt: string, sessionPrefix: readonly Message[], signal: AbortSignal, ): Promise abstract compactRegion( session: Session, start: number, end: number, agent: CompactAgentContext, signal?: AbortSignal, ): Promise ``` -Source: [`packages/compact/compact/src/index.ts:63`](../../packages/compact/compact/src/index.ts) +Types: [Message](../core-data-structures/core.md) + +Source: [`packages/compact/compact/src/index.ts:65`](../../packages/compact/compact/src/index.ts) ## `ctx.fs` — `FileSystem` (abstract seam) @@ -214,7 +216,7 @@ Source: [`packages/core/system-prompt/src/index.ts:335`](../../packages/core/sys ## `ctx.tools` — `ToolRegistry` -Tool registry (`ctx.tools`): tool plugins register definitions; the agent loop executes calls through the `tools/pre-execute` → dispatch → `tools/post-execute` pipeline. The registry contributes its schemas into the system-prompt assembly. +Tool registry (`ctx.tools`): tool plugins register definitions; the agent loop executes calls through the `tools/pre-execute` → `tools/execute` → `tools/post-execute` pipeline. The registry contributes its schemas into the system-prompt assembly. Two registration layers (`@deepseek-ai/dsh-scope`): a registration through a plain plugin context is GLOBAL (visible to every agent); one through a scoped context (`agent.ctx`) is filed in that scope's layer — visible to that agent alone, disposed with the scope, and SHADOWING a global tool of the same name for that agent (most-specific-wins; within one layer a duplicate name still throws). restrict masks the global layer per scope. One visibility function (visible) feeds prompt assembly, get, and execute, so what the model is shown, what a presenter renders, and what dispatches can never disagree. @@ -230,7 +232,18 @@ async execute(exec: ToolExecution): Promise Types: [ToolDefinition](../core-data-structures/tools.md) · [ToolExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:319`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:352`](../../packages/core/tools/src/index.ts) + +## `ctx.userInteraction` — `UserInteractionService` + +`ctx.userInteraction`: one active UI provider plus an `ask()` surface. + +```ts cordis-catalog +registerProvider(provider: UserInteractionProvider): () => void +async ask(request: AskUserQuestionRequest): Promise +``` + +Source: [`packages/ui/user-interaction/src/index.ts:82`](../../packages/ui/user-interaction/src/index.ts) ## `ctx.web` — `WebService` diff --git a/docs/core-data-structures/compaction.md b/docs/core-data-structures/compaction.md index 78eb48d38e..2f402be57d 100644 --- a/docs/core-data-structures/compaction.md +++ b/docs/core-data-structures/compaction.md @@ -50,6 +50,6 @@ interface CompactionResult { ## The service -`CompactService` (`ctx.compact`, abstract — defined in [`packages/compact/compact/src/index.ts`](../../packages/compact/compact/src/index.ts)) declares two abstract methods: `compactIfNeeded(agent, fullSystemPrompt, signal)` checks token pressure and compacts an older range if the history is too large (returning `null` when nothing needs it), and `compactRegion(session, start, end, agent, signal?)` forcibly summarizes surface nodes `[start, end]` into a single replacement node. `compactIfNeeded`'s parameters are all required — the loop's `agent/pre-step` checkpoint supplies the agent, the assembled `fullSystemPrompt`, and the turn `signal`. A backend summarizing via `ctx.llm.stream()` must forward `signal` into the call's `GenerateOptions.signal`, so an abort or dispose tears down the in-flight summarization. The entire strategy — token estimation, retention policy, event sequencing, summarization — is a HOW decision owned by the implementation. +`CompactService` (`ctx.compact`, abstract — defined in [`packages/compact/compact/src/index.ts`](../../packages/compact/compact/src/index.ts)) declares two abstract methods: `compactIfNeeded(agent, fullSystemPrompt, sessionPrefix, signal)` checks token pressure and compacts an older range if the history is too large (returning `null` when nothing needs it), and `compactRegion(session, start, end, agent, signal?)` forcibly summarizes surface nodes `[start, end]` into a single replacement node. `compactIfNeeded`'s parameters are all required — the loop's `agent/pre-step` checkpoint supplies the agent, the assembled `fullSystemPrompt`, the instance's composed `sessionPrefix` (request-only messages the derived history omits, so the pressure estimate must count them), and the turn `signal`. A backend summarizing via `ctx.llm.stream()` must forward `signal` into the call's `GenerateOptions.signal`, so an abort or dispose tears down the in-flight summarization. The entire strategy — token estimation, retention policy, event sequencing, summarization — is a HOW decision owned by the implementation. Auto-compaction runs on the serial `agent/pre-step` loop seam (fired once per step, after `turn/start` and BEFORE the step opens and its request history is derived), not the `agent/request` waterfall: compaction mutates the session surface in place — with its log-only `compact/*` records landing cleanly outside any step — and the loop derives the request from the already-compacted surface. Retention is turn-agnostic — the only structural guard is tool-pairing balance (a compacted region's edges are balanced cuts on the surface, so it never splits a step's tool-calls from their results), so a single runaway turn that alone exceeds the window compacts its own early closed steps rather than being retained verbatim. The backend that ships this (`dsh-compact-basic`) documents the retention walk, summary shrink validation, bounded re-compaction, and the crash/recoverable failure taxonomy. diff --git a/docs/core-data-structures/core.md b/docs/core-data-structures/core.md index 158a52795f..805b359170 100644 --- a/docs/core-data-structures/core.md +++ b/docs/core-data-structures/core.md @@ -19,6 +19,7 @@ Everything else is documented on a **sub-page**, not here. The rule that draws t | [session.md](session.md) | the full `SessionEventMap` variant catalog, `TurnTrigger`/`TurnEndReason`, `deriveMessages()`, the turn-enclosure invariant | | [persistence.md](persistence.md) | the durability seam: `SessionPersistence`, JSONL + SQLite backends, `session/flush`, crash recovery, `SessionHeader` | | [tools.md](tools.md) | `ToolDefinition` full fields, the schema DSL, `ToolExecution`/`ToolResult`, tool-presentation UI types, the `tools/pre-execute`/`tools/post-execute` pipeline | +| [user-interaction.md](user-interaction.md) | the UI-backed human question/answer seam: `AskUserQuestionRequest`, answer/options vocabulary, provider API, error taxonomy | | [bash.md](bash.md) | the bash executor seam: `BashExecRequest`/`Spec`, `BashRunResult`, background `BashTask`s | | [code-runtime.md](code-runtime.md) | the code-execution seam: `CodeRunRequest`/`Result`, binding namespaces, captured logs, the `CodeRunFailure` taxonomy | | [filesystem.md](filesystem.md) | the filesystem seam: `FsTarget`, read/write/edit outcomes, observed-file state, `FsErrorCode` | @@ -128,6 +129,12 @@ Source: [`packages/llm/llm/src/types.ts`](../../packages/llm/llm/src/types.ts) ```ts type-equiv interface GenerateOptions { model: string + /** + * Ordered conversation messages, exactly as the provider sees them (after + * the `system` slot). A loop-built request assembles them as + * `EpochHeader.messagePrefix` + the derived history (dsh-agent-loop); a + * hand-built one-shot passes any list. + */ messages: Message[] /** System prompt text (adapters map to the provider's system slot). */ system?: string @@ -188,7 +195,9 @@ The model-facing `ToolSchema` is the wire shape; the registered `ToolDefinition` ### The request envelope: `LlmCallConfig` and the logged header -Requests are built by the loop, not shaped per call: the non-content half of a request — the `EpochHeader`: this call configuration plus the rendered system prompt and the tool schemas in the assembly's canonical order (dsh-system-prompt's `toolOrder` config, lexicographic when unset) — is logged session state (`request/header` snapshot and delta events, [session.md](session.md#the-request-header-events-requestheader-and-requestheader-delta)), so every conversation request is a pure function of the session log ([reconstructability RFC](../rfc/implemented/architecture/2026-07-05-reconstructable-requests.md)). The `agent/request` waterfall receives a frozen `LlmCallConfig` seed and a listener returns a replacement to switch model or sampling — the loop logs whatever the request actually uses. Loop-built requests arrive at `llm/stream` deep-frozen; mutation throws. +Requests are built by the loop, not shaped per call: the non-history half of a request — the `EpochHeader`: this call configuration plus the rendered system prompt, the tool schemas in the assembly's canonical order (dsh-system-prompt's `toolOrder` config, lexicographic when unset), and the session prefix — is logged session state (`request/header` snapshot and delta events, [session.md](session.md#the-request-header-events-requestheader-and-requestheader-delta)), so every conversation request is a pure function of the session log ([reconstructability RFC](../rfc/implemented/architecture/2026-07-05-reconstructable-requests.md)). The `agent/request` waterfall receives a frozen `LlmCallConfig` seed and a listener returns a replacement to switch model or sampling; the `agent/session-prefix` waterfall — fired once per loop instance — composes the request-only messages fronting the derived history (recorded as the header's `messagePrefix`) — the loop logs whatever the request actually uses. Loop-built requests arrive at `llm/stream` deep-frozen; mutation throws. + +On the wire, a loop-built request reads in this order: the `system` slot (the rendered prompt assembly) → `messagePrefix` (the frozen session prefix) → the derived history — the boundary snapshot, whose tail is the newest `user/message` on a turn's first step and the previous step's tool results on later steps. The prefix never enters the derived history; its durable record is the header events, and the dev invariant recomputes exactly this equation against every loop-built request. FIXME(call-config-shape): revisit the exact definition of this type — which fields are genuinely epoch-level for cache purposes (`model` certainly; the sampling scalars sit here out of caution), and where provider-specific extras (reasoning options, extra body params) belong when an adapter needs them. @@ -329,7 +338,7 @@ interface Agent { } ``` -`AgentStatus` is `'idle' | 'running' | 'disposed'`. `AgentId` is a branded string. `AgentOptions` (`model?`) is merge-extensible — plugins add creation options by declaration merging; the persona is NOT an agent option but the `dsh-system-prompt` plugin's `persona` config, shared context-wide. The `agent/*` event taxonomy (lifecycle emits incl. `agent/session-start`, the serial `agent/pre-step` surface-mutation seam, and the `agent/prompt-submit`/`agent/request`/`agent/step-result`/`agent/turn-continuation` waterfalls) is in [architecture.md § Event taxonomy](../architecture.md#event-taxonomy); turn/step boundaries are durable `session/event` records, not `agent/*` emits. +`AgentStatus` is `'idle' | 'running' | 'disposed'`. `AgentId` is a branded string. `AgentOptions` (`model?`) is merge-extensible — plugins add creation options by declaration merging; the persona is NOT an agent option but the `dsh-system-prompt` plugin's `persona` config, shared context-wide. The `agent/*` event taxonomy (lifecycle emits incl. `agent/session-start`, the serial `agent/pre-step` surface-mutation seam, and the `agent/prompt-submit`/`agent/request`/`agent/session-prefix`/`agent/step-result`/`agent/turn-continuation` waterfalls) is in [architecture.md § Event taxonomy](../architecture.md#event-taxonomy); turn/step boundaries are durable `session/event` records, not `agent/*` emits. ## Interception decisions @@ -366,6 +375,8 @@ type ContinuationDecision = type SessionStartSource = 'startup' | 'resume' | 'clear' | 'compact' ``` +`agent/session-prefix` composes the session prefix — a plain `Message[]`, no dedicated payload type. Fired ONCE per loop instance, lazily on its first request: the composed list is deep-frozen, recorded as the header's `messagePrefix` ([the request envelope](#the-request-envelope-llmcallconfig-and-the-logged-header)), and placed in front of the ENTIRE derived history on every request the instance sends — the home for session-stable openers like a skills catalog or an AGENTS.md digest, never returned by `deriveMessages()`. Reuse is structural, so the prefix cannot drift mid-session (resume = a new instance = a recompose); content that changes mid-session goes through the append-only history channels instead (`agent.inject()`, `tools/post-execute` / prompt-submit `additionalContext`). Not a Decision union: the seam contributes content instead of vetoing, so the shape is the contribution itself. + ## `ToolDefinition` The one pipeline-authoring type that is core: what every registered tool *is* — a model-facing `ToolSchema` plus an `execute` function and optional UI presenters. A tool author rarely constructs it by hand (the `defineTool` DSL builds it with typed args), but it is the contract the registry holds and the loop dispatches through. diff --git a/docs/core-data-structures/session.md b/docs/core-data-structures/session.md index 6c4712114f..1b12c3fc48 100644 --- a/docs/core-data-structures/session.md +++ b/docs/core-data-structures/session.md @@ -74,16 +74,15 @@ interface SessionEventMap { */ 'request/header': { header: EpochHeader; reason: RequestHeaderReason } /** - * Amendment to the folded {@link EpochHeader}: at least one of a - * {@link SystemDelta}, a {@link ToolsDelta}, or a whole replacement - * {@link LlmCallConfig} (four scalars — not worth diffing). Appended by the - * loop inside the step, before dispatch, when the header for this request - * differs from the fold of the log so far; the writer verifies - * `applyHeaderDelta(previous, delta)` reproduces the new header exactly and - * falls back to a `'fallback'` `request/header` snapshot when it cannot, so - * a logged delta ALWAYS round-trips. NOT a {@link SurfaceEventType}. + * Amendment to the folded {@link EpochHeader}: system line-trim, name-keyed + * tools delta, whole replacement config, or whole replacement session + * prefix (an EMPTY array encodes the transition to "none"). The + * writer verifies `applyHeaderDelta(previous, delta)` reproduces the new + * header exactly and falls back to a `'fallback'` `request/header` snapshot + * when it cannot, so a logged delta ALWAYS round-trips. NOT a + * {@link SurfaceEventType}. */ - 'request/header-delta': { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig } + 'request/header-delta': { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig; messagePrefix?: Message[] } } ``` @@ -100,7 +99,7 @@ export interface TodoItem { ### The request header events: `request/header` and `request/header-delta` -The request envelope — the `EpochHeader` (call config + rendered system prompt + assembled tool schemas) — is logged session state, so every conversation request is a pure function of the log (the reconstructability RFC). A `request/header` snapshot (reason `'initial' | 'resume' | 'fallback'`) anchors the fold at conversation birth, process boundaries, and delta-encoding fallbacks; `request/header-delta` events amend it mid-run. `foldRequestHeader(events)` reconstructs the header any request was built under; the writer round-trip-verifies every delta before logging it, so a well-formed log always folds. Neither is a `SurfaceEventType` — they produce no LLM message. +The request envelope — the `EpochHeader` (call config + rendered system prompt + assembled tool schemas + the session prefix) — is logged session state, so every conversation request is a pure function of the log (the reconstructability RFC). A `request/header` snapshot (reason `'initial' | 'resume' | 'fallback'`) anchors the fold at conversation birth, process boundaries, and delta-encoding fallbacks; `request/header-delta` events amend it mid-run. `foldRequestHeader(events)` reconstructs the header any request was built under; the writer round-trip-verifies every delta before logging it, so a well-formed log always folds. Neither is a `SurfaceEventType` — they produce no LLM message. ```ts type-equiv export interface EpochHeader { @@ -110,10 +109,18 @@ export interface EpochHeader { system?: string /** Assembled tool schemas; absent for a tool-less request. */ tools?: ToolSchema[] + /** + * The session prefix: request-only messages sent BEFORE the entire derived + * history (the `agent/session-prefix` waterfall's product, composed once + * per loop instance and reused for every request it sends). Not session + * history — `deriveMessages()` never returns it — so the header is its + * only durable record; absent when the instance composed none. + */ + messagePrefix?: Message[] } ``` -Canonical form: an empty system prompt and an empty tool list are ABSENT fields, matching how requests are built. The delta payloads (`SystemDelta` — a common-prefix/suffix line trim; `ToolsDelta` — name-keyed added/removed/changed) live beside the events in [`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts). +Canonical form: an empty system prompt, an empty tool list, and an empty session prefix are ABSENT fields, matching how requests are built. `messagePrefix` is the durable record of the `agent/session-prefix` waterfall's product (the request is `messagePrefix + derived history`); composed once per loop instance and anchored by that instance's snapshot, so the loop never produces a prefix delta in practice — the delta arm (whole-array replacement, an empty array encoding the transition back to absence) exists for codec totality. The other delta payloads (`SystemDelta` — a common-prefix/suffix line trim; `ToolsDelta` — name-keyed added/removed/changed) live beside the events in [`packages/core/session/src/types.ts`](../../packages/core/session/src/types.ts). ## `SessionEvent` — one log entry diff --git a/docs/core-data-structures/tools.md b/docs/core-data-structures/tools.md index a38a5b9c15..96d3e79bdc 100644 --- a/docs/core-data-structures/tools.md +++ b/docs/core-data-structures/tools.md @@ -11,6 +11,14 @@ A `ToolSchema` (the model-facing fields) plus the `execute` function and optiona ```ts type-equiv interface ToolDefinition extends ToolSchema { execute(args: unknown, exec: ToolExecution): Promise + /** + * Cooperative tool-call timeout budget in milliseconds. Omit for no deadline. + * Enforced by `@deepseek-ai/dsh-timeout-policy` (a `tools/execute` wrapper); it + * is NEVER sent to the model — `schemas()` whitelists only name/description/ + * parameters. Declaring it asserts this tool forwards `exec.signal` to a + * cooperative implementation that can reach quiescence when the signal aborts. + */ + timeoutMs?: number /** * Optional: how to present the PENDING state of one call in a UI, derived from * the call's `args` (parsed arguments, `unknown` — the tool validates/narrows diff --git a/docs/core-data-structures/user-interaction.md b/docs/core-data-structures/user-interaction.md new file mode 100644 index 0000000000..6155fd9896 --- /dev/null +++ b/docs/core-data-structures/user-interaction.md @@ -0,0 +1,97 @@ +# User Interaction + +The user-interaction seam of [dsh-user-interaction](../../packages/ui/user-interaction). It is the provider-neutral vocabulary a tool or permission plugin uses when it needs the human to answer before the agent can continue. UI surfaces provide the active `UserInteractionProvider`: `dsh-stdio-agent` renders questions in readline, and `dsh-acp` maps them to ACP form elicitations. + +Source: [`packages/ui/user-interaction/src/index.ts`](../../packages/ui/user-interaction/src/index.ts) + +## Question options + +`AskUserQuestionOption` is the selectable-choice shape. `label` is the user-facing option text and also the model-facing selected value; `description` is optional UI help text. + +```ts type-equiv +interface AskUserQuestionOption { + /** User-facing label. */ + label: string + /** Optional extra context rendered by capable UIs. */ + description?: string +} +``` + +## Question item + +`AskUserQuestionItem` is one question in a request. The model supplies a stable `id`, which is echoed back with the answer so batched questions remain routable. + +```ts type-equiv +interface AskUserQuestionItem { + /** Stable model-provided question id, echoed in the answer. */ + id: string + /** The question to display. */ + question: string + /** Optional short heading/group label. */ + header?: string + /** Optional choices the UI can render as a menu. */ + options?: AskUserQuestionOption[] + /** Whether more than one option may be selected. Defaults to single-select. */ + multiSelect?: boolean +} +``` + +## Ask request + +`AskUserQuestionRequest` is the cross-package request. `questions` is an array so a UI can present related prompts in one flow while preserving a stable id per answer. + +```ts type-equiv +interface AskUserQuestionRequest { + /** Questions to display. */ + questions: AskUserQuestionItem[] + /** Calling agent, when the request came from an agent tool call. */ + agent?: Agent + /** Abort signal for the owning tool/step. */ + signal?: AbortSignal +} +``` + +## Answer + +Providers return one answer per answered question id. `selected` contains selected option labels, and `custom` carries a free-form "Other" answer when the user typed one. When `custom` is present, `selected` is empty; custom text is an answer override, not a supplement to selected choices. + +```ts type-equiv +interface AskUserQuestionAnswerItem { + /** The answered question id. */ + id: string + /** Selected option labels. Empty when the answer is purely custom text. */ + selected: string[] + /** Optional free-text "Other" answer. */ + custom?: string +} +``` + +```ts type-equiv +interface AskUserQuestionAnswer { + /** Structured answers keyed by question id. */ + answers: AskUserQuestionAnswerItem[] +} +``` + +## Provider + +Only one provider may be active in a context. Provider registration is effect-bound so HMR/disposal removes the active UI. + +```ts type-equiv +interface UserInteractionProvider { + ask(request: AskUserQuestionRequest): Promise +} +``` + +## Errors + +`UserInteractionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `NO_PROVIDER`, `ASK_ABORTED`, or ACP-side cancellation. + +```ts type-equiv +class UserInteractionError extends HarnessError { + constructor(message: string, code: string, options?: ErrorOptions) { + super(message, code, options) + this.name = 'UserInteractionError' + } +} +``` diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 3ea9c7cbbd..5200f6a930 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -7,17 +7,18 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent/created` | `emit` | [`packages/core/agent/src/types.ts:286`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`stdio-agent`](../packages/ui/stdio-agent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/types.ts:298`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`stdio-agent`](../packages/ui/stdio-agent) | -| `agent/error` | `emit` | [`packages/core/agent/src/types.ts:492`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | - | -| `agent/pre-step` | `serial` | [`packages/core/agent/src/types.ts:396`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic) | -| `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:414`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | -| `agent/queued` | `emit` | [`packages/core/agent/src/types.ts:326`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | - | -| `agent/request` | `waterfall` | [`packages/core/agent/src/types.ts:442`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | -| `agent/session-start` | `emit` | [`packages/core/agent/src/types.ts:346`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`invariants`](../packages/support/invariants) | -| `agent/status` | `emit` | [`packages/core/agent/src/types.ts:312`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/ui/acp), [`invariants`](../packages/support/invariants), [`stdio-agent`](../packages/ui/stdio-agent) | -| `agent/step-result` | `waterfall` | [`packages/core/agent/src/types.ts:457`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | -| `agent/turn-continuation` | `waterfall` | [`packages/core/agent/src/types.ts:475`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | +| `agent/created` | `emit` | [`packages/core/agent/src/types.ts:287`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`stdio-agent`](../packages/ui/stdio-agent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/types.ts:299`](../packages/core/agent/src/types.ts) | [`agent`](../packages/core/agent) (`emit`) | [`stdio-agent`](../packages/ui/stdio-agent) | +| `agent/error` | `emit` | [`packages/core/agent/src/types.ts:553`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | - | +| `agent/pre-step` | `serial` | [`packages/core/agent/src/types.ts:404`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic) | +| `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:422`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | +| `agent/queued` | `emit` | [`packages/core/agent/src/types.ts:327`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | - | +| `agent/request` | `waterfall` | [`packages/core/agent/src/types.ts:451`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/session-prefix` | `waterfall` | [`packages/core/agent/src/types.ts:503`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/session-start` | `emit` | [`packages/core/agent/src/types.ts:347`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`invariants`](../packages/support/invariants) | +| `agent/status` | `emit` | [`packages/core/agent/src/types.ts:313`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/ui/acp), [`invariants`](../packages/support/invariants), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard), [`stdio-agent`](../packages/ui/stdio-agent) | +| `agent/step-result` | `waterfall` | [`packages/core/agent/src/types.ts:518`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | +| `agent/turn-continuation` | `waterfall` | [`packages/core/agent/src/types.ts:536`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:123`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:138`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`emit`) | [`fs-policy`](../packages/fs/fs-policy) | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:109`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | @@ -31,9 +32,10 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:96`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude`](../packages/hooks/hooks-claude) | | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:44`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | - | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:54`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | -| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:112`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`emit`) | - | -| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:102`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | -| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:82`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | +| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:137`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`emit`) | - | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:107`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`timeout-policy`](../packages/timeout/timeout-policy) | +| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:127`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | +| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:83`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | ## Non-harness or undeclared event strings seen in package source diff --git a/docs/graph-atlas.md b/docs/graph-atlas.md index 2a3d674bec..60de01ef81 100644 --- a/docs/graph-atlas.md +++ b/docs/graph-atlas.md @@ -14,6 +14,7 @@ The process decision behind this index is recorded in [the documentation graph R | [capability seams and core services](capability-seams.md) | `hybrid generated` | | [echo-agent app composition](../examples/echo-agent/composition.md) | `hybrid generated` | | [coding-agent app composition](../examples/coding-agent/composition.md) | `hybrid generated` | +| [cordis-agent app composition](../examples/cordis-agent/composition.md) | `hybrid generated` | | [acp-agent app composition](../examples/acp-agent/composition.md) | `hybrid generated` | | [event producer/consumer matrix](event-producer-consumer.md) | `hybrid generated` | | [agent turn and step lifecycle](agent-lifecycle.md) | `curated` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 3f997e377a..2f97774f2c 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -9,6 +9,7 @@ Inter-package dependencies among the `@deepseek-ai/dsh-*` harness packages, deri flowchart TD subgraph group_util["packages/util"] pkg_brand["brand"] + pkg_timeout["timeout"] end subgraph group_llm["packages/llm"] pkg_llm["llm"] @@ -55,9 +56,15 @@ flowchart TD pkg_web_search_exa["web-search-exa"] pkg_web_search_perplexity["web-search-perplexity"] end + subgraph group_timeout["packages/timeout"] + pkg_timeout_policy["timeout-policy"] + end subgraph group_todo["packages/todo"] pkg_tool_todo["tool-todo"] end + subgraph group_cordis["packages/cordis"] + pkg_tool_cordis["tool-cordis"] + end subgraph group_hooks["packages/hooks"] pkg_hook_protocol["hook-protocol"] pkg_hooks_claude["hooks-claude"] @@ -79,12 +86,19 @@ flowchart TD pkg_acp_agent["acp-agent"] pkg_app_boot["app-boot"] pkg_stdio_agent["stdio-agent"] + pkg_tool_ask_user["tool-ask-user"] + pkg_user_interaction["user-interaction"] end subgraph group_code_runtime["packages/code-runtime"] pkg_code_runtime["code-runtime"] + pkg_code_runtime_worker["code-runtime-worker"] + end + subgraph group_guard["packages/guard"] + pkg_repeat_tool_guard["repeat-tool-guard"] end pkg_llm --> pkg_brand pkg_bash --> pkg_brand + pkg_code_runtime_worker --> pkg_code_runtime pkg_llm_deepseek --> pkg_llm pkg_llm_pi_ai --> pkg_llm pkg_session --> pkg_brand @@ -93,6 +107,7 @@ flowchart TD pkg_system_prompt --> pkg_llm pkg_system_prompt --> pkg_scope pkg_bash_local --> pkg_bash + pkg_bash_local --> pkg_timeout pkg_fs --> pkg_brand pkg_fs --> pkg_llm pkg_web --> pkg_llm @@ -105,6 +120,7 @@ flowchart TD pkg_fs_policy --> pkg_fs pkg_compact --> pkg_llm pkg_compact --> pkg_session + pkg_web_fetch_local --> pkg_timeout pkg_web_fetch_local --> pkg_web pkg_web_search_deepseek --> pkg_web pkg_web_search_exa --> pkg_web @@ -126,6 +142,8 @@ flowchart TD pkg_session_persistence_jsonl --> pkg_session_persistence pkg_session_persistence_sqlite --> pkg_session pkg_session_persistence_sqlite --> pkg_session_persistence + pkg_user_interaction --> pkg_agent + pkg_user_interaction --> pkg_llm pkg_agent_loop --> pkg_agent pkg_agent_loop --> pkg_llm pkg_agent_loop --> pkg_scope @@ -151,9 +169,14 @@ flowchart TD pkg_tool_web --> pkg_system_prompt pkg_tool_web --> pkg_tools pkg_tool_web --> pkg_web + pkg_timeout_policy --> pkg_llm + pkg_timeout_policy --> pkg_timeout + pkg_timeout_policy --> pkg_tools pkg_tool_todo --> pkg_agent pkg_tool_todo --> pkg_session pkg_tool_todo --> pkg_tools + pkg_tool_cordis --> pkg_scope + pkg_tool_cordis --> pkg_tools pkg_hooks_codex --> pkg_agent pkg_hooks_codex --> pkg_hook_protocol pkg_hooks_codex --> pkg_llm @@ -170,6 +193,12 @@ flowchart TD pkg_acp --> pkg_session pkg_acp --> pkg_session_persistence pkg_acp --> pkg_tools + pkg_acp --> pkg_user_interaction + pkg_tool_ask_user --> pkg_agent + pkg_tool_ask_user --> pkg_tools + pkg_tool_ask_user --> pkg_user_interaction + pkg_repeat_tool_guard --> pkg_agent + pkg_repeat_tool_guard --> pkg_tools pkg_agent_core --> pkg_agent pkg_agent_core --> pkg_agent_loop pkg_agent_core --> pkg_invariants @@ -210,35 +239,40 @@ flowchart TD pkg_acp_agent --> pkg_agent_core pkg_acp_agent --> pkg_app_boot pkg_acp_agent --> pkg_session_persistence_jsonl + pkg_acp_agent --> pkg_user_interaction pkg_stdio_agent --> pkg_agent pkg_stdio_agent --> pkg_agent_core pkg_stdio_agent --> pkg_app_boot pkg_stdio_agent --> pkg_llm pkg_stdio_agent --> pkg_session pkg_stdio_agent --> pkg_session_persistence_jsonl + pkg_stdio_agent --> pkg_tool_ask_user + pkg_stdio_agent --> pkg_user_interaction ``` | Package | Group | Depends on | | --- | --- | --- | | [`brand`](../packages/util/brand) | `util` | — | +| [`timeout`](../packages/util/timeout) | `util` | — | | [`scope`](../packages/core/scope) | `core` | — | | [`acp-snapshot`](../packages/support/acp-snapshot) | `support` | — | | [`app-boot`](../packages/ui/app-boot) | `ui` | — | | [`code-runtime`](../packages/code-runtime/code-runtime) | `code-runtime` | — | | [`llm`](../packages/llm/llm) | `llm` | [`brand`](../packages/util/brand) | | [`bash`](../packages/bash/bash) | `bash` | [`brand`](../packages/util/brand) | +| [`code-runtime-worker`](../packages/code-runtime/code-runtime-worker) | `code-runtime` | [`code-runtime`](../packages/code-runtime/code-runtime) | | [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`llm`](../packages/llm/llm) | | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | `llm` | [`llm`](../packages/llm/llm) | | [`session`](../packages/core/session) | `core` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash) | +| [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash), [`timeout`](../packages/util/timeout) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | | [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | | [`agent`](../packages/core/agent) | `core` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | | [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs) | | [`fs-policy`](../packages/fs/fs-policy) | `fs` | [`fs`](../packages/fs/fs) | | [`compact`](../packages/compact/compact) | `compact` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`web-fetch-local`](../packages/web/web-fetch-local) | `web` | [`web`](../packages/web/web) | +| [`web-fetch-local`](../packages/web/web-fetch-local) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`web`](../packages/web/web) | | [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`web`](../packages/web/web) | | [`web-search-perplexity`](../packages/web/web-search-perplexity) | `web` | [`web`](../packages/web/web) | @@ -249,15 +283,20 @@ flowchart TD | [`compact-basic`](../packages/compact/compact-basic) | `compact` | [`agent`](../packages/core/agent), [`compact`](../packages/compact/compact), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl) | `session-persistence` | [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence) | | [`session-persistence-sqlite`](../packages/session-persistence/session-persistence-sqlite) | `session-persistence` | [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence) | +| [`user-interaction`](../packages/ui/user-interaction) | `ui` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) | | [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-bash`](../packages/bash/tool-bash) | `bash` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`subagent`](../packages/subagent/subagent) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | +| [`timeout-policy`](../packages/timeout/timeout-policy) | `timeout` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | +| [`tool-cordis`](../packages/cordis/tool-cordis) | `cordis` | [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/hooks/hooks-codex) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | | [`invariants`](../packages/support/invariants) | `support` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`acp`](../packages/ui/acp) | `ui` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`tools`](../packages/core/tools) | +| [`acp`](../packages/ui/acp) | `ui` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | +| [`tool-ask-user`](../packages/ui/tool-ask-user) | `ui` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | +| [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | | [`agent-core`](../packages/core/agent-core) | `core` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tool-bash`](../packages/bash/tool-bash), [`tools`](../packages/core/tools) | | [`subagent-acp`](../packages/subagent/subagent-acp) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent) | | [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -266,5 +305,5 @@ flowchart TD | [`subagent-mock`](../packages/support/subagent-mock) | `support` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent) | | [`subagent-fork`](../packages/subagent/subagent-fork) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | | [`subagent-spawn`](../packages/subagent/subagent-spawn) | `subagent` | [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | -| [`acp-agent`](../packages/ui/acp-agent) | `ui` | [`acp`](../packages/ui/acp), [`agent-core`](../packages/core/agent-core), [`app-boot`](../packages/ui/app-boot), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl) | -| [`stdio-agent`](../packages/ui/stdio-agent) | `ui` | [`agent`](../packages/core/agent), [`agent-core`](../packages/core/agent-core), [`app-boot`](../packages/ui/app-boot), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl) | +| [`acp-agent`](../packages/ui/acp-agent) | `ui` | [`acp`](../packages/ui/acp), [`agent-core`](../packages/core/agent-core), [`app-boot`](../packages/ui/app-boot), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`user-interaction`](../packages/ui/user-interaction) | +| [`stdio-agent`](../packages/ui/stdio-agent) | `ui` | [`agent`](../packages/core/agent), [`agent-core`](../packages/core/agent-core), [`app-boot`](../packages/ui/app-boot), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`tool-ask-user`](../packages/ui/tool-ask-user), [`user-interaction`](../packages/ui/user-interaction) | diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 58fd548665..16ef2fb583 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -23,7 +23,7 @@ Raw stream chunk — token-level replay fidelity. Types: [StreamChunk](core-data-structures/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:304`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:313`](../packages/core/session/src/types.ts) #### `assistant/message` — surface @@ -35,7 +35,7 @@ Assembled assistant message for one step (derived history uses this). Carries th Types: [ContentBlock](core-data-structures/core.md) · [TokenUsage](core-data-structures/llm-streaming.md) -Source: [`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:320`](../packages/core/session/src/types.ts) ### `compact/*` @@ -83,7 +83,7 @@ In-session context injection (file-change notices, subdir AGENTS.md, skill conte Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:302`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:311`](../packages/core/session/src/types.ts) ### `hook/*` @@ -119,7 +119,7 @@ A queued prompt an `agent/prompt-submit` listener VETOED — the durable record Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:296`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:305`](../packages/core/session/src/types.ts) ### `request/*` @@ -131,17 +131,17 @@ Full snapshot of the EpochHeader the NEXT request is built under, with the Reque 'request/header': { header: EpochHeader; reason: RequestHeaderReason } ``` -Source: [`packages/core/session/src/types.ts:356`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:365`](../packages/core/session/src/types.ts) #### `request/header-delta` — log-only -Amendment to the folded EpochHeader: at least one of a SystemDelta, a ToolsDelta, or a whole replacement LlmCallConfig (four scalars — not worth diffing). Appended by the loop inside the step, before dispatch, when the header for this request differs from the fold of the log so far; the writer verifies `applyHeaderDelta(previous, delta)` reproduces the new header exactly and falls back to a `'fallback'` `request/header` snapshot when it cannot, so a logged delta ALWAYS round-trips. NOT a SurfaceEventType. +Amendment to the folded EpochHeader: at least one of a SystemDelta, a ToolsDelta, a whole replacement LlmCallConfig (four scalars — not worth diffing), or a whole replacement session prefix (`messagePrefix` — small advisory content, replaced whole; an EMPTY array encodes the transition to "none", mirroring the canonical form's absent field — the loop never produces one in practice: the prefix is composed once per instance and anchored by that instance's snapshot, so this arm exists for codec totality). Appended by the loop inside the step, before dispatch, when the header for this request differs from the fold of the log so far; the writer verifies `applyHeaderDelta(previous, delta)` reproduces the new header exactly and falls back to a `'fallback'` `request/header` snapshot when it cannot, so a logged delta ALWAYS round-trips. NOT a SurfaceEventType. ```ts persistence-catalog -'request/header-delta': { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig } +'request/header-delta': { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig; messagePrefix?: Message[] } ``` -Source: [`packages/core/session/src/types.ts:367`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:382`](../packages/core/session/src/types.ts) ### `steering/*` @@ -155,7 +155,7 @@ Steering content injected between steps of a running turn. Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:329`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:338`](../packages/core/session/src/types.ts) ### `step/*` @@ -167,7 +167,7 @@ Closes step `step` of turn `turn`. 'step/end': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:283`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:292`](../packages/core/session/src/types.ts) #### `step/start` — log-only @@ -177,7 +177,7 @@ Opens step `step` of turn `turn` — one model call plus the tool executions it 'step/start': { turn: number; step: number } ``` -Source: [`packages/core/session/src/types.ts:281`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:290`](../packages/core/session/src/types.ts) ### `todo/*` @@ -193,7 +193,7 @@ NOT a SurfaceEventType: it produces no LLM message and never reaches `deriveMess Types: [TodoItem](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:343`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:352`](../packages/core/session/src/types.ts) ### `tool/*` @@ -207,7 +207,7 @@ The model requested one tool invocation: `name` with the raw `arguments` JSON st Types: [CallId](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:317`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:326`](../packages/core/session/src/types.ts) #### `tool/result` — surface @@ -219,7 +219,7 @@ A completed tool call's model-facing result, plus an optional tool-private `meta Types: [CallId](core-data-structures/core.md) · [ContentBlock](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:327`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:336`](../packages/core/session/src/types.ts) ### `turn/*` @@ -233,7 +233,7 @@ Closes turn `turn` with the TurnEndReason that ended it. The loop fires the awai Types: [TurnEndReason](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:279`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:288`](../packages/core/session/src/types.ts) #### `turn/start` — log-only @@ -245,7 +245,7 @@ Opens turn `turn`. `trigger` records what started it — a drained message batch Types: [TurnTrigger](core-data-structures/session.md) -Source: [`packages/core/session/src/types.ts:273`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:282`](../packages/core/session/src/types.ts) ### `user/*` @@ -259,4 +259,4 @@ A user-visible prompt (queued message drained at turn start). Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) -Source: [`packages/core/session/src/types.ts:285`](../packages/core/session/src/types.ts) +Source: [`packages/core/session/src/types.ts:294`](../packages/core/session/src/types.ts) diff --git a/docs/rfc/INDEX.md b/docs/rfc/INDEX.md index 677e4eafb5..c27209597a 100644 --- a/docs/rfc/INDEX.md +++ b/docs/rfc/INDEX.md @@ -13,7 +13,6 @@ Generated by `pnpm run gen-rfc-index` from the RFC tree — never edit by hand; | [Code Mode — the model writes TypeScript against the tool registry](proposed/feature/2026-06-15-code-mode.md) | 2026-06-15 | | [Pre-tool input rewrite — a consistent design](proposed/feature/2026-06-30-pre-tool-input-rewrite.md) | 2026-06-30 | | [Claude Code and Codex subagent backends (out-of-process delegation to external coding agents)](proposed/feature/2026-07-07-claude-code-and-codex-subagent-backends.md) | 2026-07-07 | -| [Repeat-tool-call guard plugin](proposed/feature/2026-07-08-repeat-tool-guard.md) | 2026-07-08 | ### Simplification @@ -56,6 +55,7 @@ Generated by `pnpm run gen-rfc-index` from the RFC tree — never edit by hand; | [Compaction as a capability seam (abstract contract + basic backend)](implemented/feature/2026-06-18-compaction-capability-seam.md) | 2026-06-18 | | [Subagent capability seam](implemented/feature/2026-06-21-subagent-capability-seam.md) | 2026-06-21 | | [ACP subagent backend (out-of-process delegation)](implemented/feature/2026-06-22-acp-subagent-backend.md) | 2026-06-22 | +| [Ask-user question capability](implemented/feature/2026-06-25-ask-user-question.md) | 2026-06-25 | | [The `todo_write` tool — model task list as event-sourced session state](implemented/feature/2026-06-29-todo-write-tool.md) | 2026-06-29 | | [dsh-hooks-claude + dsh-hooks-codex — the Claude Code / Codex hook bridges](implemented/feature/2026-06-30-hook-bridges.md) | 2026-06-30 | | [dsh-hook-protocol — the shared Claude Code / Codex hook wire-protocol core](implemented/feature/2026-06-30-hook-protocol-lib.md) | 2026-06-30 | @@ -63,6 +63,9 @@ Generated by `pnpm run gen-rfc-index` from the RFC tree — never edit by hand; | [SessionStore fork API](implemented/feature/2026-06-30-session-store-fork-api.md) | 2026-06-30 | | [Subagent lifecycle enrichment — lastAssistantMessage (observe-only)](implemented/feature/2026-06-30-subagent-observe-enrich.md) | 2026-06-30 | | [Explicit model-facing tool order](implemented/feature/2026-07-06-explicit-tool-order.md) | 2026-07-06 | +| [The session prefix — request-only messages in front of the derived history](implemented/feature/2026-07-07-session-prefix.md) | 2026-07-07 | +| [Repeat-tool-call guard plugin](implemented/feature/2026-07-08-repeat-tool-guard.md) | 2026-07-08 | +| [The self-referential cordis toolset](implemented/feature/2026-07-08-self-referential-cordis-toolset.md) | 2026-07-08 | ### Simplification @@ -123,6 +126,8 @@ Generated by `pnpm run gen-rfc-index` from the RFC tree — never edit by hand; | [Prompt variables and tool-guidance ownership](implemented/architecture/2026-07-05-prompt-variables-and-tool-guidance-ownership.md) | 2026-07-05 | | [Every LLM request is reconstructable from the session log](implemented/architecture/2026-07-05-reconstructable-requests.md) | 2026-07-05 | | [Subagent provider-lifecycle events — `subagent/provider-added` / `subagent/provider-removed`](implemented/architecture/2026-07-05-subagent-provider-lifecycle-events.md) | 2026-07-05 | +| [A shared timeout/deadline primitive, with hard-kill left to each capability](implemented/architecture/2026-07-06-timeout-deadline-library.md) | 2026-07-06 | +| [Tool-call timeout policy as a plugin](implemented/architecture/2026-07-07-tool-call-timeout-policy.md) | 2026-07-07 | | [The agent is a registration scope](implemented/architecture/2026-07-08-agent-scope-contexts.md) | 2026-07-08 | ### Process diff --git a/docs/rfc/implemented/architecture/2026-07-05-reconstructable-requests.md b/docs/rfc/implemented/architecture/2026-07-05-reconstructable-requests.md index 601e64f70a..73967c14b6 100644 --- a/docs/rfc/implemented/architecture/2026-07-05-reconstructable-requests.md +++ b/docs/rfc/implemented/architecture/2026-07-05-reconstructable-requests.md @@ -20,13 +20,13 @@ Prefix-cache stability is corollary #1, not the headline: an append-only log pro **Messages.** `Session.deriveMessages()` is cached: each surface node is projected exactly once, when first seen, through the public per-node function `deriveEventMessage(event)`; a surface rewrite (a compaction `replace` — `SurfaceManager.replaceGeneration`) rebuilds. Callers get a fresh array per call over shared, deep-frozen messages: mutating logged history through a projection is unrepresentable (it throws), replacing the old clone-per-call isolation. External reconstructors fold the same public function over a log prefix, so no two paths can disagree. -**The header.** The request's non-content half — `EpochHeader`: call config (`LlmCallConfig`: model + sampling scalars), rendered system prompt, assembled tool schemas — is logged session state, in canonical form (empty system/tools ≡ absent). Two log-only, turn-enclosed events in dsh-session carry it: `request/header`, a full snapshot with reason `'initial' | 'resume' | 'fallback'`, and `request/header-delta`, an amendment (`SystemDelta`: a common-prefix/suffix line trim; `ToolsDelta`: name-keyed added/removed/changed; `config`: replaced whole). The pure trio `foldRequestHeader` / `diffHeader` / `applyHeaderDelta` reconstructs; the live session tracks the fold with the same lazy cursor as the message cache. Snapshots anchor the fold where a fold needs anchors — conversation birth and process boundaries — and each loop instance appends one on its first request (`'initial'` when the log has none, `'resume'` otherwise, even when nothing changed: the boundary itself is a recorded fact, and cross-restart drift becomes attributable while an unchanged header resumes byte-identical). Deltas are an encoding optimization with a safety valve, never a correctness dependency: the writer verifies `applyHeaderDelta(prev, delta)` reproduces the new header exactly and records a `'fallback'` snapshot when the encoding cannot express a change (a pure tool reordering), so a well-formed log always folds. +**The header.** The request's non-history half — `EpochHeader`: call config (`LlmCallConfig`: model + sampling scalars), rendered system prompt, assembled tool schemas, and the session prefix (`messagePrefix`, below) — is logged session state, in canonical form (empty system/tools/prefix ≡ absent). Two log-only, turn-enclosed events in dsh-session carry it: `request/header`, a full snapshot with reason `'initial' | 'resume' | 'fallback'`, and `request/header-delta`, an amendment (`SystemDelta`: a common-prefix/suffix line trim; `ToolsDelta`: name-keyed added/removed/changed; `config`: replaced whole; `messagePrefix`: replaced whole, an empty array encoding the transition to absence — an arm the loop never exercises in practice, kept for codec totality). The pure trio `foldRequestHeader` / `diffHeader` / `applyHeaderDelta` reconstructs; the live session tracks the fold with the same lazy cursor as the message cache. Snapshots anchor the fold where a fold needs anchors — conversation birth and process boundaries — and each loop instance appends one on its first request (`'initial'` when the log has none, `'resume'` otherwise, even when nothing changed: the boundary itself is a recorded fact, and cross-restart drift becomes attributable while an unchanged header resumes byte-identical). Deltas are an encoding optimization with a safety valve, never a correctness dependency: the writer verifies `applyHeaderDelta(prev, delta)` reproduces the new header exactly and records a `'fallback'` snapshot when the encoding cannot express a change (a pure tool reordering), so a well-formed log always folds. -**The loop, transmission-stateless.** Per step: render assembly (every step — value comparison needs no change-signal discipline, and a section that varies per step surfaces as a *logged* header event per step instead of a silent bust) → `agent/pre-step` (compaction's surface mutations land before derivation) → **messages snapshot, then `step/start` appended as the next operation in the same synchronous frame** → seed the call config (first request of the instance: from `AgentOptions`, so explicit options always beat the logged baseline — fork model-overrides and resume reconfiguration stay correct; afterwards: from the folded header) → the `agent/request` waterfall, re-typed `(agent, turn, step, config: LlmCallConfig, next) → LlmCallConfig` — a frozen seed and a returned replacement are ALL a listener shapes; content flows through the log channels (`inject()`, steering, prompt-submit `additionalContext`, sections via `system-prompt/assemble`) — → the header event the request owes the log → build `GenerateOptions` from the snapshot + header, deep-freeze (`deepFreeze` exempts the `AbortSignal`, the one live control channel — freezing one breaks `AbortController.abort()`), dispatch. The loop's only in-process bookkeeping is one boolean: whether this instance has logged its anchoring snapshot. +**The loop, transmission-stateless.** Per step: render assembly (every step — value comparison needs no change-signal discipline, and a section that varies per step surfaces as a *logged* header event per step instead of a silent bust) → on the instance's FIRST step only, the `agent/session-prefix` waterfall — request-ONLY messages fronting the entire derived history (a frozen empty seed, contributions returned as an extension of `next()`; the home for session-stable openers that must NOT become history — a skills catalog, an AGENTS.md digest), deep-frozen and cached on the instance so reuse is structural and the prefix cannot drift mid-session — → `agent/pre-step`, carrying the composed prefix (compaction's surface mutations land before derivation, and its pressure gate counts the prefix this instance will actually send — never a previous instance's logged one, which could under-gate a resumed/forked instance whose contributor grew) → **messages snapshot, then `step/start` appended as the next operation in the same synchronous frame** → seed the call config (first request of the instance: from `AgentOptions`, so explicit options always beat the logged baseline — fork model-overrides and resume reconfiguration stay correct; afterwards: from the folded header) → the `agent/request` waterfall, re-typed `(agent, turn, step, config: LlmCallConfig, next) → LlmCallConfig` — a frozen seed and a returned replacement are ALL a listener shapes; durable content flows through the log channels (`inject()`, steering, prompt-submit `additionalContext`, sections via `system-prompt/assemble`) — → the header event the request owes the log, carrying the prefix as `messagePrefix` (no session event carries it, so the header is its only durable record; resume = a new instance = a recompose, anchored by its `'resume'` snapshot) → build `GenerateOptions` from `messagePrefix + snapshot` + header, deep-freeze (`deepFreeze` exempts the `AbortSignal`, the one live control channel — freezing one breaks `AbortController.abort()`), dispatch. The loop's per-instance bookkeeping is one boolean plus the cached prefix: whether this instance has logged its anchoring snapshot, and what it composed. **The reconstruction boundary is `step/start`, unconditionally.** A step's messages are the derivation over `events[0..stepStartSeq)`. Because the snapshot precedes the `step/start` append in the same synchronous frame, nothing can enter this request past the boundary: an `agent.inject()` from an `agent/request` listener (or any concurrent task, or a `session/event` listener firing on `step/start` itself) lands in the log after the boundary and joins the NEXT request. For waterfall-window appends this matches the prior loop (it also derived before its waterfall); for a synchronous `step/start` listener it is a deliberate change — such a listener could previously reach the current request — and `agent/pre-step` is the sanctioned seam for content that must affect the CURRENT request. A step's header for reconstruction is the fold after its own `request/header*` event (which sits between its `step/start` and first response event) or the fold carried forward. -**Enforcement.** Dev-mode ([dsh-invariants](../../../../packages/support/invariants/src/index.ts)), on `llm/stream`: a frozen request with a live `sessionId` — the loop-built marker; hand-built one-shots are unfrozen and skipped — must carry messages deep-equal to the boundary derivation, rebuilt through a FRESH `Session` over `events[0..stepStartSeq)` so the live cache cannot vouch for itself, and header fields equal to `foldRequestHeader` over the log. There is no divergence allowance and nothing to allow: no seam can put unlogged content into a request. `prepend: true` only defends against the replay adapter's short-circuit (an append-registered listener); two prepended listeners have no defined mutual order in cordis, so correctness rests on the seq-bounded fold, never on listener timing. Measurement stays lean: the with-key e2e ([request-cache.e2e.ts](../../../../packages/core/agent-loop/tests/request-cache.e2e.ts)) proves `usage.cacheReadTokens > 0` on every request after the first against the live API, and per-step usage in the log is the production observable — a header event or compaction shows up as a cache-read collapse on the next step. +**Enforcement.** Dev-mode ([dsh-invariants](../../../../packages/support/invariants/src/index.ts)), on `llm/stream`: a frozen request with a live `sessionId` — the loop-built marker; hand-built one-shots are unfrozen and skipped — must carry messages deep-equal to the folded header's `messagePrefix` followed by the boundary derivation — the derivation rebuilt through a FRESH `Session` over `events[0..stepStartSeq)` so the live cache cannot vouch for itself — and header fields equal to `foldRequestHeader` over the log. There is no divergence allowance and nothing to allow: no seam can put unlogged content into a request — the `agent/session-prefix` seam's product enters only because the header event records it first. `prepend: true` only defends against the replay adapter's short-circuit (an append-registered listener); two prepended listeners have no defined mutual order in cordis, so correctness rests on the seq-bounded fold, never on listener timing. Measurement stays lean: the with-key e2e ([request-cache.e2e.ts](../../../../packages/core/agent-loop/tests/request-cache.e2e.ts)) proves `usage.cacheReadTokens > 0` on every request after the first against the live API, and per-step usage in the log is the production observable — a header event or compaction shows up as a cache-read collapse on the next step. ### The MiniCode shape: adopted, with the provenance arrow inverted @@ -44,6 +44,7 @@ What survives from `LLMClient`: the conversation is maintained, not rebuilt — ## Consequences - A request that is not explained by the log cannot be constructed by accident — not by the loop, not by a listener; mutating a built request throws; every header change is a durable, diffable log event. +- Choosing between the advisory channels is a change-frequency decision, and the design makes the stable one structural: an `agent/session-prefix` contribution is composed once per loop instance and reused verbatim, so it extends the cacheable prefix at zero marginal cost and CANNOT bust the provider cache mid-session; content that changes mid-session flows through the append-only history channels — `agent.inject()`, a `tools/post-execute` decision's `additionalContext`, prompt-submit `additionalContext` — each a durable `context/message` paid once and prefix-cached thereafter, at the price of accumulating in history and the log. Route session-frozen openers to the prefix and change notices to the history channels; a per-step request-only tail slot was deliberately dropped (no consumer, and a durable append covers every current update pattern). - What still costs full price at the provider is inherent and logged: compaction (its `compact/*` events and replace node), a real prompt/tool change (`request/header-delta`), a config switch (ditto), a process boundary with drift (`'resume'` snapshot differing from its predecessor). The provider's own reasoning-content exclusion is managed server-side. - The `step/start`-listener behavior change (above) is the one observable semantics change for plugins; `agent/pre-step` is the current-request seam. - Tool-result trimming (planned) needs no new mechanism: a logged single-node surface replace (`start === end`) carrying a trimmed `tool/result` under the same `callId` — compaction-family, replay-correct, cache-bust batched by the same pressure logic. diff --git a/docs/rfc/implemented/architecture/2026-07-06-timeout-deadline-library.md b/docs/rfc/implemented/architecture/2026-07-06-timeout-deadline-library.md new file mode 100644 index 0000000000..4902a0e833 --- /dev/null +++ b/docs/rfc/implemented/architecture/2026-07-06-timeout-deadline-library.md @@ -0,0 +1,98 @@ +# RFC: A shared timeout/deadline primitive, with hard-kill left to each capability + +Status: implemented + +## Problem + +Timeout handling was drifting apart across the tool-bearing capabilities, and the divergence was not superficial — it was the same logic re-implemented three ways, each with its own subtle correctness burden. + +- **bash** ([packages/bash/bash-local/src/run.ts](../../../../packages/bash/bash-local/src/run.ts)) had a full, correct timeout inside the process plumbing: a config-clamped `timeoutMs`, two independent triggers — a `killTimer` for the timeout and an `onAbort` listener for upstream cancellation — each calling one `kill()` closure that escalates SIGTERM→grace→SIGKILL on the process group, and two orthogonal outcome booleans (`timedOut`, `aborted`) latched independently. +- **web_fetch** ([packages/web/web-fetch-local/src/provider.ts](../../../../packages/web/web-fetch-local/src/provider.ts)) had a correct but *hand-rolled* timeout: it constructed an `AbortController`, wired `setTimeout(() => controller.abort(new WebError(…, 'WEB_FETCH_TIMEOUT')))`, manually added and removed the upstream-signal listener, cleared the timer in a `finally`, and recovered the timeout reason from `signal.reason` in a `translateAbortOrNetwork` helper because the reader surfaces a bare `AbortError`. +- **web_search** ([packages/web/tool-web/src/search.ts](../../../../packages/web/tool-web/src/search.ts)) had **no timeout at all**: `WebSearchRequest` ([packages/web/web/src/types.ts](../../../../packages/web/web/src/types.ts)) carries no `timeoutMs` field, and each provider's `search()` only forwards `exec.signal`. (web_search stays untimed here — see Consequences.) + +Each new external-process or network tool re-derived the same four things — clamp the requested value, start a timer, fuse the timeout with upstream cancellation, and distinguish "timed out" from "cancelled" on the way out — and the fusion and reason-recovery are exactly the parts that are easy to get subtly wrong (web_fetch's `signal.reason` dance is evidence). At the same time, the *termination* each performs is irreducibly different: bash kills an OS process group (work runs in a child process, outside this runtime, reachable only by signal), while web aborts an in-process `fetch` (undici tears down the socket). There is no single mechanism that can stop all of them. + +The two reference agents surveyed converged on the same split. Codex models "what will end this exec early" as one value (`ExecExpiration`, an enum fusing timeout and a cancellation token) whose `wait_with_outcome()` returns `TimedOut | Cancelled`, while the actual `kill_process_group` lives outside it — and that abstraction is reused *only* across the exec family, with MCP, model-stream, and guardian each keeping their own bespoke `tokio::time::timeout`. Claude Code shares nothing: bash and ripgrep each own a private SIGTERM→SIGKILL kill and distinguish timeout from cancellation by throwing distinct error types, while file I/O has no timeout. Both confirm the boundary drawn here: the timing-and-classification half is worth sharing within a family of like-terminated operations; the termination half is not shareable and stays in each capability. + +## Decision + +`@deepseek-ai/dsh-timeout` lives under `packages/util/` (peer to `dsh-brand`) and owns the *timing and classification* half of timeout; the *termination* half — the hard kill — stays in each capability's implementation. It is a library of pure functions, **not** a cordis service or plugin: it takes no `ctx`, registers nothing, holds no cross-call state, and emits no events. There is deliberately no central "timeout service" that would have to know how to stop every capability's work — that knowledge is exactly what a microkernel keeps out of shared layers, and what Codex's exec-only `ExecExpiration` scope demonstrates. + +### The library surface + +Three functions plus one reason type: + +```ts ignore-check +/** The internal reason attached to a timeout abort, so consumers can classify it after the fact. */ +export class TimeoutReason extends Error { + override name = 'TimeoutReason' + + constructor(readonly code: string, readonly timeoutMs: number) { + super(`${code} after ${timeoutMs}ms`) + } +} + +/** Validate/fill a caller's optional positive hint from the backend's default, then cap at its max. */ +export function clampTimeout( + requested: number | undefined, + def: number, + max: number, + name = 'timeoutMs', +): number + +/** + * Build a deadline signal that aborts on upstream cancellation OR on timeout, + * with the timeout carrying a `TimeoutReason`. `timeoutMs <= 0` means "no + * timeout" (background tasks): forward only the upstream signal, arm no timer. + * The returned object's `[Symbol.dispose]` clears the timer — `using` for a + * scope-lifetime consumer, a manual call for an event-lifetime one. + */ +export function deadline( + upstream: AbortSignal | undefined, + timeoutMs: number, + code: string, +): { signal: AbortSignal; [Symbol.dispose](): void } + +/** Recover the TimeoutReason from an aborted signal (or error); `code` scopes the match to this deadline's timer. */ +export function timeoutOf(x: AbortSignal | { reason?: unknown }, code?: string): TimeoutReason | undefined +``` + +`deadline` is `AbortSignal.any([upstream, ])` with three things the standard library does not give: a typed, identifiable `TimeoutReason` on the timeout abort (native `AbortSignal.timeout()` yields a fixed `TimeoutError`, indistinguishable across timeout kinds), an internal `timeoutMs <= 0` "no timeout" sentinel for backend-owned background work, and a `Symbol.dispose` cleanup that works with both `using` and manual disposal. `AbortSignal.any` is a Node ≥ 20 primitive; it is the single mechanism that fuses two abort sources into one, adopting the reason of whichever fires first. External request hints validate as positive finite numbers via `clampTimeout` before they reach `deadline`; `0` is not a model-/plugin-facing "disable timeout" value. When `timeoutMs <= 0` and no upstream signal is present, `deadline()` returns a never-aborting signal plus a no-op disposer so callers keep one call shape. `TimeoutReason` is an internal classification reason: providers translate it into seam-specific public errors or result fields before returning to callers. `timeoutOf`'s optional `code` scopes classification to the caller's own deadline: when the `upstream` is itself a deadline (a future `tools/execute` middleware arming a per-call deadline), `AbortSignal.any` preserves the outer `TimeoutReason` if it fires first, and an unscoped match would misreport the outer timeout as the inner capability's own; scoping to `code` reads a foreign timeout as an ordinary upstream cancel. + +### The division of labor + +| Concern | Owner | +|---|---| +| Validate request hint and clamp default/max | `dsh-timeout` (`clampTimeout`) — pure arithmetic plus the shared positive-finite request contract | +| Arm timer, abort on deadline, carry reason, fuse with upstream cancel | `dsh-timeout` (`deadline`) | +| Clear the timer | `dsh-timeout` (`[Symbol.dispose]`) | +| Classify the first abort reason after abort | `dsh-timeout` (`timeoutOf`) | +| **Actually terminate the work** | the capability's implementation | +| The default/max *values* | the capability's config | +| The timeout `code` string | the capability (`WEB_FETCH_TIMEOUT` ≠ `BASH_TIMEOUT`) | + +The signal only *notifies*; termination is always the listener's job, and the listener differs by capability. bash writes its own `addEventListener('abort', kill)` because the OS process lives outside this runtime and nothing else will kill it; web hands `d.signal` to `fetch` and undici tears down the socket. This is why file read/write/edit take **no** `timeoutMs`: a local syscall is best-effort-abortable at most, a timeout could not force `fsync`/`rename` to stop, and adding one would be an implicit default that violates explicit-over-implicit. Both reference agents leave file I/O untimed for the same reason. + +### How each capability consumes it + +- **web_fetch** — the tool stays validate-and-forward; the provider's hand-rolled controller + `setTimeout` + manual listener + `finally` + `signal.reason` recovery is replaced by provider-owned `deadline`/`timeoutOf`. A pre-aborted upstream signal still throws `WEB_ABORTED` up front; otherwise `fetch` runs against the fused `d.signal`, and `translateAbortOrNetwork` classifies a thrown error by the signal (`timeoutOf` → `WEB_FETCH_TIMEOUT`, else aborted → `WEB_ABORTED`, else network → `WEB_PROVIDER_ERROR`). The public error-code contract is unchanged, and `TimeoutReason` never crosses the web seam as the public error. +- **bash** — `resolve()` stays a pure request-to-spec step: it clamps with `clampTimeout(request.timeoutMs, config.timeoutMs, config.maxTimeoutMs, 'bash-local: request.timeoutMs')` and carries `request.signal` through unchanged. Foreground `run()` owns the timeout: `using d = deadline(spec.signal, spec.timeoutMs, 'BASH_TIMEOUT')`, then `runBash` receives only `d.signal`. `runBash` no longer owns any timer — it listens for abort and runs its existing SIGTERM→grace→SIGKILL process-group kill, and its `SpawnSpec`/`SpawnOutcome` no longer carry `timeoutMs`/`timedOut`/`aborted` (the executor classifies from the deadline signal instead). `run()` computes `timedOut = timeoutOf(d.signal, 'BASH_TIMEOUT') !== undefined` and `aborted = d.signal.aborted && !timedOut`, so the public seam booleans (`BashRunResult.timedOut`/`aborted`) are mutually exclusive — the shared deadline reports the cause that first cut the command short, and the `code` scope keeps a nested outer deadline from being misread as bash's own timeout. Background `start()` creates no deadline and forwards only the upstream signal, so background tasks stay timeout-free; a task's killed-vs-completed status reads its own `spec.signal.aborted`. + +## Consequences + +- `runBash`'s outcome no longer independently latches `timedOut` and `aborted`; a timeout and a user abort racing before process close now report a single first-abort cause instead of both being true. The uniform SIGTERM→grace→SIGKILL kill is unchanged, and the seam type `BashRunResult` keeps both booleans (now mutually exclusive), so `dsh-tool-bash`'s result rendering is untouched. +- `SpawnSpec.timeoutMs` and `SpawnOutcome.timedOut`/`aborted` were removed rather than kept as always-zero/always-false vestiges: with `runBash` owning no timer and the executor owning classification, they were read nowhere. This is the one deviation from the literal proposal shape (which passed `timeoutMs: 0` into `runBash`); an always-0 field read by nothing is dead weight under the per-file coverage gate. +- web_fetch shed its bespoke controller/timer/listener/reason-recovery; the classifier now keys off the deadline signal (`timeoutOf` + `aborted`) rather than the thrown error's shape, which is robust across both the request-phase reject-with-reason and the read-phase bare-`AbortError`. +- `AbortSignal.any` and `using`/`Symbol.dispose` enter the repo for the first time here (Node ≥ 24 baseline, already met). + +Out of scope, named to mark the boundary: `web_search` can gain an optional model-facing `timeout_ms` once its tool-schema/snapshot coverage is planned; future ripgrep-backed fs discovery tools can consume the same provider-owned deadline shape once they exist; a `tools/execute` waterfall middleware could arm a default deadline for every tool call by driving `exec.signal` — that would be a plugin that *consumes* this library and still only notifies, the hard kill remaining each capability's job. + +## Alternatives considered + +**A unified timeout *plugin* / `ctx.timeout` service.** Rejected on microkernel grounds. A service that could stop any tool's work would have to understand every capability's termination mechanism (process-group SIGKILL, socket teardown, syscall-boundary checks) — the "kernel knows too much" the architecture forbids. Codex's `ExecExpiration` is scoped to the exec family precisely because the kill it drives (`killpg`) is process-family-specific; MCP and model-stream keep their own. There is no coherent middle layer that owns termination for everything, so the shared piece can only be the pure timing/classification half — a library, not a service. + +**Per-tool ad-hoc timeout, no shared code (the prior status quo, and Claude Code's choice).** Rejected because it was already producing divergence and duplicated correctness burden: web_fetch hand-rolled the exact controller/reason logic that future network/process-backed tools would each have to re-derive, and the fusion + `signal.reason` recovery are the error-prone parts. Claude Code tolerates full duplication; this repo has a single shared abort channel (`exec.signal` on every `execute`) that makes a small shared primitive strictly cleaner, so the cost/benefit differs. + +**A `withTimeout(promise, ms)` wrapper instead of a signal factory.** Rejected because racing a promise against a timer resolves the *tool-call* promise on deadline without stopping the underlying work — the child process or fetch socket leaks on. Handing out a signal and requiring the capability to listen is what forces a real termination path to exist. This mirrors the "dispose must reach quiescence, not just request it" defensive rule. + +**Keep bash's two independent triggers (`killTimer` + `onAbort`) rather than fusing.** Rejected for the convergence goal: fusing into one `deadline` signal removes bash's bespoke timer and gives every capability one shape. The trade-off is that bash's `timedOut`/`aborted` booleans become first-abort classifications rather than independent facts that can both be true when timeout and user abort race before process close. That is acceptable because the result reports the cause that first cut the command short; the termination action stays the same uniform SIGTERM→grace→SIGKILL kill. Note the deliberate non-alignment with Codex: Codex forks its kill by outcome (timeout → immediate SIGKILL; cancel → SIGTERM + 50 ms grace → SIGKILL), whereas the fused signal drives one uniform `kill()` for both, matching Claude Code's unified bash kill. Splitting the kill by `timeoutOf` is possible later if a need appears; there is none now. diff --git a/docs/rfc/implemented/architecture/2026-07-07-tool-call-timeout-policy.md b/docs/rfc/implemented/architecture/2026-07-07-tool-call-timeout-policy.md new file mode 100644 index 0000000000..362f5cb5e8 --- /dev/null +++ b/docs/rfc/implemented/architecture/2026-07-07-tool-call-timeout-policy.md @@ -0,0 +1,110 @@ +# RFC: Tool-call timeout policy as a plugin + +Status: implemented + +## Problem + +The [timeout/deadline RFC](2026-07-06-timeout-deadline-library.md) extracted the timing-and-classification primitive into `@deepseek-ai/dsh-timeout`, but timeout policy was still attached to individual capabilities and model-facing schemas. `bash` exposed `timeoutMs`; `web_fetch` exposed `timeout_ms`; `web_search` had no model-facing timeout even though providers already honor `exec.signal`; a future grep/glob tool would either import the timeout library directly or invent its own timeout policy. That is the wrong authoring shape for a plugin SDK: a tool author should normally forward `exec.signal` to the implementation it calls, and deployment policy should decide the budget. + +At the same time, not every timeout in the repo is a model-facing tool-call budget. Hooks execute command hooks by calling `ctx.bash` directly, not through `ctx.tools.execute()`, and the `bash` model tool multiplexes foreground execution, background start, background polling, and hook reuse through the same backend. Moving every timeout into a tool plugin in one step would conflate those paths and risk breaking hook timeout semantics. + +## Decision + +Tool-call timeout is a policy that applies only to model-facing tool execution, in three parts: + +- `@deepseek-ai/dsh-timeout` remains the shared library that owns `deadline()` and `timeoutOf()`. +- `@deepseek-ai/dsh-tools` has an around-dispatch waterfall, `tools/execute`, between `tools/pre-execute` and `tools/post-execute`. +- `@deepseek-ai/dsh-timeout-policy` reads each tool's declared `timeoutMs` from the registry and wraps a call that has one by deriving a new `exec.signal`. + +The execution pipeline is: + +```text +ctx.tools.execute(exec) + -> tools/pre-execute + -> tools/execute + -> registry dispatch (the base next()) + -> tool.execute(args, exec) + -> thrown tool errors normalize to ToolExecutionResult + -> tools/post-execute +``` + +The default behavior is conservative: a tool that declares no `timeoutMs` receives no `TOOL_TIMEOUT` deadline from the plugin. + +### The `tools/execute` around seam + +`@deepseek-ai/dsh-tools` declares a `tools/execute` waterfall whose base `next()` is the dispatch-with-normalization thunk — the same inner `try`/`catch` that turns a thrown tool (or unknown tool) into an `isError` `ToolExecutionResult`. A listener receives `(exec, next)`: it calls `next()` to delegate to dispatch (returning its result, optionally wrapped) or returns a replacement result to short-circuit dispatch. The whole pipeline still sits inside `execute`'s outer try/catch, so a throwing listener becomes an `isError` result, never a turn failure. + +That the catch is the base `next` — not something outside the waterfall — is load-bearing: when a provider sees the timeout signal and throws its own upstream-abort error, registry dispatch first converts it to a normal error result, and only then can `timeout-policy` replace the final result with `TOOL_TIMEOUT`. + +### The `timeout-policy` plugin + +The plugin is `@deepseek-ai/dsh-timeout-policy`, a zero-config function/namespace plugin (`name` / `inject` / `apply`) in the `packages/timeout/` group. The per-tool budget is DECLARED on the tool, not on this plugin: a `ToolDefinition` carries an optional `timeoutMs`, which the owning tool plugin sets from its own config. `dsh-tool-web`, for example, resolves `fetchTimeoutMs` / `searchTimeoutMs` (default 30000) onto the `web_fetch` / `web_search` definitions: + +```yaml +- id: timeout-policy + name: '@deepseek-ai/dsh-timeout-policy' +- id: tool-web + name: '@deepseek-ai/dsh-tool-web' + config: + fetchTimeoutMs: 30000 + searchTimeoutMs: 30000 +``` + +Keeping the tool name out of this plugin's config is deliberate: a budget keyed by a free-text tool name could be mistyped (`web_fech`) and then silently apply to nothing. Declaring `timeoutMs` on the tool makes that failure class structurally impossible — the enforcer reads `ctx.tools.get(exec.name)?.timeoutMs`, and `exec.name` is the tool being dispatched, so the lookup always resolves and there is no unknown-name path to warn or throw about. `timeoutMs` is validated positive-finite by `defineTool` at definition time. For a tool that declares a budget the listener arms `deadline(exec.signal, timeoutMs, 'TOOL_TIMEOUT')`, swaps the derived signal onto `exec` for the downstream dispatch, restores the caller's own signal afterward, and returns a structured `TOOL_TIMEOUT` result when `timeoutOf(d.signal, 'TOOL_TIMEOUT')` matches. A tool with no declared budget delegates unchanged. + +Signal replacement is by **in-place mutation of `exec.signal`**, not by passing a new object to `next()`. Cordis's waterfall `next()` ignores any arguments handed to it and re-invokes downstream listeners with the shared payload array (`vendor/cordis/src/events.ts`), so the documented cordis idiom — mutate the shared object, then delegate — is the only mechanism that reaches dispatch. The plugin restores `exec.signal` to the caller's original in a `finally` so `tools/post-execute` never sees this plugin's (possibly already-aborted) deadline signal. + +`timeout-policy` owns both uses of the `TOOL_TIMEOUT` code: the internal deadline code passed to `deadline()`/`timeoutOf()` (scoped so a nested outer deadline reads as an ordinary cancel) and the structured tool-result error code. Its replacement result is: + +```ts ignore-check +function toolTimeoutResult(callId: CallId, timeoutMs: number): ToolExecutionResult { + return { + callId, + content: [{ type: 'text', text: `Error: tool call timed out after ${timeoutMs}ms` }], + isError: true, + error: { name: 'ToolTimeoutError', code: 'TOOL_TIMEOUT' }, + } +} +``` + +This is a cooperative deadline. It does not kill arbitrary work by racing the tool promise; the tool or the capability it calls must honor `exec.signal` and reach quiescence. Declaring `timeoutMs` therefore MEANS "this tool is cooperative with `exec.signal`", which the plugin README states as its contract. + +No new session event is needed for reconstructability: `TOOL_TIMEOUT` is the final model-facing `tool/result` for that call, so the existing session log already records the content and structured `{ name, code }` error the next model request sees. + +### Existing tool adaptation + +`web_fetch` and `web_search` are migrated. `dsh-tool-web` keeps ownership of their model-facing schemas, and those schemas expose no timeout knob: `web_fetch` dropped its `timeout_ms` parameter to match the reference-agent shape, and `web_search` stays query-only. The tool bodies do not import `@deepseek-ai/dsh-timeout`; they forward `exec.signal` to `ctx.web`. + +`dsh-web-fetch-local` keeps a provider-level timeout (`timeoutMs`/`maxTimeoutMs`) as a large resource backstop for direct `ctx.web.fetch()` callers and misconfigured deployments; it owns no model-facing timeout. When a `TOOL_TIMEOUT` signal reaches the fetch provider first, provider-scoped classification treats it as upstream `WEB_ABORTED`, and the outer `tools/execute` wrapper replaces the final tool result with `TOOL_TIMEOUT`. A shipped web-tool deployment configures the provider backstop above the `timeout-policy` budget so the tool-call policy normally wins for model calls. + +`bash` stays on the current backend timeout path. `dsh-tool-bash` continues to expose `timeoutMs` and `run_in_background`; `dsh-bash-local` continues to use `@deepseek-ai/dsh-timeout` for `BASH_TIMEOUT`; hook bridges continue to call `runHook()` and pass `timeoutMs` through `ctx.bash`. This keeps foreground/background/hook behavior stable. + +`read`, `write`, `edit`, `todo_write`, `bash_output`, and `bash_kill` do not opt into tool-call timeout: they are local filesystem or short registry/session operations where a deadline would be best-effort only or unnecessary. + +A future model-facing grep/glob tool can be implemented on top of `ctx.bash` without importing `@deepseek-ai/dsh-timeout`: it forwards `exec.signal` to `ctx.bash`, and declares its own `timeoutMs` (from its plugin's config) for the enforcer to apply. If bash-local's backend timeout becomes a problem for such a tool, the bash seam can later add a caller-owned-deadline mode; that is outside this cut. + +## Alternatives considered + +**Name the plugin `tool-timeout`.** The literal RFC name matched the `gen-tool-catalog` completeness guard's `packages/*/tool-*` glob, which requires every match to register a model-facing tool. This plugin registers none — it is a `tools/execute` wrapper — so a `tool-*` name would either fail `verify-tool-catalog` or force a misleading boot entry. The package is `@deepseek-ai/dsh-timeout-policy` in a new `packages/timeout/` group; the cordis.yml `id` can still be `timeout-policy`. + +**Keep per-tool timeout handling only.** This was the shape for `bash` and `web_fetch`, and it matches Claude Code and Codex for shell commands. It loses for web-style tools because every new timeout-capable tool must choose validation, cap semantics, docs, snapshots, and classification. The plugin centralizes policy and classification while leaving each tool's schema focused on business input. + +**Move all timeout policy out of bash-local immediately.** Cleaner long-term — bash-local would become a pure subprocess executor and all callers would own their deadlines. It loses as the first step because hooks call `ctx.bash` directly and the bash model tool has foreground/background semantics that are not the same tool-call lifetime. Keeping `BASH_TIMEOUT` preserves those paths while tool-call timeout proves itself on simpler tools. + +**Use a global default budget for every tool.** Convenient, but it surprises tool authors: any tool that accidentally runs longer than the global budget would start failing once the plugin loads. A per-tool declared budget makes adoption deliberate. + +**Expose a model-facing `timeout_ms` override.** Claude Code's `WebFetch`/`WebSearch` and Codex's web tools keep timeout out of the model-call shape. A model override would make timeout part of prompt semantics and force schema/argument-stripping rules into `timeout-policy`. Web timeout stays deployment policy only. + +**Let `timeout-policy` match tool arguments itself.** A rule engine such as "disable timeout when `bash.run_in_background` is true" would make the policy plugin know tool-specific argument semantics. Avoided by not migrating bash to tool-call timeout. + +**Use `tools/pre-execute` plus `tools/post-execute` instead of a new around seam.** A pre listener could arm a deadline and mutate `exec.signal`; a post listener could classify and replace. That loses because the deadline lifetime would cross two independent waterfalls: a call-id map, cleanup on every pre-deny/tool-throw/post-throw/dispose path, and ordering rules with every other listener. `tools/pre-execute` is also the allow/deny gate, not an execution wrapper. `tools/execute` gives the timeout one lexical scope: arm, delegate, classify, dispose. + +**Use `Promise.race` to enforce timeouts for non-cooperative tools.** Rejected for the same reason as the timeout-library RFC: it returns control to the caller while the underlying process, fetch, or provider operation may still be running. The plugin only sends a signal; termination remains the implementation's responsibility. + +## Consequences + +- `@deepseek-ai/dsh-tools` gains an around-dispatch surface after the interception seams deliberately split pre/post tool hooks. Its contract is narrow — wrap registry dispatch, not replace the pre-gate or post-result policy — and the base `next()` is dispatch-with-normalization so a wrapper never sees a raw tool throw. +- Multiple `tools/execute` listeners compose by ordinary Cordis waterfall order: a listener that calls `next()` wraps downstream listeners plus dispatch; one that returns without `next()` short-circuits them. A deployment combining timeout with a future retry/sandbox/metrics wrapper chooses semantics by registration order ("timeout covers the whole retry" vs "timeout covers each attempt"). +- Opt-in by declaration is a deliberate misconfiguration risk: a tool can declare a `timeoutMs` without honoring `exec.signal`, and that tool will not stop on timeout. The plugin contract states that declaring a budget means cooperative; the web tools prove the pattern on tools that already forward the signal. +- During the transition `bash` and the migrated web tools use different timeout paths on purpose: `TOOL_TIMEOUT` is the model-facing tool-call budget, while `BASH_TIMEOUT` remains the bash backend timeout used by bash and hooks. +- Deviation from the literal proposal, recorded per the implemented-RFC rule: the plugin package is `@deepseek-ai/dsh-timeout-policy` (not `tool-timeout`), signal replacement is in-place `exec.signal` mutation before `next()` (not `next({ ...exec, signal })`, which cordis ignores), and the per-tool budget is declared on the `ToolDefinition` (`timeoutMs`, set by the owning tool plugin from its config) rather than mapped by tool name in this plugin's config — so the enforcer is zero-config and a mistyped tool name is impossible. All three are described in `## Decision` above. diff --git a/docs/rfc/implemented/feature/2026-06-25-ask-user-question.md b/docs/rfc/implemented/feature/2026-06-25-ask-user-question.md new file mode 100644 index 0000000000..9320189de1 --- /dev/null +++ b/docs/rfc/implemented/feature/2026-06-25-ask-user-question.md @@ -0,0 +1,49 @@ +# RFC: Ask-user question capability + +Status: implemented + +## Problem + +The agent sometimes cannot proceed safely from model inference alone: it needs the human to choose a path, confirm a risky/default action, or provide missing information. Before this change, the only way to get that answer was for the model to ask in assistant text and then stop, which broke the normal tool-call loop: the agent had no structured way to pause, no option metadata for UIs, no abort/error taxonomy, and no way for non-stdio front doors to present the question consistently. + +This is a user-facing capability, but it also crosses package boundaries. A model-facing tool needs a provider-neutral request vocabulary; each UI surface needs to decide how to show and collect the answer; the agent loop should remain unchanged because a tool call already has the right async shape. + +## Decision + +Introduce `dsh-user-interaction` as the provider-neutral interface package for `ctx.userInteraction`, colocated with the model-facing consumer `dsh-tool-ask-user` under `packages/ui`. The grouping is intentional: asking a human is a UI-backed product affordance, not part of the providerless core spine. The seam still owns the stable request/answer/error vocabulary, while UI product surfaces provide the concrete provider that collects the answer. The tool registers `ask_user_question`, forwards `{ questions, agent, signal }`, and returns the provider-computed structured answers as the tool result. + +The model-facing request vocabulary is deliberately aligned with the product-research schema: `ask_user_question({ questions: [{ id, question, header?, options?: [{ label, description? }], multi_select? }] })`. `id` is supplied per question and echoed in the result so a batch can be routed without relying on question text. `label` is both user-facing display text and the selected value returned to the model; there is no separate `value`, no `recommended`, no `allow_custom`, and no `desc` alias. + +Providers return `{ answers: [{ id, selected, custom? }] }`. `selected` is always an array of selected option labels, so single-select and `multi_select` answers share one result shape. `custom` carries a free-text "Other" answer; optionless questions collect `custom` directly. When `custom` is present, it overrides any selected choices and `selected` is empty. + +`UserInteractionError` extends `HarnessError`, so failures such as `NO_PROVIDER`, `ASK_ABORTED`, ACP cancellation, or missing session routing survive `ctx.tools.execute()` as machine-routable `{ name, code }` tool errors. This matches the structured-error taxonomy and lets the model or a wrapping plugin distinguish "user cancelled" from a generic thrown exception. + +## UI mappings + +`dsh-stdio-agent`'s in-package readline module renders each question, shows each option's `description` on the next line, supports comma/space-separated numeric choices for `multi_select`, accepts free-form custom answers, and rejects pending questions on abort, provider disposal, or stdin EOF. A batched request is asked in order and resolved as one answer object. The stdio provider serializes simultaneous requests with an internal queue so only one prompt owns stdin at a time. + +`dsh-acp` provides the same seam for ACP sessions. It routes an ask request from the calling `Agent` through the bridge's `agent→sessionId` reverse map and calls ACP `unstable_createElicitation` with a session-scoped form for each question. Single-select options become a `choice` string enum; `multi_select` options become a `choice` array enum; optionless questions use a required `custom` text field. If the client returns both `choice` and non-empty `custom`, the custom answer wins. ACP `decline`/`cancel`, a missing answer, a missing session, and a client without elicitation support all become structured `UserInteractionError`s. + +The ACP mapping deliberately uses elicitation, not `session/request_permission`. `request_permission` is still reserved for the separate permission gate: it is a yes/no-or-policy authorization protocol around tool execution. `ask_user_question` is a general information-gathering tool with optional free-form answers, so ACP form elicitation is the closer protocol fit. The bridge's session routing is shared with the future permission gate, but the user intent is different. + +## Alternatives considered + +**Assistant text followed by a stopped turn.** The model could ask the user in plain assistant text and then stop. That loses the structured option metadata, gives UIs no provider-neutral way to render a choice, and forces the next human answer to arrive as a new user prompt rather than as the result of the operation that needed the answer. + +**Core-owned ask-user packages.** The first implementation split the seam and the model-facing tool across `packages/core` and `packages/ui`, but both names describe one UI-backed human-interaction affordance. The seam remains provider-neutral, but it is not providerless core infrastructure like sessions, tools, or the agent registry. Keeping `dsh-user-interaction` and `dsh-tool-ask-user` together under `packages/ui` makes the package map match the product boundary: apps and bridges provide the human-answer provider, and the stdio app opts into the model-facing tool. + +**ACP `session/request_permission`.** Permission requests are authorization around tool execution; `ask_user_question` is information gathering with optional free-form answers. Using permission for general questions would collapse two different product concepts and make the future permission gate harder to reason about. + +**A loop-level pause primitive.** The agent loop already knows how to await a tool call and resume from a tool result. Adding a new loop special case would duplicate that async shape and make every loop implementation learn about a UI concern. + +## Consequences + +ACP elicitation is currently marked unstable in the SDK. The fallback is still structured: if a client does not implement it, the tool returns `ASK_FAILED` rather than hanging. A later ACP stabilization may rename or reshape the method; that migration should stay inside `dsh-acp` because the core `ctx.userInteraction` vocabulary is provider-neutral. + +The feature gives the model a powerful pause primitive, so prompt guidance matters. The tool description tells the model to ask concise questions and use options when possible. Product policy can later wrap `tools/execute` to restrict when the tool is allowed, but the loop should not special-case it. + +`dsh-user-interaction` and `dsh-tool-ask-user` both live in `packages/ui` because they form one product-facing human-interaction capability. `agent-core` does not load either the tool or a provider. `stdio-agent` opts into the seam, its readline provider, and the model-facing tool. `acp-agent` keeps only the `userInteraction` seam/provider by default: ACP elicitation support is still client-dependent, so an ACP leaf must opt into the model-facing tool deliberately once its client can complete elicitation requests. + +## Testing + +Unit coverage pins provider registration/disposal, duplicate-provider rejection, abort-before-provider, empty-question rejection, structured tool errors through `ctx.tools.execute()`, batched answers, multi-select answers, custom answers, and the model schema including the removal of `value`, `recommended`, `allow_custom`, and `desc`. `dsh-stdio-agent` tests cover option descriptions, queued requests, EOF/abort cleanup, optionless free-form input, invalid option reprompts, duplicate multi-select numbers, and batched question flows. ACP bridge tests drive a real in-memory ACP connection with the real `ask_user_question` tool and verify selected-option, custom-overrides-choice, multi-select, and optionless free-form elicitation paths continue the agent loop. diff --git a/docs/rfc/implemented/feature/2026-07-07-session-prefix.md b/docs/rfc/implemented/feature/2026-07-07-session-prefix.md new file mode 100644 index 0000000000..6f81d12407 --- /dev/null +++ b/docs/rfc/implemented/feature/2026-07-07-session-prefix.md @@ -0,0 +1,42 @@ +# RFC: The session prefix — request-only messages in front of the derived history + +Status: implemented + +## Problem + +A plugin often owns a session-stable opener the model must always see — a skills catalog, an AGENTS.md digest, a workspace baseline. Before this seam the harness offered two homes, and both are wrong for that content. The system prompt is one rendered string: message-shaped content (a user-role `` envelope, a multi-message primer) does not fit it, and providers weight conversation messages differently from system text. Durable history (`agent.inject()`, a `context/message` at session start) makes the opener permanent: every `deriveMessages()` consumer replays it, the compaction retention walk owns it, forks bake it in stale, and a resume cannot refresh it — a catalog captured at session birth outlives the world it described. + +The obvious third option — let a plugin edit the request's `messages` on the way out — is banned by [the reconstructable-requests RFC](../architecture/2026-07-05-reconstructable-requests.md): every loop-built request is a pure function of the session log, so whatever channel carries the opener must log exactly what it sends. What was missing was a request-only message channel with a durable record. + +## Decision + +`agent/session-prefix` is a waterfall on the agent event map ([`packages/core/agent/src/types.ts`](../../../../packages/core/agent/src/types.ts)): listeners receive a frozen empty seed and return an extension (the canonical contribution is a prepend, `[mine, ...await next()]`, which yields registration order on the wire). The loop ([`packages/core/agent-loop/src/loop.ts`](../../../../packages/core/agent-loop/src/loop.ts)) fires it once per loop instance, lazily before the instance's first `agent/pre-step`; the composed list is deep-cloned, deep-frozen, cached on the instance, and placed in front of the ENTIRE derived history — directly after the provider's system slot — on every request the instance sends ([wire order](../../../core-data-structures/core.md#the-request-envelope-llmcallconfig-and-the-logged-header)). + +Three properties carry the design: + +- **Request-only, header-logged.** `deriveMessages()` never returns the prefix; its one durable record is `EpochHeader.messagePrefix` on the instance's anchoring `request/header` snapshot — the channel the reconstructable-requests RFC already owns for the request's non-history half, so no new session event exists. The dev invariant ([dsh-invariants](../../../../packages/support/invariants/src/index.ts)) recomputes `messagePrefix + boundary derivation` against every loop-built request; an unlogged prefix cannot reach the wire. +- **Frozen per instance.** Reuse is structural, not disciplined: the cached product cannot change mid-session, so the provider's prompt cache holds by construction and the prefix extends the cacheable region at zero marginal cost per step. A process restart or `ctx.agents.resume()` is a new instance: it recomposes, and any drift lands attributably on the `'resume'` header snapshot. This is the routing rule the seam creates: session-frozen openers ride the prefix; content that changes mid-session rides the append-only history channels (`agent.inject()`, a `tools/post-execute` decision's `additionalContext`, prompt-submit `additionalContext` — [the interception-seams RFC](2026-06-30-interception-seams.md)), each a durable `context/message` paid once and prefix-cached thereafter. +- **Composed before the pressure gate.** Composition precedes the instance's first `agent/pre-step`, and the seam hands the composed value through: `agent/pre-step` carries a `sessionPrefix` parameter and `CompactService.compactIfNeeded(agent, fullSystemPrompt, sessionPrefix, signal)` counts it in its token-pressure estimate — a gate reading the previous instance's folded prefix instead would under-gate a resumed or forked instance whose contributor grew, skipping compaction and shipping an over-window first request. A composition interrupted by a cancel/dispose landing inside the waterfall is discarded, never cached: an abort-aware listener's degraded fallback cannot leak into later requests, and the next turn recomposes under a live signal. + +Because composition runs before the boundary snapshot, a composing listener's session append joins the CURRENT request's derived history. Compaction structurally cannot touch the prefix (or the system prompt): it rewrites surface nodes, and header state never enters the surface. + +## Testing + +**Unit** — [interception.spec.ts](../../../../packages/core/agent-loop/tests/interception.spec.ts) pins compose-once across turns and steps (one composition, zero `request/header-delta`s), canonical prepend ordering, empty-prefix omission from the header, the frozen seed (in-place push throws), held-reference mutation immunity, and composition-precedes-pre-step with the seam receiving the composed value; [cancel.spec.ts](../../../../packages/core/agent-loop/tests/cancel.spec.ts) pins cancel/dispose landing inside the composition window and the discard-and-recompose stale-cache guard; dsh-session codec tests cover the `messagePrefix` fold/diff/apply arms (empty ≡ absent); dsh-invariants tests pin the `messagePrefix + derivation` equation; dsh-compact-basic tests pin that the pressure estimate counts the handed prefix. **Snapshot** — the acp-snapshot normalizer scrubs header prefixes to count-preserving `{{messagePrefix}}` tokens (unit-covered in dsh-acp-snapshot); header content itself is pinned per [the pinned-header scenario RFC](../testing/2026-07-06-pin-request-header-content-in-one-scenario.md), and the example tree loads no prefix contributor, so live goldens stay prefix-free. **e2e** — none prefix-specific: the seam is provider-independent and deterministic; the with-key cache measurement in [request-cache.e2e.ts](../../../../packages/core/agent-loop/tests/request-cache.e2e.ts) already proves the cacheable-prefix economics the design rests on. + +## Alternatives considered + +- **Per-request `before`/`after` slots recomputed every step** (the shape first proposed: a waterfall firing on every request, contributing frozen `before` messages ahead of the history and fresh `after` messages behind it) — rejected. A per-step `before` recompose invites silent drift — nothing anchors it to the log short of logging a header delta per step — and an `after` slot sits behind the growing history, so its tokens re-pay on every request and everything after it is uncacheable. Measured against the alternatives, every current update pattern is served cheaper by a durable append (paid once, cache-read thereafter), and the only content with no home was the session-stable opener — which wants freezing, not recomputation. +- **A system-prompt section** (`system-prompt/assemble`) — rejected for this content: the assembly renders to the single `system` string, so message-shaped openers do not fit, and the system prompt is deliberately re-assembled per step (with header deltas when it changes) while the opener wants instance-frozen semantics. +- **A durable history opener** (`inject()` at session start) — rejected: permanent history is the failure mode in the problem statement — replayed everywhere, compactable, stale across resumes. +- **Compose per turn instead of per instance** — rejected: a turn-boundary recompose either desyncs silently from the log or forces a header delta per change, and it busts the provider cache exactly as often as it fires; the legitimate refresh point is the instance boundary, where the `'resume'` snapshot already records drift attributably. +- **Compose lazily at the first request and let compaction read the folded header** (the shape as first merged) — superseded in review: the fold matches the live prefix only from the instance's second request on, so on a resumed/forked instance's first step the pressure gate read the PREVIOUS instance's prefix and could under-gate. Composing before the first pre-step and handing the live value through the seam makes the estimate exact at every step. +- **A dedicated session event carrying the prefix** — rejected: the header events are the request's non-history record by design; a second event would be a second home for the same fact and another codec to keep total. + +## Consequences + +- `agent/pre-step` and `CompactService.compactIfNeeded` carry a `sessionPrefix` parameter: every pre-step listener and compaction backend sees the real per-instance value (all in-repo implementations updated in the same change, per the pre-release stance). +- A contributor whose content changes mid-session is not re-read until the next instance — by design. A deployment needing mid-session catalog updates routes the change notice through the append-only history channels and pays one durable `context/message`. +- The dropped `after` slot leaves no request-only channel near the request tail; nothing in the repo needs one, and adding it back would re-open the every-step re-pay cost the design exists to avoid. +- The `request/header-delta` `messagePrefix` arm (whole-array replacement, empty array encoding transition to absence) exists for codec totality; the loop never exercises it, because the cached prefix cannot change within an instance. +- An empty composition is canonical absence: no-contributor deployments log no extra header bytes and their requests are the bare derivation. diff --git a/docs/rfc/implemented/feature/2026-07-08-repeat-tool-guard.md b/docs/rfc/implemented/feature/2026-07-08-repeat-tool-guard.md new file mode 100644 index 0000000000..9d0446dcad --- /dev/null +++ b/docs/rfc/implemented/feature/2026-07-08-repeat-tool-guard.md @@ -0,0 +1,73 @@ +# RFC: Repeat-tool-call guard plugin + +Status: implemented + +## Problem + +A model stuck in a loop re-issues the same tool call with byte-identical arguments — re-running a failing grep, re-reading an unchanged file, polling a command that already gave its answer — and each round trip burns tokens, wall-clock, and (for paid APIs) money without adding information. The harness has nothing that notices: the loop has no step budget, no plugin tracks call repetition, and the model only escapes when it happens to vary its own behavior. The failure mode is real and cheap to detect — [pi-repeat-tool-guard](https://github.com/Kingwl/pi-repeat-tool-guard) ships exactly this as a pi coding-agent extension: count consecutive identical calls and, past a threshold, append a `` telling the model to stop repeating itself and change course. + +The harness already has every seam the pi extension uses, and better ones: [the interception-seams RFC](2026-06-30-interception-seams.md) gives `tools/post-execute` a sanctioned way to attach model-facing context to a finished call, the loop buffers and injects that context with call/result adjacency preserved, and injected context is a logged `context/message` — so a native guard satisfies the model-visible ⟺ logged rule with no new session event. What was missing was only the plugin itself. + +## Decision + +The guard is a loop-hygiene plugin, not a model-facing tool: it never appears in the tool list, never vetoes or rewrites a call, and adds exactly one behavior — it watches each agent's stream of tool calls, counts runs of consecutive calls to the same tool with identical canonicalized arguments, and at configured run lengths injects an escalating advisory reminder telling the model to stop repeating itself, re-read the last result, and either change approach or conclude. The purpose is to break unproductive loops within a few wasted steps instead of letting them run to the turn's natural end — while leaving the decision (retry differently, gather more evidence, or finish) entirely with the model, so a legitimately repeated call is delayed by nothing and blocked by nothing. + +The plugin is `@deepseek-ai/dsh-repeat-tool-guard` at `packages/guard/repeat-tool-guard/`, opening the `guard/` group for loop-hygiene plugins (single-package groups have precedent: [the todo-write RFC](2026-06-29-todo-write-tool.md) shipped `todo/tool-todo`). It registers three listeners and holds all state in plugin-local maps keyed by `AgentId` — the tool registry is a context-level singleton whose waterfalls interleave every agent's calls (subagents run on the same context), so per-agent keying is correctness, not polish. + +- **`tools/post-execute` (waterfall)** — the one detection point. The listener receives `(exec, result)` together, so counting and reminder delivery need no cross-event pending map (the pi extension needs one only because its `tool_call`/`tool_result` hooks are separate events). It always delegates via `next()` and, when a threshold is hit, folds a reminder onto the downstream decision's `additionalContext` — the observe-and-enrich posture [the hooks bridges](2026-06-30-hook-bridges.md) already use, honoring the waterfall contract. Counting happens here rather than in `tools/pre-execute` because post-execute also runs for denied calls (`ToolRegistry.execute` routes a deny through the same pipeline), and a model hammering a denied call is exactly the loop worth breaking. +- **`agent/prompt-submit` (waterfall)** — pure reset hook: delegate via `next()`, clear the submitting agent's chain. A user interjection changes the context; repetition across it is not a loop. +- **`agent/status` (emit)** — on `disposed`, drop the agent's state, bounding the maps over harness lifetime. + +### Detection semantics + +The chain key is `(tool name, canonical arguments)`; a call identical to the previous tracked call increments the agent's consecutive counter, a different tracked call resets it to 1. Canonicalization is a deep key-sort plus `JSON.stringify`: `ToolExecution.arguments` is by construction the loop's `JSON.parse` output (or the raw string fallback for malformed argument JSON, which is itself a comparable value), so the pi original's bigint/circular/`undefined` handling has no inputs here and is deliberately dropped. + +Two deliberate rules, both documented in [the package README](../../../../packages/guard/repeat-tool-guard/README.md) because they are behavior a reader would otherwise guess at: + +- **Untracked calls are transparent to the chain.** A call excluded by `include`/`exclude` neither increments nor resets the counter, so `grep X → todo_write → grep X` still counts as two consecutive `grep X` when `todo_write` is excluded. This is what makes exclusion useful — bookkeeping tools interleaved into a loop must not launder it — and it is the pi extension's (undocumented) semantics, kept on purpose and written down. +- **Calls without an agent are ignored.** A direct `ctx.tools.execute()` caller (tests, non-loop consumers) has no model to remind and no `AgentId` to key on. + +### Reminder delivery + +Reminders ride `additionalContext` (source `{kind: 'plugin', plugin: 'repeat-tool-guard'}` — the label is load-bearing per `HookContext`), never a `content` replacement: the `tool/result` event stays the tool's own output for audit, and the loop appends buffered context as `context/message`(s) after the step's results, which the session renders as the tagged synthetic-user envelope and derived history replays. Thresholds escalate: the first configured threshold gets a short "you are repeating yourself, analyze the previous result" nudge; each later threshold gets the detailed form naming the tool, the repeat count, and the canonical arguments (head-truncated at `argumentsPreviewChars`, default 500 — a looping `write`-sized payload must not ride into the next request unbounded; the chain key always compares the full canonical string), and stating that the calls made no progress. The pi original hardcodes the gentle text to the literal count 3; the guard keys it to `thresholds[0]`, fixing that bug in the port. When the downstream decision already carries `additionalContext` (a hook bridge on the same call), the guard concatenates content under its own `source` — a `HookContext` holds one `MessageSource`, and `source.kind` is what framing depends on. + +### Config + +```yaml +- id: repeat-tool-guard + name: '@deepseek-ai/dsh-repeat-tool-guard' + config: + thresholds: [3, 5, 8] # default; consecutive counts that trigger a reminder + include: [] # tool-name patterns to track; empty ⇒ all tools + exclude: [todo_write] # tool-name patterns transparent to the chain + argumentsPreviewChars: 500 # default; cap on arguments quoted in the detailed reminder +``` + +`thresholds` is validated at load and throws on an empty list, a non-integer, a value below 2, or a duplicate — misconfiguration fails loud, replacing the pi original's silent fall-back to defaults. `include`/`exclude` entries support `*` wildcards. Patterns are predicates over whatever tools exist at call time, not references to a registry entry, so an entry matching no currently registered tool is NOT an error — unlike `toolOrder`'s referent check, `exclude: [mcp_*]` must stay valid in a deployment that loads no MCP tools. + +## Testing + +**Unit** — the suite drives a real agent loop against a scripted mock adapter (no network) and covers, at per-file 100%: counting/reset semantics (identical, different-tracked, untracked-transparent, prompt-submit reset, disposal cleanup, per-agent isolation), canonicalization (deep key-order insensitivity), threshold escalation including the `thresholds[0]` gentle-text rule, denied-call counting, no-agent transparency, wildcard escaping, config fail-loud cases, and both fold-onto-downstream paths (block and accept-with-replacement). **Snapshot** — the `repeat-tool-guard` scenario in the acp-agent example suite scripts five identical `todo_write` calls and pins both reminder tiers (gentle at the third, detailed at the fifth) as `context/message`s in the ACP transcript and the session log; the guard is loaded in the example's live tree (`cordis.yml`), inert for every other scenario (none repeats a call three times). The scenario is authored keyless (like `error-finish`/`cancel`): deterministically forcing a live model to repeat one call three times is not a stable recording. **e2e** — none: the plugin is provider-independent and deterministic, and the seam contracts it relies on are e2e-covered by their owners. + +## Alternatives considered + +- **Append the reminder into the tool result** (`accept` with replaced `content` — the pi extension's mechanism, which patches result content because that is the only channel its API offers) — rejected: it makes the logged `tool/result` lie about what the tool returned, and `additionalContext` exists precisely as the separate sanctioned channel for post-execute commentary, with loop-level buffering that preserves call/result adjacency. +- **Count in `tools/pre-execute` with a pending-reminder map** (the pi two-phase shape) — rejected: post-execute alone sees `(exec, result)` together and also fires for denied calls, so one listener with no cross-event state covers strictly more attempts with less machinery. +- **Escalate to `block` at the highest threshold** — rejected for the initial scope: a blocked call punishes legitimate identical repeats (polling a long-running terminal, re-checking a file the agent expects to change), and an advisory reminder keeps the model in control. Revisit with evidence; the decision shape (`PostToolDecision`) already supports it. +- **A per-deployment external hook via the CC/Codex bridges** (a `PostToolUse` script) — rejected as the answer: it works for one deployment, but a shipped, unit-tested, `cordis.yml`-configurable plugin is the harness-native form, without per-call subprocess cost. +- **A loop-level step or repetition budget in `agent-loop`** — rejected: "plugins, not loop changes"; a hard step budget is a blunter, orthogonal control that would need its own proposal. +- **Fuzzy/near-identical detection** (normalized paths, similar-but-not-equal arguments) — rejected: exact match after canonicalization is cheap, deterministic, and explainable to the model; similarity thresholds invite false positives and need evidence before they earn complexity. +- **Placing the package in `core/`** — rejected: core is the product spine; a behavioral guard is an optional leaf plugin, and the `todo/` precedent is a small dedicated group per plugin family. + +## Consequences + +- The reminder is advisory by design: idempotent polling patterns that repeat identical calls on purpose still receive nudges past the thresholds, and the pressure valves are config (`thresholds`, `exclude`) plus reminder text that explicitly allows finishing when enough evidence has been gathered. Each trigger costs reminder tokens on the next request; thresholds bound the frequency. +- Chain state is in-memory only: a session resumed from persistence starts with a fresh chain, so a loop spanning a resume draws its reminders later than a live one — accepted, the guard is a heuristic nudge, not a logged invariant, and persisting counter state would buy little for real complexity. +- When multiple post-execute producers attach context on one call, the fold concatenates under the guard's `source`; ordering between plugins follows listener registration order. The seam cannot represent mixed provenance — a limit inherited from `HookContext`, not owned by this plugin. +- Implementing the snapshot tier surfaced a hidden assumption in the suite kit: the fixture guard equated "authored model scenario" with "override-driven". The `Scenario` table now carries an explicit `overridden` flag, and the sidecar's presence is checked BOTH ways against it (an unregistered stray sidecar would silently replace the derived script) — the suite kit is stricter than it was before this plugin existed. + +## Deferred + +- Compaction does not reset chains: a compacted history changes what the model sees, but the repetition risk usually survives compaction. +- Escalating to `block` at a high threshold is not implemented; `PostToolDecision` already supports it if evidence arrives. +- Subagent chains stay isolated per agent; no sharing mechanism exists until a concrete case appears. diff --git a/docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md b/docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md new file mode 100644 index 0000000000..3ec6c75cbc --- /dev/null +++ b/docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md @@ -0,0 +1,84 @@ +# RFC: The self-referential cordis toolset + +Status: implemented + +## Problem + +Everything in this harness is a cordis plugin, but the agent running inside that plugin runtime cannot see or touch it: it cannot enumerate the services and events around it, cannot extend itself with a new tool mid-session, and cannot compose capabilities it invents. Handing the model that power is worth exploring — a self-referential agent that inspects and modifies its own runtime — but it raises three correctness problems at once, and the design is about answering them rather than the raw "let the model run code" mechanic. + +First, model-written registration must be validated where it happens: a malformed tool schema has to fail at registration, not when a later request tries to assemble it into a prompt. Second, model-written code has to call service APIs whose source it has never seen — guessed method signatures and, worse, guessed return-value shapes cost many steps of blind probing. Third, everything the model mounts must be fully disposable, by the model on demand and by the ordinary plugin lifecycle when the host plugin reloads, or a long session accretes orphaned listeners and tools. + +## Decision + +The toolset ships as [`@deepseek-ai/dsh-tool-cordis`](../../../../packages/cordis/tool-cordis/README.md) — a new top-level `packages/cordis/` group — and is demoed by [`examples/cordis-agent`](../../../../examples/cordis-agent/README.md). It gives the model three tools over the live cordis runtime it is running inside: inspect it, mount model-written plugins into it, dispose them again. + +The trust stance, stated once and threaded through the rest: the `node:vm` sandbox isolates the global context only — it prevents accidental global pollution, not malice — and the `ctx` a mounted plugin's `apply` receives is a whitelist façade that narrows the *surface* (framework internals withheld) but not the *privilege* of what it exposes. The verbs the façade does expose reach the real runtime: a mounted tool can shell out through `ctx.bash`, read the filesystem through `ctx.fs`, reach the network through `ctx.web`. Neither the sandbox nor the façade is a security boundary; handing the model this power is the point of the toolset. A deployment loads this plugin exactly as deliberately as it grants a bash tool — an opt-in capability in the app's `cordis.yml`, never a product default. + +### The three tools + +| Tool | Contract | +|---|---| +| `cordis_inspect` | Read-only report over the live runtime, one Markdown section per `what` value (omit `what` for all sections). Never mutates. | +| `cordis_mount` | Evaluates `code` (the body of an async JavaScript function) in a `node:vm` sandbox; the code must `return` a cordis plugin, which is mounted as a child of the `cordis-dynamic` group fiber and tracked under a fresh id (`dyn-1`, `dyn-2`, …). | +| `cordis_unmount` | Disposes one dynamic mount by id and returns only after disposal reaches quiescence — every registration the plugin made is unwound, not merely requested to stop. | + +`cordis_inspect` sections: `services` (every provided ctx service and the owning fiber, non-active owners flagged), `plugins` (a flat list of every loaded plugin with its lifecycle state, from `ctx.registry` — what capabilities are loaded, deliberately not the tree shape), `tools` (what the model can call), `dynamic` (the mount table: id, name, state, provided services, awaited services), `api` (live service signatures + the type shapes they reference, from the generated catalog), and `events` (harness events with dispatch mode and signature). The model-facing tool descriptions carry the operational rules the model needs at call time; [the generated tool catalog](../../../tool-catalog.md) is their exhaustive rendering. + +### Sandbox semantics + +Mount code runs via `vm.createContext` + `runInContext`, wrapped as the body of an async function under a per-mount filename (`cordis-mount-.js`). The vm gives the code a fresh realm: writes to `globalThis` stay inside the sandbox, and no Node API is handed in — capability access is *steered* toward the cordis services (`ctx.fs` for files, `ctx.web` for HTTP, `ctx.bash` for processes, the `ctx.timer` helpers for timing) rather than Node built-ins, so a well-behaved mount stays inspectable through `cordis_inspect` and disposable with its fiber. This is steering, not containment: consistent with the trust stance above, the small global surface keeps *honest* code on the cordis services but is not a security boundary — the host-realm helpers it exposes (`harness`, `console`, `btoa`) are reachable functions, so mount code that goes looking (through such a helper's `.constructor`, say) can still reach the host realm and Node itself, which is accepted because the `ctx` a mount ultimately receives is fully privileged anyway. The `vmTimeoutMs` config bounds only the synchronous portion of evaluation; an async body escapes the bound (also acceptable under the trust stance). + +Sandbox globals are deliberately small: a tagged write-through `console` (`[cordis:] …` on the host stdout/stderr, so a listener that fires long after the mount call still lands somewhere the user sees), the `harness.defineTool` / `harness.registerTool` registration pair, the encoding primitives fresh vm contexts lack (`btoa`/`atob` as host closures over `Buffer` — a sanctioned exception, `Buffer` itself is never exposed — plus `TextEncoder`/`TextDecoder`), and callable traps over the withheld Node APIs (`require`, `setTimeout`/`setInterval`/`setImmediate`/`clearTimeout`/`clearInterval`, `fetch`) that throw a redirect naming the cordis alternative. Only function-shaped globals are trapped; `process` and `Buffer` stay `undefined` so a `typeof` feature probe stays inert rather than detonating a throwing accessor. + +Three boundary mechanisms make model-written code behave correctly across the realm seam. **Dual-realm `instanceof`**: most objects sandbox code touches are host-realm (tool `args`, event payloads, service returns), so a plain `x instanceof Array` in the vm would silently be false — a per-sandbox prelude gives the vm realm's own constructors a `Symbol.hasInstance` that checks both the vm constructor and its host counterpart, patching only vm-realm globals. **Realm normalization of tool results**: objects built inside the vm carry the vm realm's `Object.prototype`, which the session log's append-time plainness check (`isJsonValue` in `dsh-session`, a prototype-identity comparison) rejects, so the sandbox's `harness.defineTool` JSON round-trips every `execute` return into the host realm — which also projects it onto exactly what the log durably stores — and then shape-checks it against the two `ToolExecuteReturn` forms, so a JSON-valid but wrong-shape return (a bare string, `{ content: 'ok' }`) fails that one call with a teaching error instead of entering the log as corrupt tool-result content. **A whitelist context façade**: the `ctx` a mounted plugin's `apply` receives is NOT the real context nor a pass-through proxy over it — it is a façade exposing only what a mount legitimately needs (`tools.register` marker-guarded, a read-only `tools.get`/`schemas`, `on`/`once`, `provide`, the timer helpers, and the services the plugin DECLARED in `inject`), with every framework-plumbing member (`root`, `parent`, `fiber`, `reflect`, `registry`, `extend`, `isolate`, `intercept`, `plugin`, `set`, `mixin`, …) denied with a teaching error. This closes an escape *class* rather than a single hole: a proxy that merely special-cased `ctx.tools` still handed back the raw context through `ctx.root`, `ctx.extend()`, or a service instance's `.ctx`, and mount code could then `ctx.root.tools.register({…})` to bypass the marker check and realm normalization — a raw vm-realm result then errors a real agent turn at the plainness check. The façade has no context-valued member to reach, and the one indirect leak (an injected-service method returning a `Context`) is rejected on the way back to sandbox code. Two narrower rules complete the surface. First, **service access requires an `inject` declaration**: reaching a service the mount did not declare is refused even when a global provider is live — otherwise a mount could depend on a provider cordis never sees, and unmounting that provider would neither park the consumer nor unwind the tools it registered, leaving a model-visible tool that fails only at execution time. Because the read is gated on the declaration, cross-mount `provide`/`inject` keeps its lifecycle guarantees (the plugin's own `inject` and the fiber's pending/active gating drive activation and unload); only the `apply`-time `ctx` surface is narrowed. Second, **`ctx.tools.get` returns a read-only schema view** (name/description/parameters), never the live `ToolDefinition` — handing back the definition would expose its `execute`, letting mount code call another tool directly and bypass `ToolRegistry.execute` and its pre/post-execute hooks and accounting; a mount that wants to invoke a tool must go through the registry, and one that wants to introspect gets the same view `schemas()` returns. + +Boundary errors are written around the mistakes models actually make (see [Consequences](#consequences) for how each was found), and the boundary normalizes rather than lectures wherever the input has exactly one meaning: schema `parameters` accept the JSON-Schema dialect models write by strong prior — the `{ type: 'object', properties, required: […] }` wrapper unwraps to the SchemaSpec DSL (the `required` array becoming per-property flags, at any nesting level), `type: 'integer'` maps to `number`, and `required: false` reads as optional — while genuinely meaningless input is rejected with the vocabulary enumerated (an unknown type lists the five valid ones; a non-boolean `required` names the rule). The remaining teaching errors: an unbalanced `});` closing gets the vm's offending source line plus a "code is a function body" reminder; TypeScript syntax gets the remove-annotations fix (detected on the failing line only, so an ` as ` inside a description string does not misfire); a forgotten `return` gets the two valid plugin forms; a Node built-in call gets the redirect to its cordis service; a tool-name collision on re-mount gets the unmount-first-then-remount recipe. + +### The dynamic group and mount lifecycle + +Every dynamic mount is a child of a single `cordis-dynamic` group fiber, itself a child of the `tool-cordis` plugin's fiber. The group exists so the mounts form one subtree: they are disposed as a unit, and disposing `tool-cordis` (HMR reload, config unload) cascades over every mount through the ordinary parent→child fiber lifecycle — no bespoke cleanup. Mounting settles before it reports: the returned fiber is `await()`ed, and a startup error (a throwing `apply`, a duplicate tool name, a duplicate service) disposes the fiber and surfaces as the tool error, so a failed mount never lingers. A settled fiber that is not active is a legal pending mount — cordis semantics for unsatisfied `inject` — kept mounted and reported with what it waits for. Everything the plugin registers is an effect on its fiber, so `cordis_unmount` is nothing but an awaited `fiber.dispose()`. + +### Cross-mount composition via provide/inject + +Mounts relate to each other through ordinary cordis service semantics, with their ids as the lifecycle handles: mount A calls `ctx.provide('foo', value)`, mount B declares `inject: ['foo']` and activates the moment `foo` exists; mounted first, B stays pending and names the missing service; unmounting A sends B back to pending (its registrations unwound) and a later re-provide re-runs B's `apply` through a fresh sandbox façade; a duplicate provide fails loud with the owning fiber named. One realm caveat: a service value provided by a mount is a vm-realm object — method calls on it work from anywhere, but consumers must not assume host prototypes on it. + +### The generated API catalog + +`cordis_inspect what:"api"` and `what:"events"` answer from a machine-readable catalog generated at build time, never a hand-maintained table that would drift from the JSDoc it paraphrases. [`scripts/gen-cordis-api.ts`](../../../../scripts/gen-cordis-api.ts) reuses `collectServices` / `collectEvents` from [`scripts/gen-cordis-catalog.ts`](../../../../scripts/gen-cordis-catalog.ts) — the same AST walk that generates [the cordis service catalog](../../../cordis-catalog/services.md) and [events catalog](../../../cordis-catalog/events.md) — and emits `packages/cordis/tool-cordis/src/api-catalog.ts`, a committed, banner-commented data module. The artifact carries, per service, its key + one-line summary + raw method signatures; per event, name + `@mode` + signature + summary; the comment-stripped declarations of every exported type the service signatures reference (transitive closure — so a consumer sees that a bash run's `stdout` is `{ text, truncated }`, not a string); plus the curated inherited `ctx` surface shared with the cordis catalog generator. A type name declared in more than one package (each plugin's `Config`) is dropped as ambiguous, and an oversized declaration is truncated with a marker. + +Freshness is gated like every generated artifact: `pnpm run verify-cordis-api` (in `doc-sync`) regenerates in memory and fails on any diff, so a JSDoc edit that changes a public signature cannot ship without regenerating the catalog the model reads. At runtime the inspect tool intersects the catalog with the live runtime rather than dumping it: live catalogued services render summary + signatures, live services without a catalog entry (mount-provided ones) render name + owning fiber, catalogued services with no live provider are listed tersely, and the referenced type shapes follow. + +### Configuration, rendering, and observability + +The plugin exposes one config field, validated by schemastery and documented in [the config catalog](../../../config-catalog.md): `vmTimeoutMs` (default 5000), the millisecond bound on the synchronous portion of mount-code evaluation. Tool names, the `cordis-dynamic` group name, and the `dyn-` id prefix are structural vocabulary and stay fixed. All three tools render as `generic` cards per [the tool cookbook](../../../cookbook/adding-a-tool.md) (`cordis_inspect` a `read`, `cordis_mount` an `execute` carrying the code as `rawInput`, `cordis_unmount` a `delete`), with no `presentResult` overrides. + +Model-visible ⟺ logged holds with no new session event type: a mount or unmount is visible only through its own `tool/call` / `tool/result` pair, which the loop logs, and the changed tool set a mount induces is logged by the request-header delta the loop already emits when schemas change between steps. There is deliberately no `cordis/mount` provenance event — it would duplicate what the tool-call pair records. Dynamic mounts are process-lifetime, not session state: resuming a persisted session rehydrates the conversation but does not re-mount plugins. + +## Alternatives considered + +**A structured per-capability registration tool instead of `cordis_mount`.** The most tempting alternative is a `cordis_register_tool` with explicit `name` / `description` / `parameters` / `code` fields (and siblings `cordis_register_listener`, `cordis_register_service`, …) rather than a single "mount a plugin" primitive. It was rejected because its one real win — no plugin boilerplate for the single commonest case — does not pay for its costs, while a single mount primitive answers every capability at once. + +| Dimension | Structured per-capability tools | Single `cordis_mount` | +|---|---|---| +| Schema correctness | `parameters` is still a model-written JSON object needing SchemaSpec validation, merely one step earlier | The same validation runs at the sandbox boundary, with the same instructive errors | +| The code field | An `execute` body is still model-written JS in a vm; the realm and service-call correctness problems are unchanged | One sandbox, one normalization path, one guarded registration | +| Capability coverage | Tools only; listeners, services, `inject` relations each need another structured tool — a surface that grows without bound | One vocabulary (a cordis plugin) covers every effect, present and future | +| Cross-mount composition | Not expressible in a tool-registration payload | Native `provide`/`inject`, ordinary cordis semantics | +| Inspectability | Registers something the plugin list cannot show as a plugin | What the model mounts is exactly what `cordis_inspect` renders | +| Model ergonomics | Wins for the single most common case (no plugin boilerplate) | Mitigated by the canonical recipe in the mount description plus boundary errors that teach the fix | + +The correctness investment therefore goes where it pays for every capability at once: the generated API catalog surfaced through `cordis_inspect`, and sandbox-boundary validation whose error messages teach the correct call. A structured registration tool remains addable later as sugar that synthesizes mount code; nothing here forecloses it. + +**A hand-maintained service/event reference in the tool.** The first cut of the inspect tool carried a hand-written table of service method signatures. It was replaced by the generated `api-catalog.ts` because a hand table drifts from the JSDoc the moment a signature changes and nothing gates the drift, whereas the generated artifact is freshness-checked against the same AST the docs use. + +**A new `cordis/mount` session event.** A durable provenance event recording each mount (source, name) has clear precedent (`hook/invoked`, `compact/start`). It was declined for v1: mount and unmount are already visible as `tool/call` / `tool/result` pairs and the tool-set change is already logged as a request-header delta, so a dedicated event would only duplicate the record. It remains addable if an audit use case needs mount provenance separable from the tool call. + +**A hardened / capability-restricted sandbox.** Trapping Node built-ins and handing mount code a whitelist façade rather than the raw context might suggest an intent to sandbox for safety. It is explicitly not that: the traps and the façade narrow the *surface* mount code sees — steering it onto cordis services and away from leak-prone Node built-ins and framework internals — for correctness and to close the unguarded-context escape, but the capabilities the façade exposes (`ctx.bash`, `ctx.fs`, `ctx.web`) reach the real runtime, so it is not a security boundary. A real one (separate process, permission prompts) was out of scope for a dev/opt-in toolset and would fight the entire point — handing the model the live runtime. + +## Consequences + +The toolset is a deliberate opt-in with a fully-privileged `ctx`, so a deployment adopts it as consciously as a bash tool. Several facts follow that the tool descriptions warn the model about directly: a waterfall listener (e.g. `tools/pre-execute`) that returns without calling `next()` vetoes the chain, so a mounted listener can lobotomize the agent's own tool dispatch ([waterfall semantics](../../../cordis-primer.md#cordis-waterfall-semantics)); mount code runs inside a tool call of the current turn, so awaiting anything that resolves only after the turn deadlocks; `vmTimeoutMs` bounds synchronous evaluation only; and mounts do not survive session resume. + +The instructive boundary errors were not guessed — they were written against live self-design sessions in which a real model was asked to build itself coding tools. Those sessions surfaced the failure modes now mitigated: the model closed a returned plugin object with `});` and got only a bare `Unexpected token ')'` it retried blind; it hit a false-positive "this is TypeScript" hint because a description string contained the word "as"; it guessed a bash run's `stdout` was a string and burned six steps building throwaway debug tools to discover it is `{ text, truncated }`; and it wrote tool schemas in the JSON-Schema dialect (`type: 'integer'`, `required: false`, then the full wrapper) three rejections in a row — the rejection text itself pushing it from a nearly-correct DSL attempt back to raw JSON Schema. The fixes — source-line-plus-caret parse errors, line-scoped TypeScript detection, the type-shape closure in the API catalog, the redirect traps, and schema-dialect normalization in place of rejection — cut later sessions from dozens of tool calls with repeated errors to a first-try success on every capability, including a model that hit a Node-`setTimeout` trap and self-corrected to `inject: ['timer']` in one step. + +Coverage is named per tier: package unit specs drive the three tools through a real `ToolRegistry` on a real fiber tree (the mount success/failure family, vm isolation, dual-realm `instanceof`, realm normalization against the real `isJsonValue`, the SchemaSpec and raw-registration rejections, the Node-API traps, the cross-mount provide/inject matrix, catalog-backed `api`/`events` rendering, config validation, presenters, quiescent unmount, and the HMR cascade), a `MockAdapter` loop test proves a tool mounted in one step is dispatchable in the next, and the example carries a keyless Loader smoke plus a with-key smoke that world-verifies a live model mounting a listener, building its own tool, and composing two mounts. No snapshot scenario is added: the toolset ships in no ACP-served app, so it changes no editor-facing transcript, and its presenters are unit-tested pure functions — adding it to the ACP example solely for a golden would rewrite the pinned request-header tool set of every recorded scenario. diff --git a/docs/rfc/implemented/testing/2026-06-19-acp-snapshot-tests.md b/docs/rfc/implemented/testing/2026-06-19-acp-snapshot-tests.md index 6e73d5d333..ae5ea96f83 100644 --- a/docs/rfc/implemented/testing/2026-06-19-acp-snapshot-tests.md +++ b/docs/rfc/implemented/testing/2026-06-19-acp-snapshot-tests.md @@ -68,7 +68,7 @@ The replay plugin lives in its own package, `@deepseek-ai/dsh-llm-replay` (`pack ### Two subcommands, replay in the default gate -`pnpm run test:snapshot` runs replay (keyless) and is composed into the default `pnpm run test` gate so every PR gets the regression check (the main `vitest.config.ts` include stays narrow; the gate is `test && test:snapshot`). `pnpm run test:snapshot:record` requires `DEEPSEEK_API_KEY` (loaded from repo `.env` first), hits the real API, harvests the produced `session.jsonl` (the replay source AND the expected-log artifact), and `--update`s the stdout golden in one pass. Both forward a scenario filter. A missing fixture in replay **fails loud** with a "record first" message rather than self-skipping (the e2e self-skip rule is a CI-secret accommodation, not appropriate here — a committed-fixture test that silently vanishes is a coverage hole). A no-model scenario's `session.jsonl` simply has no `assistant/chunk` events (empty derived script); fail-loud still applies if a model call happens with no entry. An orphan-fixture guard test fails on a golden/fixture not referenced by any scenario (Vitest does not prune orphaned raw goldens), and a per-kind required-fixture guard asserts each scenario ships exactly the files its kind needs (`input.json` + `stdout.golden.jsonl` + `session.jsonl` for ALL scenarios — the harness passes `/session.jsonl` to `llm-replay` unconditionally, so even a no-model scenario needs its header-only fixture or `loadReplayScript()` fails; `replay.override.json` additionally for authored model scenarios). +`pnpm run test:snapshot` runs replay (keyless) and is composed into the default `pnpm run test` gate so every PR gets the regression check (the main `vitest.config.ts` include stays narrow; the gate is `test && test:snapshot`). `pnpm run test:snapshot:record` requires `DEEPSEEK_API_KEY` (loaded from repo `.env` first), hits the real API, harvests the produced `session.jsonl` (the replay source AND the expected-log artifact), and `--update`s the stdout golden in one pass. Both forward a scenario filter. A missing fixture in replay **fails loud** with a "record first" message rather than self-skipping (the e2e self-skip rule is a CI-secret accommodation, not appropriate here — a committed-fixture test that silently vanishes is a coverage hole). A no-model scenario's `session.jsonl` simply has no `assistant/chunk` events (empty derived script); fail-loud still applies if a model call happens with no entry. An orphan-fixture guard test fails on a golden/fixture not referenced by any scenario (Vitest does not prune orphaned raw goldens), and a per-kind required-fixture guard asserts each scenario ships exactly the files its kind needs (`input.json` + `stdout.golden.jsonl` + `session.jsonl` for ALL scenarios — the harness passes `/session.jsonl` to `llm-replay` unconditionally, so even a no-model scenario needs its header-only fixture or `loadReplayScript()` fails; `replay.override.json` exactly for the scenarios whose table entry sets `overridden` — required with the flag, forbidden without it, because the harness forwards the sidecar purely on file existence and an unregistered stray would silently replace the derived script). ## Alternatives considered diff --git a/docs/rfc/proposed/feature/2026-07-08-repeat-tool-guard.md b/docs/rfc/proposed/feature/2026-07-08-repeat-tool-guard.md deleted file mode 100644 index 19193ea583..0000000000 --- a/docs/rfc/proposed/feature/2026-07-08-repeat-tool-guard.md +++ /dev/null @@ -1,79 +0,0 @@ -# RFC: Repeat-tool-call guard plugin - -Status: proposed - -## Problem - -A model stuck in a loop re-issues the same tool call with byte-identical arguments — re-running a failing grep, re-reading an unchanged file, polling a command that already gave its answer — and each round trip burns tokens, wall-clock, and (for paid APIs) money without adding information. The harness has nothing that notices: the loop has no step budget, no plugin tracks call repetition, and the model only escapes when it happens to vary its own behavior. The failure mode is real and cheap to detect — [pi-repeat-tool-guard](https://github.com/Kingwl/pi-repeat-tool-guard) ships exactly this as a pi coding-agent extension: count consecutive identical calls and, past a threshold, append a `` telling the model to stop repeating itself and change course. - -The harness already has every seam the pi extension uses, and better ones: [the interception-seams RFC](../../implemented/feature/2026-06-30-interception-seams.md) gives `tools/post-execute` a sanctioned way to attach model-facing context to a finished call, the loop buffers and injects that context with call/result adjacency preserved, and injected context is a logged `context/message` — so a native guard satisfies the model-visible ⟺ logged rule with no new session event. What is missing is only the plugin itself. - -## Proposal - -The guard is a loop-hygiene plugin, not a model-facing tool: it never appears in the tool list, never vetoes or rewrites a call, and adds exactly one behavior — it watches each agent's stream of tool calls, counts runs of consecutive calls to the same tool with identical canonicalized arguments, and at configured run lengths injects an escalating advisory reminder telling the model to stop repeating itself, re-read the last result, and either change approach or conclude. The purpose is to break unproductive loops within a few wasted steps instead of letting them run to the turn's natural end — while leaving the decision (retry differently, gather more evidence, or finish) entirely with the model, so a legitimately repeated call is delayed by nothing and blocked by nothing. - -The shape: one new leaf plugin package, `@deepseek-ai/dsh-repeat-tool-guard` at `packages/guard/repeat-tool-guard/`, opening a `guard/` group for loop-hygiene plugins (single-package groups have precedent: [the todo-write RFC](../../implemented/feature/2026-06-29-todo-write-tool.md) shipped `todo/tool-todo`). The plugin registers three listeners via `ctx.effect()` and holds all state in plugin-local maps keyed by `AgentId` — the tool registry is a context-level singleton whose waterfalls interleave every agent's calls (subagents run on the same context), so per-agent keying is correctness, not polish. - -- **`tools/post-execute` (waterfall)** — the one detection point. The listener receives `(exec, result)` together, so counting and reminder delivery need no cross-event pending map (the pi extension needs one only because its `tool_call`/`tool_result` hooks are separate events). It always delegates via `next()` and, when a threshold is hit, folds a reminder onto the downstream decision's `additionalContext` — the observe-and-enrich posture [the hooks bridges](../../implemented/feature/2026-06-30-hook-bridges.md) already use, honoring the waterfall contract. Counting happens here rather than in `tools/pre-execute` because post-execute also runs for denied calls (`ToolRegistry.execute` routes a deny through the same pipeline), and a model hammering a denied call is exactly the loop worth breaking. -- **`agent/prompt-submit` (waterfall)** — pure reset hook: delegate via `next()`, clear the submitting agent's chain. A user interjection changes the context; repetition across it is not a loop. -- **`agent/status` (emit)** — on `disposed`, drop the agent's state, bounding the maps over harness lifetime. - -### Detection semantics - -The chain key is `(tool name, canonical arguments)`; a call identical to the previous tracked call increments the agent's consecutive counter, a different tracked call resets it to 1. Canonicalization is a deep key-sort plus `JSON.stringify`: `ToolExecution.arguments` is by construction the loop's `JSON.parse` output (or the raw string fallback for malformed argument JSON, which is itself a comparable value), so the pi original's bigint/circular/`undefined` handling has no inputs here and is deliberately dropped. - -Two deliberate rules, both documented in the package README because they are behavior a reader would otherwise guess at: - -- **Untracked calls are transparent to the chain.** A call excluded by `include`/`exclude` neither increments nor resets the counter, so `grep X → todo_write → grep X` still counts as two consecutive `grep X` when `todo_write` is excluded. This is what makes exclusion useful — bookkeeping tools interleaved into a loop must not launder it — and it is the pi extension's (undocumented) semantics, kept on purpose and written down. -- **Calls without an agent are ignored.** A direct `ctx.tools.execute()` caller (tests, future non-loop consumers) has no model to remind and no `AgentId` to key on. - -### Reminder delivery - -Reminders ride `additionalContext` (source `{kind: 'plugin', plugin: 'repeat-tool-guard'}` — the label is load-bearing per `HookContext`), never a `content` replacement: the `tool/result` event stays the tool's own output for audit, and the loop already appends buffered context as `context/message`(s) after the step's results, which the session renders as the tagged synthetic-user envelope and derived history replays. Thresholds escalate: the first configured threshold gets a short "you are repeating yourself, analyze the previous result" nudge; each later threshold gets the detailed form naming the tool, the repeat count, and the canonical arguments, and stating that the calls made no progress. The pi original hardcodes the gentle text to the literal count 3; the guard keys it to `thresholds[0]`, fixing that bug in the port. When the downstream decision already carries `additionalContext` (a hook bridge on the same call), the guard folds content following the shared-merge precedent in `dsh-hook-protocol`. - -### Config - -```yaml -- id: repeat-tool-guard - name: '@deepseek-ai/dsh-repeat-tool-guard' - config: - thresholds: [3, 5, 8] # default; consecutive counts that trigger a reminder - include: [] # tool-name patterns to track; empty ⇒ all tools - exclude: [todo_write] # tool-name patterns transparent to the chain -``` - -`thresholds` is validated at load and throws on an empty list, a non-integer, a value below 2, or a duplicate — misconfiguration fails loud, replacing the pi original's silent fall-back to defaults. `include`/`exclude` entries support `*` wildcards. Patterns are predicates over whatever tools exist at call time, not references to a registry entry, so an entry matching no currently registered tool is NOT an error — unlike `toolOrder`'s referent check, `exclude: [mcp_*]` must stay valid in a deployment that loads no MCP tools. - -### Testing - -Coverage named at plan time, per tier: **unit** — counting/reset semantics (identical, different-tracked, untracked-transparent, prompt-submit reset, disposal cleanup, per-agent isolation), canonicalization, threshold escalation including the `thresholds[0]` gentle-text rule, config fail-loud cases, and the fold-onto-downstream-decision path, to per-file 100% like every `packages/*/*/src` file. **Snapshot** — one scripted-replay scenario where the model repeats a call to threshold and the reminder `context/message` appears in the transcript, pinning the model-visible text and its envelope (this is a transcript-surface change; the ACP snapshot suite is the tier that owns it). **e2e** — none: the plugin is provider-independent and deterministic, and forcing a live model to repeat a call three times is not a stable test; the seam contracts it relies on are already e2e-covered by their owners. - -## Alternatives considered - -- **Append the reminder into the tool result** (`accept` with replaced `content` — the pi extension's mechanism, which patches result content because that is the only channel its API offers) — rejected: it makes the logged `tool/result` lie about what the tool returned, and `additionalContext` exists precisely as the separate sanctioned channel for post-execute commentary, with loop-level buffering that preserves call/result adjacency. -- **Count in `tools/pre-execute` with a pending-reminder map** (the pi two-phase shape) — rejected: post-execute alone sees `(exec, result)` together and also fires for denied calls, so one listener with no cross-event state covers strictly more attempts with less machinery. -- **Escalate to `block` at the highest threshold** — rejected for the initial scope: a blocked call punishes legitimate identical repeats (polling a long-running terminal, re-checking a file the agent expects to change), and an advisory reminder keeps the model in control. Revisit with evidence; the decision shape (`PostToolDecision`) already supports it. -- **A per-deployment external hook via the CC/Codex bridges** (a `PostToolUse` script) — rejected as the answer: it works today for one deployment, but a shipped, unit-tested, `cordis.yml`-configurable plugin is the harness-native form, without per-call subprocess cost. -- **A loop-level step or repetition budget in `agent-loop`** — rejected: "plugins, not loop changes"; a hard step budget is a blunter, orthogonal control that would need its own proposal. -- **Fuzzy/near-identical detection** (normalized paths, similar-but-not-equal arguments) — rejected: exact match after canonicalization is cheap, deterministic, and explainable to the model; similarity thresholds invite false positives and need evidence before they earn complexity. -- **Placing the package in `core/`** — rejected: core is the product spine; a behavioral guard is an optional leaf plugin, and the `todo/` precedent is a small dedicated group per plugin family. - -## Acceptance criteria - -- `packages/guard/repeat-tool-guard/` exists, registers all listeners through `ctx.effect()`, and is loadable from a `cordis.yml` with the config above; the config catalog regenerates with its entry. -- Invalid `thresholds` (empty, non-integer, `< 2`, duplicate) throw at plugin load. -- Unit suite covers the semantics list above at per-file 100%; a snapshot scenario replays a threshold-crossing repetition and pins the reminder `context/message` in the transcript on macOS and Linux. -- The reminder is reconstructable from the session log alone (it is an ordinary `context/message` with a plugin source — no new session event). -- The package README opens with the plugin's purpose — an advisory loop-breaker that is not a model-facing tool, never blocks or rewrites a call, and only injects reminders — then documents the transparency rule, the per-agent keying, and the in-memory-only state; `doc-sync` is green. - -## Risks - -- **False positives on legitimately repeated calls.** Idempotent polling patterns repeat identical calls on purpose; the reminder is advisory and thresholds/`exclude` are the pressure valves, but a badly tuned deployment adds noise to the transcript. Mitigation: conservative defaults and the reminder text explicitly allowing "finish the task if enough evidence has been gathered". -- **Reminder tokens are model-visible cost.** Each trigger appends a paragraph to the next request; thresholds bound the frequency, but a pathological agent can hit 3/5/8 repeatedly across different keys. -- **State is in-memory only.** A session resumed from persistence starts with a fresh chain, so a loop spanning a resume gets its reminders later than a live one — accepted: the guard is a heuristic nudge, not a logged invariant, and persisting counter state would buy little for real complexity. -- **Multiple context producers on one call.** When a hook bridge and the guard both attach `additionalContext`, ordering follows listener registration order; the fold keeps both, but the combined envelope's readability depends on merge behavior that this RFC inherits rather than owns. - -## Open questions - -- Should compaction reset chains? A compacted history changes what the model sees, but the repetition risk usually survives compaction; the initial answer is no. -- Should subagents inherit the parent's thresholds via config only, or ever share chain state? Per-agent isolation is the proposed default; sharing looks like a smell until a concrete case appears. diff --git a/docs/testing.md b/docs/testing.md index a8cf977e85..a4a77c9d0c 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -25,7 +25,7 @@ An e2e assertion re-runs the command or re-reads the file externally; a keyword - A plugin shipped via `cordis.yml` needs at least one test through the REAL Loader path: hand-built `ctx.plugin({...})` mounts bypass `unwrapExports` and cannot catch a broken export shape ([postmortem 0001](postmortem/0001-acp-default-export-drops-inject.md); export-shape rules in [packages/AGENTS.md](../packages/AGENTS.md)). - A guard only guards if the regression actually fails it. For a plugin without `inject` (bundle/composition plugins), a Loader smoke stays green under a broken export shape — add an explicit `expect('default' in mod).toBe(false)` plus an `unwrapExports` round-trip assertion, and prove it: introduce the regression, watch red, revert. -- "Real entry path" means the published artifact: the package `bin` points at built `lib/bin.js` under plain `node`, which tsx masks (settle races, module resolution, a swallowed load failure exiting 0). Keep the built-bin smokes green (`packages/ui/*/tests/built-bin.e2e.ts`), and assert a genuinely-missing config exits non-zero. +- "Real entry path" means the published artifact: the package `bin` points at built `lib/bin.js` under plain `node`, which tsx masks (settle races, module resolution, a swallowed load failure exiting 0). The same applies to any non-index runtime entry the built package resolves at run time (the worker-thread runtime's sibling `lib/worker.js`). Keep the built-artifact smokes green (`packages/ui/*/tests/built-bin.e2e.ts`, `packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts`), and assert a genuinely-missing config exits non-zero. - An e2e that spawns an example from a temp cwd sets `TSX_TSCONFIG_PATH` to the repo-root tsconfig, or it silently falls back to stale built `lib/` ([examples/AGENTS.md](../examples/AGENTS.md)). ## When a snapshot test is required diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index a621d3299d..9a26078091 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -15,12 +15,84 @@ This table connects model-visible tool names to the plugin package and service s | Tool package | Model-visible names | Requires | Writes / affects | Shipped aliases | Deployment note | | --- | --- | --- | --- | --- | --- | +| `@deepseek-ai/dsh-tool-ask-user` | `ask_user_question` | `ctx.tools`, `ctx.userInteraction` | `tool/call`, `tool/result after a UI/provider answers the question` | - | ask_user_question pauses the tool call until the active UI provider returns a human answer. | | `@deepseek-ai/dsh-tool-bash` | `bash`, `bash_kill`, `bash_output` | `ctx.tools`, `ctx.bash` | `tool/call`, `tool/result`, `context/message via agent.inject() for background completion notices` | - | The bash/bash_output/bash_kill tools are model-facing consumers of the bash executor seam. | +| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect`, `cordis_mount`, `cordis_unmount` | `ctx.tools` | `tool/call`, `tool/result`, `live plugin-tree mutations (mount/unmount)` | - | Ships in examples/cordis-agent only (a deliberate opt-in — mounted code gets the real ctx, see docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins the model mounts may register ADDITIONAL model-visible tools at runtime; the request-header ToolsDelta logs those tool-set changes. | | `@deepseek-ai/dsh-tool-fs` | `edit`, `read`, `write` | `ctx.tools`, `ctx.fs`, `ctx.systemPrompt` | `tool/call`, `fs/write-intent or fs/edit-intent for mutations`, `fs/observed after successful file operations`, `tool/result` | - | The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-policy` (an `fs/*` event-gate plugin, no schema change); a deployment that loads these tools is expected to also load it. The tool schemas above are identical with or without the policy plugin. | | `@deepseek-ai/dsh-tool-subagent` | `subagent` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The registered tool name is the load-time `toolName` config (default `subagent`); the schema above is that default. The shipped example agents load this package once per subagent backend, so the model additionally sees `subagent_fork` (bound to the fork backend) with an identical schema — see `examples/coding-agent/cordis.yml` and `examples/acp-agent/cordis.yml`. | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist or ACP plan. | | `@deepseek-ai/dsh-tool-web` | `web_fetch`, `web_search` | `ctx.tools`, `ctx.web`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | web_search and web_fetch keep provider selection behind ctx.web so model-visible schemas stay stable across backend swaps. | +## `@deepseek-ai/dsh-tool-ask-user` + +### `ask_user_question` + +Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Send one or more questions, each with a stable id that will be echoed in the answer. + +```json +{ + "type": "object", + "properties": { + "questions": { + "type": "array", + "description": "Questions to ask the user before continuing.", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stable id for this question; echoed in the answer." + }, + "question": { + "type": "string", + "description": "The specific question to ask the user." + }, + "header": { + "type": "string", + "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." + }, + "options": { + "type": "array", + "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string", + "description": "Short user-facing option label." + }, + "description": { + "type": "string", + "description": "One sentence explaining the tradeoff or impact." + } + }, + "required": [ + "label" + ] + } + }, + "multi_select": { + "type": "boolean", + "description": "Whether the user may select more than one option. Defaults to false." + } + }, + "required": [ + "id", + "question" + ] + } + } + }, + "required": [ + "questions" + ] +} +``` + +Source: [`packages/ui/tool-ask-user/src/index.ts`](../packages/ui/tool-ask-user/src/index.ts) + +ask_user_question pauses the tool call until the active UI provider returns a human answer. + ## `@deepseek-ai/dsh-tool-bash` ### `bash` @@ -105,6 +177,78 @@ Source: [`packages/bash/tool-bash/src/index.ts`](../packages/bash/tool-bash/src/ The bash/bash_output/bash_kill tools are model-facing consumers of the bash executor seam. +## `@deepseek-ai/dsh-tool-cordis` + +### `cordis_inspect` + +Inspect the live cordis runtime that is running THIS agent. Read-only. Sections: `services` (every provided ctx service and the plugin fiber that owns it), `plugins` (a flat list of the loaded plugins with their lifecycle states), `tools` (the model-facing tools currently registered, i.e. what you can call), `dynamic` (plugins you mounted via cordis_mount: id, name, state, provided services, awaited services), `api` (method signatures AND argument/return type shapes for every LIVE service — read this before writing plugin code that calls a service), `events` (every harness event with its dispatch mode and exact signature — pick listener targets here). Omit `what` to get all six sections. + +```json +{ + "type": "object", + "properties": { + "what": { + "type": "string", + "description": "Limit the report to one section. Omit for all sections.", + "enum": [ + "services", + "plugins", + "tools", + "dynamic", + "api", + "events" + ] + } + } +} +``` + +Source: [`packages/cordis/tool-cordis/src/index.ts`](../packages/cordis/tool-cordis/src/index.ts) + +### `cordis_mount` + +Mount a NEW cordis plugin into the live runtime that is running THIS agent (self-modification). `code` runs as the body of an async JavaScript function in an isolated sandbox and MUST `return` a plugin. Two forms: FUNCTION form `return (ctx) => { … }` — declares no inject, so it can register tools, listen to events, and provide services, but reaching ANY service (e.g. ctx.bash) throws; use it only when you need no services. OBJECT form `return { name?, inject: ['bash', 'llm', …], apply(ctx) { … } }` — declares dependencies, and cordis activates the plugin only after the services exist; PREFER this form. You may reach ONLY the services you list in inject: an undeclared service throws even if it exists, because an undeclared dependency would not be cleaned up if its provider is unmounted. BEFORE calling a service from your code, read cordis_inspect what:"api" — it lists method signatures AND the type shapes of their arguments/returns (do not guess a field's type; e.g. a bash run's stdout is an object, not a string). Inside `apply`, use the standard cordis API: `ctx.on(event, listener)` to observe events (see cordis_inspect what:"events"), or call `harness.registerTool(ctx, harness.defineTool({ name, description, parameters: { text: { type: 'string', required: true } }, async execute(args) { … } }))` to give yourself a new tool — it becomes callable on your NEXT step. Tool parameters: each key IS a property — { type: 'string'|'number'|'boolean'|'object'|'array', required?: true, description?, enum?, items?, properties? }; a JSON-Schema-style { type: 'object', properties, required: […] } wrapper and type 'integer' are also accepted and normalized. A tool's `execute` MUST return an ARRAY of content blocks, e.g. `return [{ type: 'text', text: someString }]` — never a bare string. Mounts can COMPOSE: one plugin may `ctx.provide('name', value)` a service and another may declare `inject: ['name']` to consume it — the consumer stays pending until the provider exists and returns to pending when the provider is unmounted. Everything registered inside `apply` is cleaned up automatically on unmount. Sandbox globals: `console` (tagged `[cordis:]`, writes through to the harness terminal), `harness.defineTool`, `harness.registerTool`, `btoa`, `atob`, `TextEncoder`, `TextDecoder`. Node APIs are DISABLED — do filesystem/network/timer work through the cordis services, never Node built-ins: `require`, `setTimeout`/`setInterval`, and `fetch` throw redirect errors; `process` and `Buffer` are undefined. Instead use inject: ['fs'] + ctx.fs for files, inject: ['web'] + ctx.web for HTTP, inject: ['bash'] + ctx.bash for processes, and inject: ['timer'] + ctx.setTimeout/ctx.setInterval for timing (fiber effects, auto-cleaned on unmount) — cordis_inspect what:"api" shows what THIS runtime provides. Write PLAIN JavaScript, not TypeScript (no `as`, no type annotations). Cautions: (1) waterfall events (e.g. tools/pre-execute) hand the listener a trailing `next` callback which MUST be called — returning without `next()` VETOES the call; prefer plain notification events unless you intend to intercept. (2) Never await something that only resolves after the current turn (your code runs INSIDE a tool call of that turn — it would deadlock). (3) Your `ctx` is a restricted façade: you can register tools, observe events, provide/consume services, and use timers, but framework internals (ctx.root, ctx.fiber, ctx.extend, ctx.plugin, …) are withheld. It is not a security boundary though — the services you inject (e.g. ctx.bash) reach the real runtime. + +```json +{ + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "Body of an async JS function; must `return` the plugin to mount." + } + }, + "required": [ + "code" + ] +} +``` + +Source: [`packages/cordis/tool-cordis/src/index.ts`](../packages/cordis/tool-cordis/src/index.ts) + +### `cordis_unmount` + +Dispose a plugin previously mounted with cordis_mount, by id. All its registrations (event listeners, tools, services) are cleaned up through the cordis effect lifecycle. Returns only after disposal has fully completed (quiescence, not just a request to stop). + +```json +{ + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The dynamic mount id returned by cordis_mount (e.g. \"dyn-1\")." + } + }, + "required": [ + "id" + ] +} +``` + +Source: [`packages/cordis/tool-cordis/src/index.ts`](../packages/cordis/tool-cordis/src/index.ts) + +Ships in examples/cordis-agent only (a deliberate opt-in — mounted code gets the real ctx, see docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins the model mounts may register ADDITIONAL model-visible tools at runtime; the request-header ToolsDelta logs those tool-set changes. + ## `@deepseek-ai/dsh-tool-fs` ### `edit` @@ -289,10 +433,6 @@ Fetch the content of a specific HTTP(S) URL and return it decoded to text. "url": { "type": "string", "description": "The HTTP(S) URL to fetch." - }, - "timeout_ms": { - "type": "number", - "description": "Optional fetch timeout in milliseconds (capped by the provider)." } }, "required": [ diff --git a/docs/tool-execution-pipeline.md b/docs/tool-execution-pipeline.md index db50a3beec..c28c934ab2 100644 --- a/docs/tool-execution-pipeline.md +++ b/docs/tool-execution-pipeline.md @@ -3,7 +3,7 @@ # Tool Execution Pipeline -This graph shows where policy, hooks, sandboxing, filesystem guards, result rewriting, and UI rendering fit without changing the loop. The key extension points are the `tools/pre-execute` and `tools/post-execute` waterfalls. +This graph shows where policy, hooks, sandboxing, filesystem guards, result rewriting, and UI rendering fit without changing the loop. The key extension points are the `tools/pre-execute`, `tools/execute`, and `tools/post-execute` waterfalls. ```mermaid flowchart TD @@ -12,6 +12,7 @@ flowchart TD presentCall["UI pending card
presentCall(args)"] pre["tools/pre-execute waterfall
hooks, permission, sandbox"] denied["deny or ask
tool body skipped"] + around["tools/execute waterfall
timeout, retry, metrics (around dispatch)"] toolBody["Registered tool execute() body"] fsGate["fs/write-intent or fs/edit-intent
tool-fs mutations only"] owned["Tool-owned session events
todo/write, fs/observed, hook/invoked, hook/result"] @@ -22,18 +23,20 @@ flowchart TD model --> toolCall toolCall --> presentCall toolCall --> pre - pre -->|allow| toolBody + pre -->|allow| around + around --> toolBody pre -->|deny or ask| denied denied --> post toolBody --> fsGate fsGate --> toolBody toolBody --> owned - toolBody --> post + toolBody --> around + around --> post post --> context post --> toolResult toolResult --> presentResult ``` -Filesystem read-before-edit checks live below `tool-fs` on the `fs/*` event gate, while hook bridges and future permission prompts live on the generic tool waterfalls. That split lets the same hooks observe bash, fs, web, todo, and subagent calls without coupling those tools to one policy service. +Filesystem read-before-edit checks live below `tool-fs` on the `fs/*` event gate; hook bridges and future permission prompts live on the generic pre/post tool waterfalls; and around-dispatch concerns like the tool-call timeout policy (`@deepseek-ai/dsh-timeout-policy`) wrap core dispatch on `tools/execute`. That split lets the same hooks observe bash, fs, web, todo, and subagent calls without coupling those tools to one policy service. Maintenance mode: curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs. diff --git a/examples/AGENTS.md b/examples/AGENTS.md index 6c1cc717df..94597371cf 100644 --- a/examples/AGENTS.md +++ b/examples/AGENTS.md @@ -21,6 +21,7 @@ A keyless smoke that spawns the example from a temp cwd must set `TSX_TSCONFIG_P |---|---|---| | `echo-agent` | `tests/echo.e2e.ts` — boots the real `cordis.yml`, drives the echo tool round-trip and the direct canned reply | **N/A — keyless by nature** (the `mock-echo` model has no real provider) | | `coding-agent` | `tests/keyless-smoke.e2e.ts` — boots the full real tree (dummy key, no prompt → no model call), asserts banner + clean exit | `tests/{full-loop,coding-task,resume,compaction,todo-write}.e2e.ts` — real model + real bash + real todo_write, world-verified | +| `cordis-agent` | `tests/keyless-smoke.e2e.ts` — boots the real tree incl. `@deepseek-ai/dsh-tool-cordis` by package name; the tool logic is unit-tested in `packages/cordis/tool-cordis` | `tests/cordis-tools.e2e.ts` — real model mounts a listener (tagged line fires), builds+calls its own tool, composes two mounts via provide/inject | | `acp-agent` | `pnpm run test:snapshot` — boots the real ACP subprocess and replays a recorded session keyless (incl. the hook matrix: a scenario per hook point × outcome for BOTH the Claude and Codex bridges — block, deny, ask, context-fold, force-continue); `tests/acp.e2e.ts` also asserts stdout purity without a key | `tests/acp.e2e.ts` — real ACP prompt, verifies a file the agent wrote; `tests/hooks.e2e.ts` — a real `PreToolUse` hook blocks bash, verifies the file is NOT written | See [the root AGENTS.md](../AGENTS.md) for repo-wide conventions and [docs/architecture.md](../docs/architecture.md) for the design. diff --git a/examples/README.md b/examples/README.md index 1e3134ba2d..c86f83022a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -19,6 +19,12 @@ A REPL agent demo: DeepSeek V4 + the `read`/`write`/`edit` filesystem tools + th Run with: `pnpm run demo:repl` (needs `DEEPSEEK_API_KEY` in the environment or a gitignored repo-root `.env`). See [coding-agent/README.md](coding-agent/README.md) for details. +## cordis-agent + +The **self-referential** demo: the coding spine plus [`@deepseek-ai/dsh-tool-cordis`](../packages/cordis/tool-cordis), whose three tools (`cordis_inspect` / `cordis_mount` / `cordis_unmount`) let the agent inspect the live cordis runtime it runs inside, mount model-written plugins into it (an event listener, a brand-new tool for itself, or a service another mount injects), and dispose them again — all dynamic mounts grouped under one `cordis-dynamic` fiber subtree. The `ctx.fs`/`ctx.web` services ride along provider-only, as the capabilities those plugins build on. + +Run with: `pnpm run demo:cordis` (needs `DEEPSEEK_API_KEY`). See [cordis-agent/README.md](cordis-agent/README.md) for the staged demo script and [the toolset RFC](../docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md) for the design and sandbox caveats. + ## acp-agent An agent demo exposed as an **Agent Client Protocol (ACP)** server over JSON-RPC stdio, via the [`@deepseek-ai/dsh-acp-agent`](../packages/ui/acp-agent) app — drive it from Zed or any other ACP client. Also the home of the keyless snapshot tests. diff --git a/examples/acp-agent/README.md b/examples/acp-agent/README.md index 58a5984301..a1f6e818ab 100644 --- a/examples/acp-agent/README.md +++ b/examples/acp-agent/README.md @@ -6,7 +6,7 @@ The DeepSeek Harness SDK agent demo exposed as an **Agent Client Protocol (ACP)* pnpm run demo:acp # needs DEEPSEEK_API_KEY (repo-root .env or env) ``` -This example is just a leaf `cordis.yml`: it loads the [`@deepseek-ai/dsh-acp-agent`](../../packages/ui/acp-agent) app (which bundles the [`@deepseek-ai/dsh-agent-core`](../../packages/core/agent-core) spine, JSONL session persistence, and the `@deepseek-ai/dsh-acp` bridge — with **no pre-created agents**, since ACP `session/new` creates them on demand), the swappable DeepSeek, bash, and filesystem backends, and the model-facing `read`/`write`/`edit`/`subagent`/`subagent_fork`/`todo_write` tool entries. The app package bakes in the no-stdout-logger cluster, so a leaf has no logger entry to get wrong by default — keeping stdout pure for JSON-RPC. +This example is just a leaf `cordis.yml`: it loads the [`@deepseek-ai/dsh-acp-agent`](../../packages/ui/acp-agent) app (which bundles the [`@deepseek-ai/dsh-agent-core`](../../packages/core/agent-core) spine, JSONL session persistence, and the `@deepseek-ai/dsh-acp` bridge — with **no pre-created agents**, since ACP `session/new` creates them on demand), the swappable DeepSeek, bash, and filesystem backends, the model-facing `read`/`write`/`edit`/`subagent`/`subagent_fork`/`todo_write` tool entries, and the advisory `repeat-tool-guard` loop-hygiene plugin. The app package bakes in the no-stdout-logger cluster, so a leaf has no logger entry to get wrong by default — keeping stdout pure for JSON-RPC. ## stdout is the protocol diff --git a/examples/acp-agent/composition.md b/examples/acp-agent/composition.md index 2644a2b112..7fd5e25875 100644 --- a/examples/acp-agent/composition.md +++ b/examples/acp-agent/composition.md @@ -33,6 +33,8 @@ flowchart LR cfg --> plugin_acp_tool_subagent_fork plugin_acp_tool_todo["tool-todo
@deepseek-ai/dsh-tool-todo"] cfg --> plugin_acp_tool_todo + plugin_acp_repeat_tool_guard["repeat-tool-guard
@deepseek-ai/dsh-repeat-tool-guard"] + cfg --> plugin_acp_repeat_tool_guard plugin_acp_fs_local["fs-local
@deepseek-ai/dsh-fs-local"] cfg --> plugin_acp_fs_local plugin_acp_fs_policy["fs-policy
@deepseek-ai/dsh-fs-policy"] @@ -56,6 +58,7 @@ flowchart LR | `tool-subagent` | `@deepseek-ai/dsh-tool-subagent` | | `tool-subagent-fork` | `@deepseek-ai/dsh-tool-subagent` | | `tool-todo` | `@deepseek-ai/dsh-tool-todo` | +| `repeat-tool-guard` | `@deepseek-ai/dsh-repeat-tool-guard` | | `fs-local` | `@deepseek-ai/dsh-fs-local` | | `fs-policy` | `@deepseek-ai/dsh-fs-policy` | | `tool-fs` | `@deepseek-ai/dsh-tool-fs` | diff --git a/examples/acp-agent/cordis.yml b/examples/acp-agent/cordis.yml index 83ac07ce55..af2da25b86 100644 --- a/examples/acp-agent/cordis.yml +++ b/examples/acp-agent/cordis.yml @@ -86,6 +86,14 @@ - id: tool-todo name: '@deepseek-ai/dsh-tool-todo' +# The repeat-tool-call guard: advisory reminders (injected context, never a +# block) when the model re-issues the same tool call with identical arguments; +# defaults [3, 5, 8]. Loaded here so the snapshot tier exercises the reminder +# transcript (the repeat-tool-guard scenario) — no other scenario repeats a +# call three times, so it is inert everywhere else. +- id: repeat-tool-guard + name: '@deepseek-ai/dsh-repeat-tool-guard' + # Filesystem capability stack: local provider, read-before-write/edit policy # gate, then the model-facing read/write/edit tools. Relative filesystem paths # resolve from the server launch cwd; the documented Zed setup launches this diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index b864189a61..647a37e9df 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -39,8 +39,13 @@ const SCENARIOS: Scenario[] = [ { name: 'fs-read-window', hasModelTurn: true, recorded: true }, { name: 'fs-policy-reject', hasModelTurn: true, recorded: true }, { name: 'multi-turn', hasModelTurn: true, recorded: true }, - { name: 'error-finish', hasModelTurn: true, recorded: false }, - { name: 'cancel', hasModelTurn: true, recorded: false }, + { name: 'error-finish', hasModelTurn: true, recorded: false, overridden: true }, + // Keyless, authored (like error-finish/cancel): deterministically forcing a + // LIVE model to repeat one call three times is not a stable recording, so + // the fixture scripts five identical todo_write calls and pins BOTH reminder + // tiers (gentle at 3, detailed at 5) as context/message in transcript and log. + { name: 'repeat-tool-guard', hasModelTurn: true, recorded: false }, + { name: 'cancel', hasModelTurn: true, recorded: false, overridden: true }, { name: 'subagent-spawn', hasModelTurn: true, recorded: true, childSessions: 1 }, { name: 'subagent-multi', hasModelTurn: true, recorded: true, childSessions: 2 }, { name: 'subagent-fork', hasModelTurn: true, recorded: true, childSessions: 1 }, diff --git a/examples/acp-agent/tests/snapshots/repeat-tool-guard/input.json b/examples/acp-agent/tests/snapshots/repeat-tool-guard/input.json new file mode 100644 index 0000000000..9d2203ed57 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/repeat-tool-guard/input.json @@ -0,0 +1,7 @@ +{ + "steps": [ + { "op": "initialize" }, + { "op": "newSession" }, + { "op": "prompt", "text": "Write the todo list 'watch the kettle boil' five times in a row without changing it, then reply DONE." } + ] +} diff --git a/examples/acp-agent/tests/snapshots/repeat-tool-guard/session.jsonl b/examples/acp-agent/tests/snapshots/repeat-tool-guard/session.jsonl new file mode 100644 index 0000000000..7e50e71b3b --- /dev/null +++ b/examples/acp-agent/tests/snapshots/repeat-tool-guard/session.jsonl @@ -0,0 +1,70 @@ +{"type":"session","version":0,"id":"{{sessionId}}","createdAt":0,"cwd":"{{cwd}}"} +{"type":"turn/start","seq":0,"time":0,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} +{"type":"user/message","seq":1,"time":0,"data":{"content":[{"type":"text","text":"Write the todo list 'watch the kettle boil' five times in a row without changing it, then reply DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} +{"type":"step/start","seq":2,"time":0,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":3,"time":0,"data":{"header":{"config":{"model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"assistant/chunk","seq":4,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":5,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_1","name":"todo_write","argumentsDelta":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}} +{"type":"assistant/chunk","seq":6,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_1","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}}} +{"type":"assistant/chunk","seq":7,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":8,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":9,"time":0,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_1","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}],"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[4,5,6,7,8],"surfaceOp":"append"} +{"type":"tool/call","seq":10,"time":0,"data":{"turn":1,"step":1,"callId":"call_1","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}} +{"type":"todo/write","seq":11,"time":0,"data":{"todos":[{"content":"watch the kettle boil","status":"in_progress"}]}} +{"type":"tool/result","seq":12,"time":0,"data":{"turn":1,"step":1,"callId":"call_1","content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}],"isError":false},"sourceEventSeqs":[10],"surfaceOp":"append"} +{"type":"step/end","seq":13,"time":0,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":14,"time":0,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":15,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":16,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"call_2","name":"todo_write","argumentsDelta":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}} +{"type":"assistant/chunk","seq":17,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_2","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}}} +{"type":"assistant/chunk","seq":18,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":19,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"tool-call","id":"call_2","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}],"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} +{"type":"tool/call","seq":21,"time":0,"data":{"turn":1,"step":2,"callId":"call_2","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}} +{"type":"todo/write","seq":22,"time":0,"data":{"todos":[{"content":"watch the kettle boil","status":"in_progress"}]}} +{"type":"tool/result","seq":23,"time":0,"data":{"turn":1,"step":2,"callId":"call_2","content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}],"isError":false},"sourceEventSeqs":[21],"surfaceOp":"append"} +{"type":"step/end","seq":24,"time":0,"data":{"turn":1,"step":2}} +{"type":"step/start","seq":25,"time":0,"data":{"turn":1,"step":3}} +{"type":"assistant/chunk","seq":26,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":27,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"call_3","name":"todo_write","argumentsDelta":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}} +{"type":"assistant/chunk","seq":28,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_3","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}}} +{"type":"assistant/chunk","seq":29,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":30,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":31,"time":0,"data":{"turn":1,"step":3,"content":[{"type":"tool-call","id":"call_3","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}],"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[26,27,28,29,30],"surfaceOp":"append"} +{"type":"tool/call","seq":32,"time":0,"data":{"turn":1,"step":3,"callId":"call_3","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}} +{"type":"todo/write","seq":33,"time":0,"data":{"todos":[{"content":"watch the kettle boil","status":"in_progress"}]}} +{"type":"tool/result","seq":34,"time":0,"data":{"turn":1,"step":3,"callId":"call_3","content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}],"isError":false},"sourceEventSeqs":[32],"surfaceOp":"append"} +{"type":"context/message","seq":35,"time":0,"data":{"content":[{"type":"text","text":"You are repeating the exact same tool call with identical arguments. Carefully analyze the previous result before calling again: if the task is not complete, try a different approach or different arguments instead of repeating the call."}],"source":{"kind":"plugin","plugin":"repeat-tool-guard"}},"surfaceOp":"append"} +{"type":"step/end","seq":36,"time":0,"data":{"turn":1,"step":3}} +{"type":"step/start","seq":37,"time":0,"data":{"turn":1,"step":4}} +{"type":"assistant/chunk","seq":38,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":39,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"call_4","name":"todo_write","argumentsDelta":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}} +{"type":"assistant/chunk","seq":40,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_4","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}}} +{"type":"assistant/chunk","seq":41,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":42,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":43,"time":0,"data":{"turn":1,"step":4,"content":[{"type":"tool-call","id":"call_4","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}],"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[38,39,40,41,42],"surfaceOp":"append"} +{"type":"tool/call","seq":44,"time":0,"data":{"turn":1,"step":4,"callId":"call_4","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}} +{"type":"todo/write","seq":45,"time":0,"data":{"todos":[{"content":"watch the kettle boil","status":"in_progress"}]}} +{"type":"tool/result","seq":46,"time":0,"data":{"turn":1,"step":4,"callId":"call_4","content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}],"isError":false},"sourceEventSeqs":[44],"surfaceOp":"append"} +{"type":"step/end","seq":47,"time":0,"data":{"turn":1,"step":4}} +{"type":"step/start","seq":48,"time":0,"data":{"turn":1,"step":5}} +{"type":"assistant/chunk","seq":49,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":50,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"call_5","name":"todo_write","argumentsDelta":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}} +{"type":"assistant/chunk","seq":51,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_5","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}}}} +{"type":"assistant/chunk","seq":52,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":53,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":54,"time":0,"data":{"turn":1,"step":5,"content":[{"type":"tool-call","id":"call_5","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}],"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[49,50,51,52,53],"surfaceOp":"append"} +{"type":"tool/call","seq":55,"time":0,"data":{"turn":1,"step":5,"callId":"call_5","name":"todo_write","arguments":"{\"todos\": [{\"content\": \"watch the kettle boil\", \"status\": \"in_progress\"}]}"}} +{"type":"todo/write","seq":56,"time":0,"data":{"todos":[{"content":"watch the kettle boil","status":"in_progress"}]}} +{"type":"tool/result","seq":57,"time":0,"data":{"turn":1,"step":5,"callId":"call_5","content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}],"isError":false},"sourceEventSeqs":[55],"surfaceOp":"append"} +{"type":"context/message","seq":58,"time":0,"data":{"content":[{"type":"text","text":"Repeated tool call detected:\n- tool: todo_write\n- consecutive_calls: 5\n- arguments: {\"todos\":[{\"content\":\"watch the kettle boil\",\"status\":\"in_progress\"}]}\nThe repeated calls are not making progress. Do not call this tool with these exact arguments again. Inspect the latest result and choose a different action, different arguments, or finish the task if enough evidence has been gathered."}],"source":{"kind":"plugin","plugin":"repeat-tool-guard"}},"surfaceOp":"append"} +{"type":"step/end","seq":59,"time":0,"data":{"turn":1,"step":5}} +{"type":"step/start","seq":60,"time":0,"data":{"turn":1,"step":6}} +{"type":"assistant/chunk","seq":61,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} +{"type":"assistant/chunk","seq":62,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"text-delta","index":0,"text":"DONE."}}} +{"type":"assistant/chunk","seq":63,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE."}}}} +{"type":"assistant/chunk","seq":64,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":3}}}} +{"type":"assistant/chunk","seq":65,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":66,"time":0,"data":{"turn":1,"step":6,"content":[{"type":"text","text":"DONE."}],"usage":{"inputTokens":10,"outputTokens":3}},"sourceEventSeqs":[61,62,63,64,65],"surfaceOp":"append"} +{"type":"step/end","seq":67,"time":0,"data":{"turn":1,"step":6}} +{"type":"turn/end","seq":68,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/repeat-tool-guard/stdout.golden.jsonl b/examples/acp-agent/tests/snapshots/repeat-tool-guard/stdout.golden.jsonl new file mode 100644 index 0000000000..a3ae2e3870 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/repeat-tool-guard/stdout.golden.jsonl @@ -0,0 +1,19 @@ +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}"}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_1","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_1","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_2","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_2","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_3","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_3","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_4","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_4","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_5","title":"Update todo list","kind":"other","status":"in_progress","rawInput":[{"content":"watch the kettle boil","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"plan","entries":[{"content":"watch the kettle boil","priority":"medium","status":"in_progress"}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_5","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 0 completed."}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE."}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/cordis-agent/README.md b/examples/cordis-agent/README.md new file mode 100644 index 0000000000..953533d35b --- /dev/null +++ b/examples/cordis-agent/README.md @@ -0,0 +1,33 @@ +# cordis-agent + +The self-referential harness demo: the coding-agent spine (DeepSeek V4 + local bash on the stdio chat app) plus [`@deepseek-ai/dsh-tool-cordis`](../../packages/cordis/tool-cordis/README.md), which hands the model three tools over the **live cordis runtime it is running inside** — inspect it, mount new plugins into it, and dispose them again. The `ctx.fs` and `ctx.web` services are mounted (provider-only, no model-facing file/web tools) so the plugins the agent writes have real capabilities to build on; Node built-ins are trapped in the sandbox and redirect to those services. The design (sandbox semantics, mount lifecycle, cross-mount composition, caveats) lives in [the toolset RFC](../../docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). + +## Run it + +```sh +# repo root .env (gitignored) or exported env: +# DEEPSEEK_API_KEY=sk-… +# DEEPSEEK_BASE_URL=https://… # optional; defaults to the public API +pnpm run demo:cordis +``` + +The intended demo is staged — verify the listener link first, then let the agent extend itself: + +``` +> Mount a plugin that listens to the 'agent/status' event and logs every status change, then run `echo hi` with bash. + [tool call] cordis_mount({"code": "return { name: 'status-logger', apply(ctx) { ctx.on('agent/status', (agent, status) => console.log('status →', status)) } }"}) + [tool result] mounted dyn-1 (plugin "status-logger", state: active) + [tool call] bash({"command": "echo hi"}) +[cordis:dyn-1] status → … ← the mounted listener firing, live +> Now give yourself a reverse_text tool and use it on "harness". + [tool call] cordis_mount({"code": "return { name: 'reverse-text', inject: ['tools'], apply(ctx) { ctx.tools.register(harness.defineTool({ name: 'reverse_text', … })) } }"}) + [tool call] reverse_text({"text": "harness"}) ← a tool the agent built for itself, one step earlier +> Unmount both. + [tool call] cordis_unmount({"id": "dyn-1"}) +``` + +Ask for `cordis_inspect` with `what: "api"` or `what: "events"` to see the generated service/event reference the agent writes plugin code against, and try two cooperating mounts (`ctx.provide` in one, `inject` in the other) to watch cordis park and revive the consumer. + +## End-to-end tests + +`tests/keyless-smoke.e2e.ts` boots the real `cordis.yml` through the Loader with a dummy key and asserts the banner + clean EOF exit (the export-shape / real-load-path guard, now across the package-name resolution). `tests/cordis-tools.e2e.ts` is the with-key smoke: a real model mounts a status listener (asserting the tagged console line actually fires — the world, not the agent's claim), builds itself a `reverse_text` tool and uses it, and composes two mounts via provide/inject. The tool logic itself is unit-tested in [`packages/cordis/tool-cordis`](../../packages/cordis/tool-cordis) under the per-file 100% coverage gate. diff --git a/examples/cordis-agent/composition.md b/examples/cordis-agent/composition.md new file mode 100644 index 0000000000..015bec724e --- /dev/null +++ b/examples/cordis-agent/composition.md @@ -0,0 +1,49 @@ + + +# Cordis Agent App Composition + +The self-referential demo puts @deepseek-ai/dsh-tool-cordis on the coding spine, letting the agent inspect its own runtime and mount/unmount plugins into it. + +```mermaid +flowchart LR + cfg["examples/cordis-agent
cordis.yml"] + plugin_cordis_hmr["hmr
@cordisjs/plugin-hmr"] + cfg --> plugin_cordis_hmr + plugin_cordis_llm_deepseek["llm-deepseek
@deepseek-ai/dsh-llm-deepseek"] + cfg --> plugin_cordis_llm_deepseek + plugin_cordis_bash["bash
@deepseek-ai/dsh-bash-local"] + cfg --> plugin_cordis_bash + plugin_cordis_fs_local["fs-local
@deepseek-ai/dsh-fs-local"] + cfg --> plugin_cordis_fs_local + plugin_cordis_web["web
@deepseek-ai/dsh-web"] + cfg --> plugin_cordis_web + plugin_cordis_web_fetch_local["web-fetch-local
@deepseek-ai/dsh-web-fetch-local"] + cfg --> plugin_cordis_web_fetch_local + plugin_cordis_stdio_agent["stdio-agent
@deepseek-ai/dsh-stdio-agent"] + cfg --> plugin_cordis_stdio_agent + plugin_cordis_stdio_agent --> bundle_agent_core["@deepseek-ai/dsh-agent-core"] + plugin_cordis_stdio_agent --> bundle_jsonl["@deepseek-ai/dsh-session-persistence-jsonl"] + plugin_cordis_stdio_agent --> frontdoor_stdio["readline UI
console logger
pre-created main agent"] + bundle_agent_core --> spine_llm["ctx.llm"] + bundle_agent_core --> spine_sessions["ctx.sessions"] + bundle_agent_core --> spine_tools["ctx.tools + tool-bash"] + bundle_agent_core --> spine_loop["ctx.agents + ctx.agentLoop"] + plugin_cordis_tool_cordis["tool-cordis
@deepseek-ai/dsh-tool-cordis"] + cfg --> plugin_cordis_tool_cordis +``` + +| Plugin id | Package / module | +| --- | --- | +| `hmr` | `@cordisjs/plugin-hmr` | +| `llm-deepseek` | `@deepseek-ai/dsh-llm-deepseek` | +| `bash` | `@deepseek-ai/dsh-bash-local` | +| `fs-local` | `@deepseek-ai/dsh-fs-local` | +| `web` | `@deepseek-ai/dsh-web` | +| `web-fetch-local` | `@deepseek-ai/dsh-web-fetch-local` | +| `stdio-agent` | `@deepseek-ai/dsh-stdio-agent` | +| `tool-cordis` | `@deepseek-ai/dsh-tool-cordis` | + +Source config: [`examples/cordis-agent/cordis.yml`](cordis.yml). + +Maintenance mode: hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source. diff --git a/examples/cordis-agent/cordis.yml b/examples/cordis-agent/cordis.yml new file mode 100644 index 0000000000..65d5e6eb36 --- /dev/null +++ b/examples/cordis-agent/cordis.yml @@ -0,0 +1,83 @@ +# The cordis-agent plugin tree: the SELF-REFERENTIAL harness demo. Same spine +# as coding-agent (DeepSeek V4 + local bash on @deepseek-ai/dsh-stdio-agent), +# plus @deepseek-ai/dsh-tool-cordis, which gives the model three tools over the +# live cordis runtime it is running inside: cordis_inspect (services / plugin +# tree / tools / dynamic mounts / api / events), cordis_mount (evaluate +# model-written code in a vm sandbox and mount the returned plugin under the +# `cordis-dynamic` group), and cordis_unmount (dispose one mount by id). +# Requires DEEPSEEK_API_KEY (and optionally DEEPSEEK_BASE_URL) — the +# dsh-stdio-agent bin loads the gitignored repo-root .env first. +# +# Trust stance (docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md): +# the mounted code gets the REAL ctx — the +# vm sandbox only prevents accidental global pollution. Load the toolset as +# deliberately as you would grant a bash tool. + +# Hot-module reload for the dev/demo loop (needs `node --expose-internals`). +- id: hmr + name: '@cordisjs/plugin-hmr' + config: + root: ['.'] + +# The DeepSeek adapter. +- id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek' + config: + apiKey: !!js process.env.DEEPSEEK_API_KEY + baseURL: !!js process.env.DEEPSEEK_BASE_URL + models: + - deepseek-v4-pro + - deepseek-v4-flash + +# Local bash executor for agent-core's tool-bash schema — gives the agent an +# ordinary tool whose calls make the mounted listeners observably fire. +- id: bash + name: '@deepseek-ai/dsh-bash-local' + config: + timeoutMs: 60000 + +# Filesystem service for mounted plugins (ctx.fs) — the local provider only. +# The model-facing read/write/edit tools stay unmounted on purpose: this demo +# is about the agent building its own tools over the services. +- id: fs-local + name: '@deepseek-ai/dsh-fs-local' + config: + cwd: !!js process.cwd() + +# Web service for mounted plugins (ctx.web): the seam plus the anonymous local +# fetch provider (keyless). No search provider is loaded — ctx.web search +# calls fail loud until a deployment adds one. +- id: web + name: '@deepseek-ai/dsh-web' + +- id: web-fetch-local + name: '@deepseek-ai/dsh-web-fetch-local' + +# The stdio chat app: the whole spine + front-door cluster, configured for the +# self-referential demo driving a pre-created `main` agent. +- id: stdio-agent + name: '@deepseek-ai/dsh-stdio-agent' + config: + model: deepseek-v4-flash + resumeSessionId: !!js process.env.RESUME_SESSION_ID + persistenceRoot: './.sessions' + welcome: 'cordis-agent ready. Ask it to inspect its runtime, mount a listener, or invent a tool for itself.' + persona: | + You are cordis-agent, a self-referential harness demo powered by the + {{model}} model. + + You run INSIDE a cordis plugin runtime, and your cordis_* tools operate + on that live runtime: cordis_inspect to look around (its `api` and + `events` sections document the service methods, type shapes, and events + your plugin code can use), cordis_mount to add a plugin (an event + listener, a brand-new tool for yourself, or a service other mounts + inject), cordis_unmount to clean one up. In mounted code, NEVER use Node + built-ins (require/setTimeout/fetch) — use the runtime's cordis services + via inject: fs, web, bash, and timer (ctx.setTimeout). Prefer small + single-purpose plugins, prefer plain notification events over waterfall + events unless you intend to intercept, and unmount what you no longer + need. Report results briefly. + +# The self-referential cordis toolset (loaded after the app so ctx.tools exists). +- id: tool-cordis + name: '@deepseek-ai/dsh-tool-cordis' diff --git a/examples/cordis-agent/package.json b/examples/cordis-agent/package.json new file mode 100644 index 0000000000..8d5a693555 --- /dev/null +++ b/examples/cordis-agent/package.json @@ -0,0 +1,7 @@ +{ + "name": "cordis-agent-example", + "private": true, + "version": "0.0.1", + "type": "module", + "description": "Runnable demo: the self-referential harness — an agent that inspects and modifies its own cordis runtime" +} diff --git a/examples/cordis-agent/tests/cordis-tools.e2e.ts b/examples/cordis-agent/tests/cordis-tools.e2e.ts new file mode 100644 index 0000000000..388fcb0058 --- /dev/null +++ b/examples/cordis-agent/tests/cordis-tools.e2e.ts @@ -0,0 +1,156 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { Context } from 'cordis' +import { CallId } from '@deepseek-ai/dsh-llm' +import { AgentId } from '@deepseek-ai/dsh-agent' +import { cordisHarness, waitForIdle } from './harness.ts' + +/** + * With-key smoke for the self-referential cordis tools: a REAL model drives + * cordis_mount/cordis_unmount against the live context the test observes. + * World-verified, not self-reported: the mounted listener must actually WRITE + * its tagged console line, the self-made tool must actually EXIST in the + * registry and appear as a real `tool/call`, the cross-mount service must + * actually LAND in the reflect store. Key-gated (see vitest.e2e.config.ts). + */ + +let ctx: Context | undefined + +afterEach(async () => { + vi.restoreAllMocks() + // Always dispose the harness, even on failure/retry/timeout: agent-loop + // teardown stops the loop, and disposing the tree unwinds every dynamic + // mount the model left behind. + await ctx?.fiber.dispose() + ctx = undefined +}) + +/** The tagged write-through lines (`[cordis:dyn-n] …`) captured by a console spy. */ +function taggedCalls(log: { mock: { calls: unknown[][] } }): unknown[][] { + return log.mock.calls.filter(call => typeof call[0] === 'string' && /^\[cordis:dyn-\d+\]$/.test(call[0])) +} + +/** Model-facing text of one tool result, concatenated. */ +function resultText(result: { content: { type: string; text?: string }[] }): string { + return result.content.filter(block => block.type === 'text').map(block => block.text).join('') +} + +describe.skipIf(!process.env.DEEPSEEK_API_KEY)('cordis tools: a real model modifies its own runtime', () => { + it('mounts a status listener whose tagged output actually fires, then unmounts it', async () => { + ctx = await cordisHarness() + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const agent = ctx.agentLoop.create(AgentId('cordis-e2e-listener'), { model: 'deepseek-v4-flash' }) + + agent.send([{ + type: 'text', + text: 'Use cordis_mount to mount a plugin that listens to the \'agent/status\' ' + + 'cordis event and logs every change with console.log. Reply "mounted" once done.', + }]) + await waitForIdle(ctx, agent) + + // The WORLD check: the turn's own running→idle transition must have driven + // the mounted listener through the tagged sandbox console. + expect(taggedCalls(log).length).toBeGreaterThan(0) + const mid = await ctx.tools.execute({ + callId: CallId('verify-mounted'), name: 'cordis_inspect', arguments: { what: 'dynamic' }, + }) + expect(resultText(mid)).toContain('dyn-') + + agent.send([{ type: 'text', text: 'Now unmount the plugin you just mounted.' }]) + await waitForIdle(ctx, agent) + + const after = await ctx.tools.execute({ + callId: CallId('verify-unmounted'), name: 'cordis_inspect', arguments: { what: 'dynamic' }, + }) + expect(resultText(after)).toContain('(no dynamic plugins mounted)') + }, 120_000) + + it('builds itself a reverse_text tool and actually calls it', async () => { + ctx = await cordisHarness() + const agent = ctx.agentLoop.create(AgentId('cordis-e2e-selftool'), { model: 'deepseek-v4-flash' }) + + agent.send([{ + type: 'text', + text: 'Give yourself a new tool: use cordis_mount to mount a plugin with ' + + 'inject ["tools"] that calls harness.registerTool(ctx, harness.defineTool({...})) ' + + 'to register a tool named reverse_text with one required string parameter ' + + '"text", returning the text reversed. Then CALL reverse_text with the ' + + 'exact text "harness" and report its exact output.', + }]) + await waitForIdle(ctx, agent) + + // World checks: the tool exists in the registry, was invoked as a real + // tool call, and its RESULT (the self-made execute actually running) is the + // reversed string. The model's prose is not asserted — the tool result is + // the world; the summary sentence is just the self-report. + expect(ctx.tools.get('reverse_text')).toBeDefined() + const events = [...agent.session.events] + const calls = events.filter(event => event.type === 'tool/call') + expect(calls.some(event => event.data.name === 'cordis_mount')).toBe(true) + const reverseCalls = calls.filter(event => event.data.name === 'reverse_text') + expect(reverseCalls.length).toBeGreaterThan(0) + const reverseResults = events + .filter(event => event.type === 'tool/result') + .filter(event => reverseCalls.some(call => call.data.callId === event.data.callId)) + .flatMap(event => event.data.content.filter(block => block.type === 'text').map(block => block.text)) + // On failure, surface what the model actually mounted and what the tool + // returned — an e2e failing at a distance is undebuggable without it. + const mountCode = calls + .filter(event => event.data.name === 'cordis_mount') + .map(event => event.data.arguments) + .join('\n---\n') + const trace = events.map((event) => { + switch (event.type) { + case 'tool/call': return `tool/call:${event.data.name}` + case 'tool/result': return `tool/result:${event.data.isError ? 'ERR:' + JSON.stringify(event.data.content).slice(0, 200) : 'ok'}` + case 'turn/end': return `turn/end:${JSON.stringify(event.data.reason)}` + default: return event.type + } + }).join('\n') + expect( + reverseResults.some(text => text.includes('ssenrah')), + `no reversed output in reverse_text results.\nresults: ${JSON.stringify(reverseResults)}\nmount code: ${mountCode}\ntrace:\n${trace}`, + ).toBe(true) + }, 120_000) + + it('composes two mounts through provide/inject, and unmounting the provider parks the consumer', async () => { + ctx = await cordisHarness() + const agent = ctx.agentLoop.create(AgentId('cordis-e2e-compose'), { model: 'deepseek-v4-flash' }) + + agent.send([{ + type: 'text', + text: 'Mount TWO separate plugins with cordis_mount. First a provider: apply calls ' + + 'ctx.provide(\'shouter\', { shout: (s) => s.toUpperCase() }). Second a consumer with ' + + 'inject ["shouter", "tools"] that registers (via harness.registerTool + harness.defineTool) ' + + 'a tool named shout_text with one required string parameter "text" whose execute returns ' + + 'ctx.shouter.shout(args.text) as a text content block. Then CALL shout_text with "quiet" ' + + 'and report the exact output.', + }]) + await waitForIdle(ctx, agent) + + // World checks: the service is really in the store, the tool really ran. + expect(ctx.get('shouter')).toBeDefined() + expect(ctx.tools.get('shout_text')).toBeDefined() + const events = [...agent.session.events] + const shoutCalls = events + .filter(event => event.type === 'tool/call') + .filter(event => event.data.name === 'shout_text') + expect(shoutCalls.length).toBeGreaterThan(0) + const shoutResults = events + .filter(event => event.type === 'tool/result') + .filter(event => shoutCalls.some(call => call.data.callId === event.data.callId)) + .flatMap(event => event.data.content.filter(block => block.type === 'text').map(block => block.text)) + expect(shoutResults.some(text => text.includes('QUIET'))).toBe(true) + + agent.send([{ type: 'text', text: 'Now unmount ONLY the provider plugin (the one that provided shouter).' }]) + await waitForIdle(ctx, agent) + + // The consumer must have been parked by cordis itself: service gone, + // dependent tool unregistered, dynamic table naming the missing service. + expect(ctx.get('shouter')).toBeUndefined() + expect(ctx.tools.get('shout_text')).toBeUndefined() + const after = await ctx.tools.execute({ + callId: CallId('verify-parked'), name: 'cordis_inspect', arguments: { what: 'dynamic' }, + }) + expect(resultText(after)).toContain('waiting for: shouter') + }, 120_000) +}) diff --git a/examples/cordis-agent/tests/harness.ts b/examples/cordis-agent/tests/harness.ts new file mode 100644 index 0000000000..78e5b0bb93 --- /dev/null +++ b/examples/cordis-agent/tests/harness.ts @@ -0,0 +1,46 @@ +import { Context } from 'cordis' +import LlmService from '@deepseek-ai/dsh-llm' +import SessionStore from '@deepseek-ai/dsh-session' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry from '@deepseek-ai/dsh-tools' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop' +import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' +import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis' + +/** + * Shared harness for the cordis-agent e2e suite: the agent spine with the real + * DeepSeek adapter and the real `@deepseek-ai/dsh-tool-cordis` plugin, so a + * live model can mount plugins into the very context the test observes. Lives + * outside the *.e2e.ts pattern so importing it never re-registers another + * file's tests. + */ + +const PERSONA = 'You are cordis-agent, a self-referential harness demo. ' + + 'Your cordis_* tools operate on the live cordis runtime you run inside: ' + + 'cordis_inspect to look around, cordis_mount to add a plugin, cordis_unmount ' + + 'to clean one up. Follow the tool descriptions exactly and report results briefly.' + +export async function cordisHarness(): Promise { + const ctx = new Context() + await ctx.plugin(LlmService) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt, { persona: PERSONA }) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(LlmDeepSeek, { models: ['deepseek-v4-flash'] }) + await ctx.plugin(ToolCordis) + return ctx +} + +export function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise { + return new Promise((resolve) => { + const dispose = ctx.on('agent/status', (subject, status) => { + if (subject === agent && status === 'idle') { + dispose() + resolve() + } + }) + }) +} diff --git a/examples/cordis-agent/tests/keyless-smoke.e2e.ts b/examples/cordis-agent/tests/keyless-smoke.e2e.ts new file mode 100644 index 0000000000..b37ea8d83e --- /dev/null +++ b/examples/cordis-agent/tests/keyless-smoke.e2e.ts @@ -0,0 +1,94 @@ +import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, it } from 'vitest' + +/** + * Keyless Loader-path smoke for examples/cordis-agent: boot the REAL example + * through the `@deepseek-ai/dsh-stdio-agent` bin against its `cordis.yml` — + * the cordis Loader, `unwrapExports`, the full plugin tree INCLUDING the + * `@deepseek-ai/dsh-tool-cordis` package resolved by name (whose `inject` + * would crash a collapsed export shape at load, see docs/postmortem/0001) — + * then close stdin with no prompt and assert the ready banner + a clean exit. + * + * No prompt is ever sent, so the model is NEVER called — that is why it runs + * without a real key: `llm-deepseek`'s apply() only requires a key to be + * PRESENT, and the absence of any prompt guarantees no network call. The + * with-key product proof lives in cordis-tools.e2e.ts. + */ + +// The dsh-stdio-agent bin (the demo:cordis entry) and this example's cordis.yml. +// The bin resolves its config-path arg from CWD; the test spawns from a temp +// cwd, so we pass the example config's ABSOLUTE path. +const binScript = fileURLToPath(new URL('../../../packages/ui/stdio-agent/src/bin.ts', import.meta.url)) +const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url)) +const tsxLoader = fileURLToPath(import.meta.resolve('tsx')) +// Dev/test run UNBUILT: resolve `@deepseek-ai/dsh-*` through the root tsconfig +// `paths` map; tsx searches UP from cwd, and we spawn from a temp dir outside +// the repo, so point it at the repo tsconfig (root is three levels up). +const repoTsconfig = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)) + +let child: ChildProcessWithoutNullStreams | undefined +let workdir: string | undefined + +afterEach(async () => { + if (child !== undefined && child.exitCode === null) child.kill('SIGKILL') + child = undefined + if (workdir !== undefined) await rm(workdir, { recursive: true, force: true }) + workdir = undefined +}) + +async function bootAndEof(): Promise<{ stdout: string; code: number }> { + workdir = await mkdtemp(join(tmpdir(), 'cordis-smoke-')) + const cwd = workdir + return new Promise((resolve, reject) => { + const proc = spawn( + process.execPath, + // --expose-internals: cordis.yml loads the HMR plugin (mirrors demo:cordis). + ['--expose-internals', '--import', tsxLoader, binScript, configPath], + { + cwd, + env: { + ...process.env, + TSX_TSCONFIG_PATH: repoTsconfig, + // A dummy key so llm-deepseek's apply() (key-PRESENT check only) boots. + // No prompt is sent, so the adapter never streams — no network call. + DEEPSEEK_API_KEY: 'keyless-smoke-no-call', + }, + stdio: ['pipe', 'pipe', 'pipe'], + }, + ) + child = proc + let stdout = '' + let stderr = '' + proc.stdout.setEncoding('utf8') + proc.stdout.on('data', (chunk: string) => { stdout += chunk }) + proc.stderr.setEncoding('utf8') + proc.stderr.on('data', (chunk: string) => { stderr += chunk }) + + const timer = setTimeout(() => { + proc.kill('SIGKILL') + reject(new Error(`cordis-agent did not exit within 10s. stdout:\n${stdout}\nstderr:\n${stderr}`)) + }, 10_000) + + proc.on('exit', (code) => { + clearTimeout(timer) + if (code === 0) resolve({ stdout, code }) + else reject(new Error(`cordis-agent exited ${code}. stderr:\n${stderr}`)) + }) + proc.on('error', (err) => { clearTimeout(timer); reject(err) }) + + // No prompt — just EOF, so the stdio UI exits without ever running a turn. + proc.stdin.end() + }) +} + +describe('cordis-agent keyless smoke (real cordis.yml via the Loader)', () => { + it('boots the full plugin tree incl. tool-cordis, prints its banner, and exits cleanly on EOF', async () => { + const { stdout, code } = await bootAndEof() + expect(code).toBe(0) + expect(stdout).toContain('cordis-agent ready.') + }, 15_000) +}) diff --git a/knip.json b/knip.json index 8c0f71f3af..198cad3cce 100644 --- a/knip.json +++ b/knip.json @@ -8,6 +8,7 @@ "examples/echo-agent/src/*.ts", "examples/echo-agent/tests/**/*.e2e.ts", "examples/coding-agent/tests/**/*.e2e.ts", + "examples/cordis-agent/tests/**/*.e2e.ts", "examples/acp-agent/tests/**/*.e2e.ts", "examples/*/tests/**/*.snapshot.ts" ], @@ -21,6 +22,11 @@ "project": ["src/**/*.ts"], "ignoreDependencies": ["cordis"] }, + "packages/util/timeout": { + "entry": ["tests/**/*.spec.ts"], + "project": ["src/**/*.ts", "tests/**/*.ts"], + "ignoreDependencies": ["cordis"] + }, "packages/support/acp-snapshot": { "entry": ["tests/**/*.spec.ts", "tests/fixtures/fake-acp-agent.ts"], "project": ["src/**/*.ts", "tests/**/*.ts"], @@ -30,6 +36,10 @@ "entry": ["tests/**/*.spec.ts", "tests/**/*.e2e.ts"], "project": ["src/**/*.ts", "tests/**/*.ts"] }, + "packages/code-runtime/code-runtime-worker": { + "entry": ["tests/**/*.spec.ts", "tests/**/*.e2e.ts"], + "project": ["src/**/*.ts", "tests/**/*.ts"] + }, "packages/llm/llm-deepseek": { "entry": ["tests/**/*.spec.ts", "tests/**/*.e2e.ts"], "project": ["src/**/*.ts", "tests/**/*.ts"] diff --git a/package.json b/package.json index df22b4846e..3f61684408 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,8 @@ "gen-cordis-catalog": "tsx scripts/gen-cordis-catalog.ts", "gen-rfc-index": "tsx scripts/gen-rfc-index.ts", "verify-cordis-catalog": "tsx scripts/gen-cordis-catalog.ts --check", + "gen-cordis-api": "tsx scripts/gen-cordis-api.ts", + "verify-cordis-api": "tsx scripts/gen-cordis-api.ts --check", "verify-export-jsdoc": "tsx scripts/verify-export-jsdoc.ts", "gen-tool-catalog": "tsx scripts/gen-tool-catalog.ts", "verify-tool-catalog": "tsx scripts/gen-tool-catalog.ts --check", @@ -60,10 +62,11 @@ "verify-scoped-dispatch": "tsx scripts/verify-scoped-dispatch.ts", "verify-module-graph": "tsx scripts/gen-module-graph.ts --check", "constraints": "tsx scripts/check-workspace-constraints.ts", - "doc-sync": "pnpm run doc-typecheck && pnpm run verify-cordis-catalog && pnpm run verify-export-jsdoc && pnpm run verify-tool-catalog && pnpm run verify-config-catalog && pnpm run verify-persistence-catalog && pnpm run verify-doc-graphs && pnpm run verify-scoped-dispatch && pnpm run verify-md-wrap && pnpm run verify-md-links && pnpm run verify-doc-refs && pnpm run verify-package-paths && pnpm run verify-mermaid && pnpm run verify-rfc-classification && pnpm run verify-rfc-format && pnpm run verify-type-equiv && pnpm run verify-translation-pairing && pnpm run verify-doc-budgets", + "doc-sync": "pnpm run doc-typecheck && pnpm run verify-cordis-catalog && pnpm run verify-cordis-api && pnpm run verify-export-jsdoc && pnpm run verify-tool-catalog && pnpm run verify-config-catalog && pnpm run verify-persistence-catalog && pnpm run verify-doc-graphs && pnpm run verify-scoped-dispatch && pnpm run verify-md-wrap && pnpm run verify-md-links && pnpm run verify-doc-refs && pnpm run verify-package-paths && pnpm run verify-mermaid && pnpm run verify-rfc-classification && pnpm run verify-rfc-format && pnpm run verify-type-equiv && pnpm run verify-translation-pairing && pnpm run verify-doc-budgets", "hygiene": "pnpm run knip && pnpm run publint && pnpm run constraints && pnpm run verify-node-next-types", "demo:echo": "node --expose-internals --import tsx packages/ui/stdio-agent/src/bin.ts examples/echo-agent/cordis.yml", "demo:repl": "node --expose-internals --import tsx packages/ui/stdio-agent/src/bin.ts examples/coding-agent/cordis.yml", + "demo:cordis": "node --expose-internals --import tsx packages/ui/stdio-agent/src/bin.ts examples/cordis-agent/cordis.yml", "demo:acp": "node --import tsx packages/ui/acp-agent/src/bin.ts examples/acp-agent/cordis.yml", "postinstall": "node scripts/install-lefthook.mjs" }, diff --git a/packages/README.md b/packages/README.md index da75f740e8..9f6daaabe1 100644 --- a/packages/README.md +++ b/packages/README.md @@ -11,15 +11,18 @@ Packages are grouped by modular role at `packages///`. The group dir | [`core/`](core/README.md) | Product API spine: session, system-prompt, tools, agent, and the concrete loop | Product — stable surface | | [`llm/`](llm/README.md) | LLM capability family: the abstract service + provider adapters | Product — stable surface | | [`bash/`](bash/README.md) | Bash capability family: the executor seam, a local impl, and the model-facing tool | Product — stable surface | -| [`code-runtime/`](code-runtime/README.md) | Code-execution capability family: the abstract runtime seam for model-written programs | Product — stable surface | +| [`code-runtime/`](code-runtime/README.md) | Code-execution capability family: the abstract runtime seam for model-written programs + a worker-thread backend | Product — stable surface | | [`fs/`](fs/README.md) | Filesystem capability family: the abstract seam, a local impl, and the model-facing file tools | Product — stable surface | | [`compact/`](compact/README.md) | Compaction capability family: the abstract seam + a basic backend (tool deferred) | Product — stable surface | | [`subagent/`](subagent/README.md) | Subagent capability family: the provider-registry seam and the model-facing delegation tool | Product — stable surface | | [`web/`](web/README.md) | Web capability family: the abstract seam, search/fetch provider impls, and the model-facing web tools | Product — stable surface | -| [`todo/`](todo/README.md) | Todo/planning family: the model-facing `todo_write` tool (whole-list task tracking on the session log) | Product — stable surface | +| [`timeout/`](timeout/README.md) | Tool-call timeout policy: the `tools/execute` deadline enforcer | Product — stable surface | +| [`todo/`](todo/README.md) | Todo/planning family: the model-facing `todo_write` tool | Product — stable surface | +| [`guard/`](guard/README.md) | Loop-hygiene guards: advisory repeat-call reminders | Product — stable surface | +| [`cordis/`](cordis/README.md) | Self-referential runtime toolset: inspect the live runtime's plugins and services, mount/unmount model-written plugins ([design](../docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md)) | Product — stable surface | | [`hooks/`](hooks/README.md) | Hook bridges + the shared Claude Code / Codex wire-protocol library | Product — stable surface | | [`session-persistence/`](session-persistence/README.md) | Persistence capability family: the seam + JSONL/SQLite backends | Product — stable surface | -| [`ui/`](ui/README.md) | Editor/client integration surfaces (the ACP bridge) + the app packages | Product — stable surface | +| [`ui/`](ui/README.md) | Editor/client integration surfaces: ACP bridge, app packages, user-interaction seam, ask-user tool | Product — stable surface | | [`support/`](support/README.md) | Dev/test/example infrastructure (invariants, replay adapter, subagent mock) | Support — lower compatibility expectations | | [`util/`](util/README.md) | Low-level zero-dependency utilities shared across groups (the `Branded` primitive) | Support — small, stable, harness-dep-free | @@ -29,6 +32,6 @@ The split is the point: a package's group says whether it is part of the product The inter-package dependency graph is generated: [docs/module-graph.md](../docs/module-graph.md) (`pnpm run gen-module-graph`, freshness-gated in CI). -The rule it must obey: **extension plugins depend on interfaces, never on the concrete loop.** `dsh-agent-loop` is swappable — UI/hook/tool plugins keep working against the `dsh-agent` vocabulary if the loop is replaced. The sanctioned exception is a **composition/bundle** package like `dsh-agent-core`, whose whole job is to assemble the concrete spine: it depends on `dsh-agent-loop` (and the other concrete spine plugins) on purpose. The rule constrains plugins that EXTEND the system, not the bundle that COMPOSES it — swapping the loop means shipping a different bundle, not rewiring every extension. A swappable capability splits into interface / implementation / consumer packages (the bash trio is the template — see [capability seams](../docs/rfc/implemented/architecture/2026-06-13-capability-seams.md)). +The rule it must obey: **extension plugins depend on interfaces, never on the concrete loop.** `dsh-agent-loop` is swappable — UI/hook/tool plugins keep working against the `dsh-agent` vocabulary if the loop is replaced. The sanctioned exception is a **composition/bundle** package like `dsh-agent-core`, whose whole job is to assemble the concrete spine: it depends on `dsh-agent-loop` (and the other concrete spine plugins) on purpose. The rule constrains plugins that EXTEND the system, not the bundle that COMPOSES it. A swappable capability splits into interface / implementation / consumer packages (the bash trio is the template — see [capability seams](../docs/rfc/implemented/architecture/2026-06-13-capability-seams.md)). Each package has its own `README.md` with purpose, service API, events, extension points, and deliberate non-goals (TODOs). diff --git a/packages/bash/bash-local/package.json b/packages/bash/bash-local/package.json index bc1dc7eb40..e3c7ffe33b 100644 --- a/packages/bash/bash-local/package.json +++ b/packages/bash/bash-local/package.json @@ -23,6 +23,7 @@ "license": "BSD-3-Clause", "peerDependencies": { "@deepseek-ai/dsh-bash": "^0.0.1", + "@deepseek-ai/dsh-timeout": "^0.0.1", "cordis": "^4.0.0-rc.6" }, "dependencies": { @@ -30,6 +31,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-bash": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^", "cordis": "^4.0.0-rc.6" } } diff --git a/packages/bash/bash-local/src/index.ts b/packages/bash/bash-local/src/index.ts index cdac3985b8..3e09d7e35b 100644 --- a/packages/bash/bash-local/src/index.ts +++ b/packages/bash/bash-local/src/index.ts @@ -18,6 +18,7 @@ import { Context } from 'cordis' import z from 'schemastery' import { BashExecutor, BashTaskId } from '@deepseek-ai/dsh-bash' import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskRead, OwnerToken } from '@deepseek-ai/dsh-bash' +import { clampTimeout, deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' import { DEFAULT_GRACE_MS, runBash } from './run.ts' import type { RunInternals, RunningBash } from './run.ts' @@ -114,8 +115,12 @@ export class LocalBashExecutor extends BashExecutor { * values and never re-default. */ resolve(request: BashExecRequest): BashExecSpec { - if (request.timeoutMs !== undefined) assertPositiveFinite('request.timeoutMs', request.timeoutMs) - const timeoutMs = Math.min(request.timeoutMs ?? this.config.timeoutMs, this.config.maxTimeoutMs) + const timeoutMs = clampTimeout( + request.timeoutMs, + this.config.timeoutMs, + this.config.maxTimeoutMs, + 'bash-local: request.timeoutMs', + ) return { command: request.command, workdir: request.workdir ?? this.config.cwd ?? process.cwd(), @@ -132,29 +137,39 @@ export class LocalBashExecutor extends BashExecutor { } async run(spec: BashExecSpec): Promise { + // One fused deadline drives both the timeout and upstream cancellation; + // runBash listens on d.signal and runs the SIGTERM→grace→SIGKILL kill. + // `using` clears the timer across the awaited process lifetime. + using d = deadline(spec.signal, spec.timeoutMs, 'BASH_TIMEOUT') const outcome = await runBash({ command: spec.command, cwd: spec.workdir, - timeoutMs: spec.timeoutMs, maxOutputBytes: this.config.maxOutputBytes, graceMs: this.config.graceMs, - signal: spec.signal, + signal: d.signal, stdin: spec.stdin, env: spec.env, }, this.internals).done - return { ...outcome, timeoutMs: spec.timeoutMs } + // Classify the FIRST abort reason: a BASH_TIMEOUT TimeoutReason means our + // timeout cut the command short; any other abort — an upstream cancel, or a + // foreign (outer) deadline's timeout under nesting — is aborted. Scoping to + // our own code keeps a nested outer deadline from reading as our timeout. + // Mutually exclusive by construction — the fused signal reports one cause. + const timedOut = timeoutOf(d.signal, 'BASH_TIMEOUT') !== undefined + const aborted = d.signal.aborted && !timedOut + return { ...outcome, timedOut, aborted, timeoutMs: spec.timeoutMs } } start(spec: BashExecSpec): BashTask { // No timeout for background tasks (matches Claude Code, which detaches // the timeout when backgrounding); callers stop tasks via kill() — or // via spec.signal, which the seam contract honors for background runs - // too (runBash wires it to the group kill). spec.timeoutMs is ignored - // here by design. + // too (runBash wires it to the group kill). No deadline is created here, + // so spec.timeoutMs is ignored by design — background tasks stay + // timeout-free (see the timeout-library RFC). const running = runBash({ command: spec.command, cwd: spec.workdir, - timeoutMs: 0, maxOutputBytes: this.config.maxOutputBytes, graceMs: this.config.graceMs, signal: spec.signal, @@ -174,8 +189,10 @@ export class LocalBashExecutor extends BashExecutor { stdoutOffset: 0, stderrOffset: 0, done: running.done.then((outcome) => { - // Abort-killed tasks report as killed, not completed. - if (task.status === 'running') task.status = outcome.aborted ? 'killed' : 'completed' + // Abort-killed tasks report as killed, not completed. Background runs + // forward only the upstream signal (no timeout), so its aborted state + // is the authoritative "was this cancelled" signal. + if (task.status === 'running') task.status = spec.signal?.aborted === true ? 'killed' : 'completed' task.exitCode = outcome.exitCode task.signal = outcome.signal this.notifyTaskDone(task) diff --git a/packages/bash/bash-local/src/run.ts b/packages/bash/bash-local/src/run.ts index b39e45c5f5..bc4a017dea 100644 --- a/packages/bash/bash-local/src/run.ts +++ b/packages/bash/bash-local/src/run.ts @@ -6,6 +6,12 @@ * Everything here is deliberately free of Cordis concepts so it can be unit * tested in isolation; `LocalBashExecutor` owns lifecycle and configuration. * + * runBash owns NO timing: it kills the process group when its `spec.signal` + * fires and does not distinguish a timeout from a cancel. The executor fuses + * timeout + upstream cancellation into that one signal via + * `@deepseek-ai/dsh-timeout`'s `deadline`, and classifies the outcome from the + * signal afterward — the timing/classification half is shared, the kill is not. + * * Design notes (surveyed against Claude Code, OpenCode, Codex, and pi — see * the package README): spawn-per-call with `detached: true` so the child * leads its own process group; kills target the group (`kill(-pid)`) so @@ -71,13 +77,17 @@ export function childEnv(extra?: Record): NodeJS.ProcessEnv { export interface SpawnSpec { command: string cwd: string - /** Kill the process group after this many milliseconds. 0 = no timeout. */ - timeoutMs: number /** Per-stream in-memory cap; overflow spills to disk (tail kept in memory). */ maxOutputBytes: number /** Grace period between the SIGTERM and the SIGKILL escalation on a kill. */ graceMs: number - /** Abort signal — kills the process group when fired. */ + /** + * Abort signal — kills the process group when it fires. The executor owns + * timing: `run()` passes a fused timeout/cancel deadline signal (see + * `@deepseek-ai/dsh-timeout`), `start()` passes the bare upstream signal. + * runBash only listens and kills; it does NOT classify why (the executor + * reads the signal's reason afterward). + */ signal?: AbortSignal | undefined /** * Bytes to write to the child's stdin, then close it. Absent (or empty) @@ -94,12 +104,15 @@ export interface SpawnSpec { env?: Record | undefined } -/** Raw outcome of one closed process (before result shaping). */ +/** + * Raw outcome of one closed process (before result shaping). Deliberately + * carries NO timeout/cancel classification: runBash kills on abort but does not + * decide why — the executor's `run()`/`start()` reads the deadline signal it + * owns to classify `timedOut`/`aborted` (see the package README). + */ export interface SpawnOutcome { exitCode: number | null signal: NodeJS.Signals | null - timedOut: boolean - aborted: boolean stdout: CollectedOutput stderr: CollectedOutput } @@ -343,9 +356,6 @@ export function runBash(spec: SpawnSpec, internals: RunInternals = {}): RunningB child.stdout.on('data', (chunk: Buffer) => { stdout.push(chunk) }) child.stderr.on('data', (chunk: Buffer) => { stderr.push(chunk) }) - let timedOut = false - let aborted = false - let killTimer: NodeJS.Timeout | undefined let graceTimer: NodeJS.Timeout | undefined // pid is undefined when the spawn itself fails (bad cwd, missing binary); @@ -358,17 +368,12 @@ export function runBash(spec: SpawnSpec, internals: RunInternals = {}): RunningB graceTimer = setTimeout(() => { killGroup(pid, 'SIGKILL') }, spec.graceMs) } - if (spec.timeoutMs > 0) { - killTimer = setTimeout(() => { - timedOut = true - kill() - }, spec.timeoutMs) - } - - const onAbort = (): void => { - aborted = true - kill() - } + // runBash owns no timer: the executor's `run()` fuses timeout+cancel into one + // deadline signal (`@deepseek-ai/dsh-timeout`) and passes it here; we only + // listen and run the SIGTERM→grace→SIGKILL kill. Whether the abort was a + // timeout or an upstream cancel is classified by the executor from that + // signal, not tracked here. + const onAbort = (): void => { kill() } spec.signal?.addEventListener('abort', onAbort, { once: true }) // Write stdin and close it, but ONLY when the caller supplied bytes — with no @@ -401,14 +406,11 @@ export function runBash(spec: SpawnSpec, internals: RunInternals = {}): RunningB resolve({ exitCode, signal, - timedOut, - aborted, stdout: stdout.finalize(), stderr: stderr.finalize(), }) }) function cleanup(): void { - if (killTimer !== undefined) clearTimeout(killTimer) if (graceTimer !== undefined) clearTimeout(graceTimer) spec.signal?.removeEventListener('abort', onAbort) } diff --git a/packages/bash/bash-local/tests/executor.spec.ts b/packages/bash/bash-local/tests/executor.spec.ts index ce89b2a0ae..450ad7a81f 100644 --- a/packages/bash/bash-local/tests/executor.spec.ts +++ b/packages/bash/bash-local/tests/executor.spec.ts @@ -40,12 +40,14 @@ async function readUntil( ): Promise { const deadline = Date.now() + timeoutMs let last: BashTaskRead | undefined + let delta = '' while (Date.now() < deadline) { last = bash.readOutput(id) - if (last.delta.includes(expected)) return last + delta += last.delta + if (delta.includes(expected)) return { ...last, delta } await new Promise(resolve => setTimeout(resolve, 20)) } - throw new Error(`task ${id} output did not include ${JSON.stringify(expected)}; last delta was ${JSON.stringify(last?.delta ?? '')}`) + throw new Error(`task ${id} output did not include ${JSON.stringify(expected)}; output was ${JSON.stringify(delta)}, last delta was ${JSON.stringify(last?.delta ?? '')}`) } describe('LocalBashExecutor.run', () => { @@ -90,8 +92,8 @@ describe('LocalBashExecutor.run', () => { it('kill escalation uses the configured graceMs (a TERM-trapping task dies by SIGKILL)', async () => { const { bash } = await setup() // setup pins graceMs: 200 via config - const task = bash.start(bash.resolve({ command: 'trap \'\' TERM; sleep 60' })) - await new Promise(resolve => setTimeout(resolve, 100)) + const task = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo ready; while :; do sleep 60 & wait $!; done' })) + await readUntil(bash, task.id, 'ready\n') bash.kill(task.id) await task.done expect(task.signal).toBe('SIGKILL') @@ -101,6 +103,8 @@ describe('LocalBashExecutor.run', () => { const { bash } = await setup({ timeoutMs: 60_000 }) const result = await bash.run(bash.resolve({ command: 'sleep 60', timeoutMs: 100 })) expect(result.timedOut).toBe(true) + // Mutually exclusive: a timeout classifies as timedOut, never also aborted. + expect(result.aborted).toBe(false) expect(result.timeoutMs).toBe(100) }) @@ -111,6 +115,20 @@ describe('LocalBashExecutor.run', () => { setTimeout(() => { controller.abort() }, 50) const result = await pending expect(result.aborted).toBe(true) + // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut. + expect(result.timedOut).toBe(false) + }) + + it('classifies a self-killed command as neither timed out nor aborted', async () => { + // The command kills itself (SIGTERM) with no timeout and no upstream abort: + // the deadline signal never fires, so both classifications are false — the + // fused-signal classification reports the cause that cut the command short, + // and here nothing the executor owns did. + const { bash } = await setup({ timeoutMs: 60_000 }) + const result = await bash.run(bash.resolve({ command: 'kill -TERM $$' })) + expect(result.signal).toBe('SIGTERM') + expect(result.timedOut).toBe(false) + expect(result.aborted).toBe(false) }) it('rejects on spawn failure (bad workdir)', async () => { diff --git a/packages/bash/bash-local/tests/run.spec.ts b/packages/bash/bash-local/tests/run.spec.ts index d2888e2fee..1d6e93afe3 100644 --- a/packages/bash/bash-local/tests/run.spec.ts +++ b/packages/bash/bash-local/tests/run.spec.ts @@ -26,7 +26,6 @@ function spec(command: string, overrides: Partial[0]> return { command, cwd: process.cwd(), - timeoutMs: 0, maxOutputBytes: 64_000, graceMs: 3_000, ...overrides, @@ -56,13 +55,25 @@ async function waitForStdout(running: RunningBash, expected: string, timeoutMs = throw new Error(`stdout did not include ${JSON.stringify(expected)} after ${timeoutMs}ms`) } +async function waitForPidFile(path: string, timeoutMs = 5_000): Promise { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + try { + const pid = Number(readFileSync(path, 'utf8').trim()) + if (Number.isSafeInteger(pid) && pid > 0) return pid + } catch { + // The child shell has not written the pid file yet. + } + await new Promise(resolve => setTimeout(resolve, 20)) + } + throw new Error(`pid file ${path} was not written after ${timeoutMs}ms`) +} + describe('runBash', () => { it('captures stdout on success', async () => { const result = await runBash(spec('echo hello')).done expect(result.exitCode).toBe(0) expect(result.signal).toBeNull() - expect(result.timedOut).toBe(false) - expect(result.aborted).toBe(false) expect(result.stdout.text).toBe('hello\n') expect(result.stdout.truncated).toBe(false) expect(result.stderr.text).toBe('') @@ -97,17 +108,22 @@ describe('runBash', () => { expect(result.stdout.text.trim()).toMatch(/\/tmp$/) }) - it('kills with SIGTERM on timeout', async () => { + it('kills the process group with SIGTERM when the signal fires', async () => { + // runBash owns no timer: it kills on abort. The executor drives the timeout + // by firing this signal via a deadline (see executor.spec.ts); here we + // assert the kill itself lands as SIGTERM. + const controller = new AbortController() const start = Date.now() - const result = await runBash(spec('sleep 60', { timeoutMs: 100 })).done + const running = runBash(spec('sleep 60', { signal: controller.signal })) + setTimeout(() => { controller.abort('deadline') }, 100) + const result = await running.done expect(Date.now() - start).toBeLessThan(5_000) - expect(result.timedOut).toBe(true) expect(result.signal).toBe('SIGTERM') expect(result.exitCode).toBeNull() }) it('escalates to SIGKILL when SIGTERM is trapped', async () => { - const running = runBash(spec('trap \'\' TERM; echo ready; sleep 60', { graceMs: 200 })) + const running = runBash(spec('trap \'\' TERM; echo ready; while :; do sleep 60 & wait $!; done', { graceMs: 200 })) await waitForStdout(running, 'ready\n') running.kill() const result = await running.done @@ -119,8 +135,7 @@ describe('runBash', () => { // group must take the sleep down with bash. const pidFile = join(spillDir, `grandchild-${Date.now()}.pid`) const running = runBash(spec(`sleep 60 & echo $! > ${pidFile}; wait`)) - await new Promise(resolve => setTimeout(resolve, 300)) - const grandchild = Number(readFileSync(pidFile, 'utf8').trim()) + const grandchild = await waitForPidFile(pidFile) expect(grandchild).toBeGreaterThan(0) running.kill() @@ -134,7 +149,6 @@ describe('runBash', () => { const running = runBash(spec('sleep 60', { signal: controller.signal })) setTimeout(() => { controller.abort('user cancelled') }, 50) const result = await running.done - expect(result.aborted).toBe(true) expect(result.signal).toBe('SIGTERM') }) @@ -211,7 +225,6 @@ describe('stdin and extra env (set by in-process plugins)', () => { const big = 'x'.repeat(1024 * 1024) const result = await runBash(spec('exit 7', { stdin: big })).done expect(result.exitCode).toBe(7) - expect(result.aborted).toBe(false) }) }) @@ -339,11 +352,11 @@ describe('abort edge cases', () => { .toThrow(/aborted before spawn: aborted/) }) - it('reports an externally self-killed command without the timeout marker', async () => { + it('reports the terminating signal of an externally self-killed command', async () => { + // runBash reports the raw signal; whether it counts as timeout/cancel is the + // executor's classification (a self-kill is neither) — see executor.spec.ts. const result = await runBash(spec('kill -TERM $$')).done expect(result.signal).toBe('SIGTERM') - expect(result.timedOut).toBe(false) - expect(result.aborted).toBe(false) }) }) @@ -396,10 +409,9 @@ describe('review fixes: env scrubbing and spill hardening', () => { it('honors AbortSignal on background-style runs (no timeout)', async () => { const controller = new AbortController() - const running = runBash(spec('sleep 60', { timeoutMs: 0, signal: controller.signal })) + const running = runBash(spec('sleep 60', { signal: controller.signal })) setTimeout(() => { controller.abort() }, 50) const result = await running.done - expect(result.aborted).toBe(true) expect(result.signal).toBe('SIGTERM') }) }) diff --git a/packages/bash/bash-local/tsconfig.json b/packages/bash/bash-local/tsconfig.json index ae31546543..02448770f4 100644 --- a/packages/bash/bash-local/tsconfig.json +++ b/packages/bash/bash-local/tsconfig.json @@ -20,6 +20,9 @@ { "path": "../../util/brand" }, + { + "path": "../../util/timeout" + }, { "path": "../../bash/bash" } diff --git a/packages/code-runtime/README.md b/packages/code-runtime/README.md index 578f3179c1..0310a57b1a 100644 --- a/packages/code-runtime/README.md +++ b/packages/code-runtime/README.md @@ -1,9 +1,10 @@ # code-runtime/ — code-execution capability family -The code-execution capability seam (see [capability seams](../../docs/rfc/implemented/architecture/2026-06-13-capability-seams.md)): an abstract runtime interface for executing one model-written program against host-provided async bindings, capturing what it printed and returned. The consumer is the tool registry's Code Mode, and the first implementation (a Node worker-thread backend) is specified alongside it in the [Code Mode RFC](../../docs/rfc/proposed/feature/2026-06-15-code-mode.md). **Product** packages. +The code-execution capability seam (see [capability seams](../../docs/rfc/implemented/architecture/2026-06-13-capability-seams.md)): an abstract runtime interface for executing one model-written program against host-provided async bindings, capturing what it printed and returned. The consumer is the tool registry's Code Mode, specified alongside the seam in the [Code Mode RFC](../../docs/rfc/proposed/feature/2026-06-15-code-mode.md). **Product** packages. | Package | Role | ctx key | |---|---|---| | `code-runtime/` | Abstract code-execution seam (interface + vocabulary) | `ctx.codeRuntime` | +| [`code-runtime-worker/`](code-runtime-worker/README.md) | Worker-thread backend: fresh worker per run, TypeScript via host-side type-strip (annotations advisory, never type-checked), port-bridged bindings, budget/heap containment | registers `ctx.codeRuntime` | -The interface lives at `code-runtime/code-runtime/`. Backends differ by execution substrate (worker thread, process, container) and by source language — both readonly descriptors on the service — and register `ctx.codeRuntime` without touching the interface or its consumer; that split is what makes a hardened backend a drop-in later. +The interface lives at `code-runtime/code-runtime/`; the shipped backend at `code-runtime/code-runtime-worker/`. Backends differ by execution substrate (worker thread, process, container) and by source language — both readonly descriptors on the service — and register `ctx.codeRuntime` without touching the interface or its consumer; that split is what makes a hardened backend a drop-in later. diff --git a/packages/code-runtime/code-runtime-worker/README.md b/packages/code-runtime/code-runtime-worker/README.md new file mode 100644 index 0000000000..b8f440397a --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/README.md @@ -0,0 +1,32 @@ +# @deepseek-ai/dsh-code-runtime-worker + +Worker-thread implementation of the [`@deepseek-ai/dsh-code-runtime`](../code-runtime/README.md) seam: `WorkerCodeRuntime` runs each program in ONE fresh Node `worker_threads.Worker` — TypeScript in, type-stripped host-side, bindings bridged over the message port, `{ value, logs, error? }` out. **Containment, not a security boundary**: trust posture is bash-equivalent by design (the [Code Mode RFC](../../../docs/rfc/proposed/feature/2026-06-15-code-mode.md) § Trust posture), with containment bash does not have — separate isolate, empty environment, heap cap, hard termination. + +## Config + +```yaml +- id: code-runtime + name: '@deepseek-ai/dsh-code-runtime-worker' + config: + computeMs: 60000 # busy-time budget (measured event-loop active time) + maxWallMs: 600000 # wall-clock ceiling; never pauses for anything + maxLogBytes: 65536 # shared byte budget for captured log text + maxValueBytes: 32768 # rendered-completion-value cap + maxOldGenerationSizeMb: 512 # worker heap cap (resourceLimits) +``` + +Every field is validated (positive numbers) and defaulted; there are no other tunables. + +## Design + +- **One fresh worker per run, no pooling** — a program's world dies with its worker: no cross-run state to log, state bleed unrepresentable, runs reconstructable from the session log alone. +- **Type-strip host-side, in execution context** — the program is wrapped in an async-function shell, stripped with `node:module`'s `stripTypeScriptTypes` (erasable syntax only — `enum`/namespaces are rejected as a program `exception` and no worker spawns), and sliced back out byte-positioned; it then executes as the body of an `AsyncFunction`, so top-level `await`/`return` work. +- **The port assumes a hostile peer** — model code can reach `parentPort` and forge traffic, so every inbound message is shape-validated and REBUILT before anything reads it (`null`, primitives, junk types, and malformed payloads drop without a throw; forged extra fields never ride along), the host answers each call id at most once, resolves binding names as OWN properties only (a forged `constructor` cannot walk a prototype chain), drops post-settlement replies, and converts a non-cloneable binding resolution into an error reply. Forged `log`/`done` messages cannot bypass the caps: one host-side ledger bounds everything that lands in `logs`, and the completion value is re-capped host-side. Worker-side namespaces are null-prototype with `defineProperty`, so `__proto__`-shaped binding names are ordinary keys. +- **Two independent budgets, because the peer is hostile** — `computeMs` meters the worker's MEASURED busy time (`worker.performance.eventLoopUtilization()` polling): a hot loop cannot hide behind a pending decoy dispatch, and a program awaiting a slow tool accrues nothing. `maxWallMs` backstops what busy time cannot see (awaiting a promise nobody resolves). Both funnel into `worker.terminate()`, which ends hot synchronous loops too; heap overflow surfaces as the worker's OOM exit (`kind: 'worker-exit'`). +- **Logs stream eagerly** — console/stdout/stderr entries cross the port as they happen, so a timed-out or killed program still shows what it printed. ONE shared `maxLogBytes` ledger bounds everything: streamed entries, forged port traffic, and pipe bytes that bypass the patched streams (appended after), with the overflow marked in-band once. +- **Empty environment** — the worker gets `env: {}` and `execArgv: []`: no ambient credentials (stronger than the scrubbed-env rule for spawned commands) and no inherited loader flags. +- **Dispose to quiescence** — teardown fails in-flight runs as `abort` and AWAITS each worker's exit before resolving. + +## The worker entry, unbuilt and built + +`worker.ts` is deliberately erasable-only TypeScript with type-only cross-package imports: unbuilt (vitest/tsx), the host spawns `src/worker.ts` directly and Node's native type stripping loads it; built, the entry ships as the sibling bundle `lib/worker.js` (its own tsdown entry). The built path is pinned by `tests/built-lib.e2e.ts`, the real-load-path guard from [docs/testing.md](../../../docs/testing.md). diff --git a/packages/code-runtime/code-runtime-worker/package.json b/packages/code-runtime/code-runtime-worker/package.json new file mode 100644 index 0000000000..85df6a0d78 --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/package.json @@ -0,0 +1,36 @@ +{ + "name": "@deepseek-ai/dsh-code-runtime-worker", + "description": "Worker-thread implementation of the DeepSeek Harness code-execution seam", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/worker.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-code-runtime": "^0.0.1", + "cordis": "^4.0.0-rc.6" + }, + "dependencies": { + "schemastery": "^3.18.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-code-runtime": "workspace:^", + "cordis": "^4.0.0-rc.6" + } +} diff --git a/packages/code-runtime/code-runtime-worker/src/bootstrap.ts b/packages/code-runtime/code-runtime-worker/src/bootstrap.ts new file mode 100644 index 0000000000..f2e0d343f3 --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/src/bootstrap.ts @@ -0,0 +1,301 @@ +/** + * Worker-side execution logic, written as plain functions over an injected + * port so the unit suite can run every line IN-PROCESS against a fake port + * (a real worker thread is a separate V8 isolate the coverage provider + * cannot observe). The real worker entry (`worker.ts`) is a thin + * self-executing glue file over {@link runWorkerMain}, excluded from + * coverage the same way `bin.ts` entrypoints are, and exercised end-to-end + * by the integration tests that spawn real workers. + * + * @module @deepseek-ai/dsh-code-runtime-worker/src/bootstrap + */ + +import { inspect } from 'node:util' +import { serialize } from 'node:v8' +import type { CodeLogEntry } from '@deepseek-ai/dsh-code-runtime' +import { logTruncationMarker } from './protocol.ts' +import type { DoneMessage, ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts' + +/** The port surface the bootstrap needs — satisfied by `parentPort` and by the tests' fake. */ +export interface BootstrapPort { + postMessage(message: WorkerToHost): void + on(event: 'message', listener: (message: ReplyMessage) => void): void +} + +/** + * A writable stream's `write` slot, as the bootstrap patches it (see + * {@link captureStreamWrites}). Method-typed so the real + * `process.stdout`/`process.stderr` (narrower chunk parameters) remain + * assignable. + */ +export interface PatchableStream { + write(chunk: unknown, ...rest: unknown[]): boolean +} + +/** + * Ordered log capture under one shared byte budget, delivered to a sink as + * each entry lands (the real sink streams entries over the port eagerly, so + * captured output survives a mid-run termination). Once the budget is + * exhausted it emits exactly one in-band marker entry (on the `stderr` + * diagnostics channel) and silently drops everything after — the cap is a + * blast-radius bound, so "how much was lost" intentionally stays unmeasured. + */ +export class LogBuffer { + private remaining: number + private truncated = false + // Explicit fields, not constructor parameter properties: this module loads + // under Node's native strip-only mode, which rejects non-erasable syntax — + // and parameter properties are non-erasable. + private readonly maxBytes: number + private readonly sink: (entry: CodeLogEntry) => void + + constructor(maxBytes: number, sink: (entry: CodeLogEntry) => void) { + this.maxBytes = maxBytes + this.sink = sink + this.remaining = maxBytes + } + + /** + * Emit one entry to the sink, charging its text against the budget (drops + marks once exhausted). + * @param entry - the log entry to deliver. + */ + push(entry: CodeLogEntry): void { + if (this.truncated) return + const cost = Buffer.byteLength(entry.text, 'utf8') + if (cost > this.remaining) { + this.truncated = true + this.sink({ source: 'stderr', text: logTruncationMarker(this.maxBytes) }) + return + } + this.remaining -= cost + this.sink(entry) + } +} + +/** The five console methods the shim captures, in the seam's level vocabulary. */ +const CONSOLE_LEVELS = ['log', 'info', 'warn', 'error', 'debug'] as const + +/** + * A `console` replacement whose five leveled methods render their arguments + * `util.inspect`-style (matching real console formatting closely enough for + * a model to recognize its own output) into the buffer. Only these five + * exist — the program gets a deliberately small console, not Node's full + * surface. + * @param logs - the buffer every rendered line is pushed into. + * @returns the five-method console object handed to the program. + */ +export function makeConsoleShim(logs: LogBuffer): Record<(typeof CONSOLE_LEVELS)[number], (...args: unknown[]) => void> { + const render = (args: unknown[]): string => + args.map(arg => typeof arg === 'string' ? arg : inspect(arg, INSPECT_OPTIONS)).join(' ') + const shim = Object.create(null) as Record<(typeof CONSOLE_LEVELS)[number], (...args: unknown[]) => void> + for (const level of CONSOLE_LEVELS) { + shim[level] = (...args: unknown[]) => { logs.push({ source: 'console', level, text: render(args) }) } + } + return shim +} + +/** + * Redirect a stream's `write` into the log buffer (the program-visible + * `process.stdout`/`process.stderr` in the real worker), so raw writes land + * in emission order alongside console output instead of racing down a pipe. + * The shim keeps Node's `write(chunk[, encoding][, callback])` contract: the + * callback fires asynchronously once the chunk is admitted (a program + * awaiting flush completion must complete, not sit until the wall timeout), + * even for writes the exhausted budget drops. + * @param logs - the buffer captured writes are pushed into. + * @param stream - the stream whose `write` slot is patched. + * @param source - the log source the captured writes are attributed to. + * @returns the restore function (the in-process tests un-patch; the real + * worker never needs to). + */ +export function captureStreamWrites(logs: LogBuffer, stream: PatchableStream, source: 'stdout' | 'stderr'): () => void { + // The slot's VALUE is stored for restore and reassigned — never invoked + // detached, so the unbound-method concern does not apply. + // eslint-disable-next-line @typescript-eslint/unbound-method + const original = stream.write + stream.write = (chunk: unknown, ...rest: unknown[]): boolean => { + logs.push({ source, text: typeof chunk === 'string' ? chunk : String(chunk) }) + // Node's optional-encoding shape: the callback is whichever of the next + // two positions holds a function (a non-function there is the encoding). + const callback = [rest[0], rest[1]].find( + (arg): arg is (error?: Error | null) => void => typeof arg === 'function', + ) + if (callback) queueMicrotask(() => { callback(null) }) + return true + } + return () => { stream.write = original } +} + +/** Bounded inspect options: deep enough to be useful, bounded so a pathological value cannot explode the rendering. */ +const INSPECT_OPTIONS = { depth: 4, maxArrayLength: 100, maxStringLength: 10_000 } as const + +/** + * The longest prefix of `text` whose UTF-8 encoding fits `maxBytes`, cut at + * a code-point boundary (never mid-surrogate-pair). The byte caps are BYTE + * caps — `String.prototype.slice` counts UTF-16 code units, up to 3× smaller + * than what a multibyte string actually costs across the boundary. + * @param text - the string to bound. + * @param maxBytes - the UTF-8 byte budget the prefix must fit. + * @returns the prefix (all of `text` when it already fits). + */ +export function truncateUtf8Bytes(text: string, maxBytes: number): string { + if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text + let bytes = 0 + let end = 0 + for (const char of text) { + const cost = Buffer.byteLength(char, 'utf8') + if (bytes + cost > maxBytes) break + bytes += cost + end += char.length + } + return text.slice(0, end) +} + +/** + * Prepare the program's completion value for the done message: a value whose + * MEASURED cross-boundary size fits `maxValueBytes` crosses raw — exact + * bytes for a string, the structured-clone wire size (`v8.serialize`) for + * everything else, so a huge container whose BOUNDED inspect rendering + * happens to be small cannot smuggle itself past the cap. Anything else + * (non-cloneable, or oversized) is REPLACED by its bounded `util.inspect` + * rendering, byte-truncated ({@link truncateUtf8Bytes}) with an in-band + * marker — the seam contract's "a non-transferable value is replaced by a + * string rendering", extended to oversized ones so a huge return cannot + * flood the host. + * @param value - the program's completion value. + * @param maxValueBytes - the byte cap for the value. + * @returns the done-message fragment: `{}` for `undefined`, else `{ value }`. + */ +export function prepareValue(value: unknown, maxValueBytes: number): { value?: unknown } { + if (value === undefined) return {} + if (typeof value === 'string') { + if (Buffer.byteLength(value, 'utf8') <= maxValueBytes) return { value } + } else { + let size: number | undefined + try { + size = serialize(value).byteLength + } catch { + // Only the verdict matters: the value has parts the structured-clone + // algorithm rejects (functions, classes, …) and must cross as its + // rendering instead. + size = undefined + } + if (size !== undefined && size <= maxValueBytes) return { value } + } + const rendered = typeof value === 'string' ? value : inspect(value, INSPECT_OPTIONS) + const capped = Buffer.byteLength(rendered, 'utf8') > maxValueBytes + ? `${truncateUtf8Bytes(rendered, maxValueBytes)}… [truncated]` + : rendered + return { value: capped } +} + +/** One awaited binding call's settlement handles, keyed by call id in the pending map. */ +export interface PendingCall { + resolve(value: unknown): void + reject(error: Error): void +} + +/** + * Route host replies into the pending-call map: each reply settles its call + * at most once, and a reply for an unknown id (stray, or a duplicate answer + * to an id already settled) is ignored. Shared wiring between + * {@link runWorkerMain} and the tests that exercise {@link makeNamespaces} + * standalone. + * @param port - the port whose `message` events carry the replies. + * @param pending - the id-keyed map of unsettled binding calls. + */ +export function wireReplies(port: BootstrapPort, pending: Map): void { + port.on('message', (message: ReplyMessage) => { + const entry = pending.get(message.id) + if (!entry) return + pending.delete(message.id) + if (message.ok) entry.resolve(message.value) + else entry.reject(new Error(message.message)) + }) +} + +/** + * Build the binding namespace objects the program sees: one null-prototype + * global per namespace, each declared name an own enumerable async function + * that bridges over the port (`__proto__`/`constructor`/`toString` are + * ordinary keys, never prototype collisions). A non-cloneable argument + * rejects that one call with a descriptive error; the host's reply (`ok` + * false) rejects it likewise, so a failed tool call surfaces in the program + * as an ordinary promise rejection. + * @param data - the boot payload's namespace declarations (globals + names). + * @param port - the port binding calls are posted to. + * @param pending - the id-keyed map each posted call parks its handles in. + * @param nextId - the shared mutable id counter (worker-issued correlation ids). + * @returns one namespace object per declaration, in declaration order. + */ +export function makeNamespaces( + data: Pick, + port: BootstrapPort, + pending: Map, + nextId: { value: number }, +): Record[] { + return data.namespaces.map(({ global, names }) => { + const namespace = Object.create(null) as Record + for (const name of names) { + Object.defineProperty(namespace, name, { + enumerable: true, + value: (args: unknown): Promise => new Promise((resolve, reject) => { + const id = nextId.value++ + pending.set(id, { resolve, reject }) + try { + port.postMessage({ type: 'call', id, global, name, args }) + } catch (error: unknown) { + pending.delete(id) + reject(new Error(`binding arguments must be structured-cloneable: ${error instanceof Error ? error.message : String(error)}`)) + } + }), + }) + } + return namespace + }) +} + +/** + * Run one program to settlement and post the {@link DoneMessage}: wires the + * reply handler, materializes the namespaces and console shim, compiles the + * type-stripped body as an async function (top-level `await`/`return` + * work), and reports a thrown program error as the done message's `error` + * field. Exactly one done message is ever posted. + * @param port - the message port to the host (the real `parentPort`, or the tests' fake). + * @param data - the boot payload the host sent. + * @param streams - the stream objects whose `write` is captured (the real + * `process.stdout`/`process.stderr` in the worker; fakes in tests). + * @returns resolves after the done message is posted (the tests await it; + * the real entry lets the worker exit naturally). + */ +export async function runWorkerMain( + port: BootstrapPort, + data: WorkerBootData, + streams: { stdout: PatchableStream; stderr: PatchableStream }, +): Promise { + const logs = new LogBuffer(data.maxLogBytes, (entry) => { port.postMessage({ type: 'log', entry }) }) + captureStreamWrites(logs, streams.stdout, 'stdout') + captureStreamWrites(logs, streams.stderr, 'stderr') + + const pending = new Map() + wireReplies(port, pending) + + const nextId = { value: 1 } + const namespaces = makeNamespaces(data, port, pending, nextId) + const consoleShim = makeConsoleShim(logs) + + let done: DoneMessage + try { + // The async function constructor, reached through an instance because + // `AsyncFunction` is not a global. The program body is strict-mode. + /* v8 ignore next -- the arrow exists only to reach the AsyncFunction constructor; it is never invoked. */ + const AsyncFunction = (async () => {}).constructor as new (...args: string[]) => (...fnArgs: unknown[]) => Promise + const fn = new AsyncFunction(...data.namespaces.map(namespace => namespace.global), 'console', `'use strict';\n${data.code}`) + const value = await fn(...namespaces, consoleShim) + done = { type: 'done', ...prepareValue(value, data.maxValueBytes) } + } catch (error: unknown) { + const message = error instanceof Error ? error.stack ?? error.message : String(error) + done = { type: 'done', error: { message } } + } + port.postMessage(done) +} diff --git a/packages/code-runtime/code-runtime-worker/src/index.ts b/packages/code-runtime/code-runtime-worker/src/index.ts new file mode 100644 index 0000000000..f78f06cb0b --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/src/index.ts @@ -0,0 +1,441 @@ +/** + * Worker-thread implementation of the code-execution seam: one fresh Node + * worker per run, executing the model's TypeScript after a host-side + * type-strip, with bindings bridged over the message port. Containment, not + * a security boundary (bash-equivalent trust — see the Code Mode RFC's + * trust-posture section): the worker gets an EMPTY environment, a heap cap, + * and two independent budgets — `computeMs` metered on the worker's + * measured event-loop busy time (a hot loop cannot hide behind a pending + * binding call) and a never-pausing `maxWallMs` ceiling — all funneling + * into `worker.terminate()`, which ends hot synchronous loops too. + * + * @module @deepseek-ai/dsh-code-runtime-worker + */ + +import { Worker } from 'node:worker_threads' +import { stripTypeScriptTypes } from 'node:module' +import { Context } from 'cordis' +import z from 'schemastery' +import { CodeRuntime } from '@deepseek-ai/dsh-code-runtime' +import type { CodeBindingFunction, CodeLogEntry, CodeRunFailure, CodeRunRequest, CodeRunResult } from '@deepseek-ai/dsh-code-runtime' +import { prepareValue, truncateUtf8Bytes } from './bootstrap.ts' +import { logTruncationMarker } from './protocol.ts' +import type { ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts' + +export type { BootstrapPort, PatchableStream } from './bootstrap.ts' +export type { CallMessage, DoneMessage, ReplyMessage, WorkerBootData, WorkerToHost } from './protocol.ts' + +/** Plugin config: every execution cap, changeable from `cordis.yml` (no hardcoded tunables). */ +export interface Config { + /** + * Busy-time budget in milliseconds: the run fails with kind `'timeout'` + * once the worker's MEASURED event-loop active time + * (`worker.performance.eventLoopUtilization()`) exceeds this. Metering + * measured busy time — not wall time, not host-side pending-call + * bookkeeping — is what makes the budget both fair (a program awaiting a + * slow tool accrues nothing) and ungameable (a hot loop accrues whether + * or not a decoy dispatch is in flight). + */ + computeMs?: number + /** + * Wall-clock ceiling in milliseconds; never pauses for anything. The + * backstop for what busy-time cannot see (a program awaiting a promise + * nobody will resolve). + */ + maxWallMs?: number + /** Shared byte budget for captured log text (console + raw stream writes), truncation marked in-band. */ + maxLogBytes?: number + /** + * Byte cap for the completion value, measured by its real cross-boundary + * size (string bytes, or structured-clone wire size); an oversized or + * non-cloneable value crosses as a capped string rendering. + */ + maxValueBytes?: number + /** The worker's max old-generation heap in MiB (`resourceLimits`); overflow kills the worker, surfacing as kind `'worker-exit'`. */ + maxOldGenerationSizeMb?: number +} + +/** {@link Config} after schemastery fills the defaults (every field present). */ +type ResolvedConfig = Required + +/** + * How often the host samples the worker's event-loop utilization for the + * `computeMs` budget. An internal cadence, not config: the only effect of + * the interval is budget-expiry granularity (a run can overshoot by up to + * one interval), and nothing a deployment could tune here improves that + * without burning host CPU. + */ +const ELU_POLL_INTERVAL_MS = 25 + +/** ECMAScript reserved words that cannot be async-function parameter names — rejected as binding globals. */ +const RESERVED_WORDS = new Set([ + 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', + 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in', + 'instanceof', 'new', 'null', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', + 'var', 'void', 'while', 'with', 'yield', 'let', 'static', 'implements', 'interface', 'package', + 'private', 'protected', 'public', 'arguments', 'eval', +]) + +/** Valid async-function parameter name (the binding global becomes one). */ +const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/ + +/** + * The shell a program is wrapped in for the type-strip, matching the + * grammatical context it will execute in (an async function body, where + * top-level `return` and `await` are legal — a bare module parse would + * reject the `return`). Strip mode is position-preserving (removed syntax + * becomes whitespace, nothing shifts), so the wrapper survives the strip + * byte-identical and the body slices back out with the model's own + * line/column positions intact. + */ +const STRIP_WRAP = { prefix: 'async function __dsh_program__() {\n', suffix: '\n}' } as const + +/** One in-flight run's host-side state, tracked for disposal. */ +interface LiveRun { + worker: Worker + settle(failure: CodeRunFailure): void + finished: Promise +} + +/** + * The worker entry module. Source runs unbuilt (`src/worker.ts`, loadable + * directly on this repo's Node range via native type stripping — the file + * is erasable-only with type-only relative imports); the built package + * ships it as a sibling bundle (`lib/worker.js`, its own tsdown entry). + * The URL *pathname*'s extension says which world this module is in — + * pathname, because dev-time module runners (vitest) may suffix + * `import.meta.url` with a query string; relative resolution drops it. + */ +/* v8 ignore next -- the './worker.js' arm is the built-lib world, unreachable unbuilt by construction; the built-lib e2e pins it. */ +const WORKER_URL = new URL(new URL(import.meta.url).pathname.endsWith('.ts') ? './worker.ts' : './worker.js', import.meta.url) + +/** Render an unknown thrown value as a message, `Error` or not. */ +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +/** The log sources / console levels the seam vocabulary admits, as runtime sets for inbound-message validation. */ +const LOG_SOURCES = new Set(['console', 'stdout', 'stderr']) +const LOG_LEVELS = new Set(['log', 'info', 'warn', 'error', 'debug']) + +/** + * Runtime shape gate for inbound port traffic. The peer runs MODEL CODE and + * can post anything — `null`, primitives, objects with poisoned fields — so + * the compile-time `WorkerToHost` type means nothing here: everything is + * re-validated and REBUILT field by field (a forged extra field never rides + * along; a non-number call id can never be echoed into a reply). Junk returns + * `undefined` and is dropped — a throw in the host's `message` listener would + * crash the host process. + */ +function parseWorkerMessage(raw: unknown): WorkerToHost | undefined { + if (typeof raw !== 'object' || raw === null) return undefined + const m = raw as Record + switch (m.type) { + case 'call': { + if (typeof m.id !== 'number' || typeof m.global !== 'string' || typeof m.name !== 'string') return undefined + return { type: 'call', id: m.id, global: m.global, name: m.name, args: m.args } + } + case 'log': { + const entry = m.entry + if (typeof entry !== 'object' || entry === null) return undefined + const e = entry as Record + if (typeof e.text !== 'string') return undefined + if (typeof e.source !== 'string' || !LOG_SOURCES.has(e.source)) return undefined + if (e.level !== undefined && (typeof e.level !== 'string' || !LOG_LEVELS.has(e.level))) return undefined + return { + type: 'log', + entry: { + source: e.source as CodeLogEntry['source'], + ...e.level !== undefined ? { level: e.level as Exclude } : {}, + text: e.text, + }, + } + } + case 'done': { + if (m.error === undefined) return { type: 'done', ...m.value !== undefined ? { value: m.value } : {} } + const error = m.error + if (typeof error !== 'object' || error === null) return undefined + const message = (error as Record).message + if (typeof message !== 'string') return undefined + return { type: 'done', ...m.value !== undefined ? { value: m.value } : {}, error: { message } } + } + default: return undefined + } +} + +/** + * Headroom the host's value re-cap grants over `maxValueBytes`: exactly the + * truncation suffix {@link prepareValue} appends, so a value the WORKER + * already capped (byte-exact prefix + this marker) passes through unchanged + * instead of being marked twice. + */ +const VALUE_RENDER_SLACK = Buffer.byteLength('… [truncated]', 'utf8') + +/** + * The shipped {@link CodeRuntime} backend (`ctx.codeRuntime`). Registers as + * the `codeRuntime` service; every cap comes from validated config. See the + * module doc for the containment model and the class JSDoc on the seam for + * the contract this implements (error-as-field, hostile-peer port, + * no cross-run state, dispose to quiescence). + */ +export class WorkerCodeRuntime extends CodeRuntime { + static Config: z = z.object({ + computeMs: z.number().default(60_000), + maxWallMs: z.number().default(600_000), + maxLogBytes: z.number().default(65_536), + maxValueBytes: z.number().default(32_768), + maxOldGenerationSizeMb: z.number().default(512), + }) + + readonly language = 'typescript' + readonly isolation = 'worker-thread' + + private readonly config: ResolvedConfig + private readonly live = new Set() + private disposed = false + + constructor(ctx: Context, config: Config) { + super(ctx) + // Schemastery filled the defaults; the cast records that. Positivity is a + // semantic check the schema's plain number type does not carry. + this.config = config as ResolvedConfig + for (const [key, value] of Object.entries(this.config)) { + if (!(Number.isFinite(value) && value > 0)) throw new Error(`dsh-code-runtime-worker: config.${key} must be a positive number, got ${String(value)}`) + } + ctx.effect(() => () => this.teardown(), 'worker code-runtime teardown') + } + + /** + * Dispose to quiescence: mark the service unusable, fail every in-flight + * run as aborted, and AWAIT each worker's exit so no worker outlives the + * fiber. + */ + private async teardown(): Promise { + this.disposed = true + const runs = [...this.live] + for (const run of runs) run.settle({ kind: 'abort', message: 'runtime disposed' }) + await Promise.all(runs.map(run => run.finished)) + } + + /** + * Execute one program in a fresh worker. Program outcomes — including a + * type-strip syntax error, which never spawns a worker — resolve with + * `result.error`; the method rejects only for seam misuse (a disposed + * runtime, an invalid binding namespace). + * @param request - the program, its bindings, and the abort signal. + * @returns the run's outcome per the seam contract. + */ + async run(request: CodeRunRequest): Promise { + if (this.disposed) throw new Error('dsh-code-runtime-worker: run() after disposal') + const bindings = this.validateBindings(request) + if (request.signal?.aborted) { + return { logs: [], error: { kind: 'abort', message: String(request.signal.reason) } } + } + + let code: string + try { + const stripped = stripTypeScriptTypes(STRIP_WRAP.prefix + request.program + STRIP_WRAP.suffix) + code = stripped.slice(STRIP_WRAP.prefix.length, stripped.length - STRIP_WRAP.suffix.length) + } catch (error: unknown) { + // A program that does not survive the type-strip (syntax error, + // non-erasable syntax like `enum`) is a program failure, reported the + // same way a thrown exception would be — and no worker ever spawns. + return { logs: [], error: { kind: 'exception', message: messageOf(error) } } + } + + return await this.execute(request, code, bindings) + } + + /** Reject (seam misuse) malformed binding namespaces: non-identifier or reserved globals, duplicates, and the `console` collision. */ + private validateBindings(request: CodeRunRequest): Map> { + const bindings = new Map>() + for (const namespace of request.bindings) { + if (!IDENTIFIER.test(namespace.global) || RESERVED_WORDS.has(namespace.global)) { + throw new Error(`dsh-code-runtime-worker: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`) + } + if (namespace.global === 'console' || bindings.has(namespace.global)) { + throw new Error(`dsh-code-runtime-worker: duplicate binding global ${JSON.stringify(namespace.global)}`) + } + bindings.set(namespace.global, namespace.functions) + } + return bindings + } + + /** Spawn the worker for one validated, type-stripped run and drive it to settlement. */ + private execute( + request: CodeRunRequest, + code: string, + bindings: Map>, + ): Promise { + const bootData: WorkerBootData = { + code, + namespaces: [...bindings].map(([global, functions]) => ({ global, names: Object.keys(functions) })), + maxLogBytes: this.config.maxLogBytes, + maxValueBytes: this.config.maxValueBytes, + } + const worker = new Worker(WORKER_URL, { + workerData: bootData, + // Model code gets NO ambient environment — stronger than the scrubbed + // env the defensive-patterns rule requires for spawned commands. + env: {}, + // Hermetic flags too: without this the worker inherits the host + // process's execArgv (a test runner's or tsx's loader hooks), which a + // bare isolate with an empty environment cannot satisfy. The entry + // needs nothing beyond native type stripping, on this repo's whole + // Node range. + execArgv: [], + resourceLimits: { maxOldGenerationSizeMb: this.config.maxOldGenerationSizeMb }, + // Backstop capture: the bootstrap patches JS-level writes into its own + // ordered buffer, so these pipes normally stay silent; anything that + // still arrives (native-level writes) is appended after the done logs. + stdout: true, + stderr: true, + }) + + return new Promise((resolve) => { + let settled = false + const answered = new Set() + const logs: CodeLogEntry[] = [] + const strayLogs: CodeLogEntry[] = [] + + // ONE host-side ledger for everything that lands in `logs`/`strayLogs`, + // whatever the path: honest port entries, FORGED port entries (model + // code posting `log` messages directly, bypassing the worker-side + // LogBuffer), and stray pipe bytes. On the first overflow it emits the + // same in-band marker the worker's LogBuffer would and drops the rest, + // so the documented cap is one shared `maxLogBytes` however it is hit. + let logBudget = this.config.maxLogBytes + let logsTruncated = false + const admit = (entry: CodeLogEntry, sink: CodeLogEntry[]): void => { + if (logsTruncated) return + const cost = Buffer.byteLength(entry.text, 'utf8') + if (cost > logBudget) { + logsTruncated = true + sink.push({ source: 'stderr', text: logTruncationMarker(this.config.maxLogBytes) }) + return + } + logBudget -= cost + sink.push(entry) + } + + // No settled guard: `finish` snapshots the arrays when it resolves, so + // a chunk flushing after settlement mutates only the discarded buffers, + // and the ledger bounds that growth until the pipes close. + const captureStray = (source: 'stdout' | 'stderr') => (chunk: Buffer) => { + admit({ source, text: chunk.toString('utf8') }, strayLogs) + } + worker.stdout.on('data', captureStray('stdout')) + worker.stderr.on('data', captureStray('stderr')) + + // Settlement: exactly one outcome wins; every path funnels through + // here, cleans up the timers/listeners, terminates the worker, and + // resolves only after the worker actually exited (quiescence). Logs + // streamed eagerly before the settlement are kept — a timed-out or + // killed program still shows the model what it printed. + let finishResolve!: () => void + const finished = new Promise((done) => { finishResolve = done }) + const finish = (result: Omit): void => { + if (settled) return + settled = true + clearInterval(eluTimer) + clearTimeout(wallTimer) + request.signal?.removeEventListener('abort', onAbort) + this.live.delete(live) + void worker.terminate().then(() => { + finishResolve() + resolve({ ...result, logs: [...logs, ...strayLogs] }) + }) + } + + const onDone = (message: WorkerToHost): void => { + if (message.type !== 'done') return + // Re-cap the completion value HOST-side: the honest path already + // capped it in the worker (prepareValue there), but a forged done + // message bypasses the bootstrap entirely — without this, model code + // could flood the host past maxValueBytes. Honest values pass + // unchanged (see VALUE_RENDER_SLACK); the error text is bounded too. + finish({ + ...prepareValue(message.value, this.config.maxValueBytes + VALUE_RENDER_SLACK), + ...message.error ? { error: { kind: 'exception' as const, message: truncateUtf8Bytes(message.error.message, this.config.maxValueBytes) } } : {}, + }) + } + + const onCall = (message: WorkerToHost): void => { + if (message.type !== 'call' || settled) return + // Hostile-peer rules: a duplicate id is ignored, an unknown name is + // answered with a failure, and a binding throw/reject becomes the + // program-side rejection — contained here, never a host crash. + if (answered.has(message.id)) return + answered.add(message.id) + const reply = (payload: ReplyMessage): void => { + if (settled) return + try { + worker.postMessage(payload) + } catch { + // The reply value failed structured clone; renegotiate as an error + // reply, which is always clone-plain. Nothing else throws here. + worker.postMessage({ type: 'reply', id: message.id, ok: false, message: 'binding resolution is not structured-cloneable' }) + } + } + const record = bindings.get(message.global) + // Own-property lookup only: a forged name like 'constructor' or + // 'hasOwnProperty' must not walk the record's prototype chain and + // reach a callable the consumer never declared. + const fn = record && Object.hasOwn(record, message.name) ? record[message.name] : undefined + if (typeof fn !== 'function') { + reply({ type: 'reply', id: message.id, ok: false, message: `unknown binding ${JSON.stringify(`${message.global}.${message.name}`)}` }) + return + } + void (async () => { + try { + reply({ type: 'reply', id: message.id, ok: true, value: await fn(message.args) }) + } catch (error: unknown) { + reply({ type: 'reply', id: message.id, ok: false, message: messageOf(error) }) + } + })() + } + + worker.on('message', (raw: unknown) => { + // Parse before touching: the peer can post ANY shape, and a throw in + // this listener would crash the host process. Junk drops silently. + const message = parseWorkerMessage(raw) + if (!message) return + if (message.type === 'log' && !settled) admit(message.entry, logs) + onCall(message) + onDone(message) + }) + worker.on('error', (error: Error) => { + finish({ error: { kind: 'worker-exit', message: `worker error: ${error.message}` } }) + }) + worker.on('exit', (exitCode: number) => { + finish({ error: { kind: 'worker-exit', message: `worker exited with code ${exitCode} before completing` } }) + }) + + // The compute budget reads the worker's own measured busy time, so a + // hot loop expires it no matter what dispatches are in flight, while a + // program idling on a slow binding accrues nothing. + const eluTimer = setInterval(() => { + const elu = worker.performance.eventLoopUtilization() + if (elu.active > this.config.computeMs) { + finish({ error: { kind: 'timeout', message: `compute budget exhausted (${this.config.computeMs}ms busy)` } }) + } + }, ELU_POLL_INTERVAL_MS) + const wallTimer = setTimeout(() => { + finish({ error: { kind: 'timeout', message: `wall-clock ceiling reached (${this.config.maxWallMs}ms)` } }) + }, this.config.maxWallMs) + const onAbort = (): void => { + finish({ error: { kind: 'abort', message: String(request.signal?.reason) } }) + } + request.signal?.addEventListener('abort', onAbort, { once: true }) + + const live: LiveRun = { + worker, + finished, + settle: (failure: CodeRunFailure) => { finish({ error: failure }) }, + } + this.live.add(live) + }) + } +} + +export default WorkerCodeRuntime diff --git a/packages/code-runtime/code-runtime-worker/src/protocol.ts b/packages/code-runtime/code-runtime-worker/src/protocol.ts new file mode 100644 index 0000000000..b8ea122c5b --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/src/protocol.ts @@ -0,0 +1,78 @@ +/** + * Wire protocol between the host runtime and the worker bootstrap. Everything + * crossing the message port is structured-clone-plain and versionless — both + * ends ship in this package, always at the same version. The host treats + * inbound traffic as HOSTILE (the worker runs model code, which can reach + * `parentPort` via `import('node:worker_threads')` and forge any of these + * shapes); the worker treats inbound traffic as trusted. + * + * @module @deepseek-ai/dsh-code-runtime-worker/src/protocol + */ + +import type { CodeLogEntry } from '@deepseek-ai/dsh-code-runtime' + +/** What the host hands the worker at spawn, via `workerData`. */ +export interface WorkerBootData { + /** The type-stripped (plain JS) program body. */ + code: string + /** Binding namespaces to materialize: the global name plus the function names (functions themselves stay host-side). */ + namespaces: { global: string; names: string[] }[] + /** Shared byte budget for captured log text; exceeding it drops further entries after one in-band marker. */ + maxLogBytes: number + /** Byte cap for the rendered completion value (see the value-preparation contract in bootstrap.ts). */ + maxValueBytes: number +} + +/** Worker → host: one bridged binding call. */ +export interface CallMessage { + type: 'call' + /** Worker-issued correlation id; the host answers each id at most once and ignores duplicates. */ + id: number + /** The namespace global the call targets. */ + global: string + /** The function name within the namespace. */ + name: string + /** The single argument, structured-clone-plain. */ + args: unknown +} + +/** Worker → host: one captured log entry, streamed eagerly so output survives a mid-run termination (timeout, abort, OOM). */ +export interface LogMessage { + type: 'log' + entry: CodeLogEntry +} + +/** + * Worker → host: the program settled. `error` carries a program exception + * (the only failure the bootstrap itself can report — budgets, aborts, and + * substrate death are observed host-side). `value` is present only on a + * clean completion that produced one (already size-capped and + * clone-safe per the bootstrap's value preparation). Logs are NOT carried + * here — they streamed eagerly as {@link LogMessage}s. + */ +export interface DoneMessage { + type: 'done' + value?: unknown + error?: { message: string } +} + +/** Every message the worker sends. */ +export type WorkerToHost = CallMessage | LogMessage | DoneMessage + +/** Host → worker: the answer to one {@link CallMessage}. */ +export type ReplyMessage = + | { type: 'reply'; id: number; ok: true; value: unknown } + | { type: 'reply'; id: number; ok: false; message: string } + +/** + * The in-band marker entry text announcing that log capture stopped at the + * byte budget. Shared wire vocabulary: the worker's LogBuffer emits it when + * ITS budget exhausts, and the host emits the identical text when its own + * ledger drops an entry first (forged port traffic, stray pipe bytes) — so + * a truncated run reads the same however the cap was hit. + * @param maxBytes - the configured `maxLogBytes` the marker names. + * @returns the marker line. + */ +export function logTruncationMarker(maxBytes: number): string { + return `[dsh-code-runtime-worker] log capture truncated at ${maxBytes} bytes` +} diff --git a/packages/code-runtime/code-runtime-worker/src/worker.ts b/packages/code-runtime/code-runtime-worker/src/worker.ts new file mode 100644 index 0000000000..efaafdb038 --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/src/worker.ts @@ -0,0 +1,20 @@ +/** + * The worker-thread entrypoint: self-executing glue over + * `bootstrap.ts`'s {@link runWorkerMain}, kept to the spawn wiring alone. + * Like `bin.ts` CLI entrypoints, this file executes only inside a spawned + * worker isolate — a place the coverage provider cannot observe — so it is + * excluded from the coverage gate while every line of actual logic lives in + * `bootstrap.ts`, unit-tested in-process; the real spawn path is pinned by + * the integration tests that run genuine workers. + * + * @module @deepseek-ai/dsh-code-runtime-worker/src/worker + */ + +import { parentPort, workerData } from 'node:worker_threads' +import { runWorkerMain } from './bootstrap.ts' +import type { WorkerBootData } from './protocol.ts' + +// A worker always has a parent port; guard loudly rather than run detached. +if (!parentPort) throw new Error('dsh-code-runtime-worker: worker entry loaded outside a worker thread') + +await runWorkerMain(parentPort, workerData as WorkerBootData, { stdout: process.stdout, stderr: process.stderr }) diff --git a/packages/code-runtime/code-runtime-worker/tests/bootstrap.spec.ts b/packages/code-runtime/code-runtime-worker/tests/bootstrap.spec.ts new file mode 100644 index 0000000000..e41f4455bb --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/tests/bootstrap.spec.ts @@ -0,0 +1,273 @@ +import { describe, expect, it } from 'vitest' +import { EventEmitter } from 'node:events' +import { LogBuffer, makeConsoleShim, makeNamespaces, captureStreamWrites, prepareValue, runWorkerMain, truncateUtf8Bytes, wireReplies } from '@deepseek-ai/dsh-code-runtime-worker/src/bootstrap.ts' +import type { BootstrapPort, PatchableStream, PendingCall } from '@deepseek-ai/dsh-code-runtime-worker/src/bootstrap.ts' +import type { ReplyMessage, WorkerToHost } from '@deepseek-ai/dsh-code-runtime-worker/src/protocol.ts' +import type { CodeLogEntry } from '@deepseek-ai/dsh-code-runtime' + +/** + * An in-process stand-in for the worker's parentPort: the test plays the + * HOST side — inspect what the bootstrap posted, feed replies back — so + * every line of worker-side logic runs under coverage without spawning an + * isolate (real-worker behavior is pinned by runtime.spec.ts). + */ +class FakePort implements BootstrapPort { + sent: WorkerToHost[] = [] + private readonly emitter = new EventEmitter() + /** Host-scripted responder; return undefined to leave the call pending. */ + respond: (message: WorkerToHost) => ReplyMessage | undefined = () => undefined + + postMessage(message: WorkerToHost): void { + this.sent.push(message) + const reply = this.respond(message) + if (reply) queueMicrotask(() => this.emitter.emit('message', reply)) + } + + on(event: 'message', listener: (message: ReplyMessage) => void): void { + this.emitter.on(event, listener) + } + + deliver(message: ReplyMessage): void { + this.emitter.emit('message', message) + } + + logs(): CodeLogEntry[] { + return this.sent.filter(message => message.type === 'log').map(message => message.entry) + } + + done(): WorkerToHost | undefined { + return this.sent.find(message => message.type === 'done') + } +} + +function fakeStreams(): { stdout: PatchableStream; stderr: PatchableStream } { + return { stdout: { write: () => true }, stderr: { write: () => true } } +} + +const BOOT = { maxLogBytes: 65_536, maxValueBytes: 32_768 } + +describe('LogBuffer', () => { + it('streams entries to the sink until the byte budget, then emits one marker and drops the rest', () => { + const seen: CodeLogEntry[] = [] + const buffer = new LogBuffer(10, entry => seen.push(entry)) + buffer.push({ source: 'console', level: 'log', text: '12345' }) + buffer.push({ source: 'console', level: 'log', text: '123456' }) + buffer.push({ source: 'console', level: 'log', text: 'dropped' }) + expect(seen.map(entry => entry.text)).toEqual([ + '12345', + '[dsh-code-runtime-worker] log capture truncated at 10 bytes', + ]) + }) +}) + +describe('makeConsoleShim', () => { + it('captures the five levels and renders non-strings inspect-style', () => { + const seen: CodeLogEntry[] = [] + const shim = makeConsoleShim(new LogBuffer(1_000, entry => seen.push(entry))) + shim.log('plain', { a: 1 }) + shim.info('i') + shim.warn('w') + shim.error('e') + shim.debug('d') + expect(seen.map(entry => entry.level)).toEqual(['log', 'info', 'warn', 'error', 'debug']) + expect(seen[0]?.text).toBe('plain { a: 1 }') + expect(seen.every(entry => entry.source === 'console')).toBe(true) + }) +}) + +describe('captureStreamWrites', () => { + it('redirects writes into the buffer and restores on request', () => { + const seen: CodeLogEntry[] = [] + const buffer = new LogBuffer(1_000, entry => seen.push(entry)) + let underlying = '' + const stream: PatchableStream = { write: (chunk: unknown) => { underlying += String(chunk); return true } } + const restore = captureStreamWrites(buffer, stream, 'stdout') + stream.write('captured', 'utf8') + stream.write(Buffer.from('bytes')) + restore() + stream.write('after') + expect(seen.map(entry => entry.text)).toEqual(['captured', 'bytes']) + expect(seen[0]).toMatchObject({ source: 'stdout' }) + expect(underlying).toBe('after') + }) + + it('invokes the write callback asynchronously, in both optional-encoding shapes', async () => { + const buffer = new LogBuffer(1_000, () => {}) + const stream: PatchableStream = { write: () => true } + captureStreamWrites(buffer, stream, 'stdout') + const calls: (Error | null | undefined)[] = [] + stream.write('two-arg', (error?: Error | null) => calls.push(error)) + stream.write('three-arg', 'utf8', (error?: Error | null) => calls.push(error)) + // Node's contract: the callback fires after the write call returns. + expect(calls).toEqual([]) + await new Promise(resolve => stream.write('awaited flush', resolve)) + expect(calls).toEqual([null, null]) + }) + + it('still fires the callback for a write the exhausted budget drops', async () => { + const buffer = new LogBuffer(4, () => {}) + const stream: PatchableStream = { write: () => true } + captureStreamWrites(buffer, stream, 'stdout') + stream.write('this write overflows the budget and is dropped') + await new Promise(resolve => stream.write('also dropped', resolve)) + }) +}) + +describe('prepareValue', () => { + it('omits undefined, passes small cloneable values raw', () => { + expect(prepareValue(undefined, 100)).toEqual({}) + expect(prepareValue({ a: [1, 'two'] }, 100)).toEqual({ value: { a: [1, 'two'] } }) + }) + + it('replaces a non-cloneable value with its rendering', () => { + const { value } = prepareValue({ fn: () => 1 }, 1_000) + expect(typeof value).toBe('string') + expect(value).toContain('fn') + }) + + it('replaces an oversized value with a truncation-marked capped rendering', () => { + const { value } = prepareValue('x'.repeat(50), 10) + expect(value).toBe(`${'x'.repeat(10)}… [truncated]`) + }) + + it('measures a container by its structured-clone wire size, not its bounded rendering', () => { + // The bounded inspect rendering of a huge array is tiny ("... N more + // items"), but its real cross-boundary size is not — the cap must catch + // it, replacing the value with that bounded rendering. + const huge = new Array(50_000).fill(7) + const { value } = prepareValue(huge, 1_000) + expect(typeof value).toBe('string') + expect(value).toContain('more items') + }) + + it('caps a multibyte string by UTF-8 bytes, not UTF-16 length', () => { + // 4 code units but 12 UTF-8 bytes: a length-counting cap would pass the + // full string through untruncated. + expect(prepareValue('€€€€', 4)).toEqual({ value: '€… [truncated]' }) + }) + + it('caps a multibyte rendering by UTF-8 bytes too', () => { + // Wire size (24-byte string inside an array) exceeds the cap, so the + // value crosses as its rendering — whose truncation must also be + // byte-exact: "[ '" (3 bytes) + two € (6 bytes) = 9; a third € would + // overflow the 10-byte budget. + expect(prepareValue(['€€€€€€€€'], 10)).toEqual({ value: "[ '€€… [truncated]" }) + }) +}) + +describe('truncateUtf8Bytes', () => { + it('returns a fitting string whole', () => { + expect(truncateUtf8Bytes('fits', 4)).toBe('fits') + }) + + it('cuts at a code-point boundary, never mid-surrogate-pair', () => { + // Each 😀 is one code point, two code units, four UTF-8 bytes: a 5-byte + // budget fits exactly one — and never leaves a lone surrogate behind. + const cut = truncateUtf8Bytes('😀😀', 5) + expect(cut).toBe('😀') + expect(Buffer.byteLength(truncateUtf8Bytes('😀😀', 3), 'utf8')).toBe(0) + }) +}) + +describe('makeNamespaces', () => { + it('exposes prototype-colliding names as ordinary own properties', async () => { + const port = new FakePort() + port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: true, value: `${message.name}-ok` } : undefined + const pending = new Map() + wireReplies(port, pending) + const [tools] = makeNamespaces({ namespaces: [{ global: 'tools', names: ['__proto__', 'constructor', 'toString'] }] }, port, pending, { value: 1 }) as [Record Promise>] + expect(Object.getPrototypeOf(tools)).toBeNull() + await expect(tools['__proto__']?.({})).resolves.toBe('__proto__-ok') + await expect(tools['constructor']?.({})).resolves.toBe('constructor-ok') + await expect(tools['toString']?.({})).resolves.toBe('toString-ok') + }) + + it('rejects a non-cloneable argument without leaking the pending entry', async () => { + let firstCall = true + const throwingPort: BootstrapPort = { + // First call throws an Error (the real DataCloneError shape), the + // second a bare string — the rejection renders both. + postMessage: () => { + if (firstCall) { firstCall = false; throw new Error('DataCloneError-ish') } + throw 'raw-clone-failure' + }, + on: () => {}, + } + const pending = new Map() + const [tools] = makeNamespaces({ namespaces: [{ global: 'tools', names: ['x'] }] }, throwingPort, pending, { value: 1 }) as [Record Promise>] + await expect(tools.x?.(() => 1)).rejects.toThrow(/structured-cloneable: DataCloneError-ish/) + await expect(tools.x?.(() => 1)).rejects.toThrow(/structured-cloneable: raw-clone-failure/) + expect(pending.size).toBe(0) + }) +}) + +describe('runWorkerMain', () => { + it('runs a program end-to-end: bindings, console, return value', async () => { + const port = new FakePort() + port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: true, value: (message.args as { n: number }).n * 2 } : undefined + await runWorkerMain(port, { + ...BOOT, + code: 'const doubled = await tools.double({ n: 21 }); console.log("got", doubled); return { doubled };', + namespaces: [{ global: 'tools', names: ['double'] }], + }, fakeStreams()) + expect(port.logs()).toEqual([{ source: 'console', level: 'log', text: 'got 42' }]) + expect(port.done()).toEqual({ type: 'done', value: { doubled: 42 } }) + }) + + it('reports a thrown program error on the done message', async () => { + const port = new FakePort() + await runWorkerMain(port, { ...BOOT, code: 'throw new Error("boom")', namespaces: [] }, fakeStreams()) + const done = port.done() + expect(done?.type).toBe('done') + expect(done?.type === 'done' ? done.error?.message : undefined).toContain('boom') + expect(done?.type === 'done' ? done.value : undefined).toBeUndefined() + }) + + it('renders non-Error throws and stack-less Errors on the done message', async () => { + const rawPort = new FakePort() + await runWorkerMain(rawPort, { ...BOOT, code: 'throw "raw-throw"', namespaces: [] }, fakeStreams()) + expect(rawPort.done()).toEqual({ type: 'done', error: { message: 'raw-throw' } }) + + const barePort = new FakePort() + await runWorkerMain(barePort, { ...BOOT, code: 'const e = new Error("bare"); e.stack = undefined; throw e', namespaces: [] }, fakeStreams()) + expect(barePort.done()).toEqual({ type: 'done', error: { message: 'bare' } }) + }) + + it('surfaces a host failure reply as a program-side rejection it can catch', async () => { + const port = new FakePort() + port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: false, message: 'denied by host' } : undefined + await runWorkerMain(port, { + ...BOOT, + code: 'try { await tools.x({}) } catch (error) { return `caught: ${error.message}` }', + namespaces: [{ global: 'tools', names: ['x'] }], + }, fakeStreams()) + expect(port.done()).toEqual({ type: 'done', value: 'caught: denied by host' }) + }) + + it('ignores replies for unknown pending ids', async () => { + const port = new FakePort() + port.respond = (message) => { + if (message.type !== 'call') return undefined + // Deliver a stray reply first; the real one follows. + port.deliver({ type: 'reply', id: 9_999, ok: true, value: 'stray' }) + return { type: 'reply', id: message.id, ok: true, value: 'real' } + } + await runWorkerMain(port, { + ...BOOT, + code: 'return await tools.x({})', + namespaces: [{ global: 'tools', names: ['x'] }], + }, fakeStreams()) + expect(port.done()).toEqual({ type: 'done', value: 'real' }) + }) + + it('captures raw stream writes through the patched process streams', async () => { + const port = new FakePort() + const streams = fakeStreams() + await runWorkerMain(port, { ...BOOT, code: 'return 1', namespaces: [] }, streams) + streams.stdout.write('never seen — already restored? no: patch persists in worker') + // The patch stays installed for the worker's lifetime; writes during the + // program landed in order. Here the program wrote nothing via streams, so + // only the post-run write above went through the patched slot. + expect(port.logs().at(-1)).toMatchObject({ source: 'stdout' }) + }) +}) diff --git a/packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts b/packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts new file mode 100644 index 0000000000..66ce1830b6 --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts @@ -0,0 +1,55 @@ +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +/** + * BUILT-ARTIFACT smoke for the published package (the real-load-path guard + * from docs/testing.md): the unit suite runs `src/` under vitest, where the + * worker entry resolves to `src/worker.ts` — a consumer runs `lib/index.js` + * under plain `node`, where it must resolve the sibling `lib/worker.js` + * bundle instead. This spawns plain `node` (NOT tsx) from inside the package + * directory and imports the package BY NAME, so resolution flows through the + * real `exports` map exactly as it would from a downstream install; the + * program exercises the type-strip, the worker spawn, the binding bridge, + * and log capture end-to-end through the built bundles. + * + * It build-gates: SKIPS when the built artifacts are absent (suite run + * without `pnpm run build`); CI runs it after the build step. KEYLESS — no + * model is involved. + */ + +const pkgDir = fileURLToPath(new URL('..', import.meta.url)) +const built = ['lib/index.js', 'lib/worker.js'].every(file => existsSync(join(pkgDir, file))) + && existsSync(join(pkgDir, '../code-runtime/lib/index.js')) + +describe.skipIf(!built)('built lib real load path (plain node)', () => { + it('runs a TypeScript program with a binding through lib/index.js and its lib/worker.js entry', async () => { + const script = ` + const { Context } = await import('cordis') + const { WorkerCodeRuntime } = await import('@deepseek-ai/dsh-code-runtime-worker') + const ctx = new Context() + await ctx.plugin(WorkerCodeRuntime, {}) + const result = await ctx.codeRuntime.run({ + program: 'const doubled: number = await tools.double({ n: 21 }); console.log("halfway", doubled); return doubled;', + bindings: [{ global: 'tools', functions: { double: async args => args.n * 2 } }], + }) + console.log(JSON.stringify(result)) + process.exit(0) + ` + const child = spawn(process.execPath, ['--input-type=module', '-e', script], { cwd: pkgDir, stdio: ['ignore', 'pipe', 'pipe'] }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString('utf8') }) + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') }) + const exitCode = await new Promise(resolve => child.on('close', resolve)) + + expect(exitCode, `stderr:\n${stderr}`).toBe(0) + const lastLine = stdout.trim().split('\n').at(-1) ?? '' + const result = JSON.parse(lastLine) as { value?: unknown; logs: { source: string; level?: string; text: string }[]; error?: unknown } + expect(result.error).toBeUndefined() + expect(result.value).toBe(42) + expect(result.logs).toContainEqual({ source: 'console', level: 'log', text: 'halfway 42' }) + }) +}) diff --git a/packages/code-runtime/code-runtime-worker/tests/runtime.spec.ts b/packages/code-runtime/code-runtime-worker/tests/runtime.spec.ts new file mode 100644 index 0000000000..edc2bd1271 --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/tests/runtime.spec.ts @@ -0,0 +1,451 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { WorkerCodeRuntime } from '@deepseek-ai/dsh-code-runtime-worker' +import type { Config } from '@deepseek-ai/dsh-code-runtime-worker' +import type { CodeRunResult } from '@deepseek-ai/dsh-code-runtime' + +/** + * Integration suite over REAL worker threads (no mocks — workers are cheap + * and local, per docs/testing.md's real-over-mock policy). Each test builds + * a fresh context so budgets can be tuned per case. + */ +async function setup(config: Config = {}) { + const ctx = new Context() + await ctx.plugin(WorkerCodeRuntime, config) + const runtime = ctx.codeRuntime as WorkerCodeRuntime + return { ctx, runtime } +} + +/** Convenience: one namespace `tools` with the given functions. */ +function tools(functions: Record Promise>) { + return [{ global: 'tools', functions }] +} + +describe('WorkerCodeRuntime — programs and bindings (real workers)', () => { + it('registers with the seam descriptors', async () => { + const { runtime } = await setup() + expect(runtime.language).toBe('typescript') + expect(runtime.isolation).toBe('worker-thread') + }) + + it('runs TypeScript (erasable syntax), captures console/stdout in order, returns the value', async () => { + const { runtime } = await setup() + const result = await runtime.run({ + program: ` + interface Point { x: number; y: number } + const p: Point = { x: 1, y: 2 } as Point; + console.log('point', p); + process.stdout.write('raw-out\\n'); + console.warn('careful'); + return p.x + p.y; + `, + bindings: [], + }) + expect(result.error).toBeUndefined() + expect(result.value).toBe(3) + expect(result.logs.map(entry => [entry.source, entry.level ?? null])).toEqual([ + ['console', 'log'], + ['stdout', null], + ['console', 'warn'], + ]) + expect(result.logs[0]?.text).toBe('point { x: 1, y: 2 }') + }) + + it('bridges binding calls both ways and rejects the program-side call on a host rejection', async () => { + const { runtime } = await setup() + const calls: unknown[] = [] + const result = await runtime.run({ + program: ` + const first = await tools.echo({ n: 1 }); + let caught = ''; + try { await tools.fail({}) } catch (error) { caught = error.message } + let caughtRaw = ''; + try { await tools.failRaw({}) } catch (error) { caughtRaw = error.message } + return { first, caught, caughtRaw }; + `, + bindings: tools({ + echo: async (args) => { calls.push(args); return { echoed: args } }, + fail: async () => { throw new Error('nope') }, + // A non-Error throw: the host renders it, the program still catches. + failRaw: async () => { throw 'raw-nope' }, + }), + }) + expect(result.error).toBeUndefined() + expect(result.value).toEqual({ first: { echoed: { n: 1 } }, caught: 'nope', caughtRaw: 'raw-nope' }) + expect(calls).toEqual([{ n: 1 }]) + }) + + it('reports non-erasable syntax as an exception without spawning a worker', async () => { + const { runtime } = await setup() + const result = await runtime.run({ program: 'enum E { A }\nreturn 1', bindings: [] }) + expect(result.error?.kind).toBe('exception') + expect(result.error?.message).toMatch(/enum|strip/i) + }) + + it('reports a runtime throw as an exception with the message', async () => { + const { runtime } = await setup() + const result = await runtime.run({ program: 'throw new Error("kaboom")', bindings: [] }) + expect(result.error?.kind).toBe('exception') + expect(result.error?.message).toContain('kaboom') + }) + + it('gives the program an EMPTY environment', async () => { + const { runtime } = await setup() + const result = await runtime.run({ program: 'return JSON.stringify(process.env)', bindings: [] }) + expect(result.value).toBe('{}') + }) + + it('replaces a non-cloneable return value with a string rendering', async () => { + const { runtime } = await setup() + const result = await runtime.run({ program: 'return { f: () => 1 }', bindings: [] }) + expect(typeof result.value).toBe('string') + }) + + it('completes a program that returns nothing with no value at all', async () => { + const { runtime } = await setup() + const result = await runtime.run({ program: 'const x = 1', bindings: [] }) + expect(result.error).toBeUndefined() + expect('value' in result).toBe(false) + }) + + it('keeps logs streamed before a failure', async () => { + const { runtime } = await setup() + const result = await runtime.run({ + program: 'console.log("before"); throw new Error("after-log")', + bindings: [], + }) + expect(result.error?.kind).toBe('exception') + expect(result.logs.map(entry => entry.text)).toContain('before') + }) +}) + +describe('WorkerCodeRuntime — budgets and containment (real workers)', () => { + it('ends a hot loop at the compute budget — including behind a pending decoy dispatch', async () => { + const { runtime } = await setup({ computeMs: 300, maxWallMs: 30_000 }) + const result = await runtime.run({ + // The decoy: fire a call at a never-resolving binding WITHOUT awaiting, + // then spin. Host-side pending-call bookkeeping would pause a naive + // budget here; measured busy time cannot be fooled. + program: 'void tools.slow({}); for (;;) {}', + bindings: tools({ slow: () => new Promise(() => {}) }), + }) + expect(result.error?.kind).toBe('timeout') + expect(result.error?.message).toContain('compute budget') + }, 15_000) + + it('does not charge time spent awaiting a slow binding against the compute budget', async () => { + const { runtime } = await setup({ computeMs: 250, maxWallMs: 30_000 }) + const result = await runtime.run({ + program: 'return await tools.slow({})', + bindings: tools({ slow: () => new Promise(resolve => setTimeout(() => { resolve('slow-done') }, 700)) }), + }) + expect(result.error).toBeUndefined() + expect(result.value).toBe('slow-done') + }, 15_000) + + it('ends an idle-forever run at the wall-clock ceiling', async () => { + const { runtime } = await setup({ computeMs: 30_000, maxWallMs: 400 }) + const result = await runtime.run({ + program: 'await tools.never({}); return 1', + bindings: tools({ never: () => new Promise(() => {}) }), + }) + expect(result.error?.kind).toBe('timeout') + expect(result.error?.message).toContain('wall-clock ceiling') + }, 15_000) + + it('reports an abort mid-run and stops the worker', async () => { + const { runtime } = await setup() + const controller = new AbortController() + setTimeout(() => { controller.abort('user-cancel') }, 150) + const result = await runtime.run({ program: 'for (;;) {}', bindings: [], signal: controller.signal }) + expect(result.error).toEqual({ kind: 'abort', message: 'user-cancel' }) + }, 15_000) + + it('reports a pre-aborted signal without spawning', async () => { + const { runtime } = await setup() + const controller = new AbortController() + controller.abort('too-late') + const result = await runtime.run({ program: 'return 1', bindings: [], signal: controller.signal }) + expect(result.error).toEqual({ kind: 'abort', message: 'too-late' }) + }) + + it('drops a binding resolution that lands after the run settled', async () => { + const { runtime } = await setup() + const controller = new AbortController() + let replyDelivered!: Promise + const result = await runtime.run({ + program: 'void tools.late({}); for (;;) {}', + bindings: tools({ + // Anchored on invocation: abort 100ms after the call reaches the + // host, resolve 400ms after — by then the run has settled, so the + // resolution's reply hits the post-settlement drop. + late: () => new Promise((resolve) => { + setTimeout(() => { controller.abort('cancel-now') }, 100) + replyDelivered = new Promise(done => setTimeout(() => { resolve('too-late'); done() }, 400)) + }), + }), + signal: controller.signal, + }) + expect(result.error).toEqual({ kind: 'abort', message: 'cancel-now' }) + // Let the late resolution actually fire so its reply executes instead of + // being cancelled with the test. + await replyDelivered + }, 15_000) + + it('contains an OOM under resourceLimits as worker-exit, host process healthy', async () => { + const { runtime } = await setup({ maxOldGenerationSizeMb: 32 }) + const result = await runtime.run({ + program: 'const hog = []; for (;;) hog.push(new Array(1e6).fill(1));', + bindings: [], + }) + expect(result.error?.kind).toBe('worker-exit') + // And the host is fine: run something else. + const after = await runtime.run({ program: 'return "alive"', bindings: [] }) + expect(after.value).toBe('alive') + }, 30_000) + + it('truncates runaway log output at the byte budget with an in-band marker', async () => { + const { runtime } = await setup({ maxLogBytes: 300 }) + const result = await runtime.run({ + program: 'for (let i = 0; i < 1000; i++) console.log("spam line", i); return 1', + bindings: [], + }) + expect(result.logs.at(-1)?.text).toContain('truncated at 300 bytes') + const total = result.logs.reduce((sum, entry) => sum + Buffer.byteLength(entry.text, 'utf8'), 0) + expect(total).toBeLessThan(1_000) + }) + + it('caps an oversized return value with a truncation marker', async () => { + const { runtime } = await setup({ maxValueBytes: 64 }) + const result = await runtime.run({ program: 'return "y".repeat(10_000)', bindings: [] }) + expect(result.value).toBe(`${'y'.repeat(64)}… [truncated]`) + }) + + it('caps a multibyte return value by UTF-8 bytes, not string length', async () => { + // 4 code units, 12 UTF-8 bytes: a length-counting cap would let the full + // string cross. The worker's byte-exact capped rendering then passes the + // host re-cap unchanged (cap + marker is exactly the granted slack). + const { runtime } = await setup({ maxValueBytes: 4 }) + const result = await runtime.run({ program: 'return "€€€€"', bindings: [] }) + expect(result.value).toBe('€… [truncated]') + }) + + it('completes a program that awaits its write callback, capturing the chunk', async () => { + // Node's write(chunk[, encoding][, callback]) contract: dropping the + // callback would leave this promise pending until the wall ceiling and + // misreport a completed program as a timeout. + const { runtime } = await setup({ maxWallMs: 2_000 }) + const result = await runtime.run({ + program: 'await new Promise(resolve => process.stdout.write("flushed", resolve)); return "done"', + bindings: [], + }) + expect(result.error).toBeUndefined() + expect(result.value).toBe('done') + expect(result.logs).toContainEqual({ source: 'stdout', text: 'flushed' }) + }) + + it('caps a huge container whose bounded rendering is small (wire size, not rendering, is what counts)', async () => { + const { runtime } = await setup() + const result = await runtime.run({ program: 'return new Array(50_000).fill(7)', bindings: [] }) + expect(result.error).toBeUndefined() + expect(typeof result.value).toBe('string') + expect(result.value).toContain('more items') + }) + + it('captures pipe writes that bypass the patched write slot as stray logs, capped by the same budget', async () => { + const { runtime } = await setup({ maxLogBytes: 4 }) + const result = await runtime.run({ + // The bootstrap patches the stream instance's own `write`; going + // through the prototype's slot reaches the real pipe underneath, so + // the bytes arrive host-side as stray data. The pauses keep the two + // writes in separate pipe chunks and let them land before settlement. + program: ` + const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text); + write('abcd'); + await new Promise(resolve => setTimeout(resolve, 150)); + write('ef'); + await new Promise(resolve => setTimeout(resolve, 100)); + return 1; + `, + bindings: [], + }) + expect(result.error).toBeUndefined() + expect(result.logs).toContainEqual({ source: 'stdout', text: 'abcd' }) + expect(result.logs.map(entry => entry.text)).not.toContain('ef') + }, 15_000) +}) + +describe('WorkerCodeRuntime — hostile programs (real workers)', () => { + it('survives forged port traffic: unknown binding names, duplicate ids, junk shapes', async () => { + const { runtime } = await setup() + const result = await runtime.run({ + program: ` + const { parentPort } = await import('node:worker_threads'); + parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} }); + parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} }); + parentPort.postMessage({ type: 'call', id: 7778, global: 'tools', name: 'constructor', args: {} }); + parentPort.postMessage({ type: 'junk' }); + return await tools.real({}); + `, + bindings: tools({ real: async () => 'still-works' }), + }) + expect(result.error).toBeUndefined() + expect(result.value).toBe('still-works') + }) + + it('survives arbitrary junk on the port: non-objects, junk types, malformed calls, logs, and dones', async () => { + const { runtime } = await setup() + const result = await runtime.run({ + program: ` + const { parentPort } = await import('node:worker_threads'); + for (const junk of [ + null, 42, 'junk', [], + { type: 'nope' }, + { type: 'call' }, + { type: 'call', id: 'x', global: 'tools', name: 'real', args: {} }, + { type: 'call', id: 1e9, global: 7, name: 'real', args: {} }, + { type: 'call', id: 1e9, global: 'tools', name: 7, args: {} }, + { type: 'log' }, + { type: 'log', entry: null }, + { type: 'log', entry: { source: 'stdout', text: 7 } }, + { type: 'log', entry: { source: 'nope', text: 'x' } }, + { type: 'log', entry: { source: 'console', level: 'nope', text: 'x' } }, + { type: 'log', entry: { source: 'console', level: 7, text: 'x' } }, + { type: 'done', error: 5 }, + { type: 'done', error: { message: 5 } }, + ]) parentPort.postMessage(junk); + return await tools.real({}); + `, + bindings: tools({ real: async () => 'still-works' }), + }) + expect(result.error).toBeUndefined() + expect(result.value).toBe('still-works') + expect(result.logs).toEqual([]) + }) + + it('caps forged log floods and forged done values at the configured budgets, dropping forged extra fields', async () => { + const { runtime } = await setup({ maxLogBytes: 200, maxValueBytes: 64 }) + const result = await runtime.run({ + // Forged messages bypass the worker-side LogBuffer and prepareValue + // entirely — only the host-side ledger and re-cap stand between model + // code and an unbounded result. + program: ` + const { parentPort } = await import('node:worker_threads'); + for (let i = 0; i < 50; i++) parentPort.postMessage({ type: 'log', entry: { source: 'stdout', text: 'F'.repeat(100), forged: true } }); + parentPort.postMessage({ type: 'done', value: 'V'.repeat(100000) }); + for (;;) {} + `, + bindings: [], + }) + expect(typeof result.value).toBe('string') + const value = result.value as string + expect(value.startsWith('V'.repeat(64))).toBe(true) + expect(value.endsWith('… [truncated]')).toBe(true) + expect(value.length).toBeLessThan(120) + const marker = '[dsh-code-runtime-worker] log capture truncated at 200 bytes' + const total = result.logs.reduce((sum, entry) => sum + Buffer.byteLength(entry.text, 'utf8'), 0) + expect(total).toBeLessThanOrEqual(200 + Buffer.byteLength(marker, 'utf8')) + expect(result.logs.at(-1)?.text).toBe(marker) + expect(result.logs.every(entry => !('forged' in entry))).toBe(true) + }) + + it('accepts a forged done carrying both value and error (self-sabotage, contained)', async () => { + const { runtime } = await setup() + const result = await runtime.run({ + program: ` + const { parentPort } = await import('node:worker_threads'); + parentPort.postMessage({ type: 'done', value: 'lied', error: { message: 'fake failure' } }); + for (;;) {} + `, + bindings: [], + }) + expect(result.value).toBe('lied') + expect(result.error).toEqual({ kind: 'exception', message: 'fake failure' }) + }) + + it('byte-bounds forged multibyte error text at the host', async () => { + // Forged error text bypasses the worker entirely; the host bound is a + // BYTE bound (two € = 6 bytes fit an 8-byte cap, a third would not). + const { runtime } = await setup({ maxValueBytes: 8 }) + const result = await runtime.run({ + program: ` + const { parentPort } = await import('node:worker_threads'); + parentPort.postMessage({ type: 'done', error: { message: '€'.repeat(1000) } }); + for (;;) {} + `, + bindings: [], + }) + expect(result.error).toEqual({ kind: 'exception', message: '€€' }) + }) + + it('answers a binding whose resolution cannot be cloned with a failure reply', async () => { + const { runtime } = await setup() + const result = await runtime.run({ + program: 'try { await tools.bad({}) } catch (error) { return error.message }', + bindings: tools({ bad: async () => (() => 1) }), + }) + expect(result.value).toContain('not structured-cloneable') + }) + + it('exposes binding names that collide with Object.prototype as ordinary functions', async () => { + const { runtime } = await setup() + const result = await runtime.run({ + program: 'return [await tools["__proto__"]({}), await tools["constructor"]({}), typeof tools["hasOwnProperty"]]', + // Computed keys: a literal `'__proto__': …` entry would SET the record's + // prototype instead of declaring a binding of that name. + bindings: tools({ ['__proto__']: async () => 'proto-ok', ['constructor']: async () => 'ctor-ok' }), + }) + expect(result.value).toEqual(['proto-ok', 'ctor-ok', 'undefined']) + }) +}) + +describe('WorkerCodeRuntime — seam misuse and lifecycle', () => { + it('rejects invalid binding globals loudly (identifier, reserved word, duplicate, console)', async () => { + const { runtime } = await setup() + const cases: [string, RegExp][] = [ + ['not valid!', /not a usable identifier/], + ['await', /not a usable identifier/], + ['console', /duplicate binding global/], + ] + for (const [global, message] of cases) { + await expect(runtime.run({ program: 'return 1', bindings: [{ global, functions: {} }] })).rejects.toThrow(message) + } + await expect(runtime.run({ + program: 'return 1', + bindings: [{ global: 'tools', functions: {} }, { global: 'tools', functions: {} }], + })).rejects.toThrow(/duplicate binding global/) + }) + + it('rejects config values that are not positive numbers', async () => { + const ctx = new Context() + await expect(ctx.plugin(WorkerCodeRuntime, { computeMs: -1 })).rejects.toThrow(/positive number/) + }) + + it('keeps runs isolated: no state survives from one run to the next', async () => { + const { runtime } = await setup() + await runtime.run({ program: 'globalThis.leak = "value"; return 1', bindings: [] }) + const second = await runtime.run({ program: 'return typeof globalThis.leak', bindings: [] }) + expect(second.value).toBe('undefined') + }) + + it('disposal aborts in-flight runs, awaits worker exit, and rejects later runs', async () => { + const ctx = new Context() + const fiber = await ctx.plugin(WorkerCodeRuntime) + const runtime = ctx.codeRuntime as WorkerCodeRuntime + const inflight: Promise = runtime.run({ program: 'for (;;) {}', bindings: [] }) + // Give the worker a moment to actually start spinning. + await new Promise(resolve => setTimeout(resolve, 200)) + await fiber.dispose() + const result = await inflight + expect(result.error).toEqual({ kind: 'abort', message: 'runtime disposed' }) + await expect(runtime.run({ program: 'return 1', bindings: [] })).rejects.toThrow(/after disposal/) + }, 15_000) + + it('removes ctx.codeRuntime when the providing fiber disposes (HMR safety)', async () => { + const ctx = new Context() + const fiber = await ctx.plugin(WorkerCodeRuntime) + expect(ctx.get('codeRuntime')).toBeInstanceOf(WorkerCodeRuntime) + await fiber.dispose() + expect(ctx.get('codeRuntime')).toBeUndefined() + }) +}) diff --git a/packages/code-runtime/code-runtime-worker/tsconfig.json b/packages/code-runtime/code-runtime-worker/tsconfig.json new file mode 100644 index 0000000000..af962eda4f --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../code-runtime" + } + ] +} diff --git a/packages/code-runtime/code-runtime-worker/tsdown.config.ts b/packages/code-runtime/code-runtime-worker/tsdown.config.ts new file mode 100644 index 0000000000..5af39d936a --- /dev/null +++ b/packages/code-runtime/code-runtime-worker/tsdown.config.ts @@ -0,0 +1,35 @@ +import { defineConfig } from 'tsdown' + +/** + * Package-shape override (see the root tsdown.config.ts): besides the + * default lib/index.js bundle, the worker BOOTSTRAP ships as its own + * sibling entry — `new Worker(new URL('./worker.js', import.meta.url))` + * loads it as a file, so it cannot be part of the index bundle. TWO + * single-entry builds, not one two-entry build: a multi-entry build emits + * the shared bootstrap module as a `lib/bootstrap-*.js` chunk both bundles + * import, which the package.json `files` whitelist (deliberately exact) + * would omit from the packed artifact — each single-entry build inlines its + * own bootstrap copy instead, keeping every shipped file self-contained. + */ +export default defineConfig([ + { + entry: ['lib/types/index.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + }, + { + entry: ['lib/types/worker.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + }, +]) diff --git a/packages/compact/compact-basic/README.md b/packages/compact/compact-basic/README.md index f4400911c6..a06e74b818 100644 --- a/packages/compact/compact-basic/README.md +++ b/packages/compact/compact-basic/README.md @@ -8,7 +8,7 @@ This is the implementation tier of the compaction capability — see the [interf The abstract contract states only WHAT compaction does; this backend owns every HOW decision: -- **Token estimation** — `estimateContentTokens()`: chars divided by the `charsPerToken` config (default 4) with per-block structural overhead (`text`/`reasoning` = `ceil(len/charsPerToken) + 4`, `tool-call` from name + arguments, `tool-result` recursive, unknown blocks via JSON length). +- **Token estimation** — `estimateContentTokens()`: chars divided by the `charsPerToken` config (default 4) with per-block structural overhead (`text`/`reasoning` = `ceil(len/charsPerToken) + 4`, `tool-call` from name + arguments, `tool-result` recursive, unknown blocks via JSON length). The pressure gate estimates the NEXT request via `estimatePressure()`: the session prefix (the `agent/session-prefix` product — composed by the loop BEFORE the pre-step seam and handed through it, so the gate counts the prefix this instance will actually send in front of the history, never a stale logged one) + the derived history + the system prompt. - **Retention policy** — `compactIfNeeded()` walks the surface nodes tail→head summing per-node token estimates, and retains the smallest tail-run of WHOLE units (a closed step, or a single no-step node such as a pre-step `user/message` or inter-step `steering/message`) whose total reaches `retainTokens`; everything older is compacted. Retention is **turn-agnostic** — turn boundaries play no role, so a single runaway turn that alone exceeds the window compacts its OWN early closed steps rather than being retained verbatim (the failure mode that motivated dropping turn-protection: a tool-heavy turn must stay compactable or the harness dies exactly when compaction is needed). The only structural guard is **tool-pairing balance**: the compacted region's edges are balanced cuts on the surface (no unanswered tool-call crosses either edge), so it never splits a step's `assistant/message` tool-calls from their `tool/result`s. When the only compactable content left is an un-splittable open tail step, it declines (returns `null`) and retries once an older step closes. **Single-unit overflow is out of scope, by design**: if one retained unit (a single closed step, or a large pasted `user/message`) ALONE exceeds the budget, compaction cannot help and the call may go out over-budget — bounding an individual unit's size is a separate concern. `compactRegion()` enforces tool-pairing balance strictly, throwing on a boundary that would split a step. `dsh-session` exports `isToolPairingBalanced` for the check. - **Dynamic convergence** — no static summary-length config pretends to bound what the model will write. If framing/estimator/system overhead leaves the compacted surface above threshold, `compactIfNeeded()` re-compacts the head checkpoint up to `compactionRetries` extra times; if it still cannot get below threshold, it throws. A summary whose estimated stored size is not smaller than the shadowed content fails closed before it mutates the surface. - **Summarization** — `summarize()`: a `GenerateOptions` request assembled via `BlockAssembler` with a fixed system prompt that asks for a structured checkpoint (Primary Request and Intent · Key Technical Concepts · Files and Code · Errors and Fixes · Pending Tasks · Current Work · Next Step · Critical Context), every section mandatory, exact paths/commands/identifiers preserved. The request is a direct one-shot `ctx.llm.stream()` call — NOT a loop step, so it does not run `agent/request` (that seam shapes the loop's conversation requests); the model comes from `summarizationModel` falling back to the agent's own, and per-call routing happens at `llm/stream` like any other direct call. `maxTokens` is the provider-side generation cap; only text blocks from the model's reply are kept before the checkpoint is stored (reasoning is dropped so private chain-of-thought never leaks into the durable summary, and a stray `tool-call` is dropped so the synthesized `user/message` summary cannot land an orphaned call with no matching `tool-result`). The compacted region is flattened to a plain-text transcript first: text and reasoning contribute their text, and every non-text block (tool-call, tool-result, plugin-added types) contributes a type-tagged placeholder (`[tool-call: name(args)]`, `[tool-result: …]`, …) so the summarizer is told what existed rather than silently dropping it. diff --git a/packages/compact/compact-basic/src/index.ts b/packages/compact/compact-basic/src/index.ts index 03f7c9ab4b..c0d4ff483a 100644 --- a/packages/compact/compact-basic/src/index.ts +++ b/packages/compact/compact-basic/src/index.ts @@ -30,7 +30,7 @@ */ import { Context } from 'cordis' -import { CompactService } from '@deepseek-ai/dsh-compact' +import { CompactService, renderTranscript } from '@deepseek-ai/dsh-compact' import type { CompactionResult } from '@deepseek-ai/dsh-compact' import { BlockAssembler } from '@deepseek-ai/dsh-llm' import type { ContentBlock, FinishReason, GenerateOptions, Message } from '@deepseek-ai/dsh-llm' @@ -183,11 +183,11 @@ export class BasicCompactService extends CompactService { // log-only `compact/*` records and the replacement node cleanly outside a // step, so a crash mid-compaction leaves an inert orphan the turn-repair // closes — never a half-open step. - ctx.on('agent/pre-step', async (agent: Agent, _turn: number, _step: number, fullSystemPrompt: string, signal: AbortSignal) => { + ctx.on('agent/pre-step', async (agent: Agent, _turn: number, _step: number, fullSystemPrompt: string, sessionPrefix: readonly Message[], signal: AbortSignal) => { try { - const result = await this.compactIfNeeded(agent, fullSystemPrompt, signal) + const result = await this.compactIfNeeded(agent, fullSystemPrompt, sessionPrefix, signal) if (result) { - const after = this.estimateTokens(agent.session.deriveMessages(), fullSystemPrompt) + const after = this.estimatePressure(agent.session, fullSystemPrompt, sessionPrefix) ctx.logger.info( `compaction: shadowed ${result.shadowedSeqs.length} surface nodes ` + `(seqs ${result.shadowedRange.start}-${result.shadowedRange.end}, ` + @@ -359,11 +359,23 @@ export class BasicCompactService extends CompactService { // ---- Core API (implements the abstract contract) ---- /** - * The sole token-pressure gate: estimate the current surface-derived history, - * and if it exceeds the threshold (`contextWindow * thresholdRatio`), compact + * The sole token-pressure gate: estimate the NEXT request's pressure — the + * session prefix + the surface-derived history + the system prompt + * ({@link estimatePressure}) — and if it exceeds the threshold + * (`contextWindow * thresholdRatio`), compact * the oldest surface nodes outside the `retainTokens` budget. The auto- * compaction listener delegates here rather than pre-checking, so this is the - * only place the decision lives. + * only place the decision lives. The prefix counts because every request + * carries it in front of the history (`EpochHeader.messagePrefix`) even + * though it is not derived history — omitting it would under-estimate by + * exactly the prefix and let a deployment at the window edge skip + * compaction, then ship an over-window request. The loop composes the + * prefix BEFORE the pre-step seam and hands it through, so the gate sees + * this instance's actual prefix (never a previous instance's logged one — + * a resumed/forked instance whose contributor grew is gated on the grown + * value from its very first step). Compaction itself can only + * shrink HISTORY: a prefix that alone approaches the window is a + * configuration error no compactor fixes. * * Retention is a UNIFORM tail→head walk over the whole surface — turn * boundaries play NO role. Walking node-by-node from the tail and summing @@ -387,13 +399,14 @@ export class BasicCompactService extends CompactService { override async compactIfNeeded( agent: Agent, fullSystemPrompt: string, + sessionPrefix: readonly Message[], signal: AbortSignal, ): Promise { const session = agent.session const threshold = Math.floor(this.config.contextWindow * this.config.thresholdRatio) let result: CompactionResult | null = null for (let attempt = 0; attempt <= this.config.compactionRetries; attempt++) { - const totalTokens = this.estimateTokens(session.deriveMessages(), fullSystemPrompt) + const totalTokens = this.estimatePressure(session, fullSystemPrompt, sessionPrefix) if (totalTokens < threshold) return result const range = this._compactableRange(session) @@ -407,7 +420,7 @@ export class BasicCompactService extends CompactService { result = await this.compactRegion(session, range.start, range.end, agent, signal) } - const totalTokens = this.estimateTokens(session.deriveMessages(), fullSystemPrompt) + const totalTokens = this.estimatePressure(session, fullSystemPrompt, sessionPrefix) if (totalTokens < threshold) return result throw new Error( @@ -416,6 +429,20 @@ export class BasicCompactService extends CompactService { ) } + /** + * Estimated token pressure of the NEXT request: the session prefix + * (`EpochHeader.messagePrefix` — request-only messages the loop sends in + * front of the derived history, composed before the pre-step seam and + * handed to the gate), the derived history, and the system prompt. + * @param session - the session whose next request is being estimated. + * @param fullSystemPrompt - the assembled system prompt (counts toward pressure). + * @param sessionPrefix - the instance's composed session prefix (counts toward pressure). + * @returns the estimated token total the next request will carry. + */ + estimatePressure(session: Session, fullSystemPrompt: string, sessionPrefix: readonly Message[]): number { + return this.estimateTokens([...sessionPrefix, ...session.deriveMessages()], fullSystemPrompt) + } + override async compactRegion( session: Session, start: number, @@ -483,7 +510,7 @@ export class BasicCompactService extends CompactService { try { // --- Extract text and summarize --- - const text = this._extractText(session, shadowedSeqs) + const text = renderTranscript(session.events, shadowedSeqs) const { summary, model, maxTokens } = await this.summarize(text, agent, signal) // Estimate token count of the shadowed content for provenance. @@ -679,101 +706,6 @@ export class BasicCompactService extends CompactService { } return null } - - /** - * Extract plain-text conversation from a set of surface node seqs, for - * feeding into the summarization model. Walks the seqs in the order given - * (surface order, as `compactRegion` slices the surface-node list) so the - * summary follows the conversation as the model sees it — which, after a - * `replace`, is NOT ascending log-seq order (a high-seq summary node heads the - * surface before older retained lower-seq nodes). - */ - private _extractText(session: Session, seqs: number[]): string { - const lines: string[] = [] - - // Walk seqs in the order given (surface order, as compactRegion slices the - // surface-node list) — NOT ascending log-seq order. After a replace the - // summary node carries a fresh high seq while sitting at the head of the - // surface before older retained lower-seq nodes, so a log-order scan would - // feed the transcript out of order and break the checkpoint-merge prompt. - for (const seq of seqs) { - const event = session.events[seq] - /* v8 ignore next -- seq is a surface-node seq, always a valid log index by construction */ - if (!event) continue - - switch (event.type) { - case 'user/message': { - const text = this._blocksToText(event.data.content) - if (text) lines.push(`User: ${text}`) - break - } - case 'assistant/message': { - const text = this._blocksToText(event.data.content) - if (text) lines.push(`Assistant: ${text}`) - break - } - case 'tool/result': { - const text = this._blocksToText(event.data.content) - const label = event.data.isError ? 'Tool error' : 'Tool result' - if (text) lines.push(`${label} (call ${event.data.callId}): ${text}`) - break - } - case 'context/message': { - const text = this._blocksToText(event.data.content) - if (text) lines.push(`[Context: ${text}]`) - break - } - case 'steering/message': { - const text = this._blocksToText(event.data.content) - if (text) lines.push(`[Steering: ${text}]`) - break - } - // SessionEventMap is merge-extensible — unknown types are - // non-message events that carry no extractable text. - /* v8 ignore next 2 -- seqs only name surface nodes, always one of the 5 handled SurfaceEventTypes; unreachable */ - default: - break - } - } - - return lines.join('\n\n') - } - - /** - * Render content blocks to a single plain-text string for the summarization - * prompt. Text and reasoning contribute their text; every other block type - * contributes a type-tagged placeholder (`[tool-call: name(args)]`, - * `[tool-result: …]`, …) so the summarizer is told what non-text content - * existed in the region rather than silently losing it. Blocks join with - * newlines; empty-text blocks contribute nothing. - */ - private _blocksToText(blocks: readonly ContentBlock[]): string { - const parts: string[] = [] - for (const block of blocks) { - switch (block.type) { - case 'text': - if (block.text) parts.push(block.text) - break - case 'reasoning': - if (block.text) parts.push(`[reasoning: ${block.text}]`) - break - case 'tool-call': - parts.push(`[tool-call: ${block.name}(${block.arguments})]`) - break - case 'tool-result': { - const inner = this._blocksToText(block.content) - parts.push(inner ? `[tool-result: ${inner}]` : '[tool-result]') - break - } - // ContentBlockMap is merge-extensible — render an unknown block as a - // bare type-tagged placeholder so a plugin-added block type is still - // signalled to the summarizer rather than dropped. - default: - parts.push(`[${(block as ContentBlock).type}]`) - } - } - return parts.join('\n') - } } export default BasicCompactService diff --git a/packages/compact/compact-basic/tests/compact-basic.spec.ts b/packages/compact/compact-basic/tests/compact-basic.spec.ts index 990d60190a..e3d80cd567 100644 --- a/packages/compact/compact-basic/tests/compact-basic.spec.ts +++ b/packages/compact/compact-basic/tests/compact-basic.spec.ts @@ -557,6 +557,24 @@ describe('BasicCompactService.compactIfNeeded', () => { expect(result!.shadowedSeqs.length).toBeGreaterThan(0) }) + it('counts the session prefix toward pressure (every request carries it in front of the history)', async () => { + const svc = createTestService({ contextWindow: 200, thresholdRatio: 0.5, retainTokens: 10 }) + const session = multiTurnSession(3, 1) // 6 derived messages ≈ 84 estimated tokens — under the 100 threshold alone + expect(await compactIfNeeded(svc, session, '', 'm', SIGNAL)).toBeNull() + + // The loop composes the agent/session-prefix product before the pre-step + // seam and hands it to the gate; it rides every request, so pressure must + // include it — the same history now crosses the threshold. + const sessionPrefix: Message[] = [ + { role: 'user', content: [{ type: 'text', text: `opener one.${LONG_FIXTURE_TEXT}` }] }, + { role: 'user', content: [{ type: 'text', text: `opener two.${LONG_FIXTURE_TEXT}` }] }, + ] + const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL, sessionPrefix) + expect(result).not.toBeNull() + // The prefix itself is NOT history: compaction shadowed surface nodes only. + expect(sessionPrefix).toHaveLength(2) + }) + it('returns the first compaction result when a zero-retry pass converges after the loop', async () => { // With compactionRetries=0 there is no next-loop threshold check after the // first mutation, so the success path is the post-loop `return result`. @@ -982,8 +1000,9 @@ function compactIfNeeded( fullSystemPrompt: string, model: string, signal: AbortSignal, + sessionPrefix: readonly Message[] = [], ) { - return svc.compactIfNeeded(stubAgent(session, model), fullSystemPrompt, signal) + return svc.compactIfNeeded(stubAgent(session, model), fullSystemPrompt, sessionPrefix, signal) } function compactRegion( @@ -1151,7 +1170,7 @@ describe('BasicCompactService.summarize (real ctx.llm.stream)', () => { describe('BasicCompactService auto-compaction (agent/pre-step listener)', () => { /** Fire the agent/pre-step serial checkpoint as the loop does. */ function firePreStep(ctx: Context, agent: Agent, step: number, fullSystemPrompt: string): Promise { - return ctx.serial('agent/pre-step', agent, 1, step, fullSystemPrompt, SIGNAL) + return ctx.serial('agent/pre-step', agent, 1, step, fullSystemPrompt, [], SIGNAL) } it('compacts (mutating the surface) when over threshold', async () => { @@ -1253,7 +1272,7 @@ describe('BasicCompactService auto-compaction (agent/pre-step listener)', () => const session = multiTurnSession(5, 1) const agent = stubAgent(session, 'agent-model') - await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL) + await ctx.serial('agent/pre-step', agent, 1, 1, '', [], SIGNAL) expect(adapter.lastOptions?.model).toBe('routed-model') expect(session.events.some(e => e.type === 'compact/summary')).toBe(true) @@ -1278,7 +1297,7 @@ describe('BasicCompactService auto-compaction (agent/pre-step listener)', () => }) }) -describe('BasicCompactService._extractText branches', () => { +describe('BasicCompactService transcript rendering (delegated to dsh-compact)', () => { it('renders reasoning, context, and steering messages', async () => { const svc = createTestService() const s = new Session(SessionId('rich')) @@ -1392,7 +1411,7 @@ describe('BasicCompactService edge cases', () => { const session = multiTurnSession(4, 1) const agent = stubAgent(session, 'test-model') - await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL) + await ctx.serial('agent/pre-step', agent, 1, 1, '', [], SIGNAL) expect(session.events.some(e => e.type === 'compact/summary')).toBe(true) // The surface was mutated; the head message is the framed summary checkpoint. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'SUMMARY' }) @@ -1472,7 +1491,7 @@ describe('BasicCompactService edge cases', () => { const agent = stubAgent(session, 'test-model') const before = session.surface.nodes.length - await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL) + await ctx.serial('agent/pre-step', agent, 1, 1, '', [], SIGNAL) // The failure was swallowed; the surface is untouched and a warning logged. expect(session.surface.nodes.length).toBe(before) expect(session.events.some(e => e.type === 'compact/summary')).toBe(false) @@ -1489,7 +1508,7 @@ describe('BasicCompactService edge cases', () => { const agent = stubAgent(session, 'test-model') const bigSystem = 'x'.repeat(900) // ceil(900/4)=225 > threshold 200 - await ctx.serial('agent/pre-step', agent, 1, 1, bigSystem, SIGNAL) + await ctx.serial('agent/pre-step', agent, 1, 1, bigSystem, [], SIGNAL) expect(session.events.some(e => e.type === 'compact/start')).toBe(false) expect(svc.summarizeCalls.length).toBe(0) }) diff --git a/packages/compact/compact/README.md b/packages/compact/compact/README.md index 54bdcc7f4e..e98f00899f 100644 --- a/packages/compact/compact/README.md +++ b/packages/compact/compact/README.md @@ -6,7 +6,7 @@ This package is the interface tier of the compaction capability, split so each c | Package | Role | |---|---| -| `@deepseek-ai/dsh-compact` (this) | the interface: abstract service + `compact/*` events + `CompactionResult` | +| `@deepseek-ai/dsh-compact` (this) | the interface: abstract service + `compact/*` events + `CompactionResult` + the shared transcript renderer (`renderTranscript`/`renderContentBlocks`) | | `@deepseek-ai/dsh-compact-basic` (deferred) | a backend: chars-per-token estimation (`charsPerToken`, default 4) + token-budget retention + `llm.stream()` summarization | | `@deepseek-ai/dsh-tool-compact` (deferred) | the model-facing `/compact` tool over `ctx.compact` | @@ -18,7 +18,7 @@ Both methods are **abstract** — the backend owns the entire strategy (token es | Member | Semantics | |---|---| -| `compactIfNeeded(agent, fullSystemPrompt, signal)` | Estimate the surface-derived history size; if over the backend's threshold, compact an older range via `compactRegion`, keeping recent context intact. Returns the `CompactionResult`, or `null` if nothing needed compacting. All parameters required — the loop's `agent/pre-step` checkpoint supplies the agent, assembled `fullSystemPrompt`, and turn `signal`. A backend's summarization request is a direct `ctx.llm.stream()` call (not a loop step), so per-call interception happens at `llm/stream`. | +| `compactIfNeeded(agent, fullSystemPrompt, sessionPrefix, signal)` | Estimate the surface-derived history size; if over the backend's threshold, compact an older range via `compactRegion`, keeping recent context intact. Returns the `CompactionResult`, or `null` if nothing needed compacting. All parameters required — the loop's `agent/pre-step` checkpoint supplies the agent, assembled `fullSystemPrompt`, composed `sessionPrefix` (request-only messages every request carries but the derived history omits — the pressure estimate must count them), and turn `signal`. A backend's summarization request is a direct `ctx.llm.stream()` call (not a loop step), so per-call interception happens at `llm/stream`. | | `compactRegion(session, start, end, agent, signal?)` | Forcibly summarize surface nodes `[start, end]` (inclusive seqs) into a single replacement node. **Throws** if a compaction is already in progress, if `start`/`end` aren't surface nodes, or if `start` is positioned after `end` on the surface. The range is a SURFACE-POSITION span, not a numeric seq interval — after a prior replace lands a fresh high-seq summary node at the shadowed range's position, surface order no longer tracks seq order. | `compactIfNeeded` takes a required `signal`; `compactRegion`'s is optional. A backend that summarizes via `ctx.llm.stream()` **must** forward it into the call's `GenerateOptions.signal`, so an abort or fiber dispose tears down the in-flight summarization instead of leaving an orphaned model call running past the cancellation. The session being compacted comes from the agent context; the turn that the `compact/*` events belong to is recoverable from the log (the currently-open turn), so the backend stamps it from the log rather than trusting a caller-supplied value. diff --git a/packages/compact/compact/src/index.ts b/packages/compact/compact/src/index.ts index cc190ccd87..7d1138314c 100644 --- a/packages/compact/compact/src/index.ts +++ b/packages/compact/compact/src/index.ts @@ -22,10 +22,12 @@ */ import { Context, Service } from 'cordis' +import type { Message } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type { CompactionResult } from './types.ts' export type { CompactionResult } from './types.ts' +export { renderContentBlocks, renderTranscript } from './render.ts' /** Minimal agent context compaction needs without depending on the agent package. */ export interface CompactAgentContext { @@ -68,16 +70,20 @@ export abstract class CompactService extends Service { /** * Check token pressure and compact if the conversation is too large. * - * Estimates the current surface-derived history size (including the system - * prompt), and if it exceeds the backend's threshold, compacts an older range + * Estimates the NEXT request's size — the session prefix, the + * surface-derived history, and the system prompt — and if it exceeds the + * backend's threshold, compacts an older range * via {@link compactRegion}, keeping recent context intact. Returns `null` * when no compaction is needed. * * Scope and guarantees a backend MUST honor: - * - **Surface-derived history only.** The decision is made against the history - * derived from the session surface — the only thing compaction can act on. - * Non-surface context injected downstream (into the request `messages` by a - * later listener) is out of this accounting by construction. + * - **Compaction acts on surface-derived history only**, but the ESTIMATE + * counts everything the request carries: the loop composes the session + * prefix before the pre-step seam fires and hands it here, so the gate + * sees the prefix this instance will actually send (`EpochHeader.messagePrefix` + * — request-only, never derived history). Non-surface context injected + * downstream (into the request `messages` by a later listener) is out of + * this accounting by construction. * - **Head-anchored, best-effort.** Auto-compaction consolidates from the * surface HEAD up to a balanced tool-pairing cutoff, so a prior head * checkpoint is @@ -88,10 +94,14 @@ export abstract class CompactService extends Service { * - **Single-unit overflow is out of scope.** If a single retained unit (one * closed step, or a large free node such as a pasted `user/message`) ALONE * exceeds the budget, compaction cannot help and the call may go out - * over-budget. Bounding an individual unit's size is a separate concern. + * over-budget. Bounding an individual unit's size is a separate concern — + * as is a session prefix that alone approaches the window (a + * configuration error no compactor fixes: compaction cannot shrink the + * prefix). * * @param agent - agent context owning the session surface and model options. * @param fullSystemPrompt - assembled system prompt, counted toward the estimate. + * @param sessionPrefix - the instance's composed session prefix, counted toward the estimate. * @param signal - cancellation signal. A backend summarizing via * `ctx.llm.stream()` MUST forward this into the call's `GenerateOptions.signal` * so an abort/dispose tears down the in-flight summarization rather than @@ -101,6 +111,7 @@ export abstract class CompactService extends Service { abstract compactIfNeeded( agent: CompactAgentContext, fullSystemPrompt: string, + sessionPrefix: readonly Message[], signal: AbortSignal, ): Promise diff --git a/packages/compact/compact/src/render.ts b/packages/compact/compact/src/render.ts new file mode 100644 index 0000000000..6e977df007 --- /dev/null +++ b/packages/compact/compact/src/render.ts @@ -0,0 +1,118 @@ +/** + * Plain-text transcript rendering over session events: the shared projection + * used wherever a compaction-class consumer needs "what a model once saw" as + * readable text — a summarizer's input, or a recall tool's output. + * + * Extracted from the basic backend's private helpers so the summarize path and + * the recall read path render one span identically (two renderers would drift, + * and a recall reader would then see a different transcript than the one the + * summary was written from). Both functions are pure over their arguments: no + * session access beyond the provided events, no clock, no randomness — a + * rendered span is a pure function of the log, so replay reproduces it + * byte-identically. + * + * @module @deepseek-ai/dsh-compact/render + */ + +import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import type { SessionEvent } from '@deepseek-ai/dsh-session' + +/** + * Render content blocks to a single plain-text string. Text and reasoning + * contribute their text (reasoning wrapped as `[reasoning: …]`); every other + * block type contributes a type-tagged placeholder (`[tool-call: name(args)]`, + * `[tool-result: …]`, …) so the reader is told what non-text content existed + * rather than silently losing it. A `tool-result` block recurses into its + * nested content (`[tool-result: ]`), falling back to a bare + * `[tool-result]` when the nested content renders to nothing. Blocks join + * with newlines; empty-text blocks contribute nothing. + * + * @param blocks - the content blocks to render. + * @returns the newline-joined plain-text rendering; empty string when nothing renders. + */ +export function renderContentBlocks(blocks: readonly ContentBlock[]): string { + const parts: string[] = [] + for (const block of blocks) { + switch (block.type) { + case 'text': + if (block.text) parts.push(block.text) + break + case 'reasoning': + if (block.text) parts.push(`[reasoning: ${block.text}]`) + break + case 'tool-call': + parts.push(`[tool-call: ${block.name}(${block.arguments})]`) + break + case 'tool-result': { + const inner = renderContentBlocks(block.content) + parts.push(inner ? `[tool-result: ${inner}]` : '[tool-result]') + break + } + // ContentBlockMap is merge-extensible — render an unknown block as a + // bare type-tagged placeholder so a plugin-added block type is still + // signalled to the reader rather than dropped. + default: + parts.push(`[${(block as ContentBlock).type}]`) + } + } + return parts.join('\n') +} + +/** + * Render a set of surface-node seqs as a `User:`/`Assistant:`/`Tool result:` + * transcript. Walks `seqs` in the order given — callers pass surface order + * (e.g. a `compactRegion` slice of the surface-node list), which after a + * `replace` is NOT ascending log-seq order (a high-seq summary node can sit at + * the head of the surface before older retained lower-seq nodes); a log-order + * scan would render the transcript out of order. + * + * Only the five surface (message-producing) event types render; a seq naming + * any other event type contributes nothing. `SessionEventMap` is + * merge-extensible, so unknown types are simply non-message events with no + * renderable text. + * + * @param events - the session log the seqs index into (`session.events`). + * @param seqs - the surface-node seqs to render, in surface order. + * @returns the transcript, entries joined by blank lines; empty string when nothing renders. + */ +export function renderTranscript(events: readonly SessionEvent[], seqs: readonly number[]): string { + const lines: string[] = [] + + for (const seq of seqs) { + const event = events[seq] + if (!event) continue + + switch (event.type) { + case 'user/message': { + const text = renderContentBlocks(event.data.content) + if (text) lines.push(`User: ${text}`) + break + } + case 'assistant/message': { + const text = renderContentBlocks(event.data.content) + if (text) lines.push(`Assistant: ${text}`) + break + } + case 'tool/result': { + const text = renderContentBlocks(event.data.content) + const label = event.data.isError ? 'Tool error' : 'Tool result' + if (text) lines.push(`${label} (call ${event.data.callId}): ${text}`) + break + } + case 'context/message': { + const text = renderContentBlocks(event.data.content) + if (text) lines.push(`[Context: ${text}]`) + break + } + case 'steering/message': { + const text = renderContentBlocks(event.data.content) + if (text) lines.push(`[Steering: ${text}]`) + break + } + default: + break + } + } + + return lines.join('\n\n') +} diff --git a/packages/compact/compact/tests/compact.spec.ts b/packages/compact/compact/tests/compact.spec.ts index 93c4e806ce..c4daa8cc5a 100644 --- a/packages/compact/compact/tests/compact.spec.ts +++ b/packages/compact/compact/tests/compact.spec.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest' import { Context } from 'cordis' import { CompactService } from '@deepseek-ai/dsh-compact' import type { CompactionResult } from '@deepseek-ai/dsh-compact' +import type { Message } from '@deepseek-ai/dsh-llm' import { Session, SessionId } from '@deepseek-ai/dsh-session' import type { CompactAgentContext } from '@deepseek-ai/dsh-compact' @@ -18,6 +19,7 @@ class StubCompactService extends CompactService { override async compactIfNeeded( _agent: CompactAgentContext, _fullSystemPrompt: string, + _sessionPrefix: readonly Message[], signal: AbortSignal, ): Promise { this.lastSignal = signal @@ -78,7 +80,7 @@ describe('CompactService seam', () => { const ctx = new Context() const svc = new StubCompactService(ctx) const session = new Session(SessionId('s')) - expect(await svc.compactIfNeeded(stubAgent(session), '', new AbortController().signal)).toBeNull() + expect(await svc.compactIfNeeded(stubAgent(session), '', [], new AbortController().signal)).toBeNull() }) it('compact/* events merge into SessionEventMap and are log-only', async () => { @@ -107,7 +109,7 @@ describe('CompactService seam', () => { await svc.compactRegion(session, 0, 0, stubAgent(session, 'm'), controller.signal) expect(svc.lastSignal).toBe(controller.signal) - await svc.compactIfNeeded(stubAgent(session), '', controller.signal) + await svc.compactIfNeeded(stubAgent(session), '', [], controller.signal) expect(svc.lastSignal).toBe(controller.signal) }) }) diff --git a/packages/compact/compact/tests/render.spec.ts b/packages/compact/compact/tests/render.spec.ts new file mode 100644 index 0000000000..1a22296565 --- /dev/null +++ b/packages/compact/compact/tests/render.spec.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest' +import { renderContentBlocks, renderTranscript } from '@deepseek-ai/dsh-compact' +import { Session, SessionId } from '@deepseek-ai/dsh-session' +import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { CallId } from '@deepseek-ai/dsh-llm' + +function session(): Session { + return new Session(SessionId('render-spec')) +} + +describe('renderContentBlocks', () => { + it('renders text blocks verbatim and skips empty ones', () => { + expect(renderContentBlocks([ + { type: 'text', text: 'hello' }, + { type: 'text', text: '' }, + { type: 'text', text: 'world' }, + ])).toBe('hello\nworld') + }) + + it('wraps reasoning, skipping empty reasoning', () => { + expect(renderContentBlocks([ + { type: 'reasoning', text: 'think' }, + { type: 'reasoning', text: '' }, + ])).toBe('[reasoning: think]') + }) + + it('renders tool-call as a name(args) placeholder', () => { + expect(renderContentBlocks([ + { type: 'tool-call', id: CallId('c1'), name: 'read', arguments: '{"filePath":"a"}' }, + ])).toBe('[tool-call: read({"filePath":"a"})]') + }) + + it('renders tool-result with nested content, and bare when empty', () => { + expect(renderContentBlocks([ + { type: 'tool-result', toolCallId: CallId('c1'), content: [{ type: 'text', text: 'ok' }] }, + { type: 'tool-result', toolCallId: CallId('c2'), content: [] }, + ])).toBe('[tool-result: ok]\n[tool-result]') + }) + + it('renders an unknown (merge-extended) block type as a bare type tag', () => { + const unknown = { type: 'image', data: 'zzz' } as unknown as ContentBlock + expect(renderContentBlocks([unknown])).toBe('[image]') + }) + + it('returns the empty string for no blocks', () => { + expect(renderContentBlocks([])).toBe('') + }) +}) + +describe('renderTranscript', () => { + it('renders each surface event type with its label, in the seq order given', () => { + const s = session() + const user = s.append('user/message', { + content: [{ type: 'text', text: 'fix the bug' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + const assistant = s.append('assistant/message', { + turn: 0, step: 0, + content: [{ type: 'text', text: 'looking' }], + }, { surfaceOp: 'append' }) + const result = s.append('tool/result', { + turn: 0, step: 0, callId: CallId('c1'), + content: [{ type: 'text', text: 'exit 0' }], + isError: false, + }, { surfaceOp: 'append' }) + const context = s.append('context/message', { + content: [{ type: 'text', text: 'file changed' }], + source: { kind: 'plugin', plugin: 'fs' }, + }, { surfaceOp: 'append' }) + const steering = s.append('steering/message', { + turn: 0, + content: [{ type: 'text', text: 'stop that' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + + expect(renderTranscript(s.events, [user.seq, assistant.seq, result.seq, context.seq, steering.seq])).toBe([ + 'User: fix the bug', + 'Assistant: looking', + 'Tool result (call c1): exit 0', + '[Context: file changed]', + '[Steering: stop that]', + ].join('\n\n')) + }) + + it('labels an error tool result "Tool error"', () => { + const s = session() + const result = s.append('tool/result', { + turn: 0, step: 0, callId: CallId('c9'), + content: [{ type: 'text', text: 'boom' }], + isError: true, + }, { surfaceOp: 'append' }) + expect(renderTranscript(s.events, [result.seq])).toBe('Tool error (call c9): boom') + }) + + it('renders NON-log-order seqs in the order given (surface order after a replace)', () => { + const s = session() + const first = s.append('user/message', { + content: [{ type: 'text', text: 'first' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + const second = s.append('user/message', { + content: [{ type: 'text', text: 'second' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + expect(renderTranscript(s.events, [second.seq, first.seq])).toBe('User: second\n\nUser: first') + }) + + it('skips events that render to nothing, non-message events, and seqs with no event', () => { + const s = session() + const empty = s.append('user/message', { + content: [{ type: 'text', text: '' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + const emptyAssistant = s.append('assistant/message', { + turn: 0, step: 0, + content: [{ type: 'text', text: '' }], + }, { surfaceOp: 'append' }) + const emptyResult = s.append('tool/result', { + turn: 0, step: 0, callId: CallId('c3'), + content: [{ type: 'text', text: '' }], + isError: false, + }, { surfaceOp: 'append' }) + const emptyContext = s.append('context/message', { + content: [{ type: 'text', text: '' }], + source: { kind: 'plugin', plugin: 'fs' }, + }, { surfaceOp: 'append' }) + const emptySteering = s.append('steering/message', { + turn: 0, + content: [{ type: 'text', text: '' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + // A log-only (non-surface) event type: contributes nothing to a transcript. + const lock = s.append('compact/start', { turn: 0 }) + expect(renderTranscript(s.events, [ + empty.seq, emptyAssistant.seq, emptyResult.seq, emptyContext.seq, emptySteering.seq, lock.seq, 9999, + ])).toBe('') + }) +}) diff --git a/packages/cordis/README.md b/packages/cordis/README.md new file mode 100644 index 0000000000..70c7e41ce0 --- /dev/null +++ b/packages/cordis/README.md @@ -0,0 +1,7 @@ +# packages/cordis — the self-referential runtime toolset + +Model-facing tools over the live cordis runtime the agent itself runs inside: inspect the loaded plugins and service surface, mount model-written plugins, and dispose them again. Design home: [the toolset RFC](../../docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). + +| Package | Role | ctx key | +|---|---|---| +| [`tool-cordis/`](tool-cordis/README.md) | The `cordis_inspect` / `cordis_mount` / `cordis_unmount` tools: read the runtime, evaluate model-written plugin code in a `node:vm` sandbox, and manage the dynamic mounts under one group fiber | registers on `ctx.tools` | diff --git a/packages/cordis/tool-cordis/README.md b/packages/cordis/tool-cordis/README.md new file mode 100644 index 0000000000..c4f3cf11b9 --- /dev/null +++ b/packages/cordis/tool-cordis/README.md @@ -0,0 +1,33 @@ +# @deepseek-ai/dsh-tool-cordis + +The self-referential cordis toolset: three model-facing tools over the live runtime the agent runs inside. Design home — sandbox semantics, mount lifecycle, cross-mount composition, the generated API catalog, standing decisions: [the toolset RFC](../../../docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). + +## What it does + +- `cordis_inspect` — read-only report over the runtime: services, the loaded-plugin list, registered tools, the dynamic-mount table, and the catalog-backed `api` / `events` references. +- `cordis_mount` — evaluates model-written JavaScript (the body of an async function) in a `node:vm` sandbox; the code must `return` a cordis plugin, which is mounted under the `cordis-dynamic` group fiber and tracked as `dyn-`. +- `cordis_unmount` — disposes one mount by id, returning only after quiescence. + +Exact model-facing schemas: [the generated tool catalog](../../../docs/tool-catalog.md). + +## Trust stance + +The sandbox isolates the global context only — it is not a security boundary. No Node API is provided: `require`, the timers, and `fetch` are callable traps that throw a redirect to the cordis alternative (`ctx.fs` / `ctx.web` / `ctx.bash` / `inject: ['timer']` + `ctx.setTimeout`); `process` and `Buffer` are `undefined`; `globalThis` writes stay inside. These traps steer honest code onto the cordis services; they do not contain a mount that goes looking — the host-realm helpers on the sandbox global (`harness`, `console`, `btoa`) are reachable functions, so mount code can reach the host realm and Node through one of them, which is fine because `ctx` is fully privileged anyway. The `ctx` a mounted plugin's `apply` receives is a whitelist façade — register tools, observe events, provide/consume services, use timers; framework internals (`ctx.root`, `ctx.fiber`, `ctx.extend`, `ctx.plugin`, …) are withheld — but the capabilities it does expose reach the real runtime, so load this plugin as deliberately as you would grant a bash tool. + +## Config + +| Field | Default | Meaning | +|---|---|---| +| `vmTimeoutMs` | `5000` | Bound on the SYNCHRONOUS portion of mount-code evaluation; an async body escapes it | + +## The generated API catalog + +`src/api-catalog.ts` is generated by `scripts/gen-cordis-api.ts` from the same AST walk as [docs/cordis-catalog](../../../docs/cordis-catalog/services.md) and freshness-gated by `pnpm run verify-cordis-api` (in `doc-sync`) — never edit it by hand. `cordis_inspect` intersects it with the live service store at call time. + +## Rendering + +All three tools render `generic` cards (`read` / `execute` / `delete`); `cordis_mount` carries the mount code as `rawInput`. Presenters are pure functions of the args; results keep the default text rendering. + +## Export shape + +Namespace plugin: named exports `name` / `inject` / `Config` / `apply`, no default export ([docs/postmortem/0001](../../../docs/postmortem/0001-acp-default-export-drops-inject.md)). diff --git a/packages/cordis/tool-cordis/package.json b/packages/cordis/tool-cordis/package.json new file mode 100644 index 0000000000..a7d99eeea3 --- /dev/null +++ b/packages/cordis/tool-cordis/package.json @@ -0,0 +1,44 @@ +{ + "name": "@deepseek-ai/dsh-tool-cordis", + "description": "Self-referential cordis toolset: inspect the live runtime, mount and dispose model-written plugins", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-scope": "^0.0.1", + "@deepseek-ai/dsh-tools": "^0.0.1", + "cordis": "^4.0.0-rc.6" + }, + "dependencies": { + "schemastery": "^3.18.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-scope": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "@cordisjs/plugin-loader": "^1.0.0-rc.4", + "cordis": "^4.0.0-rc.6", + "@cordisjs/plugin-timer": "workspace:^" + } +} diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts new file mode 100644 index 0000000000..6025b0623c --- /dev/null +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -0,0 +1,871 @@ +/** + * Generated by scripts/gen-cordis-api.ts — do not edit by hand; run + * `pnpm run gen-cordis-api` to regenerate (freshness-gated by + * `pnpm run verify-cordis-api` in doc-sync). + * + * The machine-readable cordis API catalog `cordis_inspect` serves to the + * model: harness services (summary + public method signatures), harness + * events (mode + signature), and the inherited `ctx` surface. Produced by + * the same AST walk as docs/cordis-catalog, so this data and the rendered + * docs cannot diverge. + * + * @module @deepseek-ai/dsh-tool-cordis/api-catalog + */ + +/** One harness `ctx.` service: its one-line summary and public method signatures. */ +export interface ServiceApiEntry { + /** The `ctx.` name, e.g. `tools`. */ + key: string + /** First sentence of the service class JSDoc. */ + summary: string + /** Public method signatures, bodies stripped, in source order. */ + methods: readonly string[] +} + +/** One harness event: its dispatch mode, exact signature, and one-line summary. */ +export interface EventApiEntry { + /** The scoped event name, e.g. `agent/status`. */ + name: string + /** The dispatch mode from the declaration's `@mode` tag. */ + mode: string + /** The exact listener signature, whitespace-normalized. */ + signature: string + /** First sentence of the event JSDoc. */ + summary: string +} + +/** One inherited (cordis core + loader/hmr/timer) `ctx` member group with its summary. */ +export interface InheritedApiEntry { + /** The `ctx` member name(s), e.g. `ctx.on / ctx.once`. */ + name: string + /** One-line summary of what the member does. */ + summary: string +} + +/** One named type shape the service signatures reference. */ +export interface TypeApiEntry { + /** The exported type/interface name, e.g. `BashRunResult`. */ + name: string + /** The full declaration text, comments stripped. */ + declaration: string +} + +/** Every harness `ctx.` service, sorted by key. */ +export const SERVICE_API: readonly ServiceApiEntry[] = [ + { + key: 'agentLoop', + summary: 'The agent-loop plugin (`ctx.agentLoop`): creates ReactLoopAgents, runs their loops, and registers them in `ctx.agents`.', + methods: [ + 'create(id: AgentId, options: AgentOptions = {}): ReactLoopAgent', + 'createAgent(options: CreateAgentOptions): AgentHandle', + 'async resume(options: ResumeAgentOptions): Promise', + ], + }, + { + key: 'agents', + summary: 'Agent registry (`ctx.agents`): tracks live agents so UI, hook, and orchestrator plugins can find them without depending on the concrete loop package.', + methods: [ + 'setFactory(factory: AgentFactory): () => Promise | void', + 'create(options: CreateAgentOptions): AgentHandle', + 'async resume(options: ResumeAgentOptions): Promise', + 'register(agent: Agent): () => Promise | void', + 'get(id: AgentId): Agent | undefined', + 'list(): Agent[]', + ], + }, + { + key: 'bash', + summary: 'Abstract bash execution service.', + methods: [ + 'abstract resolve(request: BashExecRequest): BashExecSpec', + 'abstract run(spec: BashExecSpec): Promise', + 'abstract start(spec: BashExecSpec): BashTask', + 'abstract get(id: BashTaskId): BashTask | undefined', + 'abstract ownerOf(id: BashTaskId): OwnerToken | undefined', + 'abstract list(): BashTask[]', + 'abstract readOutput(id: BashTaskId): BashTaskRead', + 'abstract kill(id: BashTaskId): boolean', + 'onTaskDone(listener: BashTaskListener): () => void', + ], + }, + { + key: 'codeRuntime', + summary: 'Abstract code-execution service.', + methods: [ + 'abstract run(request: CodeRunRequest): Promise', + ], + }, + { + key: 'compact', + summary: 'Abstract compaction service.', + methods: [ + 'abstract compactIfNeeded( agent: CompactAgentContext, fullSystemPrompt: string, sessionPrefix: readonly Message[], signal: AbortSignal, ): Promise', + 'abstract compactRegion( session: Session, start: number, end: number, agent: CompactAgentContext, signal?: AbortSignal, ): Promise', + ], + }, + { + key: 'fs', + summary: 'Abstract filesystem provider service.', + methods: [ + 'abstract resolve(path: string, opts?: { cwd?: string }): Promise', + 'abstract stat(target: FsTarget, signal?: AbortSignal): Promise', + 'abstract readText(target: FsTarget, signal?: AbortSignal): Promise', + 'abstract streamText(target: FsTarget, signal?: AbortSignal): Promise>', + 'abstract listDir(target: FsTarget, signal?: AbortSignal): Promise', + 'abstract writeText(target: FsTarget, content: string, expected?: FsWriteIntent, signal?: AbortSignal): Promise', + 'abstract editText(target: FsTarget, edit: FsEditRequest, expected?: { version: FsVersion }, signal?: AbortSignal): Promise', + ], + }, + { + key: 'llm', + summary: 'The abstract `llm` service: an adapter registry plus a streaming model-call surface, interceptable via the `llm/stream` waterfall.', + methods: [ + 'registerAdapter(models: string[], adapter: LlmAdapter): () => void', + 'models(): string[]', + 'stream(options: GenerateOptions): AsyncIterable', + ], + }, + { + key: 'sessionPersistence', + summary: 'Abstract durable session-persistence service.', + methods: [ + 'abstract create(meta: SessionHeader): Promise', + 'abstract append(id: SessionId, events: readonly SessionEvent[]): Promise', + 'abstract load(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }>', + 'abstract list(): Promise', + ], + }, + { + key: 'sessions', + summary: 'In-memory session store (`ctx.sessions`).', + methods: [ + 'create(id?: SessionId, options?: CreateSessionOptions): Session', + 'prepare(id?: SessionId, options?: CreateSessionOptions): Session', + 'enter(session: Session): () => void', + 'announce(session: Session): void', + 'async flush(session: Session): Promise', + 'get(id: SessionId): Session | undefined', + 'list(): Session[]', + 'fork(source: SessionForkSource, boundary?: number, childSessionId?: SessionId): Session', + ], + }, + { + key: 'subagents', + summary: 'The `subagents` service: a registry of named SubagentProviders and a capability-checked start surface.', + methods: [ + 'registerProvider(provider: SubagentProvider): () => Promise | void', + 'getProvider(name: string): SubagentProvider | undefined', + 'list(): string[]', + 'start(name: string, request: SubagentStartRequest): SubagentRun', + ], + }, + { + key: 'systemPrompt', + summary: 'Registry service (`ctx.systemPrompt`): plugins contribute ordered text sections, tool-schema providers, and named prompt variables; the agent loop calls `assemble(context)` once per step.', + methods: [ + 'section(section: PromptSection): () => Promise | void', + 'tools(provider: (context: AssembleContext) => ToolProviderResult): () => Promise | void', + 'variable(name: string, provider: (context: AssembleContext) => string | undefined): () => Promise | void', + 'async assemble(context: AssembleContext = {}): Promise', + ], + }, + { + key: 'tools', + summary: 'Tool registry (`ctx.tools`): tool plugins register definitions; the agent loop executes calls through the `tools/pre-execute` → `tools/execute` → `tools/post-execute` pipeline.', + methods: [ + 'register(definition: ToolDefinition): () => Promise | void', + 'restrict(filter: ToolRestriction): () => Promise | void', + 'visible(scope?: ScopeKey): ToolDefinition[]', + 'get(name: string, scope?: ScopeKey): ToolDefinition | undefined', + 'schemas(scope?: ScopeKey): ToolSchema[]', + 'knownNames(scope?: ScopeKey): string[]', + 'async execute(exec: ToolExecution): Promise', + ], + }, + { + key: 'userInteraction', + summary: '`ctx.userInteraction`: one active UI provider plus an `ask()` surface.', + methods: [ + 'registerProvider(provider: UserInteractionProvider): () => void', + 'async ask(request: AskUserQuestionRequest): Promise', + ], + }, + { + key: 'web', + summary: 'The web access service.', + methods: [ + 'registerSearchProvider(provider: WebSearchProvider): () => void', + 'registerFetchProvider(provider: WebFetchProvider): () => void', + 'async search(request: WebSearchRequest, exec?: WebExecContext): Promise', + 'async fetch(request: WebFetchRequest, exec?: WebExecContext): Promise', + ], + }, +] + +/** Every harness event, sorted by name. */ +export const EVENT_API: readonly EventApiEntry[] = [ + { + name: 'agent/created', + mode: 'emit', + signature: '\'agent/created\'(this: Scoped, agent: Agent): void', + summary: 'An agent was registered in the AgentRegistry and is ready to receive messages.', + }, + { + name: 'agent/disposed', + mode: 'emit', + signature: '\'agent/disposed\'(this: Scoped, agent: Agent): void', + summary: 'An agent was disposed and removed from the registry; its fiber and any in-flight turn have been torn down.', + }, + { + name: 'agent/error', + mode: 'emit', + signature: '\'agent/error\'(this: Scoped, agent: Agent, turn: number, step: number, error: Error): void', + summary: 'A step or turn errored.', + }, + { + name: 'agent/pre-step', + mode: 'serial', + signature: '\'agent/pre-step\'(this: Scoped, agent: Agent, turn: number, step: number, fullSystemPrompt: string, sessionPrefix: readonly Message[], signal: AbortSignal): Promise | void', + summary: 'Awaited pre-step surface-mutation checkpoint, fired once per step AFTER `turn/start` (and after the prior step closed) but BEFORE this step\'s `step/start` — so anything a listener appends lands OUTSIDE the step, between `turn/start`/`step/end` and the upcoming `step/start`.', + }, + { + name: 'agent/prompt-submit', + mode: 'waterfall', + signature: '\'agent/prompt-submit\'(this: Scoped, agent: Agent, content: ContentBlock[], source: MessageSource, next: () => Promise): Promise', + summary: 'Waterfall: decide what happens to ONE drained queued message before it becomes a `user/message` — allow (optionally rewriting the prompt bytes or attaching `additionalContext`) or block it.', + }, + { + name: 'agent/queued', + mode: 'emit', + signature: '\'agent/queued\'(this: Scoped, agent: Agent, content: ContentBlock[], info: { source: MessageSource; steering: boolean }): void', + summary: 'A message entered the agent\'s inbox (queued or steering).', + }, + { + name: 'agent/request', + mode: 'waterfall', + signature: '\'agent/request\'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, next: () => Promise): Promise', + summary: 'Waterfall: shape the step\'s call configuration — model switching, sampling overrides — by returning a replacement LlmCallConfig (the frozen seed is the config the loop would otherwise use).', + }, + { + name: 'agent/session-prefix', + mode: 'waterfall', + signature: '\'agent/session-prefix\'(this: Scoped, agent: Agent, prefix: Message[], signal: AbortSignal, next: () => Promise): Promise', + summary: 'Waterfall: compose the SESSION PREFIX — request-only messages placed in front of the ENTIRE derived history (directly after the provider\'s system slot) on every request this loop instance sends.', + }, + { + name: 'agent/session-start', + mode: 'emit', + signature: '\'agent/session-start\'(this: Scoped, agent: Agent, source: SessionStartSource): void', + summary: 'The agent\'s session lifecycle began, fired once before its first turn.', + }, + { + name: 'agent/status', + mode: 'emit', + signature: '\'agent/status\'(this: Scoped, agent: Agent, status: AgentStatus): void', + summary: 'Agent status changed (`idle` ⇄ `running`, or → `disposed`).', + }, + { + name: 'agent/step-result', + mode: 'waterfall', + signature: '\'agent/step-result\'(this: Scoped, agent: Agent, turn: number, step: number, message: Message, next: () => Promise): Promise', + summary: 'Waterfall: post-process the assembled assistant Message before tool dispatch (validation, content rewriting, …).', + }, + { + name: 'agent/turn-continuation', + mode: 'waterfall', + signature: '\'agent/turn-continuation\'(this: Scoped, agent: Agent, turn: number, defaultDecision: ContinuationDecision, next: () => Promise): Promise', + summary: 'Waterfall: override the turn-continuation decision via a typed ContinuationDecision.', + }, + { + name: 'fs/edit-intent', + mode: 'waterfall', + signature: '\'fs/edit-intent\'(target: FsTarget, actor: object | undefined, next: () => { version: FsVersion } | undefined | Promise<{ version: FsVersion } | undefined>): Promise<{ version: FsVersion } | undefined>', + summary: 'Single-slot decision: produce the optional version guard for the next FileSystem.editText.', + }, + { + name: 'fs/observed', + mode: 'emit', + signature: '\'fs/observed\'(target: FsTarget, version: FsVersion, actor: object | undefined): void', + summary: 'Record that an actor observed a target at a version, after a successful read/write/edit.', + }, + { + name: 'fs/write-intent', + mode: 'waterfall', + signature: '\'fs/write-intent\'(target: FsTarget, actor: object | undefined, next: () => FsWriteIntent | undefined | Promise): Promise', + summary: 'Single-slot decision: produce the write intent for the next FileSystem.writeText.', + }, + { + name: 'llm/stream', + mode: 'waterfall', + signature: '\'llm/stream\'(this: LlmService, options: GenerateOptions, next: () => AsyncIterable): AsyncIterable', + summary: 'Waterfall around every streaming model call (retry, replay, routing).', + }, + { + name: 'session/created', + mode: 'emit', + signature: '\'session/created\'(this: Scoped, session: Session): void', + summary: 'A session was created in the store.', + }, + { + name: 'session/event', + mode: 'emit', + signature: '\'session/event\'(this: Scoped, session: Session, event: SessionEvent): void', + summary: 'An event was appended to a session log (sync, fire-and-forget).', + }, + { + name: 'session/flush', + mode: 'parallel', + signature: '\'session/flush\'(this: Scoped, session: Session): Promise | void', + summary: 'Awaited durability checkpoint.', + }, + { + name: 'subagent/end', + mode: 'emit', + signature: '\'subagent/end\'(info: SubagentRunEndInfo): void', + summary: 'A subagent run settled — emitted when SubagentRun.result resolves (any stop reason).', + }, + { + name: 'subagent/provider-added', + mode: 'emit', + signature: '\'subagent/provider-added\'(provider: SubagentProvider): void', + summary: 'A provider became resolvable in the SubagentService registry.', + }, + { + name: 'subagent/provider-removed', + mode: 'emit', + signature: '\'subagent/provider-removed\'(name: string): void', + summary: 'A provider left the registry (its plugin\'s fiber was disposed — an unload or an HMR reload).', + }, + { + name: 'subagent/start', + mode: 'emit', + signature: '\'subagent/start\'(info: SubagentRunInfo): void', + summary: 'A subagent run started — emitted after the provider is resolved and its capabilities validated, as the child run begins.', + }, + { + name: 'system-prompt/assemble', + mode: 'waterfall', + signature: '\'system-prompt/assemble\'(this: Scoped, assembly: PromptAssembly, context: AssembleContext, next: () => Promise): Promise', + summary: 'Waterfall around prompt assembly — mutate or extend the PromptAssembly (sections + tools + variables) before it is rendered.', + }, + { + name: 'system-prompt/change', + mode: 'emit', + signature: '\'system-prompt/change\'(): void', + summary: 'A section, tool provider, or variable provider was registered or unregistered (the assembly inputs changed — possibly for one scope only).', + }, + { + name: 'tools/change', + mode: 'emit', + signature: '\'tools/change\'(): void', + summary: 'A tool was registered or unregistered, or a scoped restriction changed (the available tool set changed — possibly for one scope only).', + }, + { + name: 'tools/execute', + mode: 'waterfall', + signature: '\'tools/execute\'(this: Scoped, exec: ToolExecution, next: () => Promise): Promise', + summary: 'Around-dispatch waterfall wrapping the registry\'s core tool dispatch, between the `tools/pre-execute` gate and the `tools/post-execute` seam.', + }, + { + name: 'tools/post-execute', + mode: 'waterfall', + signature: '\'tools/post-execute\'(this: Scoped, exec: ToolExecution, result: ToolExecutionResult, next: () => Promise): Promise', + summary: 'Waterfall AFTER a tool runs — where hook plugins inspect the result and accept it (optionally REPLACING the model-facing content, and/or attaching `additionalContext` for the next request) or block it with corrective `feedback` (Claude Code\'s `PostToolUse`).', + }, + { + name: 'tools/pre-execute', + mode: 'waterfall', + signature: '\'tools/pre-execute\'(this: Scoped, exec: ToolExecution, next: () => Promise): Promise', + summary: 'Waterfall BEFORE a tool runs — the gate where sandbox, permission, and hook plugins allow or deny a call (Claude Code\'s `PreToolUse`).', + }, +] + +/** Shapes of every exported type the SERVICE_API signatures reference (transitively), sorted by name. */ +export const TYPE_API: readonly TypeApiEntry[] = [ + { + name: 'Agent', + declaration: 'export interface Agent {\n readonly id: AgentId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly ctx: Context;\n send(content: ContentBlock[], options?: SendOptions): void;\n steer(content: ContentBlock[], options?: SendOptions): void;\n inject(content: ContentBlock[], options?: SendOptions): void;\n cancel(reason?: string): void;\n whenIdle(): Promise;\n}', + }, + { + name: 'AgentFactory', + declaration: 'export interface AgentFactory {\n createAgent(options: CreateAgentOptions): AgentHandle;\n resume(options: ResumeAgentOptions): Promise;\n}', + }, + { + name: 'AgentHandle', + declaration: 'export interface AgentHandle {\n agent: Agent;\n dispose(): Promise;\n}', + }, + { + name: 'AgentId', + declaration: 'export type AgentId = Branded<\'AgentId\'>;', + }, + { + name: 'AgentOptions', + declaration: 'export interface AgentOptions {\n model?: string;\n}', + }, + { + name: 'AgentStatus', + declaration: 'export type AgentStatus = \'idle\' | \'running\' | \'disposed\';', + }, + { + name: 'AskUserQuestionAnswer', + declaration: 'export interface AskUserQuestionAnswer {\n answers: AskUserQuestionAnswerItem[];\n}', + }, + { + name: 'AskUserQuestionAnswerItem', + declaration: 'export interface AskUserQuestionAnswerItem {\n id: string;\n selected: string[];\n custom?: string;\n}', + }, + { + name: 'AskUserQuestionItem', + declaration: 'export interface AskUserQuestionItem {\n id: string;\n question: string;\n header?: string;\n options?: AskUserQuestionOption[];\n multiSelect?: boolean;\n}', + }, + { + name: 'AskUserQuestionOption', + declaration: 'export interface AskUserQuestionOption {\n label: string;\n description?: string;\n}', + }, + { + name: 'AskUserQuestionRequest', + declaration: 'export interface AskUserQuestionRequest {\n questions: AskUserQuestionItem[];\n agent?: Agent;\n signal?: AbortSignal;\n}', + }, + { + name: 'AssembleContext', + declaration: 'export interface AssembleContext {\n scope?: ScopeKey;\n}', + }, + { + name: 'AssembledSection', + declaration: 'export interface AssembledSection {\n name: string;\n order: number;\n text: string;\n}', + }, + { + name: 'BashExecRequest', + declaration: 'export interface BashExecRequest {\n command: string;\n workdir?: string | undefined;\n timeoutMs?: number | undefined;\n signal?: AbortSignal | undefined;\n stdin?: string | undefined;\n env?: Record | undefined;\n owner?: OwnerToken | undefined;\n}', + }, + { + name: 'BashExecSpec', + declaration: 'export interface BashExecSpec {\n command: string;\n workdir: string;\n timeoutMs: number;\n signal?: AbortSignal | undefined;\n stdin?: string | undefined;\n env?: Record | undefined;\n owner: OwnerToken | undefined;\n}', + }, + { + name: 'BashRunResult', + declaration: 'export interface BashRunResult {\n exitCode: number | null;\n signal: NodeJS.Signals | null;\n timedOut: boolean;\n aborted: boolean;\n timeoutMs: number;\n stdout: CollectedOutput;\n stderr: CollectedOutput;\n}', + }, + { + name: 'BashTask', + declaration: 'export interface BashTask {\n readonly id: BashTaskId;\n readonly command: string;\n status: BashTaskStatus;\n exitCode: number | null;\n signal: NodeJS.Signals | null;\n readonly done: Promise;\n}', + }, + { + name: 'BashTaskId', + declaration: 'export type BashTaskId = Branded<\'BashTaskId\'>;', + }, + { + name: 'BashTaskListener', + declaration: 'export type BashTaskListener = (task: BashTask) => void;', + }, + { + name: 'BashTaskRead', + declaration: 'export interface BashTaskRead {\n task: BashTask;\n delta: string;\n lossy: boolean;\n stdoutSpillPath?: string;\n stderrSpillPath?: string;\n}', + }, + { + name: 'BashTaskStatus', + declaration: 'export type BashTaskStatus = \'running\' | \'completed\' | \'killed\';', + }, + { + name: 'Branded', + declaration: 'export type Branded = string & {\n readonly [BRAND]: B;\n};', + }, + { + name: 'CallId', + declaration: 'export type CallId = Branded<\'CallId\'>;', + }, + { + name: 'CodeBindingFunction', + declaration: 'export type CodeBindingFunction = (args: unknown) => Promise;', + }, + { + name: 'CodeBindingNamespace', + declaration: 'export interface CodeBindingNamespace {\n global: string;\n functions: Record;\n}', + }, + { + name: 'CodeLogEntry', + declaration: 'export interface CodeLogEntry {\n source: \'console\' | \'stdout\' | \'stderr\';\n level?: \'log\' | \'info\' | \'warn\' | \'error\' | \'debug\';\n text: string;\n}', + }, + { + name: 'CodeRunFailure', + declaration: 'export interface CodeRunFailure {\n kind: \'exception\' | \'timeout\' | \'abort\' | \'worker-exit\';\n message: string;\n}', + }, + { + name: 'CodeRunRequest', + declaration: 'export interface CodeRunRequest {\n program: string;\n bindings: CodeBindingNamespace[];\n signal?: AbortSignal;\n}', + }, + { + name: 'CodeRunResult', + declaration: 'export interface CodeRunResult {\n value?: unknown;\n logs: CodeLogEntry[];\n error?: CodeRunFailure;\n}', + }, + { + name: 'CollectedOutput', + declaration: 'export interface CollectedOutput {\n text: string;\n truncated: boolean;\n spillPath?: string;\n}', + }, + { + name: 'CompactAgentContext', + declaration: 'export interface CompactAgentContext {\n session: Session;\n options: {\n model?: string;\n };\n}', + }, + { + name: 'CompactionResult', + declaration: 'export interface CompactionResult {\n startSeq: number;\n summarySeq: number;\n endSeq: number;\n summary: ContentBlock[];\n shadowedRange: {\n start: number;\n end: number;\n };\n shadowedSeqs: number[];\n shadowedTokenCount: number;\n}', + }, + { + name: 'ContentBlockMap', + declaration: 'export interface ContentBlockMap {\n \'text\': TextBlock;\n \'reasoning\': ReasoningBlock;\n \'tool-call\': ToolCallBlock;\n \'tool-result\': ToolResultBlock;\n}', + }, + { + name: 'ContentBlockType', + declaration: 'export type ContentBlockType = keyof ContentBlockMap;', + }, + { + name: 'CreateAgentOptions', + declaration: 'export interface CreateAgentOptions {\n agentId: AgentId;\n sessionId: SessionId;\n meta?: {\n cwd?: string;\n parentSession?: SessionId;\n seedLength?: number;\n };\n seed?: SessionEvent[];\n agentOptions?: AgentOptions;\n setup?: (agentCtx: Context) => void;\n}', + }, + { + name: 'CreateSessionOptions', + declaration: 'export interface CreateSessionOptions {\n seed?: SessionEvent[];\n meta?: {\n cwd?: string;\n parentSession?: SessionId;\n createdAt?: number;\n seedLength?: number;\n };\n}', + }, + { + name: 'DiffCallView', + declaration: 'export interface DiffCallView {\n card: \'diff\';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n}', + }, + { + name: 'DiffResultView', + declaration: 'export interface DiffResultView {\n card: \'diff\';\n title?: string;\n diffs: FileDiff[];\n}', + }, + { + name: 'FileDiff', + declaration: 'export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n}', + }, + { + name: 'FileLocation', + declaration: 'export interface FileLocation {\n path: string;\n line?: number;\n}', + }, + { + name: 'FinishReason', + declaration: 'export type FinishReason = FinishReasonMap[keyof FinishReasonMap];', + }, + { + name: 'FinishReasonMap', + declaration: 'export interface FinishReasonMap {\n \'stop\': {\n kind: \'stop\';\n };\n \'tool-calls\': {\n kind: \'tool-calls\';\n };\n \'max-tokens\': {\n kind: \'max-tokens\';\n };\n \'aborted\': {\n kind: \'aborted\';\n };\n \'error\': {\n kind: \'error\';\n message: string;\n code?: string;\n };\n}', + }, + { + name: 'FsDirEntry', + declaration: 'export interface FsDirEntry {\n name: string;\n type: \'file\' | \'directory\' | \'other\';\n target: FsTarget;\n version?: FsVersion;\n size?: number;\n}', + }, + { + name: 'FsEditOutcome', + declaration: 'export interface FsEditOutcome {\n version: FsVersion;\n before: string;\n after: string;\n}', + }, + { + name: 'FsEditRequest', + declaration: 'export interface FsEditRequest {\n oldString: string;\n newString: string;\n replaceAll: boolean;\n}', + }, + { + name: 'FsInfo', + declaration: 'export interface FsInfo {\n version: FsVersion;\n type: \'file\' | \'directory\' | \'other\';\n size?: number;\n}', + }, + { + name: 'FsTarget', + declaration: 'export interface FsTarget {\n targetKey: FsTargetKey;\n displayPath: string;\n}', + }, + { + name: 'FsTargetKey', + declaration: 'export type FsTargetKey = Branded<\'FsTargetKey\'>;', + }, + { + name: 'FsVersion', + declaration: 'export type FsVersion = Branded<\'FsVersion\'>;', + }, + { + name: 'FsWriteIntent', + declaration: 'export type FsWriteIntent = {\n kind: \'createIfAbsent\';\n} | {\n kind: \'replaceIfVersion\';\n version: FsVersion;\n};', + }, + { + name: 'FsWriteOutcome', + declaration: 'export interface FsWriteOutcome {\n operation: \'create\' | \'update\';\n version: FsVersion;\n before: string | null;\n after: string;\n}', + }, + { + name: 'GenerateOptions', + declaration: 'export interface GenerateOptions {\n model: string;\n messages: Message[];\n system?: string;\n tools?: ToolSchema[];\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n signal?: AbortSignal;\n sessionId?: Branded<\'SessionId\'>;\n}', + }, + { + name: 'GenericCallView', + declaration: 'export interface GenericCallView {\n card: \'generic\';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n}', + }, + { + name: 'GenericResultView', + declaration: 'export interface GenericResultView {\n card: \'generic\';\n title?: string;\n content?: ContentBlock[];\n}', + }, + { + name: 'HookContext', + declaration: 'export interface HookContext {\n content: ContentBlock[];\n source: MessageSource;\n}', + }, + { + name: 'Message', + declaration: 'export interface Message {\n role: \'system\' | \'user\' | \'assistant\';\n content: ContentBlock[];\n}', + }, + { + name: 'MessageSource', + declaration: 'export type MessageSource = MessageSourceMap[keyof MessageSourceMap];', + }, + { + name: 'MessageSourceMap', + declaration: 'export interface MessageSourceMap {\n user: {\n kind: \'user\';\n };\n plugin: {\n kind: \'plugin\';\n plugin: string;\n };\n}', + }, + { + name: 'OwnerToken', + declaration: 'export type OwnerToken = Branded<\'OwnerToken\'>;', + }, + { + name: 'PromptAssembly', + declaration: 'export interface PromptAssembly {\n sections: AssembledSection[];\n tools: ToolSchema[];\n variables: Record;\n}', + }, + { + name: 'PromptSection', + declaration: 'export interface PromptSection {\n name: string;\n order: number;\n text: string | ((context: AssembleContext) => string);\n}', + }, + { + name: 'ReasoningBlock', + declaration: 'export interface ReasoningBlock {\n type: \'reasoning\';\n text: string;\n}', + }, + { + name: 'ResumeAgentOptions', + declaration: 'export interface ResumeAgentOptions {\n agentId: AgentId;\n resumeSessionId: SessionId;\n agentOptions?: AgentOptions;\n}', + }, + { + name: 'ScopeKey', + declaration: 'export type ScopeKey = object;', + }, + { + name: 'SendOptions', + declaration: 'export interface SendOptions {\n source?: MessageSource;\n}', + }, + { + name: 'SessionEvent', + declaration: 'export type SessionEvent = {\n [K in SessionEventType]: {\n type: K;\n seq: number;\n time: number;\n data: SessionEventMap[K];\n } & (K extends SurfaceEventType ? {\n sourceEventSeqs?: number[];\n surfaceOp?: SurfaceOp;\n } : object);\n}[T];', + }, + { + name: 'SessionEventMap', + declaration: 'export interface SessionEventMap {\n \'turn/start\': {\n turn: number;\n trigger: TurnTrigger;\n };\n \'turn/end\': {\n turn: number;\n reason: TurnEndReason;\n };\n \'step/start\': {\n turn: number;\n step: number;\n };\n \'step/end\': {\n turn: number;\n step: number;\n };\n \'user/message\': {\n content: ContentBlock[];\n source: MessageSource;\n };\n \'prompt/blocked\': {\n content: ContentBlock[];\n source: MessageSource;\n reason: string;\n };\n \'context/message\': {\n content: ContentBlock[];\n source: MessageSource;\n };\n \'assistant/chunk\': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n \'assistant/message\': {\n turn: number;\n step: number;\n content: ContentBlock[];\n usage?: TokenUsage;\n };\n \'tool/call\': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n \'tool/result\': {\n turn: number;\n step: number;\n callId: CallId;\n content: ContentBlock[];\n isError: boolean;\n error?: {\n name: string;\n code: string;\n };\n meta?: unknown;\n };\n \'steering/message\': {\n turn: number;\n content: ContentBlock[];\n source: MessageSource;\n };\n \'todo/write\': {\n todos: TodoItem[];\n };\n \'request/header\': {\n header: E /* …truncated — full shape in source */', + }, + { + name: 'SessionEventType', + declaration: 'export type SessionEventType = keyof SessionEventMap;', + }, + { + name: 'SessionForkSource', + declaration: 'export type SessionForkSource = Session | SessionId;', + }, + { + name: 'SessionHeader', + declaration: 'export interface SessionHeader {\n version: number;\n id: SessionId;\n createdAt: number;\n cwd?: string;\n parentSession?: SessionId;\n seedLength?: number;\n}', + }, + { + name: 'SessionId', + declaration: 'export type SessionId = Branded<\'SessionId\'>;', + }, + { + name: 'StreamChunk', + declaration: 'export type StreamChunk = {\n type: \'block-start\';\n index: number;\n blockType: ContentBlockType;\n} | {\n type: \'text-delta\';\n index: number;\n text: string;\n} | {\n type: \'reasoning-delta\';\n index: number;\n text: string;\n} | {\n type: \'tool-call-delta\';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n} | {\n type: \'block-end\';\n index: number;\n block: ContentBlock;\n} | {\n type: \'usage\';\n usage: TokenUsage;\n} | {\n type: \'finish\';\n reason: FinishReason;\n};', + }, + { + name: 'StructuredOutputSchema', + declaration: 'export type StructuredOutputSchema = StructuredSchemaNode & {\n type: \'object\';\n};', + }, + { + name: 'StructuredScalar', + declaration: 'export type StructuredScalar = string | number | boolean | null;', + }, + { + name: 'StructuredSchemaNode', + declaration: 'export interface StructuredSchemaNode {\n type: StructuredSchemaType;\n properties?: Record;\n required?: string[];\n additionalProperties?: boolean;\n items?: StructuredSchemaNode;\n enum?: StructuredScalar[];\n const?: StructuredScalar;\n description?: string;\n title?: string;\n default?: unknown;\n examples?: unknown;\n}', + }, + { + name: 'StructuredSchemaType', + declaration: 'export type StructuredSchemaType = \'object\' | \'array\' | \'string\' | \'number\' | \'integer\' | \'boolean\' | \'null\';', + }, + { + name: 'SubagentCapabilities', + declaration: 'export interface SubagentCapabilities {\n outputSchema: boolean;\n depthLimit: boolean;\n toolFilter: boolean;\n persona: boolean;\n}', + }, + { + name: 'SubagentProvider', + declaration: 'export interface SubagentProvider {\n readonly name: string;\n readonly capabilities: SubagentCapabilities;\n readonly inheritsParentContext: boolean;\n start(request: SubagentStartRequest): SubagentRun;\n}', + }, + { + name: 'SubagentResult', + declaration: 'export interface SubagentResult {\n output: ContentBlock[];\n structured?: unknown;\n stopReason: SubagentStopReason;\n}', + }, + { + name: 'SubagentRun', + declaration: 'export interface SubagentRun {\n readonly id: AgentId;\n readonly result: Promise;\n cancel(reason?: string): void;\n dispose(): Promise;\n sendMessage?(content: ContentBlock[]): void;\n resume?(content: ContentBlock[]): SubagentRun;\n}', + }, + { + name: 'SubagentStartRequest', + declaration: 'export interface SubagentStartRequest {\n prompt: ContentBlock[];\n parent: Agent;\n signal?: AbortSignal;\n agentOptions?: AgentOptions;\n outputSchema?: StructuredOutputSchema;\n maxDepth?: number;\n toolFilter?: {\n allow?: string[];\n deny?: string[];\n };\n persona?: string;\n}', + }, + { + name: 'SubagentStopReason', + declaration: 'export type SubagentStopReason = SubagentStopReasonMap[keyof SubagentStopReasonMap];', + }, + { + name: 'SubagentStopReasonMap', + declaration: 'export interface SubagentStopReasonMap {\n completed: \'completed\';\n aborted: \'aborted\';\n error: \'error\';\n \'max-tokens\': \'max-tokens\';\n refusal: \'refusal\';\n}', + }, + { + name: 'SurfaceEventType', + declaration: 'export type SurfaceEventType = \'user/message\' | \'assistant/message\' | \'tool/result\' | \'context/message\' | \'steering/message\';', + }, + { + name: 'SurfaceOp', + declaration: 'export type SurfaceOp = \'append\' | {\n op: \'replace\';\n start: number;\n end: number;\n};', + }, + { + name: 'TerminalCallView', + declaration: 'export interface TerminalCallView {\n card: \'terminal\';\n title: string;\n description?: string;\n cwd?: string;\n}', + }, + { + name: 'TerminalResultView', + declaration: 'export interface TerminalResultView {\n card: \'terminal\';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n}', + }, + { + name: 'TodoItem', + declaration: 'export interface TodoItem {\n content: string;\n status: \'pending\' | \'in_progress\' | \'completed\';\n}', + }, + { + name: 'TokenUsage', + declaration: 'export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n}', + }, + { + name: 'ToolCallBlock', + declaration: 'export interface ToolCallBlock {\n type: \'tool-call\';\n id: CallId;\n name: string;\n arguments: string;\n}', + }, + { + name: 'ToolCallKind', + declaration: 'export type ToolCallKind = \'read\' | \'edit\' | \'delete\' | \'move\' | \'search\' | \'execute\' | \'fetch\' | \'other\';', + }, + { + name: 'ToolCallView', + declaration: 'export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;', + }, + { + name: 'ToolDefinition', + declaration: 'export interface ToolDefinition extends ToolSchema {\n execute(args: unknown, exec: ToolExecution): Promise;\n timeoutMs?: number;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n}', + }, + { + name: 'ToolErrorInfo', + declaration: 'export interface ToolErrorInfo {\n name: string;\n code: string;\n}', + }, + { + name: 'ToolExecuteReturn', + declaration: 'export type ToolExecuteReturn = ContentBlock[] | {\n content: ContentBlock[];\n meta?: unknown;\n};', + }, + { + name: 'ToolExecution', + declaration: 'export interface ToolExecution {\n callId: CallId;\n name: string;\n arguments: unknown;\n agent?: Agent;\n signal?: AbortSignal;\n}', + }, + { + name: 'ToolExecutionResult', + declaration: 'export interface ToolExecutionResult {\n callId: CallId;\n content: ContentBlock[];\n isError: boolean;\n error?: ToolErrorInfo;\n additionalContext?: HookContext;\n meta?: unknown;\n}', + }, + { + name: 'ToolProviderResult', + declaration: 'export interface ToolProviderResult {\n schemas: ToolSchema[];\n knownNames?: readonly string[];\n}', + }, + { + name: 'ToolRestriction', + declaration: 'export interface ToolRestriction {\n allow?: string[];\n deny?: string[];\n}', + }, + { + name: 'ToolResult', + declaration: 'export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: unknown;\n}', + }, + { + name: 'ToolResultBlock', + declaration: 'export interface ToolResultBlock {\n type: \'tool-result\';\n toolCallId: CallId;\n content: ContentBlock[];\n isError?: boolean;\n}', + }, + { + name: 'ToolResultView', + declaration: 'export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;', + }, + { + name: 'ToolSchema', + declaration: 'export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n}', + }, + { + name: 'TurnEndReason', + declaration: 'export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];', + }, + { + name: 'TurnEndReasonMap', + declaration: 'export interface TurnEndReasonMap {\n completed: {\n kind: \'completed\';\n };\n aborted: {\n kind: \'aborted\';\n reason?: string;\n };\n error: {\n kind: \'error\';\n step: number;\n message: string;\n code?: string;\n };\n disposed: {\n kind: \'disposed\';\n };\n \'max-tokens\': {\n kind: \'max-tokens\';\n };\n rejected: {\n kind: \'rejected\';\n reason: string;\n };\n interrupted: {\n kind: \'interrupted\';\n };\n}', + }, + { + name: 'TurnTrigger', + declaration: 'export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap];', + }, + { + name: 'TurnTriggerMap', + declaration: 'export interface TurnTriggerMap {\n message: {\n kind: \'message\';\n source: MessageSource;\n };\n injection: {\n kind: \'injection\';\n source: MessageSource;\n };\n}', + }, + { + name: 'UserInteractionProvider', + declaration: 'export interface UserInteractionProvider {\n ask(request: AskUserQuestionRequest): Promise;\n}', + }, + { + name: 'WebExecContext', + declaration: 'export interface WebExecContext {\n readonly signal?: AbortSignal;\n}', + }, + { + name: 'WebFetchBody', + declaration: 'export type WebFetchBody = {\n readonly kind: \'html\';\n readonly content: string;\n} | {\n readonly kind: \'text\';\n readonly content: string;\n};', + }, + { + name: 'WebFetchProvider', + declaration: 'export interface WebFetchProvider {\n readonly id: string;\n status(): WebProviderStatus;\n fetch(request: WebFetchRequest, exec?: WebExecContext): Promise;\n}', + }, + { + name: 'WebFetchRequest', + declaration: 'export interface WebFetchRequest {\n readonly url: string;\n readonly timeoutMs?: number;\n}', + }, + { + name: 'WebFetchResult', + declaration: 'export interface WebFetchResult {\n readonly providerId: string;\n readonly url: string;\n readonly statusCode: number;\n readonly body: WebFetchBody;\n readonly truncated: boolean;\n}', + }, + { + name: 'WebProviderStatus', + declaration: 'export type WebProviderStatus = {\n readonly available: true;\n} | {\n readonly available: false;\n readonly reason: \'missing-credential\' | \'misconfigured\';\n};', + }, + { + name: 'WebSearchProvider', + declaration: 'export interface WebSearchProvider {\n readonly id: string;\n status(): WebProviderStatus;\n search(request: WebSearchRequest, exec?: WebExecContext): Promise;\n}', + }, + { + name: 'WebSearchRequest', + declaration: 'export interface WebSearchRequest {\n readonly query: string;\n readonly maxResults?: number;\n}', + }, + { + name: 'WebSearchResult', + declaration: 'export interface WebSearchResult {\n readonly providerId: string;\n readonly query: string;\n readonly content?: string;\n readonly sources: readonly WebSearchSource[];\n readonly truncated: boolean;\n}', + }, + { + name: 'WebSearchSource', + declaration: 'export interface WebSearchSource {\n readonly url: string;\n readonly title?: string;\n readonly snippet?: string;\n readonly publishedAt?: string;\n}', + }, +] + +/** The inherited `ctx` surface (cordis core + loader/hmr/timer), in curated order. */ +export const INHERITED_CTX_API: readonly InheritedApiEntry[] = [ + { name: 'ctx.on / ctx.once', summary: 'Register an event listener (disposable).' }, + { name: 'ctx.emit / ctx.parallel / ctx.serial / ctx.bail / ctx.waterfall', summary: 'Dispatch an event (sync / awaited / first-bail / veto-chain).' }, + { name: 'ctx.plugin / ctx.inject', summary: 'Load a plugin / declare required services.' }, + { name: 'ctx.effect', summary: 'Register a disposable side effect tied to the fiber.' }, + { name: 'ctx.get / ctx.set / ctx.provide / ctx.accessor / ctx.mixin', summary: 'Low-level service-store access and binding.' }, + { name: 'ctx.extend / ctx.isolate / ctx.intercept', summary: 'Derive a child context (scoped services / isolation / interception).' }, + { name: 'ctx.root / ctx.scope / ctx.fiber / ctx.registry / ctx.reflect / ctx.events / ctx.logger', summary: 'Ambient handles onto the running context graph.' }, + { name: 'ctx.timer (+ interval / timeout / throttle / debounce / setTimeout / setInterval)', summary: 'Disposable timer helpers. The `timer` key is provided at runtime; the six helpers are mixed onto ctx directly (declared via Pick).' }, + { name: 'ctx.loader', summary: 'The config Loader that booted the app (present under the loader).' }, + { name: 'ctx.hmr', summary: 'The hot-module-reload watcher (present under the hmr plugin).' }, +] diff --git a/packages/cordis/tool-cordis/src/fiber-state.ts b/packages/cordis/tool-cordis/src/fiber-state.ts new file mode 100644 index 0000000000..2b1ee166b7 --- /dev/null +++ b/packages/cordis/tool-cordis/src/fiber-state.ts @@ -0,0 +1,39 @@ +/** + * Runtime mirror of the cordis `FiberState` const enum plus human-readable + * labels, shared by the mount lifecycle (state reporting) and the inspect + * renderers (plugin-list and mount-table labels). + * + * Cordis exposes `FiberState` as a `const enum`: there is no runtime object for + * Node's type-stripping runner to import, so the members are mirrored here as + * values — each typed (via the type-only import) as the cordis enum member it + * mirrors, so enum-typed reads like `fiber.state` compare against them under a + * shared enum type. Source of truth: vendor/cordis/src/fiber.ts (pinned; drift + * only happens through a deliberate vendor sync). + * + * @module @deepseek-ai/dsh-tool-cordis/fiber-state + */ + +import type { FiberState as FiberStateEnum } from 'cordis' + +/** Value mirror of the cordis `FiberState` const enum (see the module doc for why a mirror exists). */ +export const FiberState = { + PENDING: 0 as FiberStateEnum.PENDING, + LOADING: 1 as FiberStateEnum.LOADING, + ACTIVE: 2 as FiberStateEnum.ACTIVE, + FAILED: 3 as FiberStateEnum.FAILED, + DISPOSED: 4 as FiberStateEnum.DISPOSED, + UNLOADING: 5 as FiberStateEnum.UNLOADING, +} as const + +/** The cordis `FiberState` enum type, re-exported so mirror consumers need one import. */ +export type FiberState = FiberStateEnum + +/** Human-readable label for each {@link FiberState}, keyed by member (inlining-safe — no reverse mapping). */ +export const STATE_LABELS: Record = { + [FiberState.PENDING]: 'pending', + [FiberState.LOADING]: 'loading', + [FiberState.ACTIVE]: 'active', + [FiberState.FAILED]: 'failed', + [FiberState.DISPOSED]: 'disposed', + [FiberState.UNLOADING]: 'unloading', +} diff --git a/packages/cordis/tool-cordis/src/guard.ts b/packages/cordis/tool-cordis/src/guard.ts new file mode 100644 index 0000000000..33d647db2b --- /dev/null +++ b/packages/cordis/tool-cordis/src/guard.ts @@ -0,0 +1,453 @@ +/** + * The registration boundary between sandboxed mount code and the real runtime: + * SchemaSpec normalization + validation with teaching errors, the + * marker-guarded `harness.defineTool` / `harness.registerTool` pair, the + * SANDBOX CONTEXT FAÇADE a mounted plugin's `apply` receives in place of the + * real `ctx`, and the plugin-shape helpers the mount lifecycle narrows sandbox + * return values with. + * + * The façade is a WHITELIST, not a pass-through proxy. Mount code needs to do + * exactly four things — register a tool, listen to an event, provide a service, + * call an injected service (timers included) — so the façade exposes only those + * verbs and the injected services, each object-valued service individually + * wrapped (a primitive provided value passes through as-is — see + * {@link sandboxContext}). Every framework plumbing member (`root`, `parent`, `scope`, `fiber`, `reflect`, `registry`, + * `events`, `extend`, `isolate`, `intercept`, `plugin`, `set`, `mixin`, …) is + * DENIED with a teaching error rather than passed through. This closes an + * entire escape class at once: a pass-through proxy that only special-cased + * `ctx.tools` still handed back the raw context through `ctx.root`, + * `ctx.extend()`, or a service instance's `.ctx`, and mount code could then + * `ctx.root.tools.register({…})` to bypass the marker check and host-realm + * normalization — a raw vm-realm result then errors a real agent turn at the + * session-log plainness check. The whitelist has no such hole: there is no + * context-valued member to reach, and any injected-service method that returns + * a `Context` is rejected (harness services never do — see {@link denyContext}). + * + * Two realm facts drive the tool path. Objects built inside the vm carry the vm + * realm's `Object.prototype`, and the session log's append-time plainness check + * (`dsh-session`'s `isJsonValue`, a prototype-identity comparison) rejects + * foreign-realm data — so every dynamic tool's `execute` return is JSON + * round-tripped into the host realm and shape-checked against the two + * `ToolExecuteReturn` forms before it reaches the registry (the registry + * trusts the shape blindly — it spreads `result.content`, so an unvalidated + * `{ content: 'ok' }` would enter the session log as `['o','k']` and silently + * corrupt the next model request), and the schema itself is rebuilt as fresh + * host-realm objects. And a malformed tool + * schema must fail at REGISTRATION, not when a later request assembles it — so + * dynamic tool registration accepts only definitions produced by the sandbox's + * `harness.defineTool`, which normalizes `parameters` up front. + * + * Normalize, don't lecture, where the input has exactly one meaning: models + * write the JSON-Schema dialect by strong prior (the `{ type: 'object', + * properties, required: […] }` wrapper, `type: 'integer'`, `required: false`), + * and each rejection costs a model turn — so those convert to the SchemaSpec + * DSL silently, and only genuinely meaningless input (an unknown type, a + * non-boolean `required`) is rejected, with the error enumerating the valid + * vocabulary. + * + * @module @deepseek-ai/dsh-tool-cordis/guard + */ + +import { Context } from 'cordis' +import type { Plugin } from 'cordis' +import { scopeOf } from '@deepseek-ai/dsh-scope' +import { defineTool } from '@deepseek-ai/dsh-tools' +import type { ToolDefinition, ToolExecuteReturn } from '@deepseek-ai/dsh-tools' + +const DYNAMIC_TOOL = Symbol('tool-cordis.dynamic-tool') +const SCHEMA_TYPES = new Set(['string', 'number', 'boolean', 'object', 'array']) +const VALID_TYPES = '\'string\' | \'number\' | \'boolean\' | \'object\' | \'array\'' + +type DynamicToolDefinition = ToolDefinition & { [DYNAMIC_TOOL]: true } +type DynamicToolMarker = { [DYNAMIC_TOOL]?: unknown } + +function isPlainRecord(value: unknown): value is Record { + return Object.prototype.toString.call(value) === '[object Object]' +} + +/** + * Normalize a sandbox-provided `parameters` value into a fresh host-realm + * SchemaSpec. Accepts the DSL directly, or the JSON-Schema-style + * `{ type: 'object', properties, required: […] }` wrapper models write by + * prior — the wrapper unwraps and its `required` array becomes per-property + * flags (see the module doc). + */ +function normalizeSchemaSpec(value: unknown, path = 'parameters'): Record { + if (!isPlainRecord(value)) { + throw new Error(`harness.defineTool ${path} must be a SchemaSpec object`) + } + let entries = value + const requiredNames = new Set() + if (value.type === 'object' && isPlainRecord(value.properties)) { + if (Array.isArray(value.required)) { + for (const name of value.required) requiredNames.add(name) + } + entries = value.properties + } + const spec: Record = {} + for (const [key, prop] of Object.entries(entries)) { + spec[key] = normalizeSchemaProp(prop, `${path}.${key}`, requiredNames.has(key)) + } + return spec +} + +/** Normalize one property: `integer` → `number`, `required: false` → absent, nested wrappers unwrapped recursively. */ +function normalizeSchemaProp(value: unknown, path: string, forceRequired = false): Record { + if (!isPlainRecord(value)) { + throw new Error(`harness.defineTool ${path} must be a SchemaSpec property object`) + } + const type = value.type === 'integer' ? 'number' : value.type + if (!SCHEMA_TYPES.has(type)) { + throw new Error(`harness.defineTool ${path} must declare a valid type: ${VALID_TYPES} (got ${JSON.stringify(value.type)})`) + } + // On an object property a JSON-Schema-style `required` ARRAY names required + // children (handled by the nested unwrap below); everywhere else `required` + // must be a boolean, and `false` simply reads as optional. + const nestedRequiredArray = type === 'object' && Array.isArray(value.required) + if (value.required !== undefined && typeof value.required !== 'boolean' && !nestedRequiredArray) { + throw new Error(`harness.defineTool ${path}.required must be a boolean when present`) + } + const prop: Record = { type } + if (forceRequired || value.required === true) prop.required = true + if (typeof value.description === 'string') prop.description = value.description + if (Array.isArray(value.enum)) prop.enum = [...value.enum as unknown[]] + if (value.default !== undefined) prop.default = value.default + if (value.properties !== undefined) { + if (type !== 'object') { + throw new Error(`harness.defineTool ${path}.properties is only valid for type "object"`) + } + // Re-wrap so the nested unwrap applies a nested `required` array too. + prop.properties = normalizeSchemaSpec( + { type: 'object', properties: value.properties, required: value.required }, + `${path}.properties`, + ) + } + if (value.items !== undefined) { + if (type !== 'array') { + throw new Error(`harness.defineTool ${path}.items is only valid for type "array"`) + } + prop.items = normalizeSchemaProp(value.items, `${path}.items`) + } + return prop +} + +function markDynamicTool(tool: ToolDefinition): DynamicToolDefinition { + Object.defineProperty(tool, DYNAMIC_TOOL, { value: true }) + return tool as DynamicToolDefinition +} + +function assertDynamicTool(tool: unknown): asserts tool is DynamicToolDefinition { + if (!isPlainRecord(tool) || (tool as DynamicToolMarker)[DYNAMIC_TOOL] !== true) { + throw new Error('dynamic tool registration must use a tool returned by harness.defineTool(...)') + } +} + +/** + * Structurally a content block, checked AFTER the JSON round-trip: a plain + * object carrying a string `type` tag. Deliberately nothing deeper — the + * ContentBlock union is merge-extensible (an unknown tag must pass), and every + * downstream consumer dispatches on `type` and falls through unknowns. + */ +function isContentBlockShape(value: unknown): boolean { + return isPlainRecord(value) && typeof value.type === 'string' +} + +/** + * How much of an invalid execute return the teaching error echoes back — a + * huge blob would burn the model turn the error is trying to save. + */ +const RETURN_PREVIEW_LIMIT = 120 + +/** + * Compact JSON preview of an invalid execute return for the teaching error + * (`String(…)` for the un-stringifiable undefined case), truncated to + * {@link RETURN_PREVIEW_LIMIT}. + */ +function describeReturn(value: unknown): string { + // JSON.stringify is TYPED as always returning string, but it yields + // undefined for an undefined input (the routed forgot-return case) — the + // assertion widens the type back to the runtime truth. + const json = JSON.stringify(value) as string | undefined + if (json === undefined) return String(value) + return json.length > RETURN_PREVIEW_LIMIT ? `${json.slice(0, RETURN_PREVIEW_LIMIT)}…` : json +} + +/** + * Validate a round-tripped `execute` return against the two shapes + * {@link ToolExecuteReturn} allows: an ARRAY of content blocks, or + * `{ content: blocks, meta? }`. The registry trusts the shape blindly — it + * spreads `result.content`, so an unvalidated `{ content: 'ok' }` would enter + * the session log as `['o','k']` and silently corrupt the next model request — + * so a wrong shape fails THIS call with a teaching error instead. + */ +function assertExecuteReturn(value: unknown): ToolExecuteReturn { + if (Array.isArray(value) && value.every(isContentBlockShape)) { + return value as ToolExecuteReturn + } + if (isPlainRecord(value) && Array.isArray(value.content) && value.content.every(isContentBlockShape)) { + return value as ToolExecuteReturn + } + throw new Error( + `execute returned ${describeReturn(value)} — a tool's execute must return an ARRAY of content blocks, never a bare string:\n` + + ' ✓ return [{ type: \'text\', text: someString }]\n' + + ' ✓ return { content: [{ type: \'text\', text: someString }], meta: anyJsonValue }', + ) +} + +/** + * The `harness.defineTool` handed into the sandbox: the real DSL, with + * `parameters` normalized into a fresh host-realm SchemaSpec (JSON-Schema + * wrapper unwrapped, `integer` mapped, `required: false` dropped) and the + * tool's `execute` return normalized into the host realm via a JSON round-trip + * (see the module doc). The round-trip projects the return onto exactly what + * the log would durably store, and {@link assertExecuteReturn} then vets that + * projection — so a non-JSON-serializable OR wrong-shape return surfaces as + * that one call's teaching error instead of poisoning the turn. + * @param options - the standard `defineTool` options; `parameters` may be the SchemaSpec DSL or a JSON-Schema-style wrapper. + * @returns the marker-tagged definition `harness.registerTool` (and the guarded `ctx.tools.register`) accepts. + */ +export function sandboxDefineTool(options: Parameters[0]): ToolDefinition { + const parameters = normalizeSchemaSpec((options as { parameters?: unknown }).parameters) + const tool = defineTool({ ...options, parameters } as Parameters[0]) + const execute = tool.execute.bind(tool) + return markDynamicTool({ + ...tool, + async execute(args, exec) { + // JSON.stringify yields NO JSON for an undefined (or function/symbol) + // return despite its string-typed signature — route that into + // assertExecuteReturn's teaching error rather than letting JSON.parse + // throw its cryptic '"undefined" is not valid JSON'. + const json = JSON.stringify(await execute(args, exec)) as string | undefined + return assertExecuteReturn(json === undefined ? undefined : JSON.parse(json) as unknown) + }, + }) +} + +/** + * The `harness.registerTool` handed into the sandbox: registers a + * marker-verified dynamic tool on the given context's registry. + * @param ctx - the (guarded) context whose `tools` service receives the tool. + * @param tool - a definition produced by {@link sandboxDefineTool}; anything else is rejected. + * @returns the registry disposer for the registration. + */ +export function sandboxRegisterTool(ctx: Context, tool: unknown): () => Promise | void { + assertDynamicTool(tool) + return ctx.tools.register(tool) +} + +/** + * The verbs a mounted plugin may reach through the sandbox `ctx` façade, + * beyond its injected services. `on`/`once` observe events, `provide` exposes + * a service to other mounts, and the timer helpers schedule work — each a + * fiber effect that unwinds on unmount. Everything else on a real cordis `ctx` + * is framework plumbing and is denied. Forwarded LAZILY: the timer helpers are + * mixin accessors that throw `without inject` when read on a plugin that did + * not inject `timer`, so the façade reads `ctx[verb]` only at call time — the + * plugin that never touches a timer never trips that, and one that does gets + * cordis's own inject error at the call site. + */ +const CTX_VERBS = new Set(['on', 'once', 'provide', 'timeout', 'interval', 'setTimeout', 'setInterval', 'throttle', 'debounce']) + +/** + * The tool-registry façade: `register` (marker-guarded) plus READ-ONLY + * metadata (`schemas`, and `get` returning a schema view, never the live + * `ToolDefinition`). Exposing the raw definition would hand mount code the + * tool's `execute` function, letting it call another tool directly and bypass + * `ToolRegistry.execute` — the pre/post-execute waterfall (permission gates, + * accounting) and result normalization. So `get` returns the same + * name/description/parameters view as `schemas()`, and nothing invocable. + */ +function sandboxTools(ctx: Context): Record { + // Reads resolve through the MOUNT's own scope (`scopeOf(ctx)`), mirroring + // where the façade's `register` lands its writes (the calling context's + // layer): mount code always sees the tools its own world sees — the global + // view for today's global mounts, its agent's view if a mount ever runs + // under an agent scope. + return { + register: (tool: unknown): (() => Promise | void) => sandboxRegisterTool(ctx, tool), + schemas: () => ctx.tools.schemas(scopeOf(ctx)), + get: (name: string) => ctx.tools.schemas(scopeOf(ctx)).find(schema => schema.name === name), + } +} + +/** + * Reject any injected-service return that is a cordis `Context`. Harness + * services return data, never a context; a value that is one would be a + * fresh, unguarded handle back into the runtime — the exact escape the façade + * exists to close — so it fails loud instead of reaching sandbox code. + */ +function denyContext(value: unknown, service: string): unknown { + if (value instanceof Context) { + throw new Error( + `service "${service}" returned a cordis Context, which the sandbox does not expose. ` + + 'Operate through your own plugin ctx (ctx.on / ctx.provide / ctx.tools.register) ' + + 'and the services you inject — never another context.', + ) + } + return value +} + +/** + * Wrap an injected service so its methods forward to the real instance but + * their return values pass through {@link denyContext}. Non-function members + * (plain data) pass through as-is; a returned Promise is guarded on resolve. + */ +function guardedService(service: object, name: string): unknown { + return new Proxy(service, { + get(target, prop) { + const value = Reflect.get(target, prop, target) as unknown + if (typeof value !== 'function') return denyContext(value, name) + return (...args: unknown[]): unknown => { + const result = Reflect.apply(value, target, args) as unknown + if (result instanceof Promise) return result.then(v => denyContext(v, name)) + return denyContext(result, name) + } + }, + }) +} + +/** + * The service names a plugin declared in `inject`, as a lookup set. Whatever + * declaration style the plugin used — an `inject: ['bash', 'tools']` array or + * the `{ required, optional }` object form — cordis resolves it into a single + * name-keyed map on the fiber before `apply` runs (`{ bash: null, tools: null }`), + * so the gate just reads that map's keys. A mount may reach only the services + * it declared — that is what lets cordis park the mount when a declared + * provider unmounts. + */ +function declaredInjects(ctx: Context): Set { + return new Set(Object.keys(ctx.fiber.inject)) +} + +/** + * The sandbox context façade handed to a mounted plugin's `apply` in place of + * the real `ctx`. A whitelist (see the module doc): the registration/eventing + * verbs, the timer helpers, a guarded `tools`, and injected services resolved + * through a guarded `get` / property access. A service is reachable only if the + * plugin DECLARED it in `inject` — an undeclared service is denied even when a + * global provider exists, so cordis's activation/unload semantics (park the + * mount when a declared provider goes away) actually bind. Every + * framework-plumbing member is denied with a teaching error; there is no + * context-valued member to reach. + */ +function sandboxContext(ctx: Context): Context { + const tools = sandboxTools(ctx) + const declared = declaredInjects(ctx) + // A framework member or an undeclared service — distinguish the two so the + // error teaches the right fix (declare it in inject vs it is withheld). + const denyRead = (prop: string): never => { + if (ctx.get(prop) !== undefined) { + throw new Error( + `service "${prop}" is not injected. Declare it: inject: ['${prop}', …] on your plugin, ` + + 'so cordis parks this mount if the provider is later unmounted.', + ) + } + throw new Error( + `sandbox ctx does not expose "${prop}". Available: ctx.tools.register / ctx.on / ctx.provide / ` + + 'the timer helpers (ctx.setTimeout, ctx.interval, …) and any service you declared in inject. ' + + 'Framework internals (root, fiber, registry, extend, plugin, …) are withheld by design.', + ) + } + // Read a service for either access path (property or `get`). `tools` is the + // façade's own surface. An UNDECLARED name is denied with the teaching + // error; a DECLARED one resolves to the guarded service. A declared inject + // is required in cordis (the fiber only activates once every declared + // service is live), so at `apply`/`execute` time `ctx.get(name)` is present + // for a declared name — no undefined case to handle here. `provide()` + // accepts ANY value though (cross-mount composition advertises + // `ctx.provide('name', value)`), so a primitive or null value passes + // through unwrapped: Proxy throws on a non-object target, and only an + // object can carry a method that hands back a Context. + const readService = (name: string): unknown => { + if (name === 'tools') return tools + if (!declared.has(name)) return denyRead(name) + const service = denyContext(ctx.get(name), name) + if (service === null || (typeof service !== 'object' && typeof service !== 'function')) return service + return guardedService(service, name) + } + const get = (name: string): unknown => readService(name) + return new Proxy({}, { + get(_target, prop) { + if (prop === 'tools') return tools + if (prop === 'get') return get + if (typeof prop !== 'string') return undefined + // Lazy verb forwarder — reads `ctx[verb]` only when called, so a plugin + // that never uses a timer never triggers the timer mixin's inject check + // (cordis raises its own "without inject" error there for undeclared timer use). + if (CTX_VERBS.has(prop)) { + return (...args: unknown[]): unknown => { + const method = ctx[prop as keyof Context] + return Reflect.apply(method as (...a: unknown[]) => unknown, ctx, args) + } + } + return readService(prop) + }, + // A façade is not the real ctx; block writes rather than let mount code + // stash state on a throwaway object and think it persisted. + set(_target, prop) { + throw new Error(`sandbox ctx is read-only; cannot assign "${String(prop)}"`) + }, + // `in` reflects reachability: the façade surface plus DECLARED services + // (whether or not currently live). Does not resolve/wrap — no throw. + has: (_target, prop) => prop === 'tools' || prop === 'get' + || (typeof prop === 'string' && (CTX_VERBS.has(prop) || declared.has(prop))), + }) as unknown as Context +} + +/** + * Narrow an arbitrary sandbox return value to a mountable cordis plugin: a + * function, or an object with an `apply` function. (A bare function passes the + * first arm, so the object arm never sees `Function.prototype.apply`.) + * @param value - whatever the mount code returned. + * @returns whether the value is mountable via `ctx.plugin`. + */ +export function isPlugin(value: unknown): value is Plugin { + if (typeof value === 'function') return true + return typeof value === 'object' && value !== null + && typeof (value as { apply?: unknown }).apply === 'function' +} + +/** + * Wrap a plugin so its `apply` receives the sandbox context façade instead of + * the real `ctx` (see {@link sandboxContext} and the module doc). Both + * function-form and object-form plugins go through the same wrap; the plugin's + * own `inject` declaration is preserved (cordis reads it from the plugin + * object, and pending/active gating happens on the real fiber before `apply` + * runs), so cross-mount provide/inject works unmodified. + * + * `ctx.effect(customCleanup)` is deliberately absent from the façade for now — + * `on` / `provide` / `tools.register` cover every mount seen so far, and each + * is already a fiber effect. FIXME(sandbox-effect): expose a guarded `effect` + * once a real mount needs a bespoke disposer. + * @param plugin - the plugin the mount code returned. + * @returns an equivalent plugin whose `apply` sees the sandbox context façade. + */ +export function guardedPlugin(plugin: Plugin): Plugin { + if (typeof plugin === 'function') { + const functionPlugin = plugin as (ctx: Context, config?: unknown) => unknown + return { + name: pluginName(plugin), + apply(ctx: Context, config?: unknown) { + return functionPlugin(sandboxContext(ctx), config) + }, + } + } + const objectPlugin = plugin as { apply(ctx: Context, config?: unknown): unknown } + return { + ...plugin, + apply(ctx: Context, config?: unknown) { + return objectPlugin.apply(sandboxContext(ctx), config) + }, + } +} + +/** + * Display name for a mounted plugin: its `name` property, else anonymous. + * @param plugin - the plugin the mount code returned. + * @returns the human-readable name used in mount results and inspect output. + */ +export function pluginName(plugin: Plugin): string { + const named = (plugin as { name?: unknown }).name + if (typeof named === 'string' && named.length > 0) return named + return '' +} diff --git a/packages/cordis/tool-cordis/src/index.ts b/packages/cordis/tool-cordis/src/index.ts new file mode 100644 index 0000000000..409123f7c6 --- /dev/null +++ b/packages/cordis/tool-cordis/src/index.ts @@ -0,0 +1,238 @@ +/** + * The self-referential cordis toolset: three model-facing tools that let the + * agent inspect and MODIFY the live cordis runtime it is running inside. + * + * - `cordis_inspect` — read-only: provided services, the flat plugin list + * with lifecycle states, registered tools, the dynamic mounts, and the + * catalog-backed `api` / `events` references. + * - `cordis_mount` — evaluate model-written code in a `node:vm` sandbox; the + * code returns a cordis plugin, which is mounted as a child of a dedicated + * `cordis-dynamic` group fiber and tracked under an id (`dyn-1`, `dyn-2`, …). + * - `cordis_unmount` — dispose one dynamic mount by id, awaiting quiescence. + * + * Everything the model's plugin registers (listeners via `ctx.on`, tools via + * `harness.registerTool`, services via `ctx.provide`) is an effect on the + * dynamic fiber, so unmounting — or disposing this plugin itself (HMR) — cleans + * it all up through the ordinary cordis lifecycle. The group fiber exists + * exactly so the dynamic mounts form ONE subtree, disposed as a unit with + * this plugin. Design home: + * docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md. + * + * The vm sandbox guards against ACCIDENTAL global pollution only, and the `ctx` + * a mounted plugin's `apply` receives is a WHITELIST façade (register a tool, + * observe events, provide/consume services, use timers — framework internals + * withheld; see the guard module). Neither is a security boundary: the verbs + * the façade DOES expose reach the real runtime unsandboxed (a mounted tool can + * shell out through `ctx.bash`), so a deployment loads this plugin as + * deliberately as it grants a bash tool. Design home: + * docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md. + * + * Plugin export shape: named exports, NO default. The cordis Loader's + * `unwrapExports` does `exports.default ?? exports`, so a stray default would + * collapse the module to the bare `apply` and drop `inject`, crashing at load + * (see docs/postmortem/0001). + * + * @module @deepseek-ai/dsh-tool-cordis + */ + +import type { Context } from 'cordis' +import z from 'schemastery' +import { defineTool } from '@deepseek-ai/dsh-tools' +import { STATE_LABELS } from './fiber-state.ts' +import { isPlugin, pluginName } from './guard.ts' +import { describeApi, describeDynamic, describeEvents, describePlugins, describeServices, describeTools } from './inspect.ts' +import { missingServices, mountDynamic } from './mount.ts' +import type { DynamicMount } from './mount.ts' +import { presentInspectCall, presentMountCall, presentUnmountCall } from './present.ts' +import { createSandbox, evaluateMountCode } from './sandbox.ts' + +export const name = 'tool-cordis' +export const inject = ['tools'] + +/** Config for the tool-cordis plugin: the sandbox evaluation bound. */ +export interface Config { + /** + * Milliseconds the SYNCHRONOUS portion of mount code may run in the vm + * before evaluation is aborted (default 5000). An async body escapes this + * bound — see docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md for the trust stance. + */ + vmTimeoutMs?: number +} + +/** Schemastery validator for {@link Config}: `vmTimeoutMs` must be at least 1 (defaults to 5000). */ +export const Config: z = z.object({ + vmTimeoutMs: z.number().min(1).default(5000), +}) + +/** {@link Config} with every defaulted field present, as schemastery resolves it at load. */ +type ResolvedConfig = Required + +/** + * Mount the three cordis tools on `ctx.tools` and create the `cordis-dynamic` + * group fiber every dynamic mount hangs under. + * @param ctx - the plugin context (`tools` injected). + * @param config - the schemastery-resolved {@link Config}. + */ +export function apply(ctx: Context, config: Config): void { + const { vmTimeoutMs } = config as ResolvedConfig + // The one group fiber every dynamic mount hangs under. Mounted here (a child + // of this plugin's fiber) so disposing tool-cordis cascades over the whole + // dynamic subtree — the ordinary parent→child fiber lifecycle, nothing extra. + const group = ctx.plugin({ name: 'cordis-dynamic', apply: () => {} }) + + const mounts = new Map() + let nextId = 1 + + ctx.tools.register(defineTool({ + name: 'cordis_inspect', + description: + 'Inspect the live cordis runtime that is running THIS agent. Read-only. ' + + 'Sections: `services` (every provided ctx service and the plugin fiber that owns it), ' + + '`plugins` (a flat list of the loaded plugins with their lifecycle states), ' + + '`tools` (the model-facing tools currently registered, i.e. what you can call), ' + + '`dynamic` (plugins you mounted via cordis_mount: id, name, state, provided services, awaited services), ' + + '`api` (method signatures AND argument/return type shapes for every LIVE service — read this before writing plugin code that calls a service), ' + + '`events` (every harness event with its dispatch mode and exact signature — pick listener targets here). ' + + 'Omit `what` to get all six sections.', + parameters: { + what: { + type: 'string', + enum: ['services', 'plugins', 'tools', 'dynamic', 'api', 'events'], + description: 'Limit the report to one section. Omit for all sections.', + }, + }, + execute(args, exec): Promise<{ type: 'text'; text: string }[]> { + const sections: [heading: string, body: () => string[]][] = [ + ['services', () => describeServices(ctx)], + ['plugins', () => describePlugins(ctx)], + // The calling agent's view: scoped/shadowed tools included, restricted + // globals absent — "what you can call", not the global registry. + ['tools', () => describeTools(ctx, exec.agent)], + ['dynamic', () => describeDynamic(ctx, mounts)], + ['api', () => describeApi(ctx)], + ['events', () => describeEvents()], + ] + const selected = sections.filter(([heading]) => args.what === undefined || args.what === heading) + const text = selected + .map(([heading, body]) => `## ${heading}\n${body().join('\n')}`) + .join('\n\n') + return Promise.resolve([{ type: 'text', text }]) + }, + presentCall: presentInspectCall, + })) + + ctx.tools.register(defineTool({ + name: 'cordis_mount', + description: + 'Mount a NEW cordis plugin into the live runtime that is running THIS agent ' + + '(self-modification). `code` runs as the body of an async JavaScript function ' + + 'in an isolated sandbox and MUST `return` a plugin. Two forms: ' + + 'FUNCTION form `return (ctx) => { … }` — declares no inject, so it can register ' + + 'tools, listen to events, and provide services, but reaching ANY service (e.g. ' + + 'ctx.bash) throws; use it only when you need no services. ' + + 'OBJECT form `return { name?, inject: [\'bash\', \'llm\', …], apply(ctx) { … } }` ' + + '— declares dependencies, and cordis activates the plugin only after the ' + + 'services exist; PREFER this form. You may reach ONLY the services you list in ' + + 'inject: an undeclared service throws even if it exists, because an undeclared ' + + 'dependency would not be cleaned up if its provider is unmounted. ' + + 'BEFORE calling a service from your code, read cordis_inspect what:"api" — it lists ' + + 'method signatures AND the type shapes of their arguments/returns (do not guess a ' + + 'field\'s type; e.g. a bash run\'s stdout is an object, not a string). ' + + 'Inside `apply`, use the standard cordis API: `ctx.on(event, listener)` to observe ' + + 'events (see cordis_inspect what:"events"), or call ' + + '`harness.registerTool(ctx, harness.defineTool({ name, description, parameters: ' + + '{ text: { type: \'string\', required: true } }, async execute(args) { … } }))` ' + + 'to give yourself a new tool — it becomes callable on your NEXT step. ' + + 'Tool parameters: each key IS a property — { type: \'string\'|\'number\'|\'boolean\'|\'object\'|\'array\', ' + + 'required?: true, description?, enum?, items?, properties? }; a JSON-Schema-style ' + + '{ type: \'object\', properties, required: […] } wrapper and type \'integer\' are also accepted and normalized. A ' + + 'tool\'s `execute` MUST return an ARRAY of content blocks, e.g. `return ' + + '[{ type: \'text\', text: someString }]` — never a bare string. ' + + 'Mounts can COMPOSE: one plugin may `ctx.provide(\'name\', value)` a service and ' + + 'another may declare `inject: [\'name\']` to consume it — the consumer stays pending ' + + 'until the provider exists and returns to pending when the provider is unmounted. ' + + 'Everything registered inside `apply` is cleaned up automatically on unmount. ' + + 'Sandbox globals: `console` (tagged `[cordis:]`, writes through to the harness ' + + 'terminal), `harness.defineTool`, `harness.registerTool`, ' + + '`btoa`, `atob`, `TextEncoder`, `TextDecoder`. ' + + 'Node APIs are DISABLED — do filesystem/network/timer work through the cordis services, ' + + 'never Node built-ins: `require`, `setTimeout`/`setInterval`, and `fetch` throw redirect ' + + 'errors; `process` and `Buffer` are undefined. Instead use inject: [\'fs\'] + ctx.fs for ' + + 'files, inject: [\'web\'] + ctx.web for HTTP, inject: [\'bash\'] + ctx.bash for processes, ' + + 'and inject: [\'timer\'] + ctx.setTimeout/ctx.setInterval for timing (fiber effects, ' + + 'auto-cleaned on unmount) — cordis_inspect what:"api" shows what THIS runtime provides. ' + + 'Write PLAIN JavaScript, not TypeScript (no `as`, no type annotations). ' + + 'Cautions: (1) waterfall events (e.g. tools/pre-execute) hand the listener a ' + + 'trailing `next` callback which MUST be called — returning without `next()` ' + + 'VETOES the call; prefer plain notification events unless you intend to ' + + 'intercept. (2) Never await something that only resolves after the current ' + + 'turn (your code runs INSIDE a tool call of that turn — it would deadlock). ' + + '(3) Your `ctx` is a restricted façade: you can register tools, observe ' + + 'events, provide/consume services, and use timers, but framework internals ' + + '(ctx.root, ctx.fiber, ctx.extend, ctx.plugin, …) are withheld. It is not a ' + + 'security boundary though — the services you inject (e.g. ctx.bash) reach the ' + + 'real runtime.', + parameters: { + code: { + type: 'string', + required: true, + description: 'Body of an async JS function; must `return` the plugin to mount.', + }, + }, + async execute(args) { + const id = `dyn-${nextId++}` + const sandbox = createSandbox(id) + const evaluated = await evaluateMountCode(sandbox, args.code, id, vmTimeoutMs) + if (!isPlugin(evaluated)) { + if (evaluated === undefined) { + throw new Error( + 'mount code returned `undefined` — did you forget `return`?\n' + + ' ✓ return (ctx) => { … }\n' + + ' ✓ return { name: \'…\', inject: […], apply(ctx) { … } }', + ) + } + throw new Error( + 'mount code must `return` a plugin: a function, or an object with an `apply(ctx)` method', + ) + } + const fiber = await mountDynamic(group, evaluated) + mounts.set(id, { fiber, pluginName: pluginName(evaluated) }) + // A settled fiber that is not ACTIVE is waiting on unsatisfied inject — + // legal cordis semantics (it activates when the service appears), so keep + // it mounted but tell the model what it is waiting for. + const missing = missingServices(ctx, fiber) + const state = STATE_LABELS[fiber.state] + const note = missing.length > 0 + ? ` — waiting for service(s): ${missing.join(', ')} (activates when provided)` + : '' + return [{ type: 'text', text: `mounted ${id} (plugin "${pluginName(evaluated)}", state: ${state}${note})` }] + }, + presentCall: presentMountCall, + })) + + ctx.tools.register(defineTool({ + name: 'cordis_unmount', + description: + 'Dispose a plugin previously mounted with cordis_mount, by id. All its ' + + 'registrations (event listeners, tools, services) are cleaned up through ' + + 'the cordis effect lifecycle. Returns only after disposal has fully ' + + 'completed (quiescence, not just a request to stop).', + parameters: { + id: { + type: 'string', + required: true, + description: 'The dynamic mount id returned by cordis_mount (e.g. "dyn-1").', + }, + }, + async execute(args) { + const mount = mounts.get(args.id) + if (!mount) { + throw new Error(`no dynamic plugin with id "${args.id}" (list mounts with cordis_inspect what:"dynamic")`) + } + await mount.fiber.dispose() + mounts.delete(args.id) + return [{ type: 'text', text: `unmounted ${args.id} (plugin "${mount.pluginName}")` }] + }, + presentCall: presentUnmountCall, + })) +} diff --git a/packages/cordis/tool-cordis/src/inspect.ts b/packages/cordis/tool-cordis/src/inspect.ts new file mode 100644 index 0000000000..260fa4dd14 --- /dev/null +++ b/packages/cordis/tool-cordis/src/inspect.ts @@ -0,0 +1,195 @@ +/** + * Read-only renderers over the live runtime for `cordis_inspect`: the service + * list, the flat plugin list, the registered tools, the dynamic-mount + * table (with per-mount provides/waits), and the catalog-backed `api` / + * `events` sections. Every renderer is a pure function of the runtime handles + * it receives — no session state, no clock — so inspect output is exactly the + * runtime it describes. + * + * @module @deepseek-ai/dsh-tool-cordis/inspect + */ + +import type { Context, Fiber } from 'cordis' +import type { ScopeKey } from '@deepseek-ai/dsh-scope' +import { EVENT_API, INHERITED_CTX_API, SERVICE_API, TYPE_API } from './api-catalog.ts' +import type { EventApiEntry, InheritedApiEntry, ServiceApiEntry, TypeApiEntry } from './api-catalog.ts' +import { FiberState, STATE_LABELS } from './fiber-state.ts' +import { missingServices } from './mount.ts' +import type { DynamicMount } from './mount.ts' + +/** The live service registrations from `ctx.reflect.store` (map + filter keeps the possibly-undefined index read branch-free). */ +function liveImpls(ctx: Context): { name: string; fiber: Fiber }[] { + const store = ctx.reflect.store + return Object.getOwnPropertySymbols(store) + .map(key => store[key]) + .filter((impl): impl is NonNullable => impl !== undefined) +} + +/** Whether `fiber` is `root` itself or mounted anywhere inside `root`'s subtree. */ +function withinFiber(fiber: Fiber, root: Fiber): boolean { + let current = fiber + while (true) { + if (current === root) return true + const parent = current.parent.fiber + if (parent === current) return false + current = parent + } +} + +/** The service names provided by a mount's fiber subtree, sorted. */ +function providedBy(ctx: Context, fiber: Fiber): string[] { + return liveImpls(ctx) + .filter(impl => withinFiber(impl.fiber, fiber)) + .map(impl => impl.name) + .sort() +} + +/** + * The `services` section: every provided ctx service with its owning fiber, + * annotating non-active owners with their lifecycle state. + * @param ctx - the runtime to enumerate. + * @returns one line per service, or a single placeholder line when none are provided. + */ +export function describeServices(ctx: Context): string[] { + const lines = liveImpls(ctx).map((impl) => { + const active = impl.fiber.state === FiberState.ACTIVE + return `- ${impl.name} (provided by ${impl.fiber.name}${active ? '' : `, ${STATE_LABELS[impl.fiber.state]}`})` + }) + return lines.length > 0 ? lines : ['(no services provided)'] +} + +/** + * The `plugins` section: a flat list of every fiber the registry knows, one + * line per fiber with its lifecycle state, sorted by plugin name (a plugin + * mounted more than once repeats — one line per instance). Dynamic mounts are + * listed like any other plugin; their ids live in the `dynamic` section. + * @param ctx - the runtime whose registry is enumerated. + * @returns one line per loaded plugin fiber. + */ +export function describePlugins(ctx: Context): string[] { + const fibers: Fiber[] = [] + for (const runtime of ctx.registry.values()) { + for (const fiber of runtime.fibers) fibers.push(fiber) + } + return fibers + .sort((a, b) => a.name.localeCompare(b.name)) + .map(fiber => `- ${fiber.name} [${STATE_LABELS[fiber.state]}]`) +} + +/** + * The `tools` section: the model-facing tool names the CALLING agent can see + * (its scoped layer shadowing/joining the restricted global surface) — the + * honest answer to the tool description's "what you can call". + * @param ctx - the runtime whose tool registry is read. + * @param scope - the calling agent (the viewing scope); omitted = global view. + * @returns one line per visible tool. + */ +export function describeTools(ctx: Context, scope?: ScopeKey): string[] { + return ctx.tools.schemas(scope).map(schema => `- ${schema.name}`) +} + +/** + * The `dynamic` section: one line per mount with id, plugin name, lifecycle + * state, the services its subtree provides, and — for a pending mount — the + * services it waits for. + * @param ctx - the runtime the mounts live in. + * @param mounts - the tracked mounts, in mount order. + * @returns one line per mount, or a single placeholder line when none exist. + */ +export function describeDynamic(ctx: Context, mounts: ReadonlyMap): string[] { + if (mounts.size === 0) return ['(no dynamic plugins mounted)'] + return [...mounts].map(([id, mount]) => { + const provides = providedBy(ctx, mount.fiber) + const waiting = missingServices(ctx, mount.fiber) + const providesNote = provides.length > 0 ? ` — provides: ${provides.join(', ')}` : '' + const waitingNote = waiting.length > 0 ? ` — waiting for: ${waiting.join(', ')}` : '' + return `- ${id}: ${mount.pluginName} [${STATE_LABELS[mount.fiber.state]}]${providesNote}${waitingNote}` + }) +} + +/** + * The transitive closure of catalogued type shapes referenced (word-bounded) + * by the seed texts — the runtime scoping that keeps the `api` section to the + * shapes the LIVE signatures actually mention. + */ +function typeClosure(seeds: string[], types: readonly TypeApiEntry[]): TypeApiEntry[] { + const included = new Map() + let frontier = seeds + while (frontier.length > 0) { + const next: string[] = [] + for (const entry of types) { + if (included.has(entry.name)) continue + const pattern = new RegExp(`\\b${entry.name}\\b`) + if (frontier.some(text => pattern.test(text))) { + included.set(entry.name, entry) + next.push(entry.declaration) + } + } + frontier = next + } + return [...included.values()].sort((a, b) => a.name.localeCompare(b.name)) +} + +/** + * The `api` section: the generated service catalog intersected with the LIVE + * runtime — catalogued live services render summary + method signatures, live + * services without a catalog entry (e.g. ones another mount provides) render + * name + owning fiber, catalog services that are not running are listed + * tersely, the type shapes the live signatures reference follow, and the + * inherited `ctx` surface closes the section. + * @param ctx - the runtime to intersect the catalog with. + * @param api - the service catalog (the generated one by default; injectable for tests). + * @param inherited - the inherited `ctx` surface lines (generated by default; injectable for tests). + * @param types - the type-shape catalog (generated by default; injectable for tests). + * @returns the section lines. + */ +export function describeApi( + ctx: Context, + api: readonly ServiceApiEntry[] = SERVICE_API, + inherited: readonly InheritedApiEntry[] = INHERITED_CTX_API, + types: readonly TypeApiEntry[] = TYPE_API, +): string[] { + const live = new Map() + for (const impl of liveImpls(ctx)) live.set(impl.name, impl.fiber.name) + const lines: string[] = [] + const liveMethodTexts: string[] = [] + for (const entry of api) { + if (!live.has(entry.key)) continue + lines.push(`- ${entry.key} — ${entry.summary}`) + for (const method of entry.methods) { + lines.push(` ${method}`) + liveMethodTexts.push(method) + } + } + const catalogued = new Set(api.map(entry => entry.key)) + for (const [name, fiber] of [...live].sort(([a], [b]) => a.localeCompare(b))) { + if (!catalogued.has(name)) lines.push(`- ${name} (provided by ${fiber}, no catalog entry)`) + } + const notRunning = api.filter(entry => !live.has(entry.key)).map(entry => entry.key) + if (notRunning.length > 0) lines.push(`not running (loadable services with no live provider): ${notRunning.join(', ')}`) + const shapes = typeClosure(liveMethodTexts, types) + if (shapes.length > 0) { + lines.push('type shapes (referenced by the signatures above — read these before assuming a field is a string):') + for (const shape of shapes) { + for (const declLine of shape.declaration.split('\n')) lines.push(` ${declLine}`) + } + } + lines.push('inherited ctx API:') + for (const entry of inherited) lines.push(`- ${entry.name} — ${entry.summary}`) + return lines +} + +/** + * The `events` section: every harness event with its dispatch mode, one-line + * summary, and exact signature, closed by the waterfall caution. + * @param events - the event catalog (the generated one by default; injectable for tests). + * @returns the section lines. + */ +export function describeEvents(events: readonly EventApiEntry[] = EVENT_API): string[] { + const lines = events.flatMap(event => [ + `- ${event.name} [${event.mode}] — ${event.summary}`, + ` ${event.signature}`, + ]) + lines.push('waterfall listeners receive a trailing next() and MUST call it to delegate — returning without next() vetoes the chain.') + return lines +} diff --git a/packages/cordis/tool-cordis/src/mount.ts b/packages/cordis/tool-cordis/src/mount.ts new file mode 100644 index 0000000000..a222e81da1 --- /dev/null +++ b/packages/cordis/tool-cordis/src/mount.ts @@ -0,0 +1,64 @@ +/** + * Dynamic-mount lifecycle over the `cordis-dynamic` group fiber: settle a + * sandbox-produced plugin as a child fiber (never leaving a failed fiber + * mounted), and report the services a settled-but-pending fiber still waits + * for. Disposal needs no helper — a mount unwinds through an ordinary awaited + * `fiber.dispose()`, because everything the plugin registered is an effect on + * its fiber. + * + * @module @deepseek-ai/dsh-tool-cordis/mount + */ + +import type { Context, Fiber, Plugin } from 'cordis' +import { guardedPlugin } from './guard.ts' + +/** One tracked dynamic mount: the fiber plus the display name captured at mount time. */ +export interface DynamicMount { + /** The child fiber under the `cordis-dynamic` group. */ + fiber: Fiber + /** The plugin's display name at mount time (its `name`, else ``). */ + pluginName: string +} + +/** + * Mount a plugin under the group fiber and settle it. The group fiber loads + * asynchronously right after the owning plugin's `apply`, so it is awaited + * before hanging a child off its context. The child fiber's `await()` settles + * its lifecycle work and rethrows a startup error (e.g. a throwing `apply`); + * on error the fiber is disposed first — a failed mount never lingers. + * @param group - the `cordis-dynamic` group fiber every mount hangs under. + * @param plugin - the plugin the sandbox returned; wrapped with the registration guard before mounting. + * @returns the settled child fiber (possibly pending on unsatisfied `inject`). + */ +export async function mountDynamic(group: Fiber, plugin: Plugin): Promise { + await group.await() + const fiber = group.ctx.plugin(guardedPlugin(plugin)) + try { + await fiber.await() + } catch (error) { + await fiber.dispose() + const message = error instanceof Error ? error.message : String(error) + // The commonest startup collision is remounting a NEW version of a tool + // while the old mount still holds the name — teach the replace recipe. + if (message.includes('already registered')) { + throw new Error( + `${message} — to REPLACE something an earlier mount registered, first cordis_unmount that mount's id ` + + '(find it with cordis_inspect what:"dynamic"), then mount the new version.', + ) + } + throw error instanceof Error ? error : new Error(message) + } + return fiber +} + +/** + * The services a fiber declared in `inject` that do not exist yet — a settled + * fiber that is not active is waiting on exactly these (legal cordis + * semantics: it activates when the service appears). + * @param ctx - the context to resolve service existence against. + * @param fiber - the mount fiber whose `inject` declarations are checked. + * @returns the missing service names, in declaration order. + */ +export function missingServices(ctx: Context, fiber: Fiber): string[] { + return Object.keys(fiber.inject).filter(service => ctx.get(service) === undefined) +} diff --git a/packages/cordis/tool-cordis/src/present.ts b/packages/cordis/tool-cordis/src/present.ts new file mode 100644 index 0000000000..614b070193 --- /dev/null +++ b/packages/cordis/tool-cordis/src/present.ts @@ -0,0 +1,51 @@ +/** + * ACP render intents for the three cordis tools — all `generic` cards, decided + * up front as part of the tool design. Presenters are pure functions of the + * call arguments (they run on replay too): no I/O, no session state, no clock. + * No `presentResult` overrides exist — the tools' text results are their + * correct completed rendering. + * + * @module @deepseek-ai/dsh-tool-cordis/present + */ + +import type { GenericCallView } from '@deepseek-ai/dsh-tools' + +/** + * The `cordis_inspect` call card: a read, titled with the requested section. + * @param args - the validated call arguments. + * @returns the generic card the ACP bridge renders. + */ +export function presentInspectCall(args: { what?: string }): GenericCallView { + return { + card: 'generic', + kind: 'read', + title: args.what === undefined ? 'Inspect cordis runtime' : `Inspect cordis runtime: ${args.what}`, + } +} + +/** + * The `cordis_mount` call card: an execute carrying the mount code as raw input. + * @param args - the validated call arguments. + * @returns the generic card the ACP bridge renders. + */ +export function presentMountCall(args: { code: string }): GenericCallView { + return { + card: 'generic', + kind: 'execute', + title: 'Mount plugin into live cordis runtime', + rawInput: { code: args.code }, + } +} + +/** + * The `cordis_unmount` call card: a delete, titled with the mount id. + * @param args - the validated call arguments. + * @returns the generic card the ACP bridge renders. + */ +export function presentUnmountCall(args: { id: string }): GenericCallView { + return { + card: 'generic', + kind: 'delete', + title: `Unmount ${args.id}`, + } +} diff --git a/packages/cordis/tool-cordis/src/sandbox.ts b/packages/cordis/tool-cordis/src/sandbox.ts new file mode 100644 index 0000000000..5ed6b52b50 --- /dev/null +++ b/packages/cordis/tool-cordis/src/sandbox.ts @@ -0,0 +1,201 @@ +/** + * The `node:vm` sandbox `cordis_mount` code evaluates in: a fresh realm whose + * globals are a tagged write-through console, the `harness` registration + * helpers, the encoding primitives a bare vm context lacks, and callable traps + * over the Node APIs the sandbox deliberately withholds. Capability access is + * routed through cordis services, never Node built-ins: filesystem work goes + * through `ctx.fs`, network through `ctx.web`, processes through `ctx.bash`, + * timers through the `ctx.timer` helpers (fiber effects, unwound on unmount) + * — so a well-behaved mount stays inspectable and disposable. That routing is + * STEERING toward the cordis services, not containment: the sandbox guards + * against ACCIDENTAL global pollution, and it is not a security boundary. The + * host-realm helpers on the sandbox global (`harness`, `console`, `btoa`) are + * reachable functions, so a mount that goes looking — e.g. through such a + * helper's `.constructor` — can still reach the host realm; that is accepted, + * because the `ctx` a mounted plugin's `apply` later receives is the real, + * fully privileged runtime handle, and that is the point of the toolset. + * + * @module @deepseek-ai/dsh-tool-cordis/sandbox + */ + +import { createContext, runInContext } from 'node:vm' +import { sandboxDefineTool, sandboxRegisterTool } from './guard.ts' + +/** + * A write-through console for one sandbox, tagging every line with the mount + * id. Write-through (host stdout/stderr), NOT buffered into the tool result: + * a mounted listener fires long after the mount call returned, and its output + * must land somewhere the user can see — for the stdio demo, the terminal. + */ +function taggedConsole(id: string): Record<'log' | 'info' | 'warn' | 'error' | 'debug', (...args: unknown[]) => void> { + const tag = `[cordis:${id}]` + const log = (...args: unknown[]): void => { console.log(tag, ...args) } + const error = (...args: unknown[]): void => { console.error(tag, ...args) } + return { log, info: log, warn: log, debug: log, error } +} + +/** + * Per-sandbox prelude: give the vm realm's own constructors a + * `Symbol.hasInstance` that checks BOTH realms. Model code runs against a + * fresh vm realm, but most objects it touches are HOST-realm (the `args` a + * tool's `execute` receives, event payloads a listener observes, service + * return values), so a plain `x instanceof Array` / `instanceof Object` in + * sandbox code would silently be false. The patch replaces each vm + * constructor's own `[Symbol.hasInstance]` with "ordinary check against the + * vm constructor OR the host counterpart" — the ordinary algorithm is a pure + * prototype-chain walk, so calling it with the host constructor as receiver + * needs no host-side change. ONLY vm-realm globals are modified; host + * intrinsics are passed in as values and never touched. + */ +const DUAL_REALM_INSTANCEOF_PRELUDE = ` +(hostIntrinsics) => { + 'use strict' + const ordinary = Function.prototype[Symbol.hasInstance] + for (const name of Object.keys(hostIntrinsics)) { + const VmCtor = globalThis[name] + const HostCtor = hostIntrinsics[name] + if (typeof VmCtor !== 'function' || typeof HostCtor !== 'function') continue + Object.defineProperty(VmCtor, Symbol.hasInstance, { + value: (instance) => ordinary.call(VmCtor, instance) || ordinary.call(HostCtor, instance), + configurable: true, + }) + } +} +` + +/** Run {@link DUAL_REALM_INSTANCEOF_PRELUDE} in a freshly created sandbox, handing it the host intrinsics to pair up. */ +function patchDualRealmInstanceof(sandbox: object): void { + const patch = runInContext(DUAL_REALM_INSTANCEOF_PRELUDE, sandbox) as (intrinsics: Record) => void + patch({ Object, Array, Function, Error, TypeError, RangeError, SyntaxError, Promise, RegExp, Date, Map, Set }) +} + +const TIMER_REDIRECT + = 'Node timers are unavailable. Use the cordis timer service instead: declare inject: [\'timer\'] on your plugin ' + + 'and call ctx.setTimeout / ctx.setInterval — those are fiber effects, cleaned up automatically on unmount.' + +/** + * The callable Node APIs the sandbox deliberately disables, each mapped to the + * cordis alternative its trap error names. Only FUNCTION-shaped globals are + * trapped — a data-shaped global like `process` stays `undefined`, because a + * throwing accessor would detonate the common `typeof process` feature probe + * at resolution time. + */ +const NODE_API_REDIRECTS: Record = { + require: + 'Node modules are unavailable. Use the cordis services on ctx instead — e.g. inject: [\'fs\'] for files, ' + + '[\'web\'] for HTTP, [\'bash\'] for processes; cordis_inspect what:"api" lists what THIS runtime provides.', + setTimeout: TIMER_REDIRECT, + setInterval: TIMER_REDIRECT, + setImmediate: TIMER_REDIRECT, + clearTimeout: TIMER_REDIRECT, + clearInterval: TIMER_REDIRECT, + fetch: + 'Network access goes through the cordis web service: declare inject: [\'web\'] and call ctx.web ' + + '(see cordis_inspect what:"api" for its methods).', +} + +/** Build the trap functions for {@link NODE_API_REDIRECTS}: calling one throws the redirect. */ +function nodeApiTraps(): Record never> { + const traps: Record never> = {} + for (const [name, redirect] of Object.entries(NODE_API_REDIRECTS)) { + traps[name] = () => { + throw new Error(`${name} is not available in the mount sandbox — ${redirect}`) + } + } + return traps +} + +/** + * Build the vm context one `cordis_mount` call evaluates in: the tagged + * console, the `harness` registration helpers, the encoding primitives, the + * Node-API traps, and the dual-realm `instanceof` patch, already + * `createContext`-ed. + * @param id - the mount id (`dyn-`), used as the console tag and filename stem. + * @returns the contextified sandbox object to pass to {@link evaluateMountCode}. + */ +export function createSandbox(id: string): object { + const sandbox = { + ...nodeApiTraps(), + console: taggedConsole(id), + harness: { defineTool: sandboxDefineTool, registerTool: sandboxRegisterTool }, + // Web APIs absent from fresh vm contexts — made available so the model + // can encode/decode base64 without Buffer (which is also absent). Host + // closures over Buffer, never Buffer itself. + btoa: (s: string) => Buffer.from(s, 'utf-8').toString('base64'), + atob: (s: string) => Buffer.from(s, 'base64').toString('utf-8'), + TextEncoder, + TextDecoder, + } + createContext(sandbox) + patchDualRealmInstanceof(sandbox) + return sandbox +} + +/** + * Cross-realm SyntaxError detection: a compile failure inside `runInContext` + * constructs its error in the SANDBOX realm, so a host `instanceof + * SyntaxError` is silently false — the `name` property is the realm-safe tag. + */ +function isSyntaxError(error: unknown): error is Error { + return typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'SyntaxError' +} + +/** + * The parse-failure context a vm `SyntaxError` carries: the vm prints the + * offending source line and a caret before the message, which is exactly what + * a model needs to self-correct — surface it instead of the bare message. + * Falls back to `String(error)` when the stack carries no such prelude. + * @param error - the `SyntaxError` (host- or sandbox-realm) thrown while compiling mount code. + * @returns the stack prefix up to and including the `SyntaxError: …` line. + */ +export function syntaxErrorContext(error: Error): string { + const lines = (error.stack ?? '').split('\n') + const messageIndex = lines.findIndex(line => line.startsWith('SyntaxError')) + if (messageIndex === -1) return String(error) + return lines.slice(0, messageIndex + 1).join('\n') +} + +/** + * Evaluate mount code as the body of an async function inside the sandbox. + * `vmTimeoutMs` only bounds the SYNCHRONOUS portion; an async body escapes it + * — acceptable under the module's trust stance. A parse failure is answered + * with the offending line + caret and a teaching hint: TypeScript syntax on + * the failing line gets the remove-annotations fix, anything else gets the + * function-body/bracket-balance reminder (models habitually close the returned + * plugin object with `});` as if it were a callback argument). + * @param sandbox - the contextified object from {@link createSandbox}. + * @param code - the model-written function body; must `return` a plugin. + * @param id - the mount id, used as the vm filename (`cordis-mount-.js`). + * @param vmTimeoutMs - the synchronous evaluation bound in milliseconds. + * @returns whatever the code returned, still un-narrowed (the mount lifecycle checks plugin shape). + */ +export async function evaluateMountCode(sandbox: object, code: string, id: string, vmTimeoutMs: number): Promise { + try { + return await runInContext( + `(async () => {\n${code}\n})()`, + sandbox, + { filename: `cordis-mount-${id}.js`, timeout: vmTimeoutMs }, + ) + } catch (error) { + if (!isSyntaxError(error)) throw error + const context = syntaxErrorContext(error) + // Scope the TypeScript heuristic to the OFFENDING line, not the whole + // code: an ` as ` inside an ordinary description string must not turn a + // plain syntax error into a misleading remove-annotations message. + const offendingLine = context.split('\n')[1] ?? '' + if (/\bas\b/.test(offendingLine)) { + throw new Error( + `mount code failed to parse:\n${context}\n` + + 'The sandbox runs plain JavaScript, not TypeScript. Remove type annotations:\n' + + ' ✗ { type: \'text\' as const, text: x }\n' + + ' ✓ { type: \'text\', text: x }', + ) + } + throw new Error( + `mount code failed to parse:\n${context}\n` + + 'Note: `code` runs as the BODY of an async function (line numbers are offset by the 1-line wrapper). ' + + 'Check bracket balance — ending the returned plugin object with `});` closes a call that was never opened; ' + + 'a plain `return { … }` ends with `}` (an optional `;`), never `)`.', + ) + } +} diff --git a/packages/cordis/tool-cordis/tests/cross-mount.spec.ts b/packages/cordis/tool-cordis/tests/cross-mount.spec.ts new file mode 100644 index 0000000000..dcfdb815c4 --- /dev/null +++ b/packages/cordis/tool-cordis/tests/cross-mount.spec.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from 'vitest' +import { call, CONSUMER_CODE, PROVIDER_CODE, setup, text } from './helpers.ts' + +/** + * Cross-mount composition through ordinary cordis provide/inject semantics: + * one mount provides a service, another injects it, and mount ids stay the + * lifecycle handles. Every assertion is against the WORLD — the registry, the + * service store, real tool dispatch — not the tool's own summary line. + */ + +describe('cross-mount provide/inject', () => { + it('provider first: the consumer activates immediately and its tool reaches the provided service', async () => { + const ctx = await setup() + const provider = await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) + expect(text(provider)).toContain('state: active') + + const consumer = await call(ctx, 'cordis_mount', { code: CONSUMER_CODE }) + expect(consumer.isError).toBe(false) + expect(text(consumer)).toContain('state: active') + + // The vm-realm service value is callable across mounts, and the result + // normalizes into the host realm like any dynamic tool result. + const greeted = await call(ctx, 'greet', { name: 'harness' }) + expect(greeted.isError).toBe(false) + expect(text(greeted)).toBe('hi harness') + }) + + it('consumer first: stays pending naming the missing service, then activates when the provider mounts', async () => { + const ctx = await setup() + const consumer = await call(ctx, 'cordis_mount', { code: CONSUMER_CODE }) + expect(consumer.isError).toBe(false) + expect(text(consumer)).toContain('state: pending') + expect(text(consumer)).toContain('waiting for service(s): greeter') + expect(text(await call(ctx, 'cordis_inspect', { what: 'dynamic' }))).toContain('waiting for: greeter') + expect(ctx.tools.get('greet')).toBeUndefined() + + await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) + expect(ctx.tools.get('greet')).toBeDefined() + expect(text(await call(ctx, 'greet', { name: 'late' }))).toBe('hi late') + }) + + it('unmounting the provider sends the consumer back to pending and unwinds its registrations', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) // dyn-1 + await call(ctx, 'cordis_mount', { code: CONSUMER_CODE }) // dyn-2 + expect(ctx.tools.get('greet')).toBeDefined() + + const unmounted = await call(ctx, 'cordis_unmount', { id: 'dyn-1' }) + expect(unmounted.isError).toBe(false) + expect(ctx.tools.get('greet')).toBeUndefined() + const report = text(await call(ctx, 'cordis_inspect', { what: 'dynamic' })) + expect(report).toContain('dyn-2: greeter-consumer [pending] — waiting for: greeter') + }) + + it('re-providing the service re-runs the consumer through the same guard (active again, tool back)', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) // dyn-1 + await call(ctx, 'cordis_mount', { code: CONSUMER_CODE }) // dyn-2 + await call(ctx, 'cordis_unmount', { id: 'dyn-1' }) + expect(ctx.tools.get('greet')).toBeUndefined() + + await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) // dyn-3 + expect(ctx.tools.get('greet')).toBeDefined() + expect(text(await call(ctx, 'greet', { name: 'again' }))).toBe('hi again') + expect(text(await call(ctx, 'cordis_inspect', { what: 'dynamic' }))).toContain('dyn-2: greeter-consumer [active]') + }) + + it('a duplicate provide fails loud with the owning fiber named, and the failed mount is disposed', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) + const duplicate = await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) + expect(duplicate.isError).toBe(true) + expect(text(duplicate)).toContain('has been registered') + const report = text(await call(ctx, 'cordis_inspect', { what: 'dynamic' })) + expect(report).toContain('dyn-1: greeter-provider') + expect(report).not.toContain('dyn-2') + }) + + it('inspect surfaces the linkage: provides on the provider row, the service in services and api sections', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) + await call(ctx, 'cordis_mount', { code: CONSUMER_CODE }) + + const dynamic = text(await call(ctx, 'cordis_inspect', { what: 'dynamic' })) + expect(dynamic).toContain('dyn-1: greeter-provider [active] — provides: greeter') + + const services = text(await call(ctx, 'cordis_inspect', { what: 'services' })) + expect(services).toContain('- greeter (provided by greeter-provider)') + + const api = text(await call(ctx, 'cordis_inspect', { what: 'api' })) + expect(api).toContain('- greeter (provided by greeter-provider, no catalog entry)') + }) + + it('a primitive (or null) provided value passes through the façade unwrapped, on both read paths', async () => { + const ctx = await setup() + const provider = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'answer-provider', + apply(ctx) { + ctx.provide('answer', 42) + ctx.provide('nothing', null) + }, + } + `, + }) + expect(provider.isError).toBe(false) + + const consumer = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'answer-consumer', + inject: ['answer', 'nothing', 'tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'answer', + description: 'Read the provided primitive services.', + parameters: {}, + async execute() { + return [{ type: 'text', text: ctx.answer + '/' + ctx.get('answer') + '/' + ctx.nothing }] + }, + })) + }, + } + `, + }) + expect(consumer.isError).toBe(false) + expect(text(consumer)).toContain('state: active') + expect(text(await call(ctx, 'answer', {}))).toBe('42/42/null') + }) + + it('unmounting the consumer leaves the provider and its service intact', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { code: PROVIDER_CODE }) // dyn-1 + await call(ctx, 'cordis_mount', { code: CONSUMER_CODE }) // dyn-2 + await call(ctx, 'cordis_unmount', { id: 'dyn-2' }) + + expect(ctx.tools.get('greet')).toBeUndefined() + const services = text(await call(ctx, 'cordis_inspect', { what: 'services' })) + expect(services).toContain('- greeter (provided by greeter-provider)') + expect(text(await call(ctx, 'cordis_inspect', { what: 'dynamic' }))).toContain('dyn-1: greeter-provider [active]') + }) +}) diff --git a/packages/cordis/tool-cordis/tests/helpers.ts b/packages/cordis/tool-cordis/tests/helpers.ts new file mode 100644 index 0000000000..b183a2444f --- /dev/null +++ b/packages/cordis/tool-cordis/tests/helpers.ts @@ -0,0 +1,104 @@ +import { Context } from 'cordis' +import Timer from '@cordisjs/plugin-timer' +import { CallId } from '@deepseek-ai/dsh-llm' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry from '@deepseek-ai/dsh-tools' +import type { ToolDefinition, ToolExecutionResult } from '@deepseek-ai/dsh-tools' +import * as tool from '../src/index.ts' + +/** + * Shared spec helpers: a real `SystemPrompt` + `ToolRegistry` + timer + + * tool-cordis tree (only the model is absent — the code strings below stand in + * for what it would write), plus the canonical mount-code fixtures the suites + * share. + */ + +/** Mount the plugin on a fresh context with a real ToolRegistry and the timer service. */ +export async function setup(config?: tool.Config): Promise { + const ctx = new Context() + await ctx.plugin(Timer) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(tool, config) + return ctx +} + +let callCounter = 0 + +/** Execute a registered tool through the real registry pipeline. */ +export function call(ctx: Context, name: string, args: unknown): Promise { + return ctx.tools.execute({ callId: CallId(`call-${++callCounter}`), name, arguments: args }) +} + +/** Concatenated text blocks of one tool result. */ +export function text(result: ToolExecutionResult): string { + return result.content.filter(block => block.type === 'text').map(block => block.text).join('') +} + +/** Mount code for a listener plugin: logs on every `tools/change`. */ +export const LISTENER_CODE = ` + return { + name: 'change-logger', + apply(ctx) { + ctx.on('tools/change', () => console.log('tools changed')) + }, + } +` + +/** Mount code for a self-made tool: registers `reverse_text` via the sandbox's harness helpers. */ +export const REVERSE_TOOL_CODE = ` + return { + name: 'reverse-text', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'reverse_text', + description: 'Reverse a string.', + parameters: { text: { type: 'string', required: true } }, + async execute(args) { + return [{ type: 'text', text: args.text.split('').reverse().join('') }] + }, + })) + }, + } +` + +/** Mount code providing a `greeter` service other mounts can inject. */ +export const PROVIDER_CODE = ` + return { + name: 'greeter-provider', + apply(ctx) { + ctx.provide('greeter', { greet: (name) => 'hi ' + name }) + }, + } +` + +/** Mount code consuming the `greeter` service through inject, exposing it as a tool. */ +export const CONSUMER_CODE = ` + return { + name: 'greeter-consumer', + inject: ['greeter', 'tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'greet', + description: 'Greet someone via the greeter service.', + parameters: { name: { type: 'string', required: true } }, + async execute(args) { + return [{ type: 'text', text: ctx.greeter.greet(args.name) }] + }, + })) + }, + } +` + +/** A registrable no-op tool the tests use to trigger a real `tools/change`. */ +export function dummyTool(name: string): ToolDefinition { + return { + name, + description: 'test trigger', + parameters: { type: 'object' as const, properties: {} }, + async execute(): Promise<[]> { + return [] + }, + } +} diff --git a/packages/cordis/tool-cordis/tests/inspect.spec.ts b/packages/cordis/tool-cordis/tests/inspect.spec.ts new file mode 100644 index 0000000000..1a8c39467a --- /dev/null +++ b/packages/cordis/tool-cordis/tests/inspect.spec.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'vitest' +import type { Context, Fiber } from 'cordis' +import { FiberState } from '../src/fiber-state.ts' +import { describeApi, describeEvents, describePlugins, describeServices } from '../src/inspect.ts' +import { call, LISTENER_CODE, setup, text } from './helpers.ts' + +/** + * The `cordis_inspect` sections: rendered against the real runtime through the + * tool, plus direct renderer calls for the states a minimal harness cannot + * reach (empty service store, same-named sibling fibers, a fully-live catalog). + */ + +describe('cordis_inspect', () => { + it('reports all six sections by default', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_inspect', {}) + expect(result.isError).toBe(false) + const report = text(result) + for (const heading of ['services', 'plugins', 'tools', 'dynamic', 'api', 'events']) { + expect(report).toContain(`## ${heading}`) + } + // The services section sees the real providers; the plugins list shows + // this plugin and its dynamic group flat; the tools section lists the + // cordis tools. + expect(report).toContain('- tools (provided by ToolRegistry)') + expect(report).toContain('- tool-cordis [active]') + expect(report).toContain('- cordis-dynamic [active]') + expect(report).toContain('- cordis_mount') + expect(report).toContain('(no dynamic plugins mounted)') + }) + + it('limits the report to one section via `what`', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_inspect', { what: 'tools' }) + const report = text(result) + expect(report).toContain('## tools') + expect(report).not.toContain('## services') + expect(report).not.toContain('## plugins') + }) + + it('shows a mount in the dynamic section and in the flat plugins list', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { code: LISTENER_CODE }) + const report = text(await call(ctx, 'cordis_inspect', {})) + expect(report).toContain('- dyn-1: change-logger [active]') + expect(report).toContain('- change-logger [active]') + }) + + it('renders the api section from the generated catalog intersected with the LIVE runtime', async () => { + const ctx = await setup() + const report = text(await call(ctx, 'cordis_inspect', { what: 'api' })) + // Live catalogued services render summary + signatures. + expect(report).toContain('- tools — ') + expect(report).toContain('register(definition: ToolDefinition)') + expect(report).toContain('- systemPrompt — ') + // Catalogued services with no live provider are listed tersely. + expect(report).toMatch(/not running \(loadable services with no live provider\): .*bash/) + // The type shapes the LIVE signatures reference follow (closure over the + // generated TYPE_API — a consumer can see field types, not just names). + expect(report).toContain('type shapes (referenced by the signatures above') + expect(report).toContain('export interface ToolExecution') + // A type only reachable through a NOT-live service (e.g. bash) is scoped out. + expect(report).not.toContain('export interface BashRunResult') + // The inherited ctx surface closes the section. + expect(report).toContain('inherited ctx API:') + expect(report).toContain('- ctx.effect — ') + }) + + it('renders the events section with mode badges, signatures, and the waterfall caution', async () => { + const ctx = await setup() + const report = text(await call(ctx, 'cordis_inspect', { what: 'events' })) + expect(report).toContain('- tools/change [emit]') + expect(report).toContain('- tools/pre-execute [waterfall]') + expect(report).toMatch(/'agent\/status'\(/) + expect(report).toContain('returning without next() vetoes the chain') + }) +}) + +describe('inspect renderers (direct)', () => { + it('describeServices reports an empty store as such, and labels a non-active provider', () => { + const empty = { reflect: { store: {} } } as unknown as Context + expect(describeServices(empty)).toEqual(['(no services provided)']) + + const pendingFiber = { state: FiberState.PENDING, name: 'half-loaded' } as unknown as Fiber + const store: Record = {} + store[Symbol('impl')] = { name: 'thing', fiber: pendingFiber } + const ctx = { reflect: { store } } as unknown as Context + expect(describeServices(ctx)).toEqual(['- thing (provided by half-loaded, pending)']) + }) + + it('describePlugins lists every fiber flat, sorted by name, one line per instance', () => { + const fiber = (name: string): Fiber => ({ name, state: FiberState.ACTIVE }) as unknown as Fiber + const ctx = { + registry: { values: () => [{ fibers: [fiber('beta'), fiber('alpha')] }, { fibers: [fiber('alpha')] }] }, + } as unknown as Context + expect(describePlugins(ctx)).toEqual([ + '- alpha [active]', + '- alpha [active]', + '- beta [active]', + ]) + }) + + it('describeApi omits the not-running line and type shapes when nothing applies', async () => { + const ctx = await setup() + const lines = describeApi(ctx, [{ key: 'tools', summary: 'The registry.', methods: ['register(x): void'] }], [], []) + expect(lines[0]).toBe('- tools — The registry.') + expect(lines[1]).toBe(' register(x): void') + expect(lines.join('\n')).not.toContain('not running') + expect(lines.join('\n')).not.toContain('type shapes') + }) + + it('describeEvents renders an empty catalog as just the waterfall caution', () => { + expect(describeEvents([])).toEqual([ + 'waterfall listeners receive a trailing next() and MUST call it to delegate — returning without next() vetoes the chain.', + ]) + }) +}) diff --git a/packages/cordis/tool-cordis/tests/integration.spec.ts b/packages/cordis/tool-cordis/tests/integration.spec.ts new file mode 100644 index 0000000000..94331df7c0 --- /dev/null +++ b/packages/cordis/tool-cordis/tests/integration.spec.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import LlmService from '@deepseek-ai/dsh-llm' +import SessionStore from '@deepseek-ai/dsh-session' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry from '@deepseek-ai/dsh-tools' +import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent' +import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop' +import * as ToolCordis from '../src/index.ts' +import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +import { REVERSE_TOOL_CODE } from './helpers.ts' + +/** + * Full-loop integration: a scripted mock model mounts a plugin that registers + * a NEW tool, calls that tool on the very next step (tool schemas are + * reassembled per step — the real loop proves the self-extension contract), + * and unmounts it again. Only the model is mocked; the sandbox, the fiber + * tree, and the session log are real. + */ + +async function harness(adapter: MockAdapter): Promise { + const ctx = new Context() + await ctx.plugin(LlmService) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(ToolCordis) + ctx.llm.registerAdapter(['mock'], adapter) + return ctx +} + +function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise { + return new Promise((resolve) => { + const dispose = ctx.on('agent/status', (subject, status) => { + if (subject === agent && status === 'idle') { + dispose() + resolve() + } + }) + }) +} + +describe('cordis tools through the agent loop', () => { + it('mounts a tool, calls it on the next step, and unmounts it — all as real tool/call events', async () => { + const adapter = new MockAdapter([ + toolCallResponse('call-1', 'cordis_mount', { code: REVERSE_TOOL_CODE }, 'Extending myself.'), + toolCallResponse('call-2', 'reverse_text', { text: 'harness' }), + toolCallResponse('call-3', 'cordis_unmount', { id: 'dyn-1' }), + textResponse('Done.'), + ]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(AgentId('it-cordis'), { model: 'mock' }) + + agent.send([{ type: 'text', text: 'give yourself reverse_text, use it, clean up' }]) + await waitForIdle(ctx, agent) + + const log = agent.session.events + const calls = log.filter(event => event.type === 'tool/call').map(event => event.data.name) + expect(calls).toEqual(['cordis_mount', 'reverse_text', 'cordis_unmount']) + + const results = log.filter(event => event.type === 'tool/result') + expect(results.map(event => event.data.isError)).toEqual([false, false, false]) + const reversed = results[1]!.data.content + .filter(block => block.type === 'text') + .map(block => block.text) + .join('') + expect(reversed).toBe('ssenrah') + + // After the unmount the self-made tool is gone from the registry. + expect(ctx.tools.get('reverse_text')).toBeUndefined() + }) +}) diff --git a/packages/cordis/tool-cordis/tests/mount.spec.ts b/packages/cordis/tool-cordis/tests/mount.spec.ts new file mode 100644 index 0000000000..fc29eeb2a0 --- /dev/null +++ b/packages/cordis/tool-cordis/tests/mount.spec.ts @@ -0,0 +1,575 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { isJsonValue } from '@deepseek-ai/dsh-session' +import { syntaxErrorContext } from '../src/sandbox.ts' +import { call, dummyTool, LISTENER_CODE, REVERSE_TOOL_CODE, setup, text } from './helpers.ts' + +/** + * The `cordis_mount` success/failure family: real plugins land on a genuine + * cordis fiber tree, their registrations are observable through the real + * registry/event bus, and every rejection path teaches the fix. + */ + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('cordis_mount', () => { + it('mounts a listener plugin that observes real events, tagged-logging through to the host console', async () => { + const ctx = await setup() + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + + const result = await call(ctx, 'cordis_mount', { code: LISTENER_CODE }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('mounted dyn-1 (plugin "change-logger", state: active)') + + // Fire a REAL tools/change by registering a tool; the mounted listener logs. + ctx.tools.register(dummyTool('trigger_a')) + expect(log).toHaveBeenCalledWith('[cordis:dyn-1]', 'tools changed') + }) + + it('mounts a bare-function plugin as , and a named function under its name', async () => { + const ctx = await setup() + const anonymous = await call(ctx, 'cordis_mount', { code: 'return (ctx) => { ctx.on(\'tools/change\', () => {}) }' }) + expect(anonymous.isError).toBe(false) + expect(text(anonymous)).toContain('plugin ""') + const named = await call(ctx, 'cordis_mount', { code: 'return function watcher(ctx) {}' }) + expect(text(named)).toContain('plugin "watcher"') + }) + + it('lets the agent give ITSELF a new tool, immediately callable through the registry', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { code: REVERSE_TOOL_CODE }) + expect(result.isError).toBe(false) + + expect(ctx.tools.schemas().map(schema => schema.name)).toContain('reverse_text') + const reversed = await call(ctx, 'reverse_text', { text: 'harness' }) + expect(reversed.isError).toBe(false) + expect(text(reversed)).toBe('ssenrah') + }) + + it('normalizes a self-made tool\'s result into the host realm, so the session log accepts it', async () => { + // The model's execute builds its content blocks INSIDE the vm, where + // Object.prototype is a different object — dsh-session's isJsonValue (the + // gate every `tool/result` append runs through) compares prototype + // IDENTITY, so a raw foreign-realm result would error the whole turn the + // first time the self-made tool runs. harness.defineTool round-trips the + // return into host-realm JSON before it reaches the registry. + const ctx = await setup() + await call(ctx, 'cordis_mount', { code: REVERSE_TOOL_CODE }) + const reversed = await call(ctx, 'reverse_text', { text: 'harness' }) + expect(isJsonValue({ content: reversed.content, isError: reversed.isError })).toBe(true) + }) + + it('threads the { content, meta } object return form through to the registry result', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'meta-return', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'meta_tool', + description: 'attaches a private presentation payload', + parameters: {}, + async execute() { + return { content: [{ type: 'text', text: 'ok' }], meta: { kind: 'demo' } } + }, + })) + }, + } + `, + }) + const result = await call(ctx, 'meta_tool', {}) + expect(result.isError).toBe(false) + expect(text(result)).toBe('ok') + expect(result.meta).toEqual({ kind: 'demo' }) + }) + + it.each([ + ['a bare string', 'return \'ok\'', '"ok"'], + ['an object whose content is a string', 'return { content: \'ok\' }', '{"content":"ok"}'], + ['an array of non-objects', 'return [\'ok\']', '["ok"]'], + ['blocks missing the type tag', 'return [{ text: \'hi\' }]', '[{"text":"hi"}]'], + ['object-form blocks missing the type tag', 'return { content: [{ text: \'hi\' }] }', '{"content":[{"text":"hi"}]}'], + ['undefined — a forgotten return', 'return undefined', 'undefined'], + ])('rejects an execute return of %s as that one call\'s teaching error', async (_label, returnStatement, preview) => { + // The failure this prevents: the registry trusts the return shape + // (postExecute spreads result.content), so an unvalidated { content: 'ok' } + // would enter the session log as ['o','k'] and silently corrupt the next + // model request. The shape check turns it into THIS call's error instead — + // one well-formed text block the log and the model can digest. + const ctx = await setup() + await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'bad-return', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'bad_return_tool', + description: 'returns a wrong shape', + parameters: {}, + async execute() { ${returnStatement} }, + })) + }, + } + `, + }) + const result = await call(ctx, 'bad_return_tool', {}) + expect(result.isError).toBe(true) + expect(result.content).toHaveLength(1) + expect(result.content[0]!.type).toBe('text') + expect(text(result)).toContain(`execute returned ${preview}`) + expect(text(result)).toContain('must return an ARRAY of content blocks') + expect(text(result)).toContain('✓ return { content: [{ type: \'text\', text: someString }], meta: anyJsonValue }') + }) + + it('truncates a huge invalid execute return in the teaching error', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'huge-return', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'huge_return_tool', + description: 'returns a huge wrong shape', + parameters: {}, + async execute() { return 'x'.repeat(500) }, + })) + }, + } + `, + }) + const result = await call(ctx, 'huge_return_tool', {}) + expect(result.isError).toBe(true) + expect(text(result)).toContain('…') + expect(text(result)).not.toContain('x'.repeat(200)) + }) + + it('accepts a JSON-Schema-style parameters wrapper and normalizes it to the DSL', async () => { + // The dialect models write by strong prior: the { type:'object', + // properties, required: […] } wrapper, `type: 'integer'`, and + // `required: false`. All of it has exactly one meaning — normalize instead + // of burning a model turn on a lecture. + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'json-schema-tool', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'json_schema_tool', + description: 'written in the JSON-Schema dialect', + parameters: { + type: 'object', + properties: { + text: { type: 'string', description: 'the text' }, + count: { type: 'integer', default: 1 }, + mode: { type: 'string', enum: ['fast', 'slow'] }, + extra: { type: 'string', required: false }, + }, + required: ['text'], + }, + async execute(args) { return [{ type: 'text', text: args.text + ':' + (args.count ?? 0) }] }, + })) + }, + } + `, + }) + expect(result.isError).toBe(false) + + // The registered schema is canonical JSON Schema derived from the DSL: + // the required array survived, integer became number, extra is optional. + const schema = ctx.tools.schemas().find(s => s.name === 'json_schema_tool')! + const parameters = schema.parameters as { properties: Record; required?: string[] } + expect(parameters.required).toEqual(['text']) + expect(parameters.properties.count!.type).toBe('number') + expect(parameters.properties.mode!.enum).toEqual(['fast', 'slow']) + // Arg validation enforces the normalized spec: text required, extra not. + expect((await call(ctx, 'json_schema_tool', { count: 2 })).isError).toBe(true) + expect(text(await call(ctx, 'json_schema_tool', { text: 'ok', count: 2 }))).toBe('ok:2') + }) + + it('normalizes a nested object property carrying a JSON-Schema required array', async () => { + // On an object PROPERTY, a JSON-Schema-style `required` array names the + // required children — the nested unwrap converts it just like the top level. + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'nested-json-schema', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'nested_json_schema_tool', + description: 'nested dialect', + parameters: { + cfg: { type: 'object', properties: { label: { type: 'string' } }, required: ['label'] }, + }, + async execute(args) { return [{ type: 'text', text: args.cfg.label }] }, + })) + }, + } + `, + }) + expect(result.isError).toBe(false) + const schema = ctx.tools.schemas().find(s => s.name === 'nested_json_schema_tool')! + const cfg = (schema.parameters as { properties: { cfg: { required?: string[] } } }).properties.cfg + expect(cfg.required).toEqual(['label']) + expect(text(await call(ctx, 'nested_json_schema_tool', { cfg: { label: 'hi' } }))).toBe('hi') + }) + + it.each([ + ['parameters: 42', 'must be a SchemaSpec object'], + ['parameters: { text: 42 }', 'parameters.text must be a SchemaSpec property object'], + ['parameters: { text: { type: \'str\' } }', 'parameters.text must declare a valid type: \'string\' | \'number\' | \'boolean\' | \'object\' | \'array\' (got "str")'], + ['parameters: { text: { type: \'string\', required: \'yes\' } }', 'parameters.text.required must be a boolean when present'], + ['parameters: { text: { type: \'string\', properties: {} } }', 'parameters.text.properties is only valid for type "object"'], + ['parameters: { text: { type: \'string\', items: { type: \'string\' } } }', 'parameters.text.items is only valid for type "array"'], + ])('rejects a malformed SchemaSpec (%s) with a teaching error', async (parameters, message) => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'bad-schema', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'bad_schema_tool', + description: 'bad', + ${parameters}, + async execute() { return [] }, + })) + }, + } + `, + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain(message) + }) + + it('accepts a nested object/array SchemaSpec (the DSL recursion)', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'nested-schema', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'nested_schema_tool', + description: 'nested', + parameters: { + item: { type: 'object', required: true, properties: { label: { type: 'string', required: true } } }, + tags: { type: 'array', items: { type: 'string' } }, + }, + async execute(args) { return [{ type: 'text', text: args.item.label }] }, + })) + }, + } + `, + }) + expect(result.isError).toBe(false) + const echoed = await call(ctx, 'nested_schema_tool', { item: { label: 'ok' }, tags: ['a'] }) + expect(text(echoed)).toBe('ok') + }) + + it('rejects raw dynamic ctx.tools.register calls that bypass harness helpers', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'raw-register', + inject: ['tools'], + apply(ctx) { + ctx.tools.register({ + name: 'raw_dynamic_tool', + description: 'raw', + parameters: { type: 'object', properties: {} }, + async execute() { return [] }, + }) + }, + } + `, + }) + + expect(result.isError).toBe(true) + expect(text(result)).toContain('dynamic tool registration must use a tool returned by harness.defineTool') + expect(ctx.tools.get('raw_dynamic_tool')).toBeUndefined() + }) + + it('guards the registry reached through ctx.get(\'tools\') identically', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'raw-register-get', + apply(ctx) { + ctx.get('tools').register({ name: 'raw_via_get', description: 'raw', parameters: {}, async execute() { return [] } }) + }, + } + `, + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('dynamic tool registration must use a tool returned by harness.defineTool') + expect(ctx.tools.get('raw_via_get')).toBeUndefined() + }) + + it('passes non-register registry members through the guard with correct binding', async () => { + const ctx = await setup() + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'schema-reader', + inject: ['tools'], + apply(ctx) { + console.log('sees', ctx.tools.schemas().length, 'tools; mount is', typeof ctx.tools.get('cordis_mount')) + }, + } + `, + }) + expect(result.isError).toBe(false) + expect(log).toHaveBeenCalledWith('[cordis:dyn-1]', 'sees', 3, 'tools; mount is', 'object') + }) + + it('keeps a plugin with unsatisfied inject mounted as pending and names what it waits for', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: 'return { name: \'waiter\', inject: [\'no-such-service\'], apply(ctx) {} }', + }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('state: pending') + expect(text(result)).toContain('waiting for service(s): no-such-service') + // Unmounting a pending mount works like any other. + const unmounted = await call(ctx, 'cordis_unmount', { id: 'dyn-1' }) + expect(unmounted.isError).toBe(false) + }) + + it('rejects code that throws, leaving nothing mounted', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { code: 'throw new Error(\'boom in sandbox\')' }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('boom in sandbox') + expect(text(await call(ctx, 'cordis_inspect', { what: 'dynamic' }))).toContain('(no dynamic plugins mounted)') + }) + + it('passes non-Error and null throws through untouched (no SyntaxError misclassification)', async () => { + const ctx = await setup() + const primitive = await call(ctx, 'cordis_mount', { code: 'throw \'plain-string-throw\'' }) + expect(primitive.isError).toBe(true) + expect(text(primitive)).toContain('plain-string-throw') + const nullish = await call(ctx, 'cordis_mount', { code: 'throw null' }) + expect(nullish.isError).toBe(true) + }) + + it('rejects code that does not return a plugin', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { code: 'return 42' }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('must `return` a plugin') + }) + + it('answers a missing return with the two valid plugin forms', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { code: 'const plugin = (ctx) => {}' }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('did you forget `return`?') + }) + + it('disposes a plugin whose apply throws, and reports the error', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: 'return { name: \'broken\', apply(ctx) { throw new Error(\'apply exploded\') } }', + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('apply exploded') + expect(text(await call(ctx, 'cordis_inspect', { what: 'dynamic' }))).toContain('(no dynamic plugins mounted)') + }) + + it('rolls back a plugin that collides with an existing tool name, keeping the original tool intact', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'usurper', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'cordis_mount', + description: 'dup', + parameters: {}, + async execute() { return [] }, + })) + }, + } + `, + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('already registered') + expect(text(result)).toContain('first cordis_unmount') + // The original cordis_mount still dispatches — the failed fiber is gone. + const retry = await call(ctx, 'cordis_mount', { code: LISTENER_CODE }) + expect(retry.isError).toBe(false) + }) + + it('isolates sandbox globals: no process/Buffer, and globalThis writes do not leak to the host', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + globalThis.__cordis_tool_leak = 'leaked' + return { name: 'probe-' + typeof process + '-' + typeof Buffer, apply(ctx) {} } + `, + }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('plugin "probe-undefined-undefined"') + expect((globalThis as Record).__cordis_tool_leak).toBeUndefined() + }) + + it.each([ + ['require(\'fs\')', 'require is not available in the mount sandbox', 'inject: [\'fs\']'], + ['setTimeout(() => {}, 5)', 'setTimeout is not available in the mount sandbox', 'ctx.setTimeout'], + ['fetch(\'https://example.com\')', 'fetch is not available in the mount sandbox', 'ctx.web'], + ])('traps the Node API call %s with a redirect to the cordis alternative', async (invocation, trapMessage, redirect) => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { code: `${invocation}\nreturn (ctx) => {}` }) + expect(result.isError).toBe(true) + expect(text(result)).toContain(trapMessage) + expect(text(result)).toContain(redirect) + expect(text(await call(ctx, 'cordis_inspect', { what: 'dynamic' }))).toContain('(no dynamic plugins mounted)') + }) + + it('lets a mounted plugin schedule through the cordis timer service (inject: [\'timer\'])', async () => { + const ctx = await setup() + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'ticker', + inject: ['timer'], + apply(ctx) { + ctx.setTimeout(() => console.log('tick'), 10) + }, + } + `, + }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('state: active') + await new Promise(resolve => setTimeout(resolve, 50)) + expect(log).toHaveBeenCalledWith('[cordis:dyn-1]', 'tick') + }) + + it('provides btoa/atob and the tagged console variants inside the sandbox', async () => { + const ctx = await setup() + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + const result = await call(ctx, 'cordis_mount', { + code: ` + console.warn('warned') + console.error('errored') + const round = atob(btoa('hi')) + const bytes = new TextEncoder().encode(round) + return { name: 'codec-' + new TextDecoder().decode(bytes), apply(ctx) { console.log('applied', typeof ctx.on) } } + `, + }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('plugin "codec-hi"') + expect(log).toHaveBeenCalledWith('[cordis:dyn-1]', 'warned') + expect(log).toHaveBeenCalledWith('[cordis:dyn-1]', 'applied', 'function') + expect(error).toHaveBeenCalledWith('[cordis:dyn-1]', 'errored') + }) + + it('answers TypeScript syntax in the plain-JS sandbox with the fix', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: 'return { name: \'ts\' as const, apply(ctx) {} }', + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('plain JavaScript, not TypeScript') + }) + + it('surfaces the offending line + caret and the bracket-balance hint on a syntax error', async () => { + const ctx = await setup() + // The canonical model mistake: closing the returned object with `});` as + // if it were a callback argument. The word "as" in a STRING elsewhere must + // not trigger the TypeScript hint — the heuristic reads the failing line. + const result = await call(ctx, 'cordis_mount', { + code: 'const note = \'treat pattern as regex\'\nreturn {\n name: \'oops\',\n apply(ctx) {}\n});', + }) + expect(result.isError).toBe(true) + const message = text(result) + expect(message).toContain('failed to parse') + expect(message).toContain('});') + expect(message).toContain('^') + expect(message).toContain('BODY of an async function') + expect(message).not.toContain('TypeScript') + }) + + it('syntaxErrorContext falls back to String(error) when the stack has no vm prelude', () => { + const doctored = new SyntaxError('boom') + delete (doctored as { stack?: string }).stack + expect(syntaxErrorContext(doctored)).toBe('SyntaxError: boom') + const plain = new SyntaxError('bang') + plain.stack = 'not-a-vm-stack' + expect(syntaxErrorContext(plain)).toBe('SyntaxError: bang') + }) + + it('handles a runtime-thrown SyntaxError (no source-line prelude) with the generic hint', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { code: 'throw new SyntaxError(\'user-crafted\')' }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('failed to parse') + expect(text(result)).toContain('user-crafted') + }) + + it('honors the configured vmTimeoutMs for the synchronous portion', async () => { + const ctx = await setup({ vmTimeoutMs: 50 }) + const result = await call(ctx, 'cordis_mount', { code: 'while (true) {}' }) + expect(result.isError).toBe(true) + expect(text(result)).toMatch(/timed? ?out/i) + expect(text(await call(ctx, 'cordis_inspect', { what: 'dynamic' }))).toContain('(no dynamic plugins mounted)') + }) + + it('makes instanceof inside the sandbox see BOTH realms (patched vm constructors, host untouched)', async () => { + // The args a tool's execute receives are HOST-realm objects; without the + // dual-realm Symbol.hasInstance prelude, `args.items instanceof Array` in + // sandbox code is silently false. The patch lives on the vm realm's own + // constructors only — the host realm's must stay pristine. + const ctx = await setup() + await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'probe-instanceof', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'probe_instanceof', + description: 'report instanceof checks across realms', + parameters: { items: { type: 'array', required: true, items: { type: 'string' } } }, + async execute(args) { + const checks = { + hostArray: args.items instanceof Array, + hostObject: args instanceof Object, + vmArray: [] instanceof Array, + vmObject: ({}) instanceof Object, + } + return [{ type: 'text', text: JSON.stringify(checks) }] + }, + })) + }, + } + `, + }) + const probed = await call(ctx, 'probe_instanceof', { items: ['a'] }) + expect(probed.isError).toBe(false) + expect(JSON.parse(text(probed))).toEqual({ hostArray: true, hostObject: true, vmArray: true, vmObject: true }) + // The host realm's constructors keep their default instanceof: no own + // Symbol.hasInstance was added to them. + expect(Object.getOwnPropertySymbols(Object)).not.toContain(Symbol.hasInstance) + expect(Object.getOwnPropertySymbols(Array)).not.toContain(Symbol.hasInstance) + }) +}) diff --git a/packages/cordis/tool-cordis/tests/present.spec.ts b/packages/cordis/tool-cordis/tests/present.spec.ts new file mode 100644 index 0000000000..d8f380439f --- /dev/null +++ b/packages/cordis/tool-cordis/tests/present.spec.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest' +import { presentInspectCall, presentMountCall, presentUnmountCall } from '../src/present.ts' +import { setup } from './helpers.ts' + +/** + * Render-intent presenters: pure functions of the call args (no I/O, no + * session state — they run on replay too), wired onto the registered tools. + */ + +describe('presenters', () => { + it('cordis_inspect renders a generic read card titled with the section', () => { + expect(presentInspectCall({})).toEqual({ card: 'generic', kind: 'read', title: 'Inspect cordis runtime' }) + expect(presentInspectCall({ what: 'api' })).toEqual({ card: 'generic', kind: 'read', title: 'Inspect cordis runtime: api' }) + }) + + it('cordis_mount renders a generic execute card carrying the code as raw input', () => { + expect(presentMountCall({ code: 'return (ctx) => {}' })).toEqual({ + card: 'generic', + kind: 'execute', + title: 'Mount plugin into live cordis runtime', + rawInput: { code: 'return (ctx) => {}' }, + }) + }) + + it('cordis_unmount renders a generic delete card titled with the id', () => { + expect(presentUnmountCall({ id: 'dyn-1' })).toEqual({ card: 'generic', kind: 'delete', title: 'Unmount dyn-1' }) + }) + + it('is wired onto the registered definitions through the defineTool soft-validation path', async () => { + const ctx = await setup() + expect(ctx.tools.get('cordis_inspect')!.presentCall!({ what: 'tools' })).toEqual({ + card: 'generic', + kind: 'read', + title: 'Inspect cordis runtime: tools', + }) + expect(ctx.tools.get('cordis_mount')!.presentCall!({ code: 'return 1' })).toMatchObject({ kind: 'execute' }) + expect(ctx.tools.get('cordis_unmount')!.presentCall!({ id: 'dyn-2' })).toMatchObject({ title: 'Unmount dyn-2' }) + // Soft validation: presenter args that fail the schema render as no card, never a throw. + expect(ctx.tools.get('cordis_unmount')!.presentCall!({ id: 42 })).toBeUndefined() + }) +}) diff --git a/packages/cordis/tool-cordis/tests/sandbox-context.spec.ts b/packages/cordis/tool-cordis/tests/sandbox-context.spec.ts new file mode 100644 index 0000000000..d3ade92572 --- /dev/null +++ b/packages/cordis/tool-cordis/tests/sandbox-context.spec.ts @@ -0,0 +1,295 @@ +import { describe, expect, it } from 'vitest' +import { call, setup, text } from './helpers.ts' + +/** + * The sandbox context façade is a whitelist, not a pass-through proxy: mount + * code reaches only the registration/eventing verbs, the timer helpers, a + * guarded `tools`, and its injected services. Every framework-plumbing member + * that could hand back an UNGUARDED context — through which a plugin could + * `ctx..tools.register({…})` to bypass the marker check and host-realm + * normalization — is denied. These are the regression guards for that escape + * class (the review finding on the original pass-through proxy). + */ + +/** Mount a plugin whose `apply` touches one framework member, and report the error text. */ +async function mountTouching(ctx: Awaited>, expr: string): Promise { + const result = await call(ctx, 'cordis_mount', { + code: `return { name: 'probe', inject: ['tools'], apply(ctx) { ${expr} } }`, + }) + expect(result.isError).toBe(true) + return text(result) +} + +describe('sandbox context façade — escape surface is closed', () => { + it.each([ + ['ctx.root', 'const c = ctx.root'], + ['ctx.parent', 'const c = ctx.parent'], + ['ctx.scope', 'const c = ctx.scope'], + ['ctx.fiber', 'const f = ctx.fiber'], + ['ctx.reflect', 'const r = ctx.reflect'], + ['ctx.registry', 'const r = ctx.registry'], + ['ctx.events', 'const e = ctx.events'], + ['ctx.extend()', 'ctx.extend({})'], + ['ctx.isolate()', 'ctx.isolate("x")'], + ['ctx.intercept()', 'ctx.intercept("x", {})'], + ['ctx.plugin()', 'ctx.plugin({ apply() {} })'], + ['ctx.set()', 'ctx.set("tools", 1)'], + ['ctx.mixin()', 'ctx.mixin("x", [])'], + ])('denies %s with a teaching error', async (_label, expr) => { + const ctx = await setup() + const message = await mountTouching(ctx, expr) + expect(message).toContain('sandbox ctx does not expose') + expect(message).toContain('withheld by design') + }) + + it('the classic ctx.root.tools.register bypass registers nothing and fails loud', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'root-bypass', + inject: ['tools'], + apply(ctx) { + ctx.root.tools.register({ + name: 'smuggled', + description: 'raw, unguarded', + parameters: { type: 'object', properties: {} }, + async execute() { return [] }, + }) + }, + } + `, + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('sandbox ctx does not expose "root"') + // The whole point: the bypass never reaches the registry. + expect(ctx.tools.get('smuggled')).toBeUndefined() + }) + + it('rejects assignment to the façade rather than silently dropping it', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: 'return { name: \'writer\', apply(ctx) { ctx.stash = 1 } }', + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('sandbox ctx is read-only') + }) + + it('denies a service whose method returns a Context (the .ctx escape), registering nothing', async () => { + // A cordis Service instance carries `.ctx` (a real Context), so + // `ctx.systemPrompt.ctx.root.tools.register(…)` would be a fresh unguarded + // handle. The service wrapper's return-value guard rejects any Context on + // the way back to sandbox code, so the escape never lands. (`systemPrompt` + // is in the setup harness, so the plugin activates and its apply runs.) + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'svc-ctx-escape', + inject: ['systemPrompt', 'tools'], + apply(ctx) { + ctx.systemPrompt.ctx.root.tools.register({ + name: 'smuggled_via_service', + description: 'raw, unguarded', + parameters: { type: 'object', properties: {} }, + async execute() { return [] }, + }) + }, + } + `, + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('returned a cordis Context, which the sandbox does not expose') + expect(ctx.tools.get('smuggled_via_service')).toBeUndefined() + }) + + it('guards an async injected-service method: a host-realm Promise resolves through the guard', async () => { + // The return guard's Promise arm only fires for a HOST-realm Promise + // (a vm-realm one is not `instanceof` the host `Promise`). Provide a + // host-realm service from the test, then inject + await it from a mount: + // the resolved value is non-Context data and passes through. + const ctx = await setup() + ctx.plugin({ + name: 'host-async-svc', + apply(c) { c.provide('hostAsync', { grab: async () => 'host-fetched' }) }, + }) + await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'async-consumer', + inject: ['hostAsync', 'tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'do_fetch', + description: 'awaits the host async service', + parameters: {}, + async execute() { + const value = await ctx.hostAsync.grab() + return [{ type: 'text', text: value }] + }, + })) + }, + } + `, + }) + const result = await call(ctx, 'do_fetch', {}) + expect(result.isError).toBe(false) + expect(text(result)).toBe('host-fetched') + }) + + it('reads a symbol property as undefined and answers the `in` operator without throwing', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'introspector', + inject: ['tools'], + apply(ctx) { + const sym = ctx[Symbol.iterator] + console.log('probe', sym === undefined, 'tools' in ctx, 'on' in ctx, 'root' in ctx) + }, + } + `, + }) + expect(result.isError).toBe(false) + }) +}) + +describe('sandbox context façade — inject gate on services', () => { + it('denies an undeclared live service (property access), naming the inject fix', async () => { + // `systemPrompt` is a live global service in the setup harness, but this + // mount does not declare it — reaching it would let the mount depend on a + // provider cordis does not know about, so it is refused. + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: 'return { name: \'undeclared\', inject: [\'tools\'], apply(ctx) { const s = ctx.systemPrompt } }', + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('service "systemPrompt" is not injected') + expect(text(result)).toContain('inject: [\'systemPrompt\', …]') + }) + + it('denies an undeclared live service reached through ctx.get too', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: 'return { name: \'undeclared-get\', inject: [\'tools\'], apply(ctx) { ctx.get(\'systemPrompt\') } }', + }) + expect(result.isError).toBe(true) + expect(text(result)).toContain('service "systemPrompt" is not injected') + }) + + it('allows a service the mount DID declare in inject', async () => { + const ctx = await setup() + const result = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'declared', + inject: ['systemPrompt', 'tools'], + apply(ctx) { console.log('has systemPrompt:', typeof ctx.systemPrompt) } + } + `, + }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('state: active') + }) + + it('a cross-mount consumer must declare the provider — the undeclared path is refused, not left as a zombie tool', async () => { + // The finding's scenario: a consumer registers a tool built on a provider's + // service WITHOUT declaring inject. cordis would then never park the + // consumer when the provider unmounts, leaving a tool that fails only at + // execution. The gate refuses the undeclared access up front, so the + // dependency is always visible to cordis. + const ctx = await setup() + await call(ctx, 'cordis_mount', { + code: 'return { name: \'greeter-provider\', apply(ctx) { ctx.provide(\'greeter\', { greet: (n) => \'hi \' + n }) } }', + }) + const undeclared = await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'sloppy-consumer', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'greet_undeclared', + description: 'uses greeter without declaring it', + parameters: { n: { type: 'string', required: true } }, + async execute(args) { return [{ type: 'text', text: ctx.greeter.greet(args.n) }] }, + })) + }, + } + `, + }) + // The tool registers (its execute is lazy), but calling it hits the gate: + // `ctx.greeter` is undeclared, so it fails with the teaching error rather + // than silently working and later stranding. + expect(undeclared.isError).toBe(false) + const called = await call(ctx, 'greet_undeclared', { n: 'x' }) + expect(called.isError).toBe(true) + expect(text(called)).toContain('service "greeter" is not injected') + }) +}) + +describe('sandbox tools façade — get is a read-only schema view', () => { + it('ctx.tools.get returns a schema, not the live ToolDefinition with execute', async () => { + // The finding: returning the raw ToolDefinition hands mount code the + // tool's execute function, letting it bypass ToolRegistry.execute (and its + // pre/post hooks). get now returns the same name/description/parameters + // view as schemas(), with no execute. Asserted via a self-made tool that + // reports the shape it saw — world-checked, not self-reported. + const ctx = await setup() + await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'reporter', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'report_view', + description: 'reports the shape of a tool view', + parameters: {}, + async execute() { + const view = ctx.tools.get('cordis_mount') + return [{ type: 'text', text: JSON.stringify({ + hasExecute: 'execute' in view, + hasPresentCall: 'presentCall' in view, + name: view.name, + keys: Object.keys(view).sort(), + }) }] + }, + })) + }, + } + `, + }) + const reported = await call(ctx, 'report_view', {}) + expect(reported.isError).toBe(false) + const shape = JSON.parse(text(reported)) as { hasExecute: boolean; hasPresentCall: boolean; name: string; keys: string[] } + expect(shape.hasExecute).toBe(false) + expect(shape.hasPresentCall).toBe(false) + expect(shape.name).toBe('cordis_mount') + expect(shape.keys).toEqual(['description', 'name', 'parameters']) + }) + + it('ctx.tools.get returns undefined for an unknown tool', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { + code: ` + return { + name: 'unknown-probe', + inject: ['tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'probe_unknown', + description: 'reports whether an unknown tool resolves', + parameters: {}, + async execute() { + return [{ type: 'text', text: String(ctx.tools.get('no_such_tool') === undefined) }] + }, + })) + }, + } + `, + }) + expect(text(await call(ctx, 'probe_unknown', {}))).toBe('true') + }) +}) diff --git a/packages/cordis/tool-cordis/tests/tool-cordis.spec.ts b/packages/cordis/tool-cordis/tests/tool-cordis.spec.ts new file mode 100644 index 0000000000..8953b5da94 --- /dev/null +++ b/packages/cordis/tool-cordis/tests/tool-cordis.spec.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest' +import Loader from '@cordisjs/plugin-loader' +import * as tool from '../src/index.ts' +import { setup } from './helpers.ts' + +/** + * Export-shape and registration surface: the namespace-plugin contract the + * real Loader path depends on, the registered tool set, and the Config + * validator's defaults and rejections. + */ + +describe('export shape', () => { + it('has no default export, and survives the real Loader unwrapExports', () => { + // A stray `export default` would make `unwrapExports` (`exports.default ?? + // exports`) collapse the module to the bare function and DROP `inject`, + // crashing at real load (docs/postmortem/0001). Assert directly AND through + // the real unwrap so adding `export default apply` fails here. + expect('default' in tool).toBe(false) + const loader = Object.create(Loader.prototype) as Loader + const unwrapped = loader.unwrapExports(tool) as Record + expect(unwrapped).toBe(tool) + expect(unwrapped.name).toBe('tool-cordis') + expect(unwrapped.inject).toEqual(['tools']) + expect(typeof unwrapped.apply).toBe('function') + expect(typeof unwrapped.Config).toBe('function') + }) +}) + +describe('tool registration', () => { + it('registers the three cordis tools with the documented schemas', async () => { + const ctx = await setup() + const names = ctx.tools.schemas().map(schema => schema.name) + expect(names).toEqual(expect.arrayContaining(['cordis_inspect', 'cordis_mount', 'cordis_unmount'])) + const inspect = ctx.tools.schemas().find(schema => schema.name === 'cordis_inspect')! + const props = (inspect.parameters as { properties: Record }).properties + expect(props.what?.enum).toEqual(['services', 'plugins', 'tools', 'dynamic', 'api', 'events']) + }) +}) + +describe('Config', () => { + it('defaults vmTimeoutMs to 5000', () => { + expect(new tool.Config()).toEqual({ vmTimeoutMs: 5000 }) + }) + + it('rejects a non-positive vmTimeoutMs at validation time (misconfiguration fails loud)', () => { + expect(() => new tool.Config({ vmTimeoutMs: 0 })).toThrow() + expect(() => new tool.Config({ vmTimeoutMs: -1 })).toThrow() + }) +}) diff --git a/packages/cordis/tool-cordis/tests/unmount-hmr.spec.ts b/packages/cordis/tool-cordis/tests/unmount-hmr.spec.ts new file mode 100644 index 0000000000..718a213968 --- /dev/null +++ b/packages/cordis/tool-cordis/tests/unmount-hmr.spec.ts @@ -0,0 +1,82 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from 'cordis' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry from '@deepseek-ai/dsh-tools' +import * as tool from '../src/index.ts' +import { call, dummyTool, LISTENER_CODE, REVERSE_TOOL_CODE, setup, text } from './helpers.ts' + +/** + * Disposal semantics: `cordis_unmount` reaches quiescence before returning, + * and disposing the tool-cordis fiber itself (the HMR path) cascades over the + * whole dynamic subtree through the ordinary parent→child fiber lifecycle. + */ + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('cordis_unmount', () => { + it('disposes the mount and its registrations have stopped by the time it returns (quiescence)', async () => { + const ctx = await setup() + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + await call(ctx, 'cordis_mount', { code: LISTENER_CODE }) + + ctx.tools.register(dummyTool('trigger_before')) + expect(log).toHaveBeenCalledTimes(1) + + const result = await call(ctx, 'cordis_unmount', { id: 'dyn-1' }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('unmounted dyn-1') + + // Immediately after the awaited unmount, the listener must be gone — no + // grace period, no eventual consistency. + ctx.tools.register(dummyTool('trigger_after')) + expect(log).toHaveBeenCalledTimes(1) + expect(text(await call(ctx, 'cordis_inspect', { what: 'dynamic' }))).toContain('(no dynamic plugins mounted)') + }) + + it('unregisters a self-made tool on unmount', async () => { + const ctx = await setup() + await call(ctx, 'cordis_mount', { code: REVERSE_TOOL_CODE }) + expect(ctx.tools.get('reverse_text')).toBeDefined() + + await call(ctx, 'cordis_unmount', { id: 'dyn-1' }) + expect(ctx.tools.get('reverse_text')).toBeUndefined() + }) + + it('rejects an unknown id, and a second unmount of the same id', async () => { + const ctx = await setup() + const unknown = await call(ctx, 'cordis_unmount', { id: 'dyn-99' }) + expect(unknown.isError).toBe(true) + expect(text(unknown)).toContain('no dynamic plugin with id "dyn-99"') + + await call(ctx, 'cordis_mount', { code: LISTENER_CODE }) + await call(ctx, 'cordis_unmount', { id: 'dyn-1' }) + const again = await call(ctx, 'cordis_unmount', { id: 'dyn-1' }) + expect(again.isError).toBe(true) + }) +}) + +describe('HMR safety', () => { + it('disposing the tool-cordis fiber cascades over the dynamic subtree and its registrations', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + const fiber = await ctx.plugin(tool) + + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + await call(ctx, 'cordis_mount', { code: LISTENER_CODE }) + await call(ctx, 'cordis_mount', { code: REVERSE_TOOL_CODE }) + expect(ctx.tools.get('reverse_text')).toBeDefined() + + await fiber.dispose() + + // The whole subtree is gone: the self-made tool, the cordis tools, and the + // mounted listener (no log on a fresh tools/change). + expect(ctx.tools.get('reverse_text')).toBeUndefined() + expect(ctx.tools.get('cordis_mount')).toBeUndefined() + const calls = log.mock.calls.length + ctx.tools.register(dummyTool('trigger_post_dispose')) + expect(log).toHaveBeenCalledTimes(calls) + }) +}) diff --git a/packages/cordis/tool-cordis/tsconfig.json b/packages/cordis/tool-cordis/tsconfig.json new file mode 100644 index 0000000000..cc9928d81f --- /dev/null +++ b/packages/cordis/tool-cordis/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/timer" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/scope" + }, + { + "path": "../../core/tools" + } + ] +} diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index b00ad6aad1..b5eb717dc8 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -57,12 +57,15 @@ forever: STEP loop: drain steering assembly = systemPrompt.assemble({agent}) ⟵ renderPrompt(assembly) IS the full prompt - await serial agent/pre-step ⟵ surface mutation (compaction) outside the step + prefix ??= waterfall agent/session-prefix ⟵ once per instance (first step): frozen + session prefix; on the header, never history + await serial agent/pre-step(…, prefix) ⟵ surface mutation (compaction) outside the step; + pressure gates see the prefix the request carries boundary = session.deriveMessages() ⟵ reconstruction boundary: same sync frame, session('step/start') strictly before step/start config = waterfall agent/request ⟵ frozen seed; return a replacement to switch session('request/header'[-delta]) ⟵ the header event this request owes the log - stream llm.stream(freeze({header..., messages: boundary})) → session('assistant/chunk') + stream llm.stream(freeze({header..., messages: prefix+boundary})) → session('assistant/chunk') message = waterfall agent/step-result session('assistant/message') each tool-call: session('tool/call') @@ -86,7 +89,7 @@ Cancellation: `agent.cancel()` is the single public stop primitive — it clears ### What is NOT here Everything that goes beyond "call the model, run the tools, repeat" belongs to plugins listening on the event taxonomy: -- Hooks: `agent/session-start`, `agent/prompt-submit`, `agent/pre-step`, `agent/request`, `agent/step-result`, `tools/pre-execute`, `tools/post-execute`, `agent/turn-continuation` +- Hooks: `agent/session-start`, `agent/prompt-submit`, `agent/pre-step`, `agent/request`, `agent/session-prefix`, `agent/step-result`, `tools/pre-execute`, `tools/post-execute`, `agent/turn-continuation` - Compaction: `agent/pre-step` - Sandbox, permission, plan mode: `tools/pre-execute` (deny/ask gate), `tools/post-execute` - Sub-agents: implemented outside the loop as `ctx.subagents` providers; in-process providers use `ctx.agents.create()` and owned `AgentHandle` teardown, while child streaming/progress and background/poll collection remain deferred. diff --git a/packages/core/agent-loop/src/loop.ts b/packages/core/agent-loop/src/loop.ts index dbb66ad7b0..efceb101fa 100644 --- a/packages/core/agent-loop/src/loop.ts +++ b/packages/core/agent-loop/src/loop.ts @@ -159,13 +159,17 @@ export interface LoopHandle { * assembly = ctx.systemPrompt.assemble(assembleContextFor(agent)) ⟵ waterfall system-prompt/assemble * (scope-filtered; scoped sections/tools join); renderPrompt * (persona section + {{variables}}) IS the full prompt - * await events.serial('agent/pre-step') ⟵ surface mutation (compaction) OUTSIDE the step + * prefix ??= waterfall agent/session-prefix ⟵ once per loop instance (first step): frozen + * session prefix; logged on the header, never + * session history (scope-filtered, fused dispatch) + * await events.serial('agent/pre-step', …, prefix) ⟵ surface mutation (compaction) OUTSIDE the step; + * pressure gates see the prefix the request carries * boundary = session.deriveMessages() ⟵ the reconstruction boundary: snapshot in the * session('step/start') same sync frame, strictly before step/start * config = waterfall agent/request(config) ⟵ frozen seed; a returned replacement switches * session('request/header'|'request/header-delta') ⟵ the header event this request owes the * log (initial/resume anchor, delta, fallback) - * req = freeze({header..., messages: boundary, sessionId, signal}) + * req = freeze({header..., messages: prefix+boundary, sessionId, signal}) * stream ctx.llm.stream(req) ⟵ waterfall llm/stream (raw chunks, frozen req) * session('assistant/chunk') * msg = waterfall agent/step-result ⟵ BEFORE the log append, so the @@ -478,6 +482,50 @@ async function runTurn( break } + // Compose the session prefix ONCE per loop instance, lazily before the + // instance's first pre-step: request-only messages placed in front of + // the ENTIRE derived history on every request this instance sends. It + // MUST precede the pre-step seam so compaction gates on THIS instance's + // prefix — reading a previous instance's logged prefix would let a + // resumed/forked instance whose contributor grew skip compaction and + // ship an over-window first request. The result is deep-cloned + // (decoupled from listener-held references), deep-frozen, and cached on + // the transmission bookkeeping, so reuse is structural — the prefix + // cannot change mid-session and the provider prefix cache holds by + // construction (resume = a new instance = a recompose, anchored by its + // 'resume' snapshot). The prefix is not session history — the header + // event in runStep is its only durable record + // (EpochHeader.messagePrefix). The frozen empty seed serves both the + // listener chain and the no-listener fallback: a contribution is a + // RETURNED extension of `await next()`, never an in-place push. This + // runs OUTSIDE the step, before the boundary snapshot: a composing + // listener's session append lands before the boundary and joins the + // CURRENT request. + if (transmission.sessionPrefix === undefined) { + const emptyPrefix: Message[] = deepFreeze([]) + const composed = await events.waterfall( + 'agent/session-prefix', emptyPrefix, abort.signal, + () => Promise.resolve(emptyPrefix), + ) + + // Interruption landing during prefix composition: mirror the assembly + // window above — drop the about-to-start step without running the + // seam, and DISCARD the composition instead of caching it. An + // abort-aware listener may have returned a degraded fallback under + // the firing signal; committing it would ship a prefix no request + // ever used (and no header ever logged) on this instance's next real + // request. The next turn recomposes under a live signal — the cache + // only ever holds a fully composed prefix. The cache-hit path needs + // no such check: nothing awaits between the assembly check above and + // the pre-step seam. + if (handle.isCancelled() || handle.isDisposed()) { + handle.setAbort(undefined) + reason = handle.isDisposed() ? { kind: 'disposed' } : { kind: 'aborted', reason: handle.cancelReason() } + break + } + transmission.sessionPrefix = deepFreeze(structuredClone(composed)) + } + // Pre-step surface-mutation checkpoint (compaction), fired OUTSIDE the // step: after `turn/start` (and the prior step's close) but before // `step/start`, so a compaction's log-only `compact/*` records and its @@ -488,8 +536,10 @@ async function runTurn( // concurrent listeners cannot interleave their `session.append`s. A // throwing listener escapes to the outer catch, which closes the (not-yet- // open) step as a no-op and ends the turn via failTurn — a broken - // pre-step plugin ends the turn, not the loop. - await events.serial('agent/pre-step', turn, step, fullSystemPrompt, abort.signal) + // pre-step plugin ends the turn, not the loop. The composed session + // prefix rides along so token-pressure listeners count everything the + // request will actually carry. + await events.serial('agent/pre-step', turn, step, fullSystemPrompt, transmission.sessionPrefix, abort.signal) // Interruption landing during the pre-step seam: do not open an empty step. if (handle.isCancelled() || handle.isDisposed()) { @@ -682,11 +732,12 @@ function drainSteering(agent: ReactLoopAgent, turn: number): boolean { } /** One step: build the request from the boundary snapshot + the step's - * header → log the header event the request owes → stream model → record → - * execute tools. The caller assembles the system prompt, fires the - * `agent/pre-step` seam, snapshots the derivation, and opens the step BEFORE - * calling this, so `boundaryMessages` is exactly the surface prefix at - * step/start and already reflects any compaction. */ + * header → compose the session prefix if this instance has none yet → log + * the header event the request owes → stream model → record → execute + * tools. The caller assembles the + * system prompt, fires the `agent/pre-step` seam, snapshots the derivation, + * and opens the step BEFORE calling this, so `boundaryMessages` is exactly + * the surface prefix at step/start and already reflects any compaction. */ async function runStep( ctx: Context, events: AgentEventDispatch, @@ -727,22 +778,30 @@ async function runStep( throw new Error(`agent "${agent.id}" has no model: set AgentOptions.model or supply one via the agent/request waterfall`) } + // The session prefix was composed (once per instance) before this step's + // pre-step seam — the caller guarantees it, so the cache is always set here. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- runTurn composes the prefix before every runStep call + const sessionPrefix = transmission.sessionPrefix! + // The request header (the log's request/header* vocabulary): canonical form, - // recorded before dispatch so the log always explains the request. + // recorded before dispatch so the log always explains the request — + // including the session prefix, which no other event carries. const header = canonicalHeader({ config, ...system ? { system } : {}, ...assembly.tools.length > 0 ? { tools: assembly.tools } : {}, + ...sessionPrefix.length > 0 ? { messagePrefix: sessionPrefix } : {}, }) recordRequestHeader(session, transmission, header) // Build and freeze: the request is a pure function of (boundary snapshot, // logged header) — llm/stream listeners and adapters read it, mutation // throws. sessionId + frozen is the loop-built marker the dev invariant - // keys on. + // keys on. Message order: header.messagePrefix, then the boundary + // snapshot — the reconstruction equation the invariant recomputes. const request: GenerateOptions = deepFreeze({ model: header.config.model, - messages: boundaryMessages, + messages: [...header.messagePrefix ?? [], ...boundaryMessages], ...header.system !== undefined ? { system: header.system } : {}, ...header.tools !== undefined ? { tools: header.tools } : {}, ...header.config.temperature !== undefined ? { temperature: header.config.temperature } : {}, diff --git a/packages/core/agent-loop/src/request-log.ts b/packages/core/agent-loop/src/request-log.ts index 90f47068fa..d2763f5c2a 100644 --- a/packages/core/agent-loop/src/request-log.ts +++ b/packages/core/agent-loop/src/request-log.ts @@ -12,11 +12,20 @@ import { diffHeader, headerEquals, applyHeaderDelta } from '@deepseek-ai/dsh-session' import type { EpochHeader, Session } from '@deepseek-ai/dsh-session' +import type { Message } from '@deepseek-ai/dsh-llm' /** Per-loop-instance bookkeeping: whether THIS instance has logged a header yet. */ export interface TransmissionLog { /** True once this loop instance appended its anchoring `request/header` snapshot. */ loggedHeader: boolean + /** + * The instance's composed session prefix (the `agent/session-prefix` + * waterfall's deep-frozen product), cached on the instance's first + * request-building step and reused verbatim for every request it sends — + * the structural guarantee that the prefix never changes mid-session. + * `undefined` until composed. + */ + sessionPrefix?: Message[] } /** @@ -61,7 +70,7 @@ export function recordRequestHeader(session: Session, state: TransmissionLog, he const baseline = session.requestHeader()! if (headerEquals(baseline, header)) return const delta = diffHeader(baseline, header) - /* v8 ignore next -- headerEquals false ⟹ diffHeader defined: both compare the same three parts */ + /* v8 ignore next -- headerEquals false ⟹ diffHeader defined: both compare the same four parts */ if (delta === undefined) return if (headerEquals(applyHeaderDelta(baseline, delta), header)) { session.append('request/header-delta', delta) diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index 0e77f0bcbf..63a75447ca 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -12,7 +12,7 @@ import { describe, expect, it } from 'vitest' import { Context } from 'cordis' -import LlmService from '@deepseek-ai/dsh-llm' +import LlmService, { type Message } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, TurnEndReason } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry from '@deepseek-ai/dsh-tools' @@ -166,6 +166,103 @@ describe('Agent.cancel()', () => { expect(reasons.length).toBe(2) }) + it('cancel from inside the agent/session-prefix waterfall drops the step (prefix-composition window)', async () => { + const adapter = new MockAdapter([textResponse('should not stream')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + + // Prefix composition runs before the pre-step seam on the instance's first + // step; a cancel landing inside it must drop the about-to-start step + // without running the seam or the model. + let streamed = false + ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true }) + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => { + agent.cancel('from prefix composition') + return next() + }) + + const reasons: TurnEndReason[] = [] + ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) }) + + send(agent, 'go') + await waitForIdle(ctx, agent) + + expect(streamed).toBe(false) + expect(reasons).toEqual([{ kind: 'aborted', reason: 'from prefix composition' }]) + }) + + it('disposal from inside the agent/session-prefix waterfall ends the turn disposed (prefix-composition window)', async () => { + const adapter = new MockAdapter([textResponse('should not stream')]) + const ctx = new Context() + await ctx.plugin(LlmService) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(AgentLoop, { agents: [] }) + ctx.llm.registerAdapter(['mock'], adapter) + + const handle = ctx.agents.create({ + agentId: AgentId('a-dispose-prefix'), + sessionId: SessionId('dispose-prefix-session'), + agentOptions: { model: 'mock' }, + }) + const agent = handle.agent as ReactLoopAgent + + let disposalDone: Promise | undefined + let streamed = false + ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true }) + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => { + disposalDone = handle.dispose() + return next() + }) + + send(agent, 'go') + await new Promise(resolve => setTimeout(resolve, 0)) + await disposalDone + await agent.done + + // No step opened, no model call ran, and the turn closed disposed. + expect(streamed).toBe(false) + expect(adapter.requests).toHaveLength(0) + const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end') + expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' }) + }) + + it('a cancel-interrupted prefix composition is discarded: the next send recomposes and ships the fresh prefix (stale-cache guard)', async () => { + const adapter = new MockAdapter([textResponse('reply')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + + // The first composition is interrupted mid-waterfall and — like an + // abort-aware listener bailing on a firing signal — contributes nothing. + // Caching that degraded result would silently strip the prefix from every + // later request of this instance; the loop must discard it and recompose + // on the next send, and the SECOND composition's value must be what the + // wire and the header log carry. + const opener: Message = { role: 'user', content: [{ type: 'text', text: 'fresh opener' }] } + let compositions = 0 + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise => { + compositions += 1 + if (compositions === 1) { + agent.cancel('mid-composition') + return next() + } + return [opener, ...await next()] + }) + + send(agent, 'dropped') + await waitForIdle(ctx, agent) + send(agent, 'real prompt') + await waitForIdle(ctx, agent) + + expect(compositions).toBe(2) + expect(adapter.requests).toHaveLength(1) + expect(adapter.requests[0]?.messages[0]).toEqual(opener) + const headerEvent = agent.session.events.find(e => e.type === 'request/header') + expect(headerEvent?.type === 'request/header' && headerEvent.data.header.messagePrefix).toEqual([opener]) + }) + it('cancel from a synchronous turn/start session-event listener drops the step (step-start window)', async () => { const adapter = new MockAdapter([textResponse('should not stream')]) const ctx = await harness(adapter) diff --git a/packages/core/agent-loop/tests/interception.spec.ts b/packages/core/agent-loop/tests/interception.spec.ts index e76ac30fa9..bab2ae6ea1 100644 --- a/packages/core/agent-loop/tests/interception.spec.ts +++ b/packages/core/agent-loop/tests/interception.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { Context } from 'cordis' -import LlmService, { CallId } from '@deepseek-ai/dsh-llm' +import LlmService, { CallId, type Message } from '@deepseek-ai/dsh-llm' import SessionStore, { type SessionEvent, type TurnEndReason } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { defineTool, type PostToolDecision, type PreToolDecision } from '@deepseek-ai/dsh-tools' @@ -310,6 +310,162 @@ describe('agent/session-start', () => { }) }) +describe('agent/session-prefix', () => { + it('composes once per loop instance and fronts every request; the header records it; history stays untouched', async () => { + const adapter = new MockAdapter([ + toolCallResponse('c1', 'echo', { text: 'ping' }), + textResponse('done'), + textResponse('again'), + ]) + const ctx = await harness(adapter) + ctx.tools.register(defineTool({ + name: 'echo', description: 'echo', parameters: { text: { type: 'string' } }, + async execute(args) { return [{ type: 'text', text: String(args.text) }] }, + })) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + + const reminder: Message = { role: 'user', content: [{ type: 'text', text: 'catalog' }] } + let composed = 0 + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise => { + composed += 1 + return [...await next(), reminder] + }) + + send(agent, 'go') + await waitForIdle(ctx, agent) + send(agent, 'next turn') + await waitForIdle(ctx, agent) + + // Three requests (two turns), ONE composition: the frozen product is + // reused verbatim, so the prefix cannot drift mid-session. + expect(adapter.requests).toHaveLength(3) + expect(composed).toBe(1) + for (const request of adapter.requests) { + expect(request.messages[0]).toEqual(reminder) + } + // The anchoring snapshot is the prefix's durable record — and the ONLY + // header event: reuse means no request/header-delta ever. + const headerEvents = events(agent).filter(e => e.type === 'request/header' || e.type === 'request/header-delta') + expect(headerEvents).toHaveLength(1) + expect(headerEvents[0]?.type === 'request/header' && headerEvents[0].data.header.messagePrefix).toEqual([reminder]) + // Never session history: the derivation starts at the real user prompt. + expect(agent.session.deriveMessages()[0]).toEqual({ role: 'user', content: [{ type: 'text', text: 'go' }] }) + }) + + it('composes before the first pre-step and hands the prefix to the seam (pressure gates see the real value)', async () => { + const adapter = new MockAdapter([textResponse('ok')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + + const reminder: Message = { role: 'user', content: [{ type: 'text', text: 'opener' }] } + const order: string[] = [] + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise => { + order.push('compose') + return [reminder, ...await next()] + }) + const seen: (readonly Message[])[] = [] + ctx.on('agent/pre-step', (_agent, _turn, _step, _system, sessionPrefix) => { + order.push('pre-step') + seen.push(sessionPrefix) + }) + + send(agent, 'hi') + await waitForIdle(ctx, agent) + + // Composition precedes the pre-step seam, and the seam receives THIS + // instance's composed prefix — a token-pressure gate (compaction) counts + // what the request will actually carry, never a stale logged prefix. + expect(order).toEqual(['compose', 'pre-step']) + expect(seen[0]).toEqual([reminder]) + }) + + it('the canonical prepend pattern composes contributions in registration order', async () => { + const adapter = new MockAdapter([textResponse('ok')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + + // Both listeners use the canonical `[mine, ...await next()]` prepend: the + // waterfall unwinds innermost-first (the second listener's array is built + // first), so prepending puts the FIRST-registered contribution first. + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise => { + return [{ role: 'user', content: [{ type: 'text', text: 'first' }] }, ...await next()] + }) + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise => { + return [{ role: 'user', content: [{ type: 'text', text: 'second' }] }, ...await next()] + }) + + send(agent, 'hi') + await waitForIdle(ctx, agent) + + const texts = adapter.requests[0]!.messages.map(m => m.content[0]?.type === 'text' ? m.content[0].text : '') + expect(texts).toEqual(['first', 'second', 'hi']) + }) + + it('with no contributions the header omits messagePrefix and the request is the bare derivation', async () => { + const adapter = new MockAdapter([textResponse('ok')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + + // A listener that delegates without contributing — the canonical no-op. + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => next()) + + send(agent, 'hi') + await waitForIdle(ctx, agent) + + const headerEvent = events(agent).find(e => e.type === 'request/header') + expect(headerEvent?.type === 'request/header' && 'messagePrefix' in headerEvent.data.header).toBe(false) + expect(adapter.requests[0]!.messages).toEqual([{ role: 'user', content: [{ type: 'text', text: 'hi' }] }]) + }) + + it('the frozen seed rejects in-place mutation — a contribution is a returned extension', async () => { + const adapter = new MockAdapter([textResponse('ok')]) + const ctx = await harness(adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + + let mutationError: unknown + ctx.on('agent/session-prefix', async (_agent, prefix, _signal, next): Promise => { + try { + prefix.push({ role: 'user', content: [{ type: 'text', text: 'smuggled' }] }) + } catch (error: unknown) { + mutationError = error + } + return next() + }) + + send(agent, 'hi') + await waitForIdle(ctx, agent) + + expect(mutationError).toBeInstanceOf(TypeError) + expect(adapter.requests[0]!.messages).toEqual([{ role: 'user', content: [{ type: 'text', text: 'hi' }] }]) + }) + + it('mutating a listener-held reference after composition cannot alter later requests (the cache is a frozen clone)', async () => { + const adapter = new MockAdapter([ + toolCallResponse('c1', 'echo', { text: 'ping' }), + textResponse('done'), + ]) + const ctx = await harness(adapter) + ctx.tools.register(defineTool({ + name: 'echo', description: 'echo', parameters: { text: { type: 'string' } }, + async execute(args) { return [{ type: 'text', text: String(args.text) }] }, + })) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + + const held: Message = { role: 'user', content: [{ type: 'text', text: 'v1' }] } + ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise => [...await next(), held]) + + send(agent, 'go') + await waitForIdle(ctx, agent) + + // The listener mutates the object it contributed AFTER composition; the + // cached prefix is a deep-frozen clone, so step 2's request is unchanged. + held.content = [{ type: 'text', text: 'v2' }] + expect(adapter.requests[1]!.messages[0]).toEqual({ role: 'user', content: [{ type: 'text', text: 'v1' }] }) + expect(events(agent).filter(e => e.type === 'request/header-delta')).toHaveLength(0) + }) +}) + + describe('agent/turn-continuation (ContinuationDecision)', () => { it('a continue decision with a reason records next-step steering in the same turn', async () => { const adapter = new MockAdapter([textResponse('step 1 no tools'), textResponse('step 2')]) diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 5c7b723739..e857676b0f 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -45,8 +45,9 @@ Turn and step boundaries are NOT mirrored as `agent/*` emits: a consumer that ne - `agent/session-start` (emit) — fired once before the first turn; a listener seeds context via `agent.inject()` (it cannot veto startup). - `agent/prompt-submit` — decide what happens to one drained queued message before it becomes a `user/message`: `PromptDecision` = `allow` (optionally rewriting the prompt `content` or attaching `additionalContext`) or `block` (drop it; a batch whose every prompt is blocked opens a zero-step turn that ends `rejected`). Maps onto Claude Code's `UserPromptSubmit`. -- `agent/pre-step` (serial) — mutate the session surface before the step opens and history is derived (compaction). Fires after `turn/start` and before `step/start`, so a listener's appended events land outside the step. +- `agent/pre-step` (serial) — mutate the session surface before the step opens and history is derived (compaction). Fires after `turn/start` and before `step/start`, so a listener's appended events land outside the step; carries the assembled system prompt and the instance's composed session prefix so a token-pressure gate counts everything the request will carry. - `agent/request` — shape the call config before the model call: a frozen `LlmCallConfig` seed in, a replacement out (model switching, sampling overrides). Content is not shapeable here — every request is a pure function of the session log ([reconstructability RFC](../../../docs/rfc/implemented/architecture/2026-07-05-reconstructable-requests.md)); the loop logs whatever config the request actually uses as a `request/header*` event +- `agent/session-prefix` — compose the session prefix: request-only messages placed in front of the ENTIRE derived history on every request. Fired ONCE per loop instance, lazily before its first pre-step (so pressure gates see this instance's real prefix, never a previous instance's logged one); the composed result is deep-frozen, recorded as `EpochHeader.messagePrefix` on the anchoring `request/header` snapshot, and reused verbatim afterwards — the prefix cannot change mid-session, so the provider prefix cache holds by construction (resume = a new instance = a recompose, attributably anchored by its `'resume'` snapshot). The home for session-stable openers that must not become durable history (a skills catalog, an AGENTS.md digest); `deriveMessages()` never returns it. Content that CHANGES mid-session belongs in the append-only history channels instead — `agent.inject()`, `tools/post-execute` `additionalContext`, prompt-submit `additionalContext` — each a durable `context/message` paid once and prefix-cached thereafter - `agent/step-result` — post-process the assembled assistant message before tool dispatch (validates what the log records) - `agent/turn-continuation` — override the continue/stop decision via `ContinuationDecision` = `{action:'stop'}` or `{action:'continue', reason?}` (a `continue` `reason` is recorded as next-step steering in the same turn — the typed `/goal` pattern). Force-continue `/loop`, force-stop budget guard. diff --git a/packages/core/agent/src/types.ts b/packages/core/agent/src/types.ts index ff6f79d039..a0ef52e735 100644 --- a/packages/core/agent/src/types.ts +++ b/packages/core/agent/src/types.ts @@ -17,7 +17,8 @@ * consumer that wants the live transcript subscribes here. * - **`agent/*`** (this module) — the LIVE runtime surface. Always carries the * live `Agent`. Two shapes: INTERCEPTION seams (the `agent/prompt-submit`/ - * `agent/request`/`agent/step-result`/`agent/turn-continuation` waterfalls and + * `agent/request`/`agent/session-prefix`/`agent/step-result`/ + * `agent/turn-continuation` waterfalls and * the serial `agent/pre-step`) that mutate/veto, and TRANSIENT emits * (`agent/status`, `agent/error`, `agent/created`/ * `agent/disposed`, `agent/queued`, `agent/session-start`) @@ -374,7 +375,12 @@ declare module 'cordis' { * value; this event is typed and documented as `void`, so listeners must not * return a semantic veto value. `fullSystemPrompt` is the assembled prompt a * listener needs to measure pressure (the system prompt counts toward the - * budget). `signal` cancels any in-flight work a listener starts (e.g. a + * budget), and `sessionPrefix` is the instance's composed + * {@link agent/session-prefix} product for the same reason — every request + * carries it in front of the derived history, and it is composed BEFORE + * this seam fires precisely so a pressure gate counts the prefix the + * request will actually send (never a stale logged one). `signal` cancels + * any in-flight work a listener starts (e.g. a * summarization model call). * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): a listener registered * through `agent.ctx` fires only for that agent's dispatches; a listener on a @@ -385,15 +391,17 @@ declare module 'cordis' { * @param turn - the already-open turn this step belongs to. * @param step - the number of the step about to start. * @param fullSystemPrompt - the assembled prompt, for measuring token pressure. + * @param sessionPrefix - the instance's frozen session prefix, for the same measurement. * @param signal - aborts in-flight listener work when the turn is torn down. * @mode serial */ - // TODO: `fullSystemPrompt` is a smell on a generic per-step seam — compaction - // is its only consumer, so a wide event carries a string just one listener + // TODO: `fullSystemPrompt`/`sessionPrefix` are a smell on a generic + // per-step seam — compaction + // is their only consumer, so a wide event carries payloads just one listener // reads. Revisit if no second consumer appears: e.g. hand listeners a lazy // prompt provider, or move token-pressure measurement behind a // compaction-specific seam instead of the shared pre-step checkpoint. - 'agent/pre-step'(this: Scoped, agent: Agent, turn: number, step: number, fullSystemPrompt: string, signal: AbortSignal): Promise | void + 'agent/pre-step'(this: Scoped, agent: Agent, turn: number, step: number, fullSystemPrompt: string, sessionPrefix: readonly Message[], signal: AbortSignal): Promise | void /** * Waterfall: decide what happens to ONE drained queued message before it * becomes a `user/message` — allow (optionally rewriting the prompt bytes or @@ -419,8 +427,9 @@ declare module 'cordis' { * ALL a listener shapes here: every request is a pure function of the * session log (the reconstructability RFC), so model-visible content * flows through the log channels — `inject()`, steering, prompt-submit - * `additionalContext`, prompt sections via `system-prompt/assemble` — - * never through request mutation, and the loop records whatever config + * `additionalContext`, prompt sections via `system-prompt/assemble`, or + * the header-logged session prefix via {@link agent/session-prefix} + * — never through request mutation, and the loop records whatever config * the request actually uses as a `request/header*` event before dispatch. * The step's messages are already snapshotted when this fires (the * `step/start` boundary): an `inject()` from a listener here lands in the @@ -440,6 +449,58 @@ declare module 'cordis' { * @mode waterfall */ 'agent/request'(this: Scoped, agent: Agent, turn: number, step: number, config: LlmCallConfig, next: () => Promise): Promise + /** + * Waterfall: compose the SESSION PREFIX — request-only messages placed in + * front of the ENTIRE derived history (directly after the provider's + * system slot) on every request this loop instance sends. Fired ONCE per + * loop instance, lazily before its first step's {@link agent/pre-step} + * seam — BEFORE the pre-step so a token-pressure gate (compaction) counts + * the prefix this instance will actually send, never a previous + * instance's logged one. The composed + * result is deep-frozen, recorded as `EpochHeader.messagePrefix` on the + * instance's anchoring `'initial'`/`'resume'` header snapshot, and reused + * verbatim for every subsequent request — never recomputed mid-session, + * so the provider prefix cache holds by construction (a process restart + * or `ctx.agents.resume()` is a new instance: it recomposes, and any + * drift lands attributably on the `'resume'` snapshot). Composition runs + * outside the step, before the boundary snapshot: a composing listener's + * session append joins the CURRENT request's derived history. A + * composition interrupted by a cancel/dispose landing inside the + * waterfall is discarded — never cached, logged, or sent — and the next + * turn recomposes under a live signal, so an abort-aware listener's + * degraded fallback cannot leak into later requests. + * + * This is the home for session-stable openers the model must always see + * but that must NOT become durable history — a skills catalog, an + * AGENTS.md digest, a workspace baseline: `Session.deriveMessages()` + * never returns the prefix, and the header events are its only durable + * record, so the request stays reconstructable from the log. Content + * that CHANGES mid-session belongs in the append-only history channels + * instead — `agent.inject()`, a `tools/post-execute` decision's + * `additionalContext`, prompt-submit `additionalContext` — each a + * durable `context/message` paid once and prefix-cached thereafter. + * + * The seed is a frozen empty list; a contributing listener returns a NEW + * array — never an in-place push. The canonical contribution is a + * PREPEND, `[mine, ...await next()]`: the waterfall unwinds + * innermost-first (the LAST-registered listener's `next()` resolves + * first), so prepending yields registration order on the wire, and every + * plugin using it composes deterministically. The append form + * `[...await next(), mine]` is legal but places a contribution AFTER + * every later-registered plugin's — reverse registration order when all + * contributors append. Call `next()` to + * delegate, or return a list without it to short-circuit. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): a listener registered + * through `agent.ctx` fires only for that agent's dispatches; a listener on a + * plain plugin context fires for every agent. The dispatch `this` is the + * scope carrier (`Scoped`), built by the emitting side via + * `scopeTarget`/`agentEvents`. + * @param agent - the agent whose session prefix is being composed. + * @param prefix - the frozen empty seed; return an extended replacement to contribute. + * @param signal - aborts in-flight listener work (e.g. a discovery scan) when the step is torn down. + * @mode waterfall + */ + 'agent/session-prefix'(this: Scoped, agent: Agent, prefix: Message[], signal: AbortSignal, next: () => Promise): Promise /** * Waterfall: post-process the assembled assistant {@link Message} before * tool dispatch (validation, content rewriting, …). diff --git a/packages/core/session/README.md b/packages/core/session/README.md index 767008d8ee..629cef5aec 100644 --- a/packages/core/session/README.md +++ b/packages/core/session/README.md @@ -52,7 +52,7 @@ Plain class (not a Cordis Service). Create via `ctx.sessions.create()`. ### Request-header reconstruction (`request-header.ts`) -The `request/header` (full `EpochHeader` snapshot with a `RequestHeaderReason`) and `request/header-delta` (system line-trim / name-keyed tools delta / whole config) events make the request envelope logged session state, so every conversation request is a pure function of the log. The pure trio reconstructs it: `foldRequestHeader(events)` folds a log (or any prefix) into the header in force; `diffHeader(prev, next)` encodes a change (undefined when equal); `applyHeaderDelta(prev, delta)` replays one. Writer contract: every logged delta is round-trip-verified (`apply(prev, delta)` deep-equals the new header) with a `'fallback'` snapshot when the encoding cannot express the change (a pure tool reordering), so folding never needs error recovery on a well-formed log. `canonicalHeader` pins the one representation of absence (empty system/tools ≡ absent fields). +The `request/header` (full `EpochHeader` snapshot with a `RequestHeaderReason`) and `request/header-delta` (system line-trim / name-keyed tools delta / whole config / whole session prefix) events make the request envelope logged session state, so every conversation request is a pure function of the log. The pure trio reconstructs it: `foldRequestHeader(events)` folds a log (or any prefix) into the header in force; `diffHeader(prev, next)` encodes a change (undefined when equal); `applyHeaderDelta(prev, delta)` replays one. Writer contract: every logged delta is round-trip-verified (`apply(prev, delta)` deep-equals the new header) with a `'fallback'` snapshot when the encoding cannot express the change (a pure tool reordering), so folding never needs error recovery on a well-formed log. `canonicalHeader` pins the one representation of absence (empty system/tools/messagePrefix ≡ absent fields; a delta's EMPTY prefix array encodes the transition back to absence). `EpochHeader.messagePrefix` is the durable record of the `agent/session-prefix` waterfall's product — composed once per loop instance, the request is `messagePrefix + derived history`, and `deriveMessages()` never returns it. ### Session event vocabulary (`types.ts`) diff --git a/packages/core/session/src/request-header.ts b/packages/core/session/src/request-header.ts index d83da16197..eeb2fe40ed 100644 --- a/packages/core/session/src/request-header.ts +++ b/packages/core/session/src/request-header.ts @@ -13,15 +13,23 @@ */ import { callConfigEquals } from '@deepseek-ai/dsh-llm' -import type { LlmCallConfig, ToolSchema } from '@deepseek-ai/dsh-llm' +import type { LlmCallConfig, Message, ToolSchema } from '@deepseek-ai/dsh-llm' import type { EpochHeader, SessionEvent, SystemDelta, ToolsDelta } from './types.ts' +/** The `request/header-delta` payload shape: each present field amends the folded header. */ +type HeaderDelta = { + system?: SystemDelta + tools?: ToolsDelta + config?: LlmCallConfig + messagePrefix?: Message[] +} + /** - * Normalize a header to canonical form: an empty system prompt and an empty - * tool list become ABSENT fields, matching how requests are built (both - * request-build spreads skip empty values). Diff, fold, and comparison all - * operate on canonical headers, so "no system prompt" has exactly one - * representation. + * Normalize a header to canonical form: an empty system prompt, an empty + * tool list, and an empty session prefix become ABSENT fields, matching how + * requests are built (the request-build spreads skip empty values). Diff, + * fold, and comparison all operate on canonical headers, so "no system + * prompt" (and "no session prefix") has exactly one representation. * @param header - the header to normalize (not mutated). * @returns the canonical header. */ @@ -30,6 +38,7 @@ export function canonicalHeader(header: EpochHeader): EpochHeader { config: header.config, ...header.system !== undefined && header.system.length > 0 ? { system: header.system } : {}, ...header.tools !== undefined && header.tools.length > 0 ? { tools: header.tools } : {}, + ...header.messagePrefix !== undefined && header.messagePrefix.length > 0 ? { messagePrefix: header.messagePrefix } : {}, } } @@ -109,37 +118,46 @@ function applyTools(prev: readonly ToolSchema[], delta: ToolsDelta): ToolSchema[ * writer's round-trip guard runs (`applyHeaderDelta(prev, delta)` must equal * the intended header) and the loop runs to skip logging an unchanged header. * Tools compare per-schema IN ORDER (canonical JSON), so a pure reordering is - * correctly unequal. + * correctly unequal; the session prefix compares as canonical JSON (both + * sides come from the same build path, so key order matches when the values + * do). * @param a - one canonical header. * @param b - the other. - * @returns whether config, system, and tools (in order) all match. + * @returns whether config, system, tools (in order), and the session prefix all match. */ export function headerEquals(a: EpochHeader, b: EpochHeader): boolean { if (!callConfigEquals(a.config, b.config) || a.system !== b.system) return false + if (!sameMessages(a.messagePrefix, b.messagePrefix)) return false const at = a.tools ?? [] const bt = b.tools ?? [] return at.length === bt.length && at.every((tool, i) => sameSchema(tool, bt[i] as ToolSchema)) } +/** Canonical JSON equality over session-prefix arrays; absence equals the empty array. */ +function sameMessages(a: readonly Message[] | undefined, b: readonly Message[] | undefined): boolean { + return JSON.stringify(a ?? []) === JSON.stringify(b ?? []) +} + /** * Compute the `request/header-delta` payload between two canonical headers, * or undefined when they are equal. The caller MUST round-trip the result * ({@link applyHeaderDelta} on `prev` deep-equals `next`) before logging it — * the encoding cannot express every change (a pure tool reordering) — and * fall back to a full `request/header` snapshot when the check fails. + * The session prefix is replaced whole (small advisory content, not worth + * diffing); an empty replacement array encodes the transition to "none". * @param prev - the folded header the log currently implies. * @param next - the header the next request will actually use. * @returns the delta payload, or undefined when nothing changed. */ -export function diffHeader( - prev: EpochHeader, next: EpochHeader, -): { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig } | undefined { - const delta: { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig } = {} +export function diffHeader(prev: EpochHeader, next: EpochHeader): HeaderDelta | undefined { + const delta: HeaderDelta = {} if (prev.system !== next.system) delta.system = diffSystem(prev.system, next.system) const prevTools = prev.tools ?? [] const nextTools = next.tools ?? [] if (JSON.stringify(prevTools) !== JSON.stringify(nextTools)) delta.tools = diffTools(prevTools, nextTools) if (!callConfigEquals(prev.config, next.config)) delta.config = next.config + if (!sameMessages(prev.messagePrefix, next.messagePrefix)) delta.messagePrefix = next.messagePrefix ?? [] return Object.keys(delta).length > 0 ? delta : undefined } @@ -151,15 +169,15 @@ export function diffHeader( * @param delta - the logged delta payload. * @returns the canonical header after the delta. */ -export function applyHeaderDelta( - prev: EpochHeader, delta: { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig }, -): EpochHeader { +export function applyHeaderDelta(prev: EpochHeader, delta: HeaderDelta): EpochHeader { const system = delta.system !== undefined ? applySystem(prev.system, delta.system) : prev.system const tools = delta.tools !== undefined ? applyTools(prev.tools ?? [], delta.tools) : prev.tools + const messagePrefix = delta.messagePrefix ?? prev.messagePrefix return canonicalHeader({ config: delta.config ?? prev.config, ...system !== undefined ? { system } : {}, ...tools !== undefined ? { tools } : {}, + ...messagePrefix !== undefined ? { messagePrefix } : {}, }) } diff --git a/packages/core/session/src/types.ts b/packages/core/session/src/types.ts index e2e0e1b216..ca6779e1dc 100644 --- a/packages/core/session/src/types.ts +++ b/packages/core/session/src/types.ts @@ -1,5 +1,5 @@ import type { Branded } from '@deepseek-ai/dsh-brand' -import type { CallId, ContentBlock, LlmCallConfig, MessageSource, StreamChunk, TokenUsage, ToolSchema } from '@deepseek-ai/dsh-llm' +import type { CallId, ContentBlock, LlmCallConfig, Message, MessageSource, StreamChunk, TokenUsage, ToolSchema } from '@deepseek-ai/dsh-llm' /** Identifies one session in the store (and its persistence artifacts). */ export type SessionId = Branded<'SessionId'> @@ -183,14 +183,15 @@ export interface TodoItem { } /** - * The request header: everything about an LLM request besides its message - * content — the call configuration plus the rendered system prompt and tool - * schemas. Logged session state (the reconstructability RFC): a + * The request header: everything about an LLM request besides its derived + * message history — the call configuration plus the rendered system prompt, + * tool schemas, and the session prefix. Logged session state (the + * reconstructability RFC): a * {@link SessionEventMap} `request/header` snapshot installs one, a * `request/header-delta` amends it, and folding those events over the log * (`foldRequestHeader`) reconstructs the header any request was built under. - * Canonical form: an empty system prompt and an empty tool list are ABSENT - * fields, matching how requests are built. + * Canonical form: an empty system prompt, an empty tool list, and an empty + * prefix are ABSENT fields, matching how requests are built. */ export interface EpochHeader { /** The conversation's call configuration (model + sampling scalars). */ @@ -199,6 +200,14 @@ export interface EpochHeader { system?: string /** Assembled tool schemas; absent for a tool-less request. */ tools?: ToolSchema[] + /** + * The session prefix: request-only messages sent BEFORE the entire derived + * history (the `agent/session-prefix` waterfall's product, composed once + * per loop instance and reused for every request it sends). Not session + * history — `deriveMessages()` never returns it — so the header is its + * only durable record; absent when the instance composed none. + */ + messagePrefix?: Message[] } /** @@ -356,15 +365,21 @@ export interface SessionEventMap { 'request/header': { header: EpochHeader; reason: RequestHeaderReason } /** * Amendment to the folded {@link EpochHeader}: at least one of a - * {@link SystemDelta}, a {@link ToolsDelta}, or a whole replacement - * {@link LlmCallConfig} (four scalars — not worth diffing). Appended by the + * {@link SystemDelta}, a {@link ToolsDelta}, a whole replacement + * {@link LlmCallConfig} (four scalars — not worth diffing), or a whole + * replacement session prefix (`messagePrefix` — small advisory content, + * replaced whole; an EMPTY array encodes the transition to "none", + * mirroring the canonical form's absent field — the loop never produces + * one in practice: the prefix is composed once per instance and anchored + * by that instance's snapshot, so this arm exists for codec totality). + * Appended by the * loop inside the step, before dispatch, when the header for this request * differs from the fold of the log so far; the writer verifies * `applyHeaderDelta(previous, delta)` reproduces the new header exactly and * falls back to a `'fallback'` `request/header` snapshot when it cannot, so * a logged delta ALWAYS round-trips. NOT a {@link SurfaceEventType}. */ - 'request/header-delta': { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig } + 'request/header-delta': { system?: SystemDelta; tools?: ToolsDelta; config?: LlmCallConfig; messagePrefix?: Message[] } } /** The appendable event-type keys of {@link SessionEventMap}, plugin-merged extensions included. */ diff --git a/packages/core/session/tests/request-header.spec.ts b/packages/core/session/tests/request-header.spec.ts index c2368c46fe..8a5af819c3 100644 --- a/packages/core/session/tests/request-header.spec.ts +++ b/packages/core/session/tests/request-header.spec.ts @@ -8,9 +8,9 @@ */ import { describe, expect, it } from 'vitest' -import { Session, SessionId, applyHeaderDelta, canonicalHeader, diffHeader, foldRequestHeader } from '@deepseek-ai/dsh-session' +import { Session, SessionId, applyHeaderDelta, canonicalHeader, diffHeader, foldRequestHeader, headerEquals } from '@deepseek-ai/dsh-session' import type { EpochHeader, SessionEvent } from '@deepseek-ai/dsh-session' -import type { ToolSchema } from '@deepseek-ai/dsh-llm' +import type { Message, ToolSchema } from '@deepseek-ai/dsh-llm' const CONFIG = { model: 'm' } @@ -18,6 +18,10 @@ function tool(name: string, description = 'd'): ToolSchema { return { name, description, parameters: { type: 'object' } } } +function msg(text: string): Message { + return { role: 'user', content: [{ type: 'text', text }] } +} + /** Round-trip helper: diff must reproduce `next` from `prev` exactly. */ function roundTrip(prev: EpochHeader, next: EpochHeader): ReturnType { const delta = diffHeader(prev, next) @@ -103,6 +107,48 @@ describe('diffHeader / applyHeaderDelta', () => { }) }) +describe('the session prefix (messagePrefix)', () => { + it('canonicalHeader normalizes an empty prefix to an absent field', () => { + expect(canonicalHeader({ config: CONFIG, messagePrefix: [] })).toEqual({ config: CONFIG }) + const full = canonicalHeader({ config: CONFIG, messagePrefix: [msg('p')] }) + expect(full.messagePrefix).toEqual([msg('p')]) + }) + + it('headerEquals treats absence and empty as one representation, content differences as unequal', () => { + expect(headerEquals(canonicalHeader({ config: CONFIG }), { config: CONFIG, messagePrefix: [] })).toBe(true) + expect(headerEquals({ config: CONFIG, messagePrefix: [msg('a')] }, { config: CONFIG, messagePrefix: [msg('b')] })).toBe(false) + expect(headerEquals({ config: CONFIG, messagePrefix: [msg('a')] }, { config: CONFIG })).toBe(false) + }) + + it('replaces a changed prefix whole and leaves untouched parts alone', () => { + const prev = canonicalHeader({ config: CONFIG, system: 'keep', messagePrefix: [msg('old')] }) + const next = canonicalHeader({ config: CONFIG, system: 'keep', messagePrefix: [msg('new'), msg('more')] }) + const delta = roundTrip(prev, next) + expect(delta).toEqual({ messagePrefix: [msg('new'), msg('more')] }) + }) + + it('round-trips a prefix gained from a bare header and lost back to one (empty array encodes absence)', () => { + const none = canonicalHeader({ config: CONFIG }) + const some = canonicalHeader({ config: CONFIG, messagePrefix: [msg('p')] }) + const gained = roundTrip(none, some) + expect(gained).toEqual({ messagePrefix: [msg('p')] }) + const lost = roundTrip(some, none) + expect(lost).toEqual({ messagePrefix: [] }) + }) + + it('folds prefix deltas over the log like any other header amendment', () => { + const session = new Session(SessionId('fold-prefix')) + session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + const first = canonicalHeader({ config: CONFIG, messagePrefix: [msg('catalog v1')] }) + session.append('request/header', { header: first, reason: 'initial' }) + const second = canonicalHeader({ config: CONFIG, messagePrefix: [msg('catalog v2')] }) + session.append('request/header-delta', diffHeader(first, second)!) + expect(foldRequestHeader(session.events)).toEqual(second) + session.append('request/header-delta', diffHeader(second, canonicalHeader({ config: CONFIG }))!) + expect(foldRequestHeader(session.events)).toEqual({ config: CONFIG }) + }) +}) + describe('foldRequestHeader', () => { function headerEvents(session: Session): readonly SessionEvent[] { return session.events diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index e5e953bc84..df8b198737 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -1,6 +1,6 @@ # dsh-tools -Tool registry and execution pipeline. Tool plugins register their schemas and executors; the agent loop executes each call through `tools/pre-execute` (the allow/deny gate) → core dispatch → `tools/post-execute` (inspect/replace the result, attach context). +Tool registry and execution pipeline. Tool plugins register their schemas and executors; the agent loop executes each call through `tools/pre-execute` (the allow/deny gate) → `tools/execute` (an around-dispatch wrapper for timeout/retry/metrics plugins) → `tools/post-execute` (inspect/replace the result, attach context). ## Service: `ToolRegistry` (ctx key: `tools`) @@ -12,7 +12,7 @@ Tool registry and execution pipeline. Tool plugins register their schemas and ex - `ctx.tools.visible(scope?: ScopeKey): ToolDefinition[]` THE visibility function — restricted global layer ∪ the scope's own layer — feeding prompt assembly, `get`, and `execute`, so what the model sees and what dispatches can never disagree. - `ctx.tools.knownNames(scope?: ScopeKey): string[]` The PRE-restriction name universe configuration (`toolOrder`, `restrict`) validates against: a typo fails loud while a restricted-away tool stays a normal absence. - `ctx.tools.schemas(scope?: ScopeKey): ToolSchema[]` Schemas of everything the scope can see (without the `execute` functions). The shipped tools' schemas are catalogued in [docs/tool-catalog.md](../../../docs/tool-catalog.md), generated by booting each tool plugin and harvesting this method (see [the tool-schema-catalog RFC](../../../docs/rfc/implemented/process/2026-07-02-tool-schema-catalog.md)). -- `ctx.tools.execute(exec: ToolExecution): Promise` Execute one tool call through the `tools/pre-execute` → dispatch → `tools/post-execute` pipeline. +- `ctx.tools.execute(exec: ToolExecution): Promise` Execute one tool call through the `tools/pre-execute` → `tools/execute` → `tools/post-execute` pipeline. ### Injected services @@ -23,12 +23,13 @@ Tool registry and execution pipeline. Tool plugins register their schemas and ex | Event | Mode | Purpose | |---|---|---| | `tools/pre-execute` | waterfall | Allow/deny gate BEFORE a tool runs (sandbox, permission, hooks); returns `PreToolDecision`. Scope-filtered by `exec.agent`: an `agent.ctx` listener gates only its own agent | +| `tools/execute` | waterfall | Around-dispatch wrapper (timeout, retry, metrics): `(exec, next)` → the dispatched `ToolExecutionResult`; `next()` is dispatch-with-normalization (resolving through the caller's visible view). Scope-filtered by `exec.agent` like the gate | | `tools/post-execute` | waterfall | Inspect/replace the result AFTER a tool runs, attach context; returns `PostToolDecision` | | `tools/change` | emit | A tool or restriction was registered or unregistered (possibly for one scope); deliberately unfiltered | ### Key types -- `ToolDefinition` — `ToolSchema` + `execute(args, exec): Promise` (the bare array is the model-facing content; the object form additionally attaches an opaque, JSON-serializable `meta` presentation payload persisted on the `tool/result` event and handed back to `presentResult`), plus optional `presentCall(args)` / `presentResult(args, result)` for tool-owned UI presentation (see below). +- `ToolDefinition` — `ToolSchema` + `execute(args, exec): Promise` (the bare array is the model-facing content; the object form additionally attaches an opaque, JSON-serializable `meta` presentation payload persisted on the `tool/result` event and handed back to `presentResult`), plus optional `presentCall(args)` / `presentResult(args, result)` for tool-owned UI presentation (see below). It also carries an optional cooperative timeout budget `timeoutMs?: number` (ms) enforced by `@deepseek-ai/dsh-timeout-policy`, never sent to the model. - `ToolExecution` — one pending tool call: `{ callId, name, arguments, agent?, signal? }`. - `ToolExecutionResult` — outcome: `{ callId, content, isError, error?, additionalContext?, meta? }`. On failure with a `HarnessError`, `error: { name, code }` carries the structured failure class alongside the model-facing text (the loop forwards it onto the `tool/result` session event for retry/sandbox plugins and replay). `additionalContext` (a `HookContext`) ferries any `tools/post-execute` context up to the loop, which buffers it and appends it as a `context/message` after all `tool/result`s in the step. `meta` is the tool's opaque presentation payload from a successful `execute` (the object return form); the loop forwards it onto the `tool/result` session event for result-card rendering. - `PreToolDecision` — `{kind:'allow'}` | `{kind:'deny', reason}` | `{kind:'ask', reason?}`. Input rewrite (changing `arguments`) is deliberately NOT offered (it would desync the pre-execution audit/history/UI from what ran — its own proposed RFC); `ask` degrades to `deny` until the permission system lands. @@ -38,7 +39,7 @@ Tool registry and execution pipeline. Tool plugins register their schemas and ex ### Extension points - Tool plugins call `ctx.tools.register()` — schemas flow into the assembly automatically. -- `tools/pre-execute` is the allow/deny gate (sandbox, permission, hooks): listeners receive `(exec, next)` and call `next()` to delegate to the default (allow) or return a `PreToolDecision` to short-circuit; a `deny`/`ask` skips dispatch and yields an `isError` result. `tools/post-execute` is the inspect/transform seam: `(exec, result, next)` → a `PostToolDecision` that can replace content, block with feedback, or attach `additionalContext`. Core dispatch sits between them as plain code; the tool body keeps its own try/catch so a thrown tool still reaches `post-execute` as an `isError`. Both follow the typed-Decision idiom shared with the `agent/*` interception seams (see [`dsh-agent`](../agent/README.md)). +- `tools/pre-execute` is the allow/deny gate (sandbox, permission, hooks): listeners receive `(exec, next)` and call `next()` to delegate to the default (allow) or return a `PreToolDecision` to short-circuit; a `deny`/`ask` skips dispatch and yields an `isError` result. `tools/execute` is the around-dispatch seam (timeout, retry, metrics): listeners receive `(exec, next)` and call `next()` to delegate to core dispatch (returning its `ToolExecutionResult`, optionally wrapped), or return a replacement result to short-circuit dispatch; the base `next()` IS dispatch-with-normalization, so `await next()` already yields an `isError` result for a thrown/unknown tool (never a raw throw). A wrapper mutates `exec` in place before `next()` — e.g. replacing `exec.signal` with a per-call deadline — because cordis `next()` ignores passed arguments. `tools/post-execute` is the inspect/transform seam: `(exec, result, next)` → a `PostToolDecision` that can replace content, block with feedback, or attach `additionalContext`. Core dispatch is the base of the `tools/execute` waterfall; the tool body keeps its own try/catch so a thrown tool still reaches `post-execute` as an `isError`. All follow the typed-Decision idiom shared with the `agent/*` interception seams (see [`dsh-agent`](../agent/README.md)); `@deepseek-ai/dsh-timeout-policy` is the reference `tools/execute` wrapper. - MCP servers: one plugin per server, discover tools, call `ctx.tools.register()` with the server's schemas. ### Typed tool parameter schemas @@ -74,6 +75,8 @@ A `defineTool` tool also **validates the model-generated arguments against its ` See `defineTool`, `validateArgs`, `ToolArgsError`, `SchemaSpec`, `InferArgs`, and `schemaSpecToJsonSchema` in the public API for details. +`defineTool` also validates an optional `timeoutMs` at definition time when present: it must be a positive finite number, or the helper throws — the budget is attached to the produced `ToolDefinition` (for `@deepseek-ai/dsh-timeout-policy`) and never reaches the model. + ### Structured-output schema subset A separate vocabulary for callers that DEMAND a machine-readable value from an agent — the subagent seam's `SubagentStartRequest.outputSchema` (and, by extension, a workflow's `agent({ schema })`). Unlike `SchemaSpec` (the author-facing DSL for tool parameters), a `StructuredOutputSchema` is an object-rooted **raw JSON Schema subset** as data: it travels verbatim to the model as a forced tool's `parameters`, and the produced value is validated against it. diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index d449fb7801..56146576e8 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -1,9 +1,10 @@ /** * Tool registry and execution pipeline. Plugins register tools; the registry * feeds schemas into the system prompt, and `execute()` dispatches each call - * through `tools/pre-execute` (the allow/deny gate) → core dispatch → - * `tools/post-execute` (inspect/replace the result, attach context) for - * sandbox, permission, and hook plugins to gate or transform a call. + * through `tools/pre-execute` (the allow/deny gate) → `tools/execute` (an + * around-dispatch wrapper for timeout/retry/metrics plugins) → `tools/post-execute` + * (inspect/replace the result, attach context) for sandbox, permission, and hook + * plugins to gate or transform a call. * * @module @deepseek-ai/dsh-tools */ @@ -80,17 +81,41 @@ declare module 'cordis' { * @mode waterfall */ 'tools/pre-execute'(this: Scoped, exec: ToolExecution, next: () => Promise): Promise + /** + * Around-dispatch waterfall wrapping the registry's core tool dispatch, + * between the `tools/pre-execute` gate and the `tools/post-execute` seam. A + * listener receives `(exec, next)`: call `next()` to delegate to dispatch + * (returning its {@link ToolExecutionResult}, optionally wrapped), or return a + * replacement result without calling `next()` to short-circuit dispatch. The + * base `next()` IS the dispatch-with-normalization thunk — a thrown tool (or + * unknown tool) is already normalized to an `isError` result by the time a + * listener's `await next()` returns, so a wrapper never sees a raw throw from + * the tool body. This is the seam a timeout/retry/metrics plugin wraps: it can + * mutate `exec` (e.g. replace `exec.signal` with a per-call deadline) BEFORE + * `next()` and inspect the result AFTER. (Cordis `next()` ignores any passed + * arguments and re-invokes downstream with the shared payload, so a wrapper + * mutates `exec` in place rather than passing a new object to `next()`.) + * Multiple listeners compose by registration order — an outer one wraps the + * inner ones plus dispatch. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): the carrier is keyed by + * `exec.agent` — a listener registered through `agent.ctx` wraps only that + * agent's calls; a plain plugin listener wraps every call (including + * agent-less ones, which dispatch subject-less). + * @param exec - the allowed call about to dispatch (name, parsed arguments, caller agent, signal). + * @mode waterfall + */ + 'tools/execute'(this: Scoped, exec: ToolExecution, next: () => Promise): Promise /** * Waterfall AFTER a tool runs — where hook plugins inspect the result and * accept it (optionally REPLACING the model-facing content, and/or attaching * `additionalContext` for the next request) or block it with corrective * `feedback` (Claude Code's `PostToolUse`). Listeners receive * `(exec, result, next)`: call `next()` to delegate to the default (accept - * unchanged), or return a {@link PostToolDecision} to override. The core tool - * dispatch sits between the two waterfalls as plain code, all inside - * `execute`'s outer try/catch (and the tool body keeps its own inner - * try/catch, so a thrown tool still reaches `post-execute` as an `isError` - * result). + * unchanged), or return a {@link PostToolDecision} to override. Core tool + * dispatch runs earlier as the base `next()` of the `tools/execute` + * waterfall, all inside `execute`'s outer try/catch (and the tool body keeps + * its own inner try/catch, so a thrown tool still reaches `post-execute` as an + * `isError` result). * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): the carrier is keyed by * `exec.agent` — a listener registered through `agent.ctx` fires only for * that agent's calls; a plain plugin listener fires for every call @@ -132,6 +157,14 @@ export type ToolExecuteReturn = ContentBlock[] | { content: ContentBlock[]; meta /** A registered tool: its schema plus the execution function. */ export interface ToolDefinition extends ToolSchema { execute(args: unknown, exec: ToolExecution): Promise + /** + * Cooperative tool-call timeout budget in milliseconds. Omit for no deadline. + * Enforced by `@deepseek-ai/dsh-timeout-policy` (a `tools/execute` wrapper); it + * is NEVER sent to the model — `schemas()` whitelists only name/description/ + * parameters. Declaring it asserts this tool forwards `exec.signal` to a + * cooperative implementation that can reach quiescence when the signal aborts. + */ + timeoutMs?: number /** * Optional: how to present the PENDING state of one call in a UI, derived from * the call's `args` (parsed arguments, `unknown` — the tool validates/narrows @@ -302,7 +335,7 @@ export interface ToolRestriction { /** * Tool registry (`ctx.tools`): tool plugins register definitions; the agent - * loop executes calls through the `tools/pre-execute` → dispatch → + * loop executes calls through the `tools/pre-execute` → `tools/execute` → * `tools/post-execute` pipeline. The registry contributes its schemas into the * system-prompt assembly. * @@ -533,18 +566,21 @@ export class ToolRegistry extends Service { } /** - * Execute one tool call through the `tools/pre-execute` → dispatch → - * `tools/post-execute` pipeline. The two waterfalls are the gate (allow/deny) - * and the inspect/transform seam; core dispatch sits between them as plain - * code. The whole thing is wrapped in one outer try/catch so a throwing - * listener (in either waterfall) becomes an `isError` result instead of - * failing the turn; the tool body ALSO keeps its own inner try/catch, so a - * thrown tool becomes an `isError` result that `post-execute` listeners can - * still inspect. If the tool is not registered, the result is an `isError` - * carrying a `UNKNOWN_TOOL` structured error. A thrown {@link HarnessError} - * surfaces its `{ name, code }` on the result. + * Execute one tool call through the `tools/pre-execute` → `tools/execute` + * (around dispatch) → `tools/post-execute` pipeline. `pre-execute` is the gate + * (allow/deny), `tools/execute` wraps core dispatch (a timeout/retry/metrics + * seam), and `post-execute` is the inspect/transform seam; core dispatch sits + * as the base `next()` of the `tools/execute` waterfall. The whole thing is + * wrapped in one outer try/catch so a throwing listener (in any waterfall) + * becomes an `isError` result instead of failing the turn; the tool body ALSO + * keeps its own inner try/catch, so a thrown tool becomes an `isError` result + * that `tools/execute` and `post-execute` listeners can still inspect. If the + * tool is not registered (or not visible to the calling agent — a + * restricted-away global is exactly as absent as a nonexistent one), the + * result is an `isError` carrying a `UNKNOWN_TOOL` structured error. A thrown + * {@link HarnessError} surfaces its `{ name, code }` on the result. * @param exec - the call to run (name, parsed arguments, caller agent, signal). - * @returns the final result after both waterfalls; failures resolve as + * @returns the final result after every waterfall; failures resolve as * `isError` results, never rejections. */ async execute(exec: ToolExecution): Promise { @@ -573,27 +609,36 @@ export class ToolRegistry extends Service { return await this.postExecute(exec, denied) } - // --- Core dispatch (plain code between the waterfalls). The tool body's - // own try/catch turns a throw into an isError result so post-execute can - // inspect it; an unknown tool routes through the same catch. --- - let result: ToolExecutionResult - try { - // Resolve through the CALLER's visible view ({@link get}): a scoped - // tool shadows its global name-twin for that agent, and a - // restricted-away global tool is exactly as absent as a nonexistent - // one — same UNKNOWN_TOOL result, no capability leak in the error. - const tool = this.get(exec.name, exec.agent) - if (!tool) throw new ToolNotFoundError(exec.name) - // Normalize the two `execute` return shapes: a bare ContentBlock[] (no - // meta) or a { content, meta } object (a tool attaching a private - // presentation payload). An array IS the content; the object carries it. - const returned = await tool.execute(exec.arguments, exec) - const content = Array.isArray(returned) ? returned : returned.content - const meta = Array.isArray(returned) ? undefined : returned.meta - result = { callId: exec.callId, content, isError: false, ...meta !== undefined ? { meta } : {} } - } catch (error: unknown) { - result = toolErrorResult(exec.callId, error) - } + // --- Around-dispatch: tools/execute. The base `next` is the dispatch- + // with-normalization thunk — the tool body's own try/catch turns a throw + // into an isError result so a wrapper (and post-execute) can inspect it; + // an unknown tool routes through the same catch. A `tools/execute` listener + // (e.g. a timeout plugin) wraps this thunk: it may mutate `exec` before + // delegating and inspect the normalized result after. Dispatched with the + // same carrier as the gate, so an `agent.ctx` wrapper wraps only its own + // agent's calls. --- + const result = await this.ctx.waterfall( + carrier, 'tools/execute', exec, + async (): Promise => { + try { + // Resolve through the CALLER's visible view ({@link get}): a scoped + // tool shadows its global name-twin for that agent, and a + // restricted-away global tool is exactly as absent as a nonexistent + // one — same UNKNOWN_TOOL result, no capability leak in the error. + const tool = this.get(exec.name, exec.agent) + if (!tool) throw new ToolNotFoundError(exec.name) + // Normalize the two `execute` return shapes: a bare ContentBlock[] (no + // meta) or a { content, meta } object (a tool attaching a private + // presentation payload). An array IS the content; the object carries it. + const returned = await tool.execute(exec.arguments, exec) + const content = Array.isArray(returned) ? returned : returned.content + const meta = Array.isArray(returned) ? undefined : returned.meta + return { callId: exec.callId, content, isError: false, ...meta !== undefined ? { meta } : {} } + } catch (error: unknown) { + return toolErrorResult(exec.callId, error) + } + }, + ) return await this.postExecute(exec, result) } catch (error: unknown) { diff --git a/packages/core/tools/src/schema.ts b/packages/core/tools/src/schema.ts index 16eff5c324..1a428ffd40 100644 --- a/packages/core/tools/src/schema.ts +++ b/packages/core/tools/src/schema.ts @@ -295,6 +295,13 @@ export interface DefineToolOptions { * standard JSON Schema at runtime. */ parameters: S + /** + * Optional cooperative tool-call timeout budget in milliseconds. When given it + * must be a positive finite number; it is attached to the produced + * {@link ToolDefinition} for `@deepseek-ai/dsh-timeout-policy` to enforce and + * is never sent to the model. + */ + timeoutMs?: number /** * Tool execution function. `args` is typed as {@link InferArgs} — zero * casts needed. Returns either a bare {@link ContentBlock}`[]` (model-facing @@ -362,10 +369,14 @@ export function defineTool(options: DefineToolOptions): const userPresentCall = options.presentCall // eslint-disable-next-line @typescript-eslint/unbound-method const userPresentResult = options.presentResult + if (options.timeoutMs !== undefined && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) { + throw new Error(`defineTool(${options.name}): timeoutMs must be a positive finite number`) + } const tool: ToolDefinition = { name: options.name, description: options.description, parameters: schemaSpecToJsonSchema(options.parameters) as unknown as Record, + ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), async execute(args: unknown, exec: ToolExecution): Promise { // Validate the model-generated args before the typed body runs. On // mismatch we throw ToolArgsError; the registry turns it into an diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index cacc2eef66..3754e93abc 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -35,7 +35,7 @@ describe('gen-tool-catalog collectToolCatalog', () => { it('boots every shipped tool package and harvests its model-facing schemas', async () => { const catalog = await collectToolCatalog() const names = catalog.flatMap(entry => entry.schemas.map(s => s.name)).sort() - expect(names).toEqual(['bash', 'bash_kill', 'bash_output', 'edit', 'read', 'subagent', 'todo_write', 'web_fetch', 'web_search', 'write']) + expect(names).toEqual(['ask_user_question', 'bash', 'bash_kill', 'bash_output', 'cordis_inspect', 'cordis_mount', 'cordis_unmount', 'edit', 'read', 'subagent', 'todo_write', 'web_fetch', 'web_search', 'write']) // Every tool carries a JSON-Schema `parameters` object (what the model sees). for (const entry of catalog) { for (const schema of entry.schemas) { diff --git a/packages/core/tools/tests/tools.spec.ts b/packages/core/tools/tests/tools.spec.ts index 8892cadd1a..4cea334552 100644 --- a/packages/core/tools/tests/tools.spec.ts +++ b/packages/core/tools/tests/tools.spec.ts @@ -5,6 +5,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { defineTool, schemaSpecToJsonSchema, validateArgs, ToolArgsError, ToolNotFoundError, type InferArgs, type SchemaSpec, type PreToolDecision, type PostToolDecision, + type ToolExecution, type ToolExecutionResult, } from '@deepseek-ai/dsh-tools' async function setup() { @@ -62,6 +63,17 @@ describe('ToolRegistry', () => { expect(schema.execute).toBeUndefined() }) + it('schemas() excludes timeoutMs — the budget must never reach the model', async () => { + const ctx = await setup() + ctx.tools.register(defineTool({ + name: 'budgeted', description: 'has a budget', parameters: {}, timeoutMs: 5_000, + async execute() { return [{ type: 'text' as const, text: 'ok' }] }, + })) + const schema = ctx.tools.schemas().find(s => s.name === 'budgeted') + expect(schema).toBeDefined() + expect('timeoutMs' in (schema as object)).toBe(false) + }) + it('executes a tool and returns its content', async () => { const ctx = await setup() ctx.tools.register(echoTool) @@ -272,6 +284,151 @@ describe('ToolRegistry', () => { expect(order).toEqual(['pre:before', 'pre:after', 'post:before', 'post:after']) }) + it('runs tools/execute after an allowed pre-execute, around dispatch, and before post-execute', async () => { + const ctx = await setup() + const order: string[] = [] + ctx.tools.register(defineTool({ + name: 'traced', + description: 'echo', + parameters: { text: { type: 'string' } }, + async execute(args) { + order.push('dispatch') + return [{ type: 'text' as const, text: args.text ?? '' }] + }, + })) + + ctx.on('tools/pre-execute', async (_exec, next) => { order.push('pre'); return next() }) + ctx.on('tools/execute', async (_exec: ToolExecution, next: () => Promise): Promise => { + order.push('execute:before') + const result = await next() + order.push('execute:after') + return result + }) + ctx.on('tools/post-execute', async (_exec, _result, next) => { order.push('post'); return next() }) + + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'traced', arguments: { text: 'hi' } }) + expect(result).toEqual({ callId: CallId('c1'), content: [{ type: 'text', text: 'hi' }], isError: false }) + // The around seam wraps dispatch; pre gates before it, post runs over its result. + expect(order).toEqual(['pre', 'execute:before', 'dispatch', 'execute:after', 'post']) + }) + + it('a pre-execute deny short-circuits before tools/execute (the seam never runs)', async () => { + const ctx = await setup() + ctx.tools.register(echoTool) + + let entered = false + ctx.on('tools/pre-execute', async (_exec, _next): Promise => ({ kind: 'deny', reason: 'nope' })) + ctx.on('tools/execute', async (_exec: ToolExecution, next: () => Promise): Promise => { + entered = true + return next() + }) + + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } }) + expect(result.isError).toBe(true) + expect(result.content[0]).toMatchObject({ text: 'Error: nope' }) + expect(entered).toBe(false) // a denied call never enters the around-dispatch seam + }) + + it('a thrown tool is normalized to an isError result BEFORE a tools/execute listener sees next()', async () => { + const ctx = await setup() + ctx.tools.register({ + ...echoTool, + name: 'boom', + async execute() { throw new HarnessError('kaboom', 'BOOM') }, + }) + + let seen: { isError: boolean; error?: unknown } | undefined + ctx.on('tools/execute', async (_exec: ToolExecution, next: () => Promise): Promise => { + const result = await next() + // The base next() IS dispatch-with-normalization: the wrapper sees the + // normalized isError result, never a raw throw from the tool body. + seen = { isError: result.isError, error: result.error } + return result + }) + + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'boom', arguments: {} }) + expect(seen).toEqual({ isError: true, error: { name: 'HarnessError', code: 'BOOM' } }) + expect(result.isError).toBe(true) + expect(result.content[0]).toMatchObject({ text: 'Error: kaboom' }) + }) + + it('a thrown tool normalized inside tools/execute still reaches post-execute', async () => { + const ctx = await setup() + ctx.tools.register({ + ...echoTool, + name: 'boom', + async execute() { throw new Error('exploded') }, + }) + + let postSaw: boolean | undefined + ctx.on('tools/execute', async (_exec: ToolExecution, next: () => Promise): Promise => next()) + ctx.on('tools/post-execute', async (_exec, result, next) => { + postSaw = result.isError + return next() + }) + + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'boom', arguments: {} }) + expect(postSaw).toBe(true) // the normalized isError still flows through post-execute + expect(result.isError).toBe(true) + expect(result.content[0]).toMatchObject({ text: 'Error: exploded' }) + }) + + it('a tools/execute listener can replace exec.signal for the dispatched tool (deadline pattern)', async () => { + const ctx = await setup() + let seenSignal: AbortSignal | undefined + ctx.tools.register({ + ...echoTool, + name: 'signal-probe', + async execute(_args, exec) { + seenSignal = exec.signal + return [{ type: 'text' as const, text: 'ok' }] + }, + }) + + const upstream = new AbortController().signal + const replacement = new AbortController().signal + ctx.on('tools/execute', async (exec: ToolExecution, next: () => Promise): Promise => { + expect(exec.signal).toBe(upstream) + // Cordis next() ignores passed arguments, so a wrapper mutates exec in + // place (the documented "mutate the shared object, then delegate" idiom). + exec.signal = replacement + return next() + }) + + await ctx.tools.execute({ callId: CallId('c1'), name: 'signal-probe', arguments: {}, signal: upstream }) + expect(seenSignal).toBe(replacement) // dispatch saw the wrapper's replacement, not the upstream + }) + + it('a tools/execute listener can short-circuit dispatch by returning a result without next()', async () => { + const ctx = await setup() + let dispatched = false + ctx.tools.register({ + ...echoTool, + name: 'never-runs', + async execute() { dispatched = true; return [] }, + }) + + ctx.on('tools/execute', async (exec: ToolExecution, _next: () => Promise): Promise => + ({ callId: exec.callId, content: [{ type: 'text', text: 'short-circuited' }], isError: false })) + + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'never-runs', arguments: {} }) + expect(dispatched).toBe(false) // returning without next() skips core dispatch + expect(result.content[0]).toMatchObject({ text: 'short-circuited' }) + }) + + it('returns an isError result when a tools/execute listener throws', async () => { + const ctx = await setup() + ctx.tools.register(echoTool) + ctx.on('tools/execute', async () => { throw new Error('wrapper broke') }) + + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'echo', arguments: { text: 'hi' } }) + expect(result).toEqual({ + callId: CallId('c1'), + content: [{ type: 'text', text: 'Error: wrapper broke' }], + isError: true, + }) + }) + it('returns an isError result when a tools/pre-execute listener throws', async () => { const ctx = await setup() ctx.tools.register(echoTool) @@ -1018,6 +1175,38 @@ describe('defineTool validation (the runtime-validation RFC, part 1)', () => { const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'raw', arguments: {} }) expect(result.isError).toBe(false) }) + + it('attaches a positive-finite timeoutMs to the definition', () => { + const tool = defineTool({ + name: 'x', description: 'd', parameters: {}, timeoutMs: 30_000, + async execute() { return [{ type: 'text' as const, text: 'ok' }] }, + }) + expect(tool.timeoutMs).toBe(30_000) + }) + + it('omits timeoutMs when not declared', () => { + const tool = defineTool({ + name: 'x', description: 'd', parameters: {}, + async execute() { return [{ type: 'text' as const, text: 'ok' }] }, + }) + expect(tool.timeoutMs).toBeUndefined() + }) + + it('throws when timeoutMs is zero or negative', () => { + const make = (ms: number) => defineTool({ + name: 'x', description: 'd', parameters: {}, timeoutMs: ms, + async execute() { return [{ type: 'text' as const, text: 'ok' }] }, + }) + expect(() => make(0)).toThrow('timeoutMs must be a positive finite number') + expect(() => make(-5)).toThrow('positive finite number') + }) + + it('throws when timeoutMs is non-finite', () => { + expect(() => defineTool({ + name: 'x', description: 'd', parameters: {}, timeoutMs: Infinity, + async execute() { return [{ type: 'text' as const, text: 'ok' }] }, + })).toThrow('positive finite number') + }) }) describe('defineTool presentation (presentCall / presentResult)', () => { diff --git a/packages/fs/README.md b/packages/fs/README.md index 985a9f3ad6..ec3bb62afb 100644 --- a/packages/fs/README.md +++ b/packages/fs/README.md @@ -10,3 +10,7 @@ The filesystem stack: a provider seam (text IO + atomic mutation with an optiona | `tool-fs/` | Model-facing `read`/`write`/`edit` tools AND the executor (reads via `ctx.fs`, owns read windowing, dispatches `fs/*`) | (registers on `ctx.tools`) | The interface lives at `fs/fs/`. A sandboxed, remote, or project-scoped filesystem backend can replace `fs-local` without touching the seam, the policy gate, or the model-facing tool schemas. The policy (`fs-policy/`) is a plugin that participates only through the `fs/*` event gate, not a service the tool injects — so dropping it gracefully loses the policy and leaves the unconstrained bare provider rather than breaking the tool. A deployment that loads `tool-fs/` is expected to also load it. + +## No timeouts on file IO + +`read`/`write`/`edit` take **no** `timeoutMs`, and the provider seam arms no deadline — unlike bash and web, which consume [`@deepseek-ai/dsh-timeout`](../util/timeout/README.md). A local syscall is best-effort-abortable at most: a timeout could not force an in-progress `fsync`/`rename` to stop, so a deadline here would be a knob that cannot deliver on its promise. Adding one would also be an implicit default in the exact place explicit-over-implicit forbids. Both reference agents (Claude Code, Codex) leave file IO untimed for the same reason; cancellation still propagates through the tool-execution signal for best-effort abort at syscall boundaries. diff --git a/packages/guard/README.md b/packages/guard/README.md new file mode 100644 index 0000000000..9198698b20 --- /dev/null +++ b/packages/guard/README.md @@ -0,0 +1,9 @@ +# guard/ — loop-hygiene guard family + +Behavioral guard plugins that watch the agent loop for unproductive patterns and nudge the model back on course. A single **product** package — there is no interface/implementation seam here, because a guard is a self-contained consumer of existing core seams (`tools/post-execute`, `agent/prompt-submit`, `agent/status`), not a swappable capability. + +| Package | Role | ctx key | +|---|---|---| +| `repeat-tool-guard/` | Advisory reminders when an agent loops on identical tool calls | (listens on `ctx.tools`' waterfalls) | + +Reminders travel as `additionalContext` on the `tools/post-execute` decision; the agent loop appends them as logged `context/message` events after the step's tool results (see [the tools package](../core/tools)), so everything a guard says to the model is reconstructable from the session log. diff --git a/packages/guard/repeat-tool-guard/README.md b/packages/guard/repeat-tool-guard/README.md new file mode 100644 index 0000000000..dc385bc033 --- /dev/null +++ b/packages/guard/repeat-tool-guard/README.md @@ -0,0 +1,37 @@ +# @deepseek-ai/dsh-repeat-tool-guard + +An advisory loop-breaker, not a model-facing tool: it never appears in the tool list, never vetoes or rewrites a call, and adds exactly one behavior — it watches each agent's stream of tool calls, counts runs of consecutive calls to the same tool with identical canonicalized arguments, and at configured run lengths injects an escalating advisory reminder telling the model to stop repeating itself, re-read the last result, and either change approach or conclude. The decision (retry differently, gather more evidence, or finish) stays entirely with the model: a legitimately repeated call is delayed by nothing and blocked by nothing. Decision record: [the repeat-tool-guard RFC](../../../docs/rfc/implemented/feature/2026-07-08-repeat-tool-guard.md). + +## Config + +```yaml +- id: repeat-tool-guard + name: '@deepseek-ai/dsh-repeat-tool-guard' + config: + thresholds: [3, 5, 8] # default; consecutive counts that trigger a reminder + include: [] # tool-name patterns to track; empty ⇒ all tools + exclude: [todo_write] # tool-name patterns transparent to the chain + argumentsPreviewChars: 500 # default; cap on arguments quoted in the detailed reminder +``` + +`thresholds` fails loud at plugin load: an empty list, a non-integer, a value below 2, or a duplicate throws, never a silent fall-back to defaults; `argumentsPreviewChars` equally rejects anything but an integer >= 1. The list is normalized to ascending order; the FIRST threshold delivers a short generic nudge, every later threshold delivers the detailed form naming the tool, the run length, and the canonical arguments — head-truncated at `argumentsPreviewChars` with an omitted-count marker, so a looping `write`/`edit` payload cannot ride into the next request unbounded (the chain key always compares the FULL canonical string; the cap bounds the reminder, never the detection). + +`include`/`exclude` entries support `*` wildcards and are predicates over whatever tools exist at call time, not references to registry entries — a pattern matching no currently registered tool is NOT an error (`exclude: [mcp_*]` stays valid in a deployment that loads no MCP tools), unlike `toolOrder`'s referent check. + +## Chain semantics + +The chain key is `(tool name, canonical arguments)` — canonicalization is a deep key-sort plus `JSON.stringify`, so argument objects differing only in property order count as identical. A call identical to the previous tracked call increments the agent's consecutive counter; a different tracked call resets it to 1. + +- **Untracked calls are transparent to the chain.** A call excluded by `include`/`exclude` neither increments nor resets the counter, so `grep X → todo_write → grep X` still counts as two consecutive `grep X` when `todo_write` is excluded. This is what makes exclusion useful: bookkeeping tools interleaved into a loop must not launder it. +- **Denied calls count.** Detection sits on `tools/post-execute`, which also runs for calls a `tools/pre-execute` listener denied — a model hammering a denied call is exactly the loop worth breaking. +- **Calls without an agent are ignored.** A direct `ctx.tools.execute()` caller has no model to remind and no `AgentId` to key on. +- **Per-agent keying.** The tool registry is context-level and subagents interleave through the same waterfall, so chains are keyed by `AgentId`; one agent's repetition never trips another's reminder. A user prompt (`agent/prompt-submit`) resets the submitting agent's chain; agent disposal drops its state. +- **In-memory only.** A session resumed from persistence starts with a fresh chain — the guard is a heuristic nudge, not a logged invariant, later reminders are the accepted cost. + +## Reminder delivery + +Reminders ride the post-execute decision's `additionalContext` (source `{kind: 'plugin', plugin: 'repeat-tool-guard'}`), never a `content` replacement: the `tool/result` event stays the tool's own output for audit. The loop buffers the context and appends it as a `context/message` after the step's tool results, which the session renders as the tagged synthetic-user envelope — so the reminder is model-visible, source-attributed, and reconstructable from the session log with no new session event. The guard always delegates via `next()` and folds its reminder onto the downstream decision (both variants — a blocked call still gets the nudge); when a downstream listener attached its own `additionalContext`, the fold concatenates content and carries the guard's `source` (a `HookContext` holds one `MessageSource`; `source.kind` is what framing depends on). + +## Testing + +Unit suites drive a real agent loop against a mock adapter (no network) and cover the chain semantics above to per-file 100%. The snapshot tier owns the transcript surface: a scripted-replay scenario repeats a call five times and pins both reminder tiers (gentle at 3, detailed at 5) as `context/message`s in the ACP transcript. diff --git a/packages/guard/repeat-tool-guard/package.json b/packages/guard/repeat-tool-guard/package.json new file mode 100644 index 0000000000..9b085bb015 --- /dev/null +++ b/packages/guard/repeat-tool-guard/package.json @@ -0,0 +1,41 @@ +{ + "name": "@deepseek-ai/dsh-repeat-tool-guard", + "description": "Repeat-tool-call guard plugin: advisory reminders when an agent loops on identical tool calls", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "dependencies": { + "schemastery": "^3.18.0" + }, + "peerDependencies": { + "@deepseek-ai/dsh-agent": "^0.0.1", + "@deepseek-ai/dsh-tools": "^0.0.1", + "cordis": "^4.0.0-rc.6" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "cordis": "^4.0.0-rc.6" + } +} diff --git a/packages/guard/repeat-tool-guard/src/index.ts b/packages/guard/repeat-tool-guard/src/index.ts new file mode 100644 index 0000000000..919d0541ba --- /dev/null +++ b/packages/guard/repeat-tool-guard/src/index.ts @@ -0,0 +1,268 @@ +/** + * Repeat-tool-call guard: advisory loop-breaker for agents stuck re-issuing + * the same tool call with identical arguments. + * + * Not a model-facing tool — it registers no tool, never vetoes or rewrites a + * call, and adds exactly one behavior: watch each agent's stream of tool calls + * through the `tools/post-execute` waterfall, count runs of consecutive calls + * to the same tool with identical canonicalized arguments, and at configured + * run lengths fold an escalating advisory reminder onto the decision's + * `additionalContext`. The loop appends that context as a logged + * `context/message` after the step's tool results, so the reminder is + * model-visible, source-attributed, and reconstructable from the session log + * with no new session event. Decision record: + * docs/rfc/implemented/feature/2026-07-08-repeat-tool-guard.md. + * + * ```yaml + * - id: repeat-tool-guard + * name: '@deepseek-ai/dsh-repeat-tool-guard' + * config: + * thresholds: [3, 5, 8] # consecutive counts that trigger a reminder + * include: [] # tool-name patterns to track; empty = all tools + * exclude: [todo_write] # tool-name patterns transparent to the chain + * ``` + * + * Chain state is keyed per {@link AgentId} — the tool registry is a + * context-level singleton whose waterfalls interleave every agent's calls, so + * a shared counter would let one agent's repetition trip another's reminder. + * State is in-memory only: a session resumed from persistence starts with a + * fresh chain (the guard is a heuristic nudge, not a logged invariant). + * + * Plugin export shape: named exports, NO default. The cordis Loader's + * `unwrapExports` does `exports.default ?? exports`, so a stray default would + * collapse the module to the bare `apply` (see docs/postmortem/0001). + * + * @module @deepseek-ai/dsh-repeat-tool-guard + */ + +import type { Context } from 'cordis' +import z from 'schemastery' +import type { AgentId, HookContext, PromptDecision } from '@deepseek-ai/dsh-agent' +import type { MessageSource } from '@deepseek-ai/dsh-llm' +import type { PostToolDecision, ToolExecution } from '@deepseek-ai/dsh-tools' + +export const name = 'repeat-tool-guard' + +/** + * Plugin config, validated by the same-named schemastery schema plus the + * load-time checks in `apply` (misconfiguration fails loud: an empty + * `thresholds` list, a non-integer, a value below 2, or a duplicate throws at + * plugin load, never a silent fall-back). `include`/`exclude` entries are + * `*`-wildcard predicates over tool names at call time, not references to + * registry entries — a pattern matching no currently registered tool is valid + * (`exclude: [mcp_*]` must stay legal in a deployment that loads no MCP tools). + */ +export interface Config { + /** Consecutive-repeat counts that trigger a reminder (default `[3, 5, 8]`). */ + thresholds?: number[] + /** Tool-name patterns to track; empty means every tool is tracked. */ + include?: string[] + /** Tool-name patterns transparent to the chain (neither count nor reset). */ + exclude?: string[] + /** + * Maximum characters of canonical arguments quoted in the DETAILED reminder + * (default 500). Large payloads (a `write` body, a long command) would + * otherwise ride into the next request unbounded — precisely in a loop + * scenario; the cap bounds the reminder, never the detection (the chain key + * always compares the FULL canonical string). + */ + argumentsPreviewChars?: number +} + +export const Config: z = z.object({ + thresholds: z.array(z.number()).default([3, 5, 8]), + include: z.array(z.string()).default([]), + exclude: z.array(z.string()).default([]), + argumentsPreviewChars: z.number().default(500), +}) + +/** + * The `{kind:'plugin'}` source stamped on every reminder this guard injects — + * the label is load-bearing (an unlabeled context would render as a user + * prompt in derived history). + */ +const PLUGIN_SOURCE: MessageSource = { kind: 'plugin', plugin: 'repeat-tool-guard' } + +/** + * The gentle first-threshold reminder. Keyed to `thresholds[0]`, not a literal + * count, so a custom first threshold keeps the gentle-then-detailed escalation. + */ +const GENTLE_REMINDER = + 'You are repeating the exact same tool call with identical arguments. ' + + 'Carefully analyze the previous result before calling again: if the task is ' + + 'not complete, try a different approach or different arguments instead of ' + + 'repeating the call.' + +/** The detailed later-threshold reminder naming the tool, the run length, and the canonical arguments. */ +function detailedReminder(toolName: string, count: number, canonicalArguments: string): string { + return 'Repeated tool call detected:\n' + + `- tool: ${toolName}\n` + + `- consecutive_calls: ${count}\n` + + `- arguments: ${canonicalArguments}\n` + + 'The repeated calls are not making progress. Do not call this tool with ' + + 'these exact arguments again. Inspect the latest result and choose a ' + + 'different action, different arguments, or finish the task if enough ' + + 'evidence has been gathered.' +} + +/** + * Deep key-sort of a parsed-JSON value so two argument objects that differ + * only in property order canonicalize identically. Arguments reach the guard + * as the loop's `JSON.parse` output (or its raw-string fallback for malformed + * argument JSON), so JSON's value domain is the whole input domain — no + * bigint, cycle, or `undefined` handling exists because no input path can + * produce them. + */ +function sortJsonValue(value: unknown): unknown { + if (Array.isArray(value)) return value.map(sortJsonValue) + if (value !== null && typeof value === 'object') { + const record = value as Record + const sorted: Record = {} + for (const key of Object.keys(record).sort()) { + sorted[key] = sortJsonValue(record[key]) + } + return sorted + } + return value +} + +/** Canonical string form of a call's arguments: deep key-sort, then stringify. */ +function canonicalize(argumentsValue: unknown): string { + return JSON.stringify(sortJsonValue(argumentsValue)) +} + +/** Compile one `*`-wildcard pattern to an anchored RegExp (every other regex metacharacter is matched literally). */ +function wildcardToRegExp(pattern: string): RegExp { + const escaped = pattern.replace(/[|\\{}()[\]^$+?.]/g, String.raw`\$&`) + return new RegExp(`^${escaped.replaceAll('*', '.*')}$`) +} + +/** + * Head-truncate the canonical arguments for quoting in the detailed reminder, + * marking how much was omitted. Bounds only the model-visible text — the + * chain key always uses the full canonical string. + */ +function previewArguments(canonical: string, cap: number): string { + if (canonical.length <= cap) return canonical + return `${canonical.slice(0, cap)}… (+${canonical.length - cap} more chars)` +} + +/** + * Validate `thresholds` per the fail-loud contract and return them sorted + * ascending (the escalation rule reads `thresholds[0]` as the gentle tier, so + * order is normalized here, once). + */ +function validateThresholds(values: number[]): number[] { + if (values.length === 0) { + throw new Error('repeat-tool-guard: `thresholds` must not be empty') + } + for (const value of values) { + if (!Number.isInteger(value) || value < 2) { + throw new Error(`repeat-tool-guard: invalid threshold ${value} — every threshold must be an integer >= 2`) + } + } + if (new Set(values).size !== values.length) { + throw new Error('repeat-tool-guard: `thresholds` must not contain duplicates') + } + return [...values].sort((a, b) => a - b) +} + +/** + * Concatenate the guard's reminder context with a downstream listener's + * optional one so folding drops neither. The merged block carries the guard's + * `source` — a `HookContext` holds one `MessageSource` and the seam cannot + * represent mixed provenance; the rendered `context/message` only + * distinguishes by `source.kind`, so a downstream plugin's text is still + * correctly framed as plugin context. + */ +function concatContext(ours: HookContext, theirs: HookContext | undefined): HookContext { + if (!theirs) return ours + return { content: [...ours.content, ...theirs.content], source: ours.source } +} + +/** One agent's consecutive-repeat chain: the last tracked call's identity key and its run length. */ +interface Chain { + key: string + count: number +} + +/** + * Install the guard's listeners. + * @param ctx - plugin context; listeners are scoped to it and disposed with it. + * @param config - validated {@link Config}; `thresholds` is re-checked fail-loud here. + */ +export function apply(ctx: Context, config: Config): void { + // schemastery's .default() guarantees the fields are set after validation. + const thresholds = validateThresholds(config.thresholds as number[]) + const thresholdSet = new Set(thresholds) + const includePatterns = (config.include as string[]).map(wildcardToRegExp) + const excludePatterns = (config.exclude as string[]).map(wildcardToRegExp) + const argumentsPreviewChars = config.argumentsPreviewChars as number + if (!Number.isInteger(argumentsPreviewChars) || argumentsPreviewChars < 1) { + throw new Error(`repeat-tool-guard: invalid argumentsPreviewChars ${argumentsPreviewChars} — must be an integer >= 1`) + } + + const chains = new Map() + + /** Whether a tool participates in the chain (untracked calls are transparent: they neither count nor reset). */ + function tracked(toolName: string): boolean { + if (includePatterns.length > 0 && !includePatterns.some(pattern => pattern.test(toolName))) return false + return !excludePatterns.some(pattern => pattern.test(toolName)) + } + + /** + * Advance the calling agent's chain for one attempt and return the reminder + * to deliver, if this attempt's run length hits a configured threshold. + * Counting happens here — in post-execute — because denied calls also flow + * through this waterfall (`ToolRegistry.execute` routes a deny through the + * same pipeline), and a model hammering a denied call is exactly the loop + * worth breaking. + */ + function observe(exec: ToolExecution): HookContext | undefined { + // A direct `ctx.tools.execute()` caller has no model to remind and no id + // to key on; only agent-loop calls participate. + if (!exec.agent) return undefined + if (!tracked(exec.name)) return undefined + const canonical = canonicalize(exec.arguments) + const key = JSON.stringify([exec.name, canonical]) + const chain = chains.get(exec.agent.id) + const count = chain !== undefined && chain.key === key ? chain.count + 1 : 1 + chains.set(exec.agent.id, { key, count }) + if (!thresholdSet.has(count)) return undefined + const text = count === thresholds[0] + ? GENTLE_REMINDER + : detailedReminder(exec.name, count, previewArguments(canonical, argumentsPreviewChars)) + return { content: [{ type: 'text', text }], source: PLUGIN_SOURCE } + } + + // Observe-and-enrich, never veto: count first (state advances regardless of + // the downstream outcome), DELEGATE so a later listener can still block or + // replace, then fold the reminder onto whatever came back — additionalContext + // rides both decision variants, so a blocked call still gets the nudge. + ctx.on('tools/post-execute', async (exec, _result, next): Promise => { + const reminder = observe(exec) + const downstream = await next() + if (!reminder) return downstream + if (downstream.kind === 'block') { + return { kind: 'block', feedback: downstream.feedback, additionalContext: concatContext(reminder, downstream.additionalContext) } + } + return { + kind: 'accept', + ...downstream.content !== undefined ? { content: downstream.content } : {}, + additionalContext: concatContext(reminder, downstream.additionalContext), + } + }) + + // A user interjection changes the context; repetition across it is not a + // loop. Pure reset hook: always delegates (attaching nothing, vetoing + // nothing). + ctx.on('agent/prompt-submit', (agent, _content, _source, next): Promise => { + chains.delete(agent.id) + return next() + }) + + // Drop state when an agent goes away, bounding the map over harness lifetime. + ctx.on('agent/status', (agent, status) => { + if (status === 'disposed') chains.delete(agent.id) + }) +} diff --git a/packages/guard/repeat-tool-guard/tests/repeat-tool-guard.spec.ts b/packages/guard/repeat-tool-guard/tests/repeat-tool-guard.spec.ts new file mode 100644 index 0000000000..565f1076b5 --- /dev/null +++ b/packages/guard/repeat-tool-guard/tests/repeat-tool-guard.spec.ts @@ -0,0 +1,401 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import LlmService, { CallId } from '@deepseek-ai/dsh-llm' +import SessionStore, { type SessionEvent } from '@deepseek-ai/dsh-session' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools' +import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent' +import AgentLoop, { type ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop' +import * as RepeatToolGuard from '@deepseek-ai/dsh-repeat-tool-guard' +import type { Config } from '@deepseek-ai/dsh-repeat-tool-guard' +import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' + +/** + * Behavior suite for the repeat-tool-call guard: chain semantics (identical / + * different-tracked / untracked-transparent / per-agent / resets), threshold + * escalation incl. the `thresholds[0]` gentle-text rule, canonicalization, + * fold-onto-downstream-decision, and fail-loud config validation — all driven + * through a real agent loop against a scripted mock adapter (no network). + */ + +/** Boot the core spine + the guard; the caller registers adapters and extra listeners. */ +async function harness(config: Config = {}): Promise { + const ctx = new Context() + await ctx.plugin(LlmService) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(AgentLoop, { agents: [] }) + await ctx.plugin(RepeatToolGuard, config) + ctx.tools.register(defineTool({ name: 'probe', description: 'p', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } })) + ctx.tools.register(defineTool({ name: 'other', description: 'o', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } })) + return ctx +} + +function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise { + return new Promise((resolve) => { const d = ctx.on('agent/status', (s, st) => { if (s === agent && st === 'idle') { d(); resolve() } }) }) +} + +/** Every `context/message` in the agent's log, flattened to joined text + source for terse assertions. */ +function reminders(agent: ReactLoopAgent): { text: string; source: unknown }[] { + return [...agent.session.events] + .filter((e): e is SessionEvent<'context/message'> => e.type === 'context/message') + .map(e => ({ + text: e.data.content.map(block => block.type === 'text' ? block.text : '').join('|'), + source: e.data.source, + })) +} + +const GUARD_SOURCE = { kind: 'plugin', plugin: 'repeat-tool-guard' } + +describe('threshold escalation', () => { + it('reminds gently at the first default threshold (3) and in detail at the second (5)', async () => { + const ctx = await harness() + const adapter = new MockAdapter([ + ...Array.from({ length: 5 }, (_, i) => toolCallResponse(`c${i}`, 'probe', { q: 'same' })), + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + const found = reminders(agent) + expect(found).toHaveLength(2) + expect(found[0]!.text).toContain('repeating the exact same tool call') + expect(found[0]!.source).toEqual(GUARD_SOURCE) + expect(found[1]!.text).toContain('consecutive_calls: 5') + expect(found[1]!.text).toContain('- tool: probe') + expect(found[1]!.text).toContain('{"q":"same"}') + expect(found[1]!.source).toEqual(GUARD_SOURCE) + }) + + it('keys the gentle text to thresholds[0], not the literal 3', async () => { + const ctx = await harness({ thresholds: [4, 2] }) // unsorted on purpose: normalized ascending + const adapter = new MockAdapter([ + ...Array.from({ length: 4 }, (_, i) => toolCallResponse(`c${i}`, 'probe', {})), + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + const found = reminders(agent) + expect(found).toHaveLength(2) + expect(found[0]!.text).toContain('repeating the exact same tool call') // gentle at 2 + expect(found[1]!.text).toContain('consecutive_calls: 4') // detailed at 4 + }) +}) + +describe('chain semantics', () => { + it('caps the detailed reminder arguments at argumentsPreviewChars (detection still keys on the full string)', async () => { + const ctx = await harness({ thresholds: [2, 3], argumentsPreviewChars: 24 }) + const bigPayload = 'x'.repeat(400) + const adapter = new MockAdapter([ + toolCallResponse('c1', 'probe', { body: bigPayload }), + toolCallResponse('c2', 'probe', { body: bigPayload }), + toolCallResponse('c3', 'probe', { body: bigPayload }), + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + const found = reminders(agent) + expect(found).toHaveLength(2) // gentle at 2, detailed at 3 — full-key matching survived the cap + const detailed = found[1]!.text + expect(detailed).toContain('- arguments: {"body":"xxxxxxxxxxxxxx') // 24-char head + expect(detailed).toContain('… (+387 more chars)') + expect(detailed).not.toContain(bigPayload) + }) + + it('a different tracked call resets the chain', async () => { + const ctx = await harness() + const adapter = new MockAdapter([ + toolCallResponse('c1', 'probe', { q: 1 }), + toolCallResponse('c2', 'probe', { q: 1 }), + toolCallResponse('c3', 'other', {}), // tracked, different → reset + toolCallResponse('c4', 'probe', { q: 1 }), + toolCallResponse('c5', 'probe', { q: 1 }), + toolCallResponse('c6', 'probe', { q: 1 }), // 3rd consecutive AFTER the reset + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + expect(reminders(agent)).toHaveLength(1) + }) + + it('excluded calls are transparent: they neither count nor reset', async () => { + const ctx = await harness({ exclude: ['other'] }) + const adapter = new MockAdapter([ + toolCallResponse('c1', 'probe', { q: 1 }), + toolCallResponse('c2', 'other', {}), // excluded → invisible to the chain + toolCallResponse('c3', 'probe', { q: 1 }), + toolCallResponse('c4', 'other', {}), + toolCallResponse('c5', 'probe', { q: 1 }), // 3rd consecutive probe + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + const found = reminders(agent) + expect(found).toHaveLength(1) + expect(found[0]!.text).toContain('repeating the exact same tool call') + }) + + it('include patterns track only matching tools (wildcard star)', async () => { + const ctx = await harness({ include: ['pro*'] }) + const adapter = new MockAdapter([ + toolCallResponse('c1', 'other', {}), + toolCallResponse('c2', 'other', {}), + toolCallResponse('c3', 'other', {}), // 3 identical, but untracked + toolCallResponse('c4', 'probe', {}), + toolCallResponse('c5', 'probe', {}), + toolCallResponse('c6', 'probe', {}), // 3 identical, tracked + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + const found = reminders(agent) + expect(found).toHaveLength(1) + expect(found[0]!.text).toContain('repeating the exact same tool call') + }) + + it('escapes regex metacharacters in patterns (a dot matches only a literal dot)', async () => { + const ctx = await harness({ exclude: ['pr.be'] }) // would match 'probe' as a regex; must not as a wildcard + const adapter = new MockAdapter([ + ...Array.from({ length: 3 }, (_, i) => toolCallResponse(`c${i}`, 'probe', {})), + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + expect(reminders(agent)).toHaveLength(1) // probe was NOT excluded + }) + + it('canonicalization ignores property order, deeply', async () => { + const ctx = await harness() + const adapter = new MockAdapter([ + toolCallResponse('c1', 'probe', { a: 1, nested: { x: [1, 2], y: null } }), + toolCallResponse('c2', 'probe', { nested: { y: null, x: [1, 2] }, a: 1 }), + toolCallResponse('c3', 'probe', { a: 1, nested: { x: [1, 2], y: null } }), + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + expect(reminders(agent)).toHaveLength(1) // all three canonicalize identically + }) + + it('keys chains per agent: one agent repeating never trips another', async () => { + const ctx = await harness() + ctx.llm.registerAdapter(['mock-a'], new MockAdapter([ + toolCallResponse('a1', 'probe', { q: 1 }), + toolCallResponse('a2', 'probe', { q: 1 }), + textResponse('done'), + ])) + ctx.llm.registerAdapter(['mock-b'], new MockAdapter([ + toolCallResponse('b1', 'probe', { q: 1 }), + toolCallResponse('b2', 'probe', { q: 1 }), + toolCallResponse('b3', 'probe', { q: 1 }), + textResponse('done'), + ])) + const agentA = ctx.agentLoop.create(AgentId('a'), { model: 'mock-a' }) + const agentB = ctx.agentLoop.create(AgentId('b'), { model: 'mock-b' }) + agentA.send([{ type: 'text', text: 'go' }]) + agentB.send([{ type: 'text', text: 'go' }]) + await Promise.all([waitForIdle(ctx, agentA), waitForIdle(ctx, agentB)]) + + expect(reminders(agentA)).toHaveLength(0) // 2 repeats < 3, despite B's 3 in the same registry + expect(reminders(agentB)).toHaveLength(1) + }) + + it('a new user prompt resets the chain', async () => { + const ctx = await harness() + const adapter = new MockAdapter([ + toolCallResponse('c1', 'probe', { q: 1 }), + toolCallResponse('c2', 'probe', { q: 1 }), + textResponse('turn one done'), + toolCallResponse('c3', 'probe', { q: 1 }), // without the reset this would be the 3rd + textResponse('turn two done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + agent.send([{ type: 'text', text: 'again' }]) + await waitForIdle(ctx, agent) + + expect(reminders(agent)).toHaveLength(0) + }) + + it('drops an agent chain on disposal', async () => { + const ctx = await harness({ thresholds: [2] }) + ctx.llm.registerAdapter(['mock'], new MockAdapter([ + toolCallResponse('c1', 'probe', { q: 1 }), + textResponse('done'), + toolCallResponse('c2', 'probe', { q: 1 }), // same id, fresh agent: count 1, not 2 + textResponse('done'), + ])) + // Loop agents are torn down by disposing the scope that created them + // (the loop.spec pattern): a child plugin fiber owns `first`. + let first!: ReactLoopAgent + const fiber = await ctx.plugin(Object.assign((inner: Context) => { + first = inner.agentLoop.create(AgentId('reused'), { model: 'mock' }) + }, { inject: ['agentLoop'] })) + first.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, first) + await fiber.dispose() + await first.done + + const second = ctx.agentLoop.create(AgentId('reused'), { model: 'mock' }) + second.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, second) + + expect(reminders(second)).toHaveLength(0) + }) + + it('counts denied calls: hammering a denied tool still draws the reminder', async () => { + const ctx = await harness({ thresholds: [2] }) + ctx.on('tools/pre-execute', async () => ({ kind: 'deny' as const, reason: 'sealed' })) + const adapter = new MockAdapter([ + toolCallResponse('c1', 'probe', { q: 1 }), + toolCallResponse('c2', 'probe', { q: 1 }), + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + expect(reminders(agent)).toHaveLength(1) + }) + + it('ignores direct executes with no agent (they neither crash nor advance any chain)', async () => { + const ctx = await harness({ thresholds: [2] }) + const direct = await ctx.tools.execute({ callId: CallId('d1'), name: 'probe', arguments: { q: 1 } }) + expect(direct.isError).toBe(false) + + ctx.llm.registerAdapter(['mock'], new MockAdapter([ + toolCallResponse('c1', 'probe', { q: 1 }), // if the direct call had counted, this would be #2 + textResponse('done'), + ])) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + expect(reminders(agent)).toHaveLength(0) + }) +}) + +describe('fold onto the downstream decision', () => { + it('folds the reminder onto a downstream block and keeps its feedback', async () => { + const ctx = await harness({ thresholds: [2] }) + ctx.on('tools/post-execute', async () => ({ + kind: 'block' as const, + feedback: [{ type: 'text' as const, text: 'nope' }], + additionalContext: { content: [{ type: 'text' as const, text: 'downstream-ctx' }], source: { kind: 'plugin' as const, plugin: 'test' } }, + })) + const adapter = new MockAdapter([ + toolCallResponse('c1', 'probe', { q: 1 }), + toolCallResponse('c2', 'probe', { q: 1 }), + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + const found = reminders(agent) + expect(found).toHaveLength(2) + // Call 1: below threshold — the downstream context passes through untouched. + expect(found[0]!.text).toBe('downstream-ctx') + expect(found[0]!.source).toEqual({ kind: 'plugin', plugin: 'test' }) + // Call 2: reminder folded in front, single merged context, the guard's source. + expect(found[1]!.text).toContain('repeating the exact same tool call') + expect(found[1]!.text).toContain('|downstream-ctx') + expect(found[1]!.source).toEqual(GUARD_SOURCE) + // The block's feedback reached the tool result unchanged. + const results = [...agent.session.events].filter((e): e is SessionEvent<'tool/result'> => e.type === 'tool/result') + expect(results.every(r => r.data.isError)).toBe(true) + expect(results[1]!.data.content).toEqual([{ type: 'text', text: 'nope' }]) + }) + + it('preserves a downstream accept content replacement while folding', async () => { + const ctx = await harness({ thresholds: [2] }) + ctx.on('tools/post-execute', async () => ({ + kind: 'accept' as const, + content: [{ type: 'text' as const, text: 'replaced' }], + })) + const adapter = new MockAdapter([ + toolCallResponse('c1', 'probe', { q: 1 }), + toolCallResponse('c2', 'probe', { q: 1 }), + textResponse('done'), + ]) + ctx.llm.registerAdapter(['mock'], adapter) + const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) + agent.send([{ type: 'text', text: 'go' }]) + await waitForIdle(ctx, agent) + + const found = reminders(agent) + expect(found).toHaveLength(1) + expect(found[0]!.text).toContain('repeating the exact same tool call') + const results = [...agent.session.events].filter((e): e is SessionEvent<'tool/result'> => e.type === 'tool/result') + expect(results[1]!.data.content).toEqual([{ type: 'text', text: 'replaced' }]) + }) +}) + +describe('config validation fails loud', () => { + async function spine(): Promise { + const ctx = new Context() + await ctx.plugin(LlmService) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + await ctx.plugin(AgentLoop, { agents: [] }) + return ctx + } + + it('rejects an empty thresholds list', async () => { + const ctx = await spine() + await expect(ctx.plugin(RepeatToolGuard, { thresholds: [] })).rejects.toThrow(/must not be empty/) + }) + + it('rejects a threshold below 2', async () => { + const ctx = await spine() + await expect(ctx.plugin(RepeatToolGuard, { thresholds: [1, 3] })).rejects.toThrow(/integer >= 2/) + }) + + it('rejects a non-integer threshold', async () => { + const ctx = await spine() + await expect(ctx.plugin(RepeatToolGuard, { thresholds: [2.5] })).rejects.toThrow(/integer >= 2/) + }) + + it('rejects duplicate thresholds', async () => { + const ctx = await spine() + await expect(ctx.plugin(RepeatToolGuard, { thresholds: [3, 3] })).rejects.toThrow(/duplicates/) + }) + + it('rejects a non-positive or fractional argumentsPreviewChars', async () => { + const ctx = await spine() + await expect(ctx.plugin(RepeatToolGuard, { argumentsPreviewChars: 0 })).rejects.toThrow(/argumentsPreviewChars/) + const ctx2 = await spine() + await expect(ctx2.plugin(RepeatToolGuard, { argumentsPreviewChars: 12.5 })).rejects.toThrow(/argumentsPreviewChars/) + }) +}) diff --git a/packages/guard/repeat-tool-guard/tsconfig.json b/packages/guard/repeat-tool-guard/tsconfig.json new file mode 100644 index 0000000000..66439bcd5f --- /dev/null +++ b/packages/guard/repeat-tool-guard/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../llm/llm" + } + ] +} diff --git a/packages/llm/llm/src/types.ts b/packages/llm/llm/src/types.ts index 1644885a73..e3339869a5 100644 --- a/packages/llm/llm/src/types.ts +++ b/packages/llm/llm/src/types.ts @@ -172,6 +172,12 @@ export interface ToolSchema { /** A single model request, fully assembled. */ export interface GenerateOptions { model: string + /** + * Ordered conversation messages, exactly as the provider sees them (after + * the `system` slot). A loop-built request assembles them as + * `EpochHeader.messagePrefix` + the derived history (dsh-agent-loop); a + * hand-built one-shot passes any list. + */ messages: Message[] /** System prompt text (adapters map to the provider's system slot). */ system?: string diff --git a/packages/support/acp-snapshot/src/normalize.ts b/packages/support/acp-snapshot/src/normalize.ts index 2cbe914b42..017dd504b3 100644 --- a/packages/support/acp-snapshot/src/normalize.ts +++ b/packages/support/acp-snapshot/src/normalize.ts @@ -13,8 +13,9 @@ * (deterministic — `seq = log.length`, part of the event-log contract). * * A separate, composable normalizer — {@link scrubRequestHeaders} — replaces - * the bulky request-header CONTENT (the composed system prompt and the tool - * schema list) with `{{system}}`/`{{tools}}` tokens. It is deliberately NOT + * the bulky request-header CONTENT (the composed system prompt, the tool + * schema list, and the session prefix) with + * `{{system}}`/`{{tools}}`/`{{messagePrefix}}` tokens. It is deliberately NOT * folded into {@link normalizeSessionLog}: each suite's one header-pinning * scenario compares that content verbatim, every other scenario composes the * scrub in (the `pinsHeader` flag on the scenario table, consumed by the suite @@ -30,6 +31,7 @@ const SESSION_ID = '{{sessionId}}' const CWD = '{{cwd}}' const SYSTEM = '{{system}}' const TOOLS = '{{tools}}' +const MESSAGE_PREFIX = '{{messagePrefix}}' /** A UUID v4 string, the shape `randomUUID()` produces for session ids. */ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi @@ -135,15 +137,22 @@ export function normalizeSessionLog(rawLog: string, ctx: NormalizeContext): stri /** * Replace request-header CONTENT in a session JSONL with stable tokens, * keeping its structure: a `request/header` event's `data.header.system` → - * `{{system}}` and `data.header.tools` → `{{tools}}`; a + * `{{system}}`, `data.header.tools` → `{{tools}}`, and + * `data.header.messagePrefix` → one `{{messagePrefix}}` token per message + * (the session prefix is model-visible bulk — an AGENTS digest, a skills + * catalog — so its COUNT stays a structural fact while its text never lands + * in a fixture); a * `request/header-delta` event keeps every structural fact — the system * delta's `keepStart`/`keepEnd` line positions and inserted-line COUNT (one * `{{system}}` token per inserted line), the tools delta's - * added/removed/changed tool NAMES — and tokenizes only the bulk (prompt - * text; each added/changed schema's fields other than `name` → `{{tools}}`), + * added/removed/changed tool NAMES, the prefix replacement's message COUNT — + * and tokenizes only the bulk (prompt + * text; each added/changed schema's fields other than `name` → `{{tools}}`; + * each replacement prefix message → `{{messagePrefix}}`), * so two different deltas still compare different. - * Absent fields stay absent — WHETHER a header carried a system prompt or - * tools is behavior and stays visible; `config` and `reason` are small and + * Absent fields stay absent — WHETHER a header carried a system prompt, + * tools, or a prefix is behavior and stays visible; `config` and `reason` + * are small and * stable, so they stay verbatim (a model swap churns every fixture by design * — it invalidates the recorded responses; a prompt/schema edit churns none — * replay never reads this content, see dsh-llm-replay). @@ -166,9 +175,10 @@ export function scrubRequestHeaders(rawLog: string): string { if (record.type === 'request/header') { const header = data.header as Record | null | undefined if (header === null || typeof header !== 'object') return line - if (!('system' in header) && !('tools' in header)) return line + if (!('system' in header) && !('tools' in header) && !('messagePrefix' in header)) return line if ('system' in header) header.system = SYSTEM if ('tools' in header) header.tools = TOOLS + if (Array.isArray(header.messagePrefix)) header.messagePrefix = header.messagePrefix.map(() => MESSAGE_PREFIX) return JSON.stringify(record) } if (record.type === 'request/header-delta') { @@ -183,6 +193,10 @@ export function scrubRequestHeaders(rawLog: string): string { if (Array.isArray(tools.added)) { tools.added = tools.added.map(scrubToolSchema); touched = true } if (Array.isArray(tools.changed)) { tools.changed = tools.changed.map(scrubToolSchema); touched = true } } + if (Array.isArray(data.messagePrefix)) { + data.messagePrefix = data.messagePrefix.map(() => MESSAGE_PREFIX) + touched = true + } return touched ? JSON.stringify(record) : line } return line diff --git a/packages/support/acp-snapshot/src/suite.ts b/packages/support/acp-snapshot/src/suite.ts index 14a4df54da..9718fc7d5e 100644 --- a/packages/support/acp-snapshot/src/suite.ts +++ b/packages/support/acp-snapshot/src/suite.ts @@ -52,12 +52,22 @@ export interface Scenario { /** * Whether `test:snapshot:record` regenerates this scenario's `session.jsonl` * from the LIVE API. `recorded` scenarios are model-driven and reproducible; - * `authored` scenarios (a hand-written `replay.override.json` sidecar drives - * replay — e.g. a provider error or a cancel, which the live API can't be - * coaxed into deterministically — or a deterministic hook scenario whose - * derived empty script needs no sidecar) are NEVER re-recorded. + * `authored` scenarios (fixtures hand-written or hand-harvested — e.g. a + * provider error or a cancel the live API can't be coaxed into + * deterministically, a deterministic hook scenario, or a scripted repetition + * a live model won't reproduce) are NEVER re-recorded. */ recorded: boolean + /** + * Whether replay is driven by a hand-written `replay.override.json` sidecar + * (a `ReplayEntry[]` that REPLACES the script derived from `session.jsonl`) + * — the throw/hang cases chunks cannot express. The fixture guard requires + * the sidecar exactly when this is set: the harness forwards the file purely + * on existence, so an unregistered stray sidecar would silently replace the + * derived script — the guard fails loud on either mismatch. Defaults to + * false (replay derives from the fixture's `assistant/chunk` events). + */ + overridden?: boolean /** * How many SUBAGENT child sessions this scenario records beyond the top-level * one (0 for a single-session scenario). Each child rides in a sibling fixture @@ -317,17 +327,18 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { // throws "fixture not found" when it is absent and no override replaces it. // A no-model scenario ships a header-only `session.jsonl` (it derives to an // empty script — no model call is made); a model scenario's fixture also - // doubles as the expected-log artifact the run is diffed against. An authored - // (non-`recorded`) model scenario additionally ships a `replay.override.json` - // sidecar for the throw/hang cases a derived script cannot express. - for (const { name, hasModelTurn, recorded, childSessions } of scenarios) { + // doubles as the expected-log artifact the run is diffed against. The + // `replay.override.json` sidecar is matched BOTH ways against the table's + // `overridden` flag: required when set, forbidden when not — the harness + // forwards the file purely on existence, so an unregistered stray sidecar + // would silently replace the derived script. + for (const { name, overridden, childSessions } of scenarios) { const dir = join(snapshotsDir, name) expect(existsSync(join(dir, 'input.json')), `${name}/input.json`).toBe(true) expect(existsSync(join(dir, 'stdout.golden.jsonl')), `${name}/stdout.golden.jsonl`).toBe(true) expect(existsSync(join(dir, 'session.jsonl')), `${name}/session.jsonl`).toBe(true) - if (hasModelTurn && !recorded) { - expect(existsSync(join(dir, 'replay.override.json')), `${name}/replay.override.json`).toBe(true) - } + expect(existsSync(join(dir, 'replay.override.json')), `${name}/replay.override.json presence must match \`overridden\``) + .toBe(overridden === true) // A nested-agent scenario ships one child fixture per recorded subagent // session (`session.1.jsonl` …), the replay source for that child session. for (const childFixture of childFixturePaths(dir, childSessions ?? 0)) { diff --git a/packages/support/acp-snapshot/tests/normalize.spec.ts b/packages/support/acp-snapshot/tests/normalize.spec.ts index 8ebd1412b9..daa9f8342d 100644 --- a/packages/support/acp-snapshot/tests/normalize.spec.ts +++ b/packages/support/acp-snapshot/tests/normalize.spec.ts @@ -155,6 +155,38 @@ describe('scrubRequestHeaders', () => { expect(toolsOnly).not.toContain('{{system}}') }) + it('scrubs the header session prefix to one token per message, keeping the count', () => { + const ev = headerEvent({ + config: { model: 'm' }, + messagePrefix: [ + { role: 'user', content: [{ type: 'text', text: 'workspace AGENTS digest' }] }, + { role: 'user', content: [{ type: 'text', text: 'skills catalog' }] }, + ], + }) + const out = scrubRequestHeaders(`${headerLine}\n${ev}\n`) + expect(out).toContain('"messagePrefix":["{{messagePrefix}}","{{messagePrefix}}"]') + expect(out).not.toContain('AGENTS digest') + expect(out).not.toContain('skills catalog') + // Absence stays absent — a prefix-less header gains no token… + expect(scrubRequestHeaders(`${headerLine}\n${headerEvent({ system: 's' })}\n`)).not.toContain('{{messagePrefix}}') + // …and a non-array shape passes through untouched. + const odd = JSON.stringify({ type: 'request/header', seq: 4, time: 9, data: { header: { config: { model: 'm' }, messagePrefix: 'weird' }, reason: 'initial' } }) + expect(scrubRequestHeaders(`${headerLine}\n${odd}\n`)).toContain('"messagePrefix":"weird"') + }) + + it('scrubs a header-delta prefix replacement to one token per message', () => { + const delta = JSON.stringify({ + type: 'request/header-delta', seq: 8, time: 9, + data: { messagePrefix: [{ role: 'user', content: [{ type: 'text', text: 'leaked opener' }] }] }, + }) + const out = scrubRequestHeaders(`${headerLine}\n${delta}\n`) + expect(out).toContain('"messagePrefix":["{{messagePrefix}}"]') + expect(out).not.toContain('leaked opener') + // The empty-array transition-to-absence stays a structural fact. + const toNone = JSON.stringify({ type: 'request/header-delta', seq: 9, time: 9, data: { messagePrefix: [] } }) + expect(scrubRequestHeaders(`${headerLine}\n${toNone}\n`)).toContain('"messagePrefix":[]') + }) + it('leaves a delta with no scrubbable payload byte-identical (config-only, or non-array shapes)', () => { const configOnly = JSON.stringify({ type: 'request/header-delta', seq: 8, time: 9, data: { config: { model: 'm2' } } }) const oddShapes = JSON.stringify({ type: 'request/header-delta', seq: 9, time: 9, data: { system: { insert: 'not-an-array' }, tools: null } }) diff --git a/packages/support/acp-snapshot/tests/suite.spec.ts b/packages/support/acp-snapshot/tests/suite.spec.ts index 0bc15aeec2..e14f525b30 100644 --- a/packages/support/acp-snapshot/tests/suite.spec.ts +++ b/packages/support/acp-snapshot/tests/suite.spec.ts @@ -39,14 +39,14 @@ const REPLAY_SCENARIOS: Scenario[] = [ { name: 'plain-turn', hasModelTurn: true, recorded: true, childSessions: 1 }, { name: 'no-model', hasModelTurn: false, recorded: false }, { name: 'blocked-log', hasModelTurn: false, comparesLog: true, recorded: false }, - { name: 'authored-error', hasModelTurn: true, recorded: false }, + { name: 'authored-error', hasModelTurn: true, recorded: false, overridden: true }, ] const RECORD_SCENARIOS: Scenario[] = [ { name: 'rec-pin', hasModelTurn: true, recorded: true, pinsHeader: true }, { name: 'rec-child', hasModelTurn: true, recorded: true, childSessions: 1 }, // recorded:false in record mode → registered but skipped (never re-recorded). - { name: 'rec-skip', hasModelTurn: true, recorded: false }, + { name: 'rec-skip', hasModelTurn: true, recorded: false, overridden: true }, ] // Record mode mutates its snapshots dir, so run it on a throwaway copy — diff --git a/packages/support/invariants/src/index.ts b/packages/support/invariants/src/index.ts index d4b772b317..8fd425392d 100644 --- a/packages/support/invariants/src/index.ts +++ b/packages/support/invariants/src/index.ts @@ -387,10 +387,12 @@ export function apply(ctx: Context, config: Config = {}): void { 'agent/pre-step': args => args[0], 'agent/prompt-submit': args => args[0], 'agent/request': args => args[0], + 'agent/session-prefix': args => args[0], 'agent/step-result': args => args[0], 'agent/turn-continuation': args => args[0], 'agent/error': args => args[0], 'tools/pre-execute': args => (args[0] as ToolExecution).agent, + 'tools/execute': args => (args[0] as ToolExecution).agent, 'tools/post-execute': args => (args[0] as ToolExecution).agent, 'system-prompt/assemble': args => (args[1] as AssembleContext).scope, 'session/created': null, @@ -457,8 +459,11 @@ export function apply(ctx: Context, config: Config = {}): void { // hand-built one-shot (compaction summarize) is unfrozen and skipped — must // be EXACTLY what the session log reconstructs: // - // - messages: the derivation over the log prefix strictly before the - // in-flight step's `step/start` (the reconstruction boundary). Compared + // - messages: the folded header's session prefix (messagePrefix — the + // `agent/session-prefix` product, logged on the header because no + // session event carries it) followed by the + // derivation over the log prefix strictly before the in-flight step's + // `step/start` (the reconstruction boundary). The derivation is compared // against a FRESH Session built over that prefix — the same projection // code with zero shared state, so the live cache under test cannot vouch // for itself. Boundary-correct by construction: content appended after @@ -498,18 +503,22 @@ export function apply(ctx: Context, config: Config = {}): void { if (boundary === -1) { throw new InvariantError('a loop-built request with no step/start in its session log') } - const rebuilt = new Session(SessionId(`${String(session.id)}-invariant-rebuild`), structuredClone(events.slice(0, boundary))) - // JSON equality is sound here: both sides are structuredClones produced by - // the same projection code path, so key insertion order matches when the - // values do. - if (JSON.stringify(options.messages) !== JSON.stringify(rebuilt.deriveMessages())) { - throw new InvariantError(`llm request for session "${String(session.id)}" diverges from the boundary derivation (log-reconstruction desync)`) - } - const header = foldRequestHeader(events) if (header === undefined) { throw new InvariantError('a loop-built request with no request/header event in its session log') } + const rebuilt = new Session(SessionId(`${String(session.id)}-invariant-rebuild`), structuredClone(events.slice(0, boundary))) + // The reconstruction equation: the folded header's session prefix, then + // the boundary derivation — the loop + // logs the header event BEFORE dispatch, so the fold already covers this + // request's prefix. JSON equality is sound here: both sides are + // structuredClones produced by the same projection/build code path, so key + // insertion order matches when the values do. + const expected = [...header.messagePrefix ?? [], ...rebuilt.deriveMessages()] + if (JSON.stringify(options.messages) !== JSON.stringify(expected)) { + throw new InvariantError(`llm request for session "${String(session.id)}" diverges from the boundary derivation (log-reconstruction desync)`) + } + const headerMatches = options.model === header.config.model && options.system === header.system && options.temperature === header.config.temperature diff --git a/packages/support/invariants/tests/invariants.spec.ts b/packages/support/invariants/tests/invariants.spec.ts index 9bd796955d..0186aaf31a 100644 --- a/packages/support/invariants/tests/invariants.spec.ts +++ b/packages/support/invariants/tests/invariants.spec.ts @@ -708,6 +708,21 @@ describe('request-reconstruction cross-check (llm/stream)', () => { expect(() => { dispatch(ctx, options) }).not.toThrow() }) + it('expects the folded header\'s session prefix ahead of the derivation (prefix + derived)', async () => { + const { ctx, session, boundary } = await requestSetup() + const prefix = { role: 'user' as const, content: [{ type: 'text' as const, text: 'catalog' }] } + session.append('request/header-delta', { messagePrefix: [prefix] }) + // The prefixed request matches the fold… + const prefixed = Object.freeze({ model: 'm', messages: Object.freeze([prefix, ...boundary]), sessionId: session.id }) + expect(() => { dispatch(ctx, prefixed) }).not.toThrow() + // …a request that DROPPED the logged prefix diverges… + const bare = Object.freeze({ model: 'm', messages: Object.freeze([...boundary]), sessionId: session.id }) + expect(() => { dispatch(ctx, bare) }).toThrow(/diverges from the boundary derivation/) + // …and so does one that misplaced it (prefix sent after the history). + const misplaced = Object.freeze({ model: 'm', messages: Object.freeze([...boundary, prefix]), sessionId: session.id }) + expect(() => { dispatch(ctx, misplaced) }).toThrow(/diverges from the boundary derivation/) + }) + it('rejects a frozen request whose messages diverge from the boundary derivation', async () => { const { ctx, session, boundary } = await requestSetup() const messages = [...boundary, { role: 'user', content: [{ type: 'text', text: 'phantom' }] }] diff --git a/packages/timeout/README.md b/packages/timeout/README.md new file mode 100644 index 0000000000..36f52abaf3 --- /dev/null +++ b/packages/timeout/README.md @@ -0,0 +1,9 @@ +# timeout/ — tool-call timeout policy + +The tool-call timeout policy plugin. A single **product** package: it is a deployment-policy consumer of the `tools/execute` around-dispatch seam (owned by [`dsh-tools`](../core/tools)) and the pure [`dsh-timeout`](../util/timeout) library — not a swappable capability with an interface/implementation split, so it needs no seam trio. + +| Package | Role | ctx key | +|---|---|---| +| `timeout-policy/` | A `tools/execute` wrapper: for each configured tool it arms a per-call deadline on `exec.signal` and returns a structured `TOOL_TIMEOUT` result when that deadline wins | (registers a `tools/execute` listener; injects nothing) | + +Timeout is split across three layers: [`dsh-timeout`](../util/timeout) owns the pure timing/classification primitive (`deadline`/`timeoutOf`), each capability owns termination (bash kills its process group, the fetch provider tears down its socket), and this package owns the *model-facing tool-call budget as deployment policy* — no model-facing timeout argument, no global default. It is the middleware the [timeout-library RFC](../../docs/rfc/implemented/architecture/2026-07-06-timeout-deadline-library.md) foresaw. `bash` and hook command execution keep their own `BASH_TIMEOUT` backend timeout and do not route through this policy. diff --git a/packages/timeout/timeout-policy/README.md b/packages/timeout/timeout-policy/README.md new file mode 100644 index 0000000000..e637a658bf --- /dev/null +++ b/packages/timeout/timeout-policy/README.md @@ -0,0 +1,34 @@ +# dsh-timeout-policy + +Tool-call timeout enforcer: a single `tools/execute` around-dispatch listener that arms a per-call cooperative deadline on `exec.signal` for a tool declaring `timeoutMs` on its `ToolDefinition` and returns a structured `TOOL_TIMEOUT` result when that deadline wins. The budget is read from the tool's own declaration (`ToolDefinition.timeoutMs`, set by the owning tool plugin), so this plugin is **zero-config**. It is the reference `tools/execute` wrapper and the enforcement home for model-facing tool-call budgets (the timeout-library RFC's foreseen middleware). + +## Plugin (namespace: `timeout-policy`) + +A function/namespace plugin (`name` / `inject` / `apply`), not a service. It registers no tool and takes no config — it consumes `ctx.tools`'s `tools/execute` waterfall (which the `dsh-tools` registry always provides) and reads each dispatched tool's declared `timeoutMs` from the registry (`ctx.tools.get(exec.name)`). + +```yaml +- id: timeout-policy + name: '@deepseek-ai/dsh-timeout-policy' +``` + +The per-tool budget is declared by the tool plugin (e.g. `dsh-tool-web`'s `fetchTimeoutMs`/`searchTimeoutMs` config, attached as `ToolDefinition.timeoutMs`); this plugin only enforces it, so a mistyped tool name is not possible. + +### Behavior + +For a tool that **declares a `timeoutMs`** the listener: + +1. Reads the budget from the tool's own declaration in the registry (`ctx.tools.get(exec.name)?.timeoutMs`) and arms `deadline(exec.signal, timeoutMs, 'TOOL_TIMEOUT')` — one signal fusing the caller's abort with this plugin's timer (`@deepseek-ai/dsh-timeout`). +2. Swaps that derived signal onto `exec` for the downstream dispatch, then restores the caller's own signal afterward (cordis `next()` ignores passed arguments, so the wrapper mutates the shared `exec` in place; restoring keeps `tools/post-execute` seeing the caller's signal). +3. After dispatch, if `timeoutOf(d.signal, 'TOOL_TIMEOUT')` matches — this plugin's own timer fired — replaces the result with a structured `TOOL_TIMEOUT` tool result: `{ isError: true, error: { name: 'ToolTimeoutError', code: 'TOOL_TIMEOUT' }, content: 'Error: tool call timed out after ms' }`. + +A tool that **declares no budget** delegates untouched (no deadline). + +The base `next()` of `tools/execute` is the registry's dispatch-with-normalization thunk, so when the timeout signal reaches a provider that throws its own upstream-abort error, dispatch first turns it into a normal error result, and this wrapper then replaces that with `TOOL_TIMEOUT`. That ordering is why the replacement is keyed off the signal (`timeoutOf`), not off the dispatched result's shape. + +### Cooperative, not a hard kill + +The derived signal only **notifies**; termination stays with the tool and the capability it forwards `exec.signal` to (the `dsh-timeout` library owns no kill). **Declaring `timeoutMs` therefore means "cooperative with `exec.signal`"**: a tool that ignores the signal will not stop on timeout. Only signal-forwarding tools should declare it — the shipped `web_fetch`/`web_search` (which forward through `ctx.web` to providers) are the reference. `TOOL_TIMEOUT` needs no session event for reconstructability: it is the final model-facing `tool/result`, already logged by the loop. + +### Composing with other `tools/execute` wrappers + +Multiple `tools/execute` listeners compose by cordis registration order. Combined with a future retry/sandbox/metrics wrapper, registration order chooses the semantics — "timeout covers the whole retry operation" (timeout registered outer) versus "timeout covers each attempt" (timeout registered inner). diff --git a/packages/timeout/timeout-policy/package.json b/packages/timeout/timeout-policy/package.json new file mode 100644 index 0000000000..9069735b86 --- /dev/null +++ b/packages/timeout/timeout-policy/package.json @@ -0,0 +1,36 @@ +{ + "name": "@deepseek-ai/dsh-timeout-policy", + "description": "Tool-call timeout policy: a tools/execute wrapper that arms a per-tool deadline on exec.signal and returns TOOL_TIMEOUT when it wins", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-llm": "^0.0.1", + "@deepseek-ai/dsh-timeout": "^0.0.1", + "@deepseek-ai/dsh-tools": "^0.0.1", + "cordis": "^4.0.0-rc.6" + }, + "devDependencies": { + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "cordis": "^4.0.0-rc.6" + } +} diff --git a/packages/timeout/timeout-policy/src/index.ts b/packages/timeout/timeout-policy/src/index.ts new file mode 100644 index 0000000000..2e9ed0d635 --- /dev/null +++ b/packages/timeout/timeout-policy/src/index.ts @@ -0,0 +1,119 @@ +/** + * `@deepseek-ai/dsh-timeout-policy`: the tool-call timeout ENFORCER. It registers + * ONE `tools/execute` around-dispatch listener that, for a tool declaring a + * `timeoutMs` on its {@link ToolDefinition}, arms a per-call deadline on + * `exec.signal` and returns a structured `TOOL_TIMEOUT` result when that deadline + * wins. The budget is DECLARED by the tool (see `ToolDefinition.timeoutMs`, set + * by the owning tool plugin from its own config); this plugin only enforces it, + * so it is zero-config and there is no tool-name map to mistype. + * + * This is a COOPERATIVE deadline, not a hard kill: the derived signal only + * NOTIFIES. A tool that declares `timeoutMs` (and the capability it forwards + * `exec.signal` to) must honor that signal and reach quiescence — the plugin + * never races the tool promise or terminates work itself (see the timeout-library + * RFC's rejection of `Promise.race`). Declaring `timeoutMs` therefore MEANS "this + * tool is cooperative with `exec.signal`": a tool that ignores the signal will + * not stop on timeout, so only signal-forwarding tools should declare it (the + * shipped web tools are the reference). + * + * Ownership of the `TOOL_TIMEOUT` code is entirely here: it is both the internal + * {@link deadline} code (so {@link timeoutOf} scopes the classification to THIS + * plugin's own timer, reading a foreign/nested outer deadline as an ordinary + * cancel) and the structured `{ name, code }` on the replacement tool result. + * No new session event is needed for reconstructability: the `TOOL_TIMEOUT` + * result IS the final model-facing `tool/result`, already logged by the loop. + * + * Why a `tools/execute` around seam and not a `pre`/`post` pair: the deadline + * needs ONE lexical scope — arm on `exec.signal`, delegate to dispatch, classify + * the result, dispose the timer — which the around seam gives directly. A + * pre/post split would spread one deadline's lifetime across two independent + * waterfalls (a call-id map, cleanup on every deny/throw/dispose path). + * + * @module @deepseek-ai/dsh-timeout-policy + */ + +import type { Context } from 'cordis' +import type { CallId } from '@deepseek-ai/dsh-llm' +import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' +import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' + +/** + * The code owned by this plugin, used BOTH as the internal {@link deadline} + * classification code AND as the structured error `code` on the replacement + * tool result. Scoping {@link timeoutOf} to it keeps a nested outer deadline + * (another `tools/execute` wrapper's timer that fired first) from being misread + * as this plugin's own timeout — it reads as an ordinary upstream cancel. + */ +export const TOOL_TIMEOUT = 'TOOL_TIMEOUT' + +/** Cordis plugin name used by loader diagnostics. */ +export const name = 'timeout-policy' + +/** The tool registry seam this plugin wraps (`tools/execute`) and reads (`get`). */ +export const inject = ['tools'] + +/** + * The structured result substituted when this plugin's deadline wins. `content` + * is the model-facing message; `error.code` is the same {@link TOOL_TIMEOUT} + * this plugin owns, so a retry/sandbox plugin (and replay) can route on it. + * + * @param callId - the timed-out call's id, carried onto the replacement result. + * @param timeoutMs - the elapsed budget, rendered into the model-facing message. + * @returns the `isError` {@link ToolExecutionResult} with a `TOOL_TIMEOUT` error. + */ +export function toolTimeoutResult(callId: CallId, timeoutMs: number): ToolExecutionResult { + return { + callId, + content: [{ type: 'text', text: `Error: tool call timed out after ${timeoutMs}ms` }], + isError: true, + error: { name: 'ToolTimeoutError', code: TOOL_TIMEOUT }, + } +} + +/** + * Register the tool-call timeout enforcer. For a tool whose {@link ToolDefinition} + * declares `timeoutMs`, the listener arms a {@link deadline} on the caller's + * `exec.signal`, swaps it onto `exec` for the downstream dispatch (cordis + * `next()` ignores passed arguments, so a wrapper mutates the shared `exec` in + * place), restores the original signal afterward so `tools/post-execute` sees the + * caller's own signal, and replaces the result with {@link toolTimeoutResult} + * when its own timer fired. A tool that declares no budget delegates untouched. + * + * The budget source is the tool's own declaration read from the registry + * (`ctx.tools.get(exec.name, exec.agent)?.timeoutMs`), NOT a plugin config map — + * `exec.name` is the tool being dispatched, so the lookup always resolves and + * there is no mistypable tool name and no unknown-name path to warn or throw + * about. Resolution goes through the CALLER's visible view (the `exec.agent` + * scope), exactly like dispatch itself: a scoped tool's own `timeoutMs` governs + * its calls, and a global name-twin's budget is never misapplied to a shadowing + * per-agent variant. + */ +export function apply(ctx: Context): void { + ctx.on('tools/execute', async (exec, next): Promise => { + const timeoutMs = ctx.tools.get(exec.name, exec.agent)?.timeoutMs + // A tool that declares no budget: no deadline, delegate unchanged. + if (timeoutMs === undefined) return next() + + using d = deadline(exec.signal, timeoutMs, TOOL_TIMEOUT) + // Swap the derived deadline onto exec for dispatch, then restore the + // caller's own signal so post-execute listeners never see this plugin's + // (possibly already-aborted) timeout signal. `undefined` is not assignable to + // the optional `signal` under exactOptionalPropertyTypes, so branch on it. + const upstream = exec.signal + exec.signal = d.signal + try { + const result = await next() + // If OUR timer fired (scoped by code — a nested outer deadline reads as + // undefined here), the tool/capability saw the abort and reached + // quiescence; replace whatever it returned (its own abort result) with the + // structured TOOL_TIMEOUT the model sees. + if (timeoutOf(d.signal, TOOL_TIMEOUT) !== undefined) { + return toolTimeoutResult(exec.callId, timeoutMs) + } + return result + } finally { + if (upstream === undefined) delete exec.signal + else exec.signal = upstream + } + }) +} diff --git a/packages/timeout/timeout-policy/tests/timeout-policy.spec.ts b/packages/timeout/timeout-policy/tests/timeout-policy.spec.ts new file mode 100644 index 0000000000..ef5c52030f --- /dev/null +++ b/packages/timeout/timeout-policy/tests/timeout-policy.spec.ts @@ -0,0 +1,200 @@ +/** + * Unit + real-load-path coverage for @deepseek-ai/dsh-timeout-policy. The + * timeout-wins cases drive the deadline under fake timers (deterministic — no + * wall-clock race) and use a COOPERATIVE tool that settles only when its + * `exec.signal` aborts, mirroring how a real capability forwards the signal and + * reaches quiescence. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { Context } from 'cordis' +import Loader from '@cordisjs/plugin-loader' +import { CallId, HarnessError } from '@deepseek-ai/dsh-llm' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry, { defineTool, type ToolExecution, type ToolExecutionResult, type PostToolDecision } from '@deepseek-ai/dsh-tools' +import * as timeoutPolicy from '@deepseek-ai/dsh-timeout-policy' +import { TOOL_TIMEOUT, toolTimeoutResult } from '@deepseek-ai/dsh-timeout-policy' + +/** Mount the registry + the zero-config timeout-policy enforcer. */ +async function setup() { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(timeoutPolicy) + return ctx +} + +/** A cooperative tool that settles ONLY when its exec.signal aborts (returns text). */ +const cooperativeTool = defineTool({ + name: 'slow', description: 'stops when aborted', parameters: {}, timeoutMs: 100, + execute(_args, exec): Promise<{ type: 'text'; text: string }[]> { + const done = [{ type: 'text' as const, text: 'stopped cooperatively' }] + if (exec.signal?.aborted) return Promise.resolve(done) + return new Promise((resolve) => { exec.signal?.addEventListener('abort', () => { resolve(done) }) }) + }, +}) + +/** A cooperative tool that THROWS its own upstream-abort error when aborted (web-provider shape). */ +const abortThrowingTool = defineTool({ + name: 'aborter', description: 'throws WEB_ABORTED when aborted', parameters: {}, timeoutMs: 100, + execute(_args, exec): Promise { + if (exec.signal?.aborted) return Promise.reject(new HarnessError('web fetch aborted', 'WEB_ABORTED')) + return new Promise((_resolve, reject) => { exec.signal?.addEventListener('abort', () => { reject(new HarnessError('web fetch aborted', 'WEB_ABORTED')) }) }) + }, +}) + +describe('timeout-policy delegation (unconfigured / fast)', () => { + it('delegates a tool with NO declared budget unchanged and does not touch exec.signal', async () => { + const ctx = await setup() + let seenSignal: AbortSignal | undefined + ctx.tools.register(defineTool({ name: 'probe', description: 'd', parameters: {}, + async execute(_a, exec) { seenSignal = exec.signal; return [{ type: 'text' as const, text: 'ok' }] } })) + const upstream = new AbortController().signal + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'probe', arguments: {}, signal: upstream }) + expect(result.isError).toBe(false) + expect(seenSignal).toBe(upstream) + }) + + it('a tool with a budget that returns fast keeps its own result (no timeout)', async () => { + const ctx = await setup() + ctx.tools.register(defineTool({ name: 'fast', description: 'd', parameters: {}, timeoutMs: 10_000, + async execute() { return [{ type: 'text' as const, text: 'ok' }] } })) + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'fast', arguments: {} }) + expect(result).toEqual({ callId: CallId('c1'), content: [{ type: 'text', text: 'ok' }], isError: false }) + }) + + it('a budgeted tool receives the DERIVED deadline signal (not the caller signal) during dispatch', async () => { + const ctx = await setup() + let seenSignal: AbortSignal | undefined + ctx.tools.register(defineTool({ name: 'probe', description: 'd', parameters: {}, timeoutMs: 10_000, + async execute(_a, exec) { seenSignal = exec.signal; return [{ type: 'text' as const, text: 'ok' }] } })) + const upstream = new AbortController().signal + await ctx.tools.execute({ callId: CallId('c1'), name: 'probe', arguments: {}, signal: upstream }) + expect(seenSignal).toBeDefined() + expect(seenSignal).not.toBe(upstream) + }) +}) + +describe('timeout-policy signal restoration', () => { + it('restores the caller signal for post-execute after wrapping', async () => { + const ctx = await setup() + ctx.tools.register(defineTool({ name: 'fast', description: 'd', parameters: {}, timeoutMs: 10_000, + async execute() { return [{ type: 'text' as const, text: 'ok' }] } })) + let postSignal: AbortSignal | undefined | 'unset' = 'unset' + ctx.on('tools/post-execute', async (exec, _result, next): Promise => { postSignal = exec.signal; return next() }) + const upstream = new AbortController().signal + await ctx.tools.execute({ callId: CallId('c1'), name: 'fast', arguments: {}, signal: upstream }) + expect(postSignal).toBe(upstream) + }) + + it('deletes exec.signal again when the caller passed none', async () => { + const ctx = await setup() + ctx.tools.register(defineTool({ name: 'fast', description: 'd', parameters: {}, timeoutMs: 10_000, + async execute() { return [{ type: 'text' as const, text: 'ok' }] } })) + let hadSignal: boolean | undefined + ctx.on('tools/post-execute', async (exec, _result, next): Promise => { hadSignal = 'signal' in exec && exec.signal !== undefined; return next() }) + await ctx.tools.execute({ callId: CallId('c1'), name: 'fast', arguments: {} }) + expect(hadSignal).toBe(false) + }) +}) + +describe('timeout-policy TOOL_TIMEOUT replacement (deadline wins)', () => { + beforeEach(() => { vi.useFakeTimers() }) + afterEach(() => { vi.useRealTimers() }) + + it('replaces a cooperative tool result with TOOL_TIMEOUT when its own deadline fires', async () => { + const ctx = await setup() + ctx.tools.register(cooperativeTool) + const pending = ctx.tools.execute({ callId: CallId('c1'), name: 'slow', arguments: {} }) + await vi.advanceTimersByTimeAsync(150) + const result = await pending + expect(result).toEqual({ + callId: CallId('c1'), + content: [{ type: 'text', text: 'Error: tool call timed out after 100ms' }], + isError: true, + error: { name: 'ToolTimeoutError', code: 'TOOL_TIMEOUT' }, + }) + }) + + it('replaces a provider-owned abort ERROR result with TOOL_TIMEOUT when the signal was ours', async () => { + const ctx = await setup() + ctx.tools.register(abortThrowingTool) + const pending = ctx.tools.execute({ callId: CallId('c1'), name: 'aborter', arguments: {} }) + await vi.advanceTimersByTimeAsync(150) + const result = await pending + expect(result.isError).toBe(true) + expect(result.error).toEqual({ name: 'ToolTimeoutError', code: 'TOOL_TIMEOUT' }) + expect(result.content[0]).toMatchObject({ text: 'Error: tool call timed out after 100ms' }) + }) + + it('does NOT replace when the caller aborts first (upstream cancel, not our timeout)', async () => { + const ctx = await setup() + ctx.tools.register(cooperativeTool) + const upstream = new AbortController() + const pending = ctx.tools.execute({ callId: CallId('c1'), name: 'slow', arguments: {}, signal: upstream.signal }) + upstream.abort('user cancelled') + await vi.advanceTimersByTimeAsync(0) + const result = await pending + expect(result.isError).toBe(false) + expect(result.content[0]).toMatchObject({ text: 'stopped cooperatively' }) + }) +}) + +describe('toolTimeoutResult', () => { + it('builds the structured TOOL_TIMEOUT result', () => { + expect(toolTimeoutResult(CallId('c9'), 250)).toEqual({ + callId: CallId('c9'), + content: [{ type: 'text', text: 'Error: tool call timed out after 250ms' }], + isError: true, + error: { name: 'ToolTimeoutError', code: 'TOOL_TIMEOUT' }, + } satisfies ToolExecutionResult) + }) + + it('exposes the owned code constant', () => { + expect(TOOL_TIMEOUT).toBe('TOOL_TIMEOUT') + }) +}) + +describe('timeout-policy disposal (HMR safety)', () => { + it('removes its tools/execute listener when the plugin fiber disposes', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + let seenSignal: AbortSignal | undefined + ctx.tools.register(defineTool({ name: 'probe', description: 'd', parameters: {}, timeoutMs: 10_000, + async execute(_a, exec) { seenSignal = exec.signal; return [{ type: 'text' as const, text: 'ok' }] } })) + const fiber = await ctx.plugin(timeoutPolicy) + const upstream = new AbortController().signal + await ctx.tools.execute({ callId: CallId('c1'), name: 'probe', arguments: {}, signal: upstream }) + expect(seenSignal).not.toBe(upstream) + await fiber.dispose() + await ctx.tools.execute({ callId: CallId('c2'), name: 'probe', arguments: {}, signal: upstream }) + expect(seenSignal).toBe(upstream) + }) +}) + +describe('dsh-timeout-policy real-load-path guard', () => { + it('has no default export and keeps name/inject through unwrapExports', () => { + expect('default' in timeoutPolicy).toBe(false) + const loader = Object.create(Loader.prototype) as Loader + const unwrapped = loader.unwrapExports(timeoutPolicy) as Record + expect(unwrapped).toBe(timeoutPolicy) + expect(unwrapped.name).toBe('timeout-policy') + expect(unwrapped.inject).toEqual(['tools']) + expect(typeof unwrapped.apply).toBe('function') + }) + + it('boots over ctx.tools through the unwrapped module and wraps a budgeted tool', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + ctx.tools.register(defineTool({ name: 'fast', description: 'd', parameters: {}, timeoutMs: 5_000, + async execute() { return [{ type: 'text' as const, text: 'ok' }] } })) + const loader = Object.create(Loader.prototype) as Loader + const unwrapped = loader.unwrapExports(timeoutPolicy) as Parameters[0] + const fiber = await ctx.plugin(unwrapped) + const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'fast', arguments: {} } satisfies ToolExecution) + expect(result.isError).toBe(false) + await fiber.dispose() + }) +}) diff --git a/packages/timeout/timeout-policy/tsconfig.json b/packages/timeout/timeout-policy/tsconfig.json new file mode 100644 index 0000000000..8c0b47716e --- /dev/null +++ b/packages/timeout/timeout-policy/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cosmokit" }, + { "path": "../../../vendor/cordis" }, + { "path": "../../../vendor/schemastery" }, + { "path": "../../llm/llm" }, + { "path": "../../util/timeout" }, + { "path": "../../core/tools" } + ] +} diff --git a/packages/ui/README.md b/packages/ui/README.md index 8b0293cf9e..e87a5e4a10 100644 --- a/packages/ui/README.md +++ b/packages/ui/README.md @@ -5,10 +5,14 @@ Integrations that expose the agent to an external editor or client. These are ** | Package | Role | ctx key | |---|---|---| | `acp/` | Agent Client Protocol bridge: serves the agent to an ACP editor (Zed) over JSON-RPC stdio | (drives `ctx.agents`/`ctx.sessions`) | +| `user-interaction/` | Abstract human question/answer seam used by UI-backed confirmation tools | `ctx.userInteraction` | +| `tool-ask-user/` | Model-facing `ask_user_question` tool over `ctx.userInteraction` | (registers on `ctx.tools`) | | `stdio-agent/` | Terminal stdio chat APP: the agent-core spine + console logger + readline UI + a pre-created `main` agent, with a `bin` | (composition + `bin`) | | `acp-agent/` | ACP server APP: the agent-core spine + JSONL persistence + the `acp` bridge (no stdout logger), with a `bin` | (composition + `bin`) | | `app-boot/` | Shared boot glue for the two app bins: `.env` loading, fail-loud Loader guards, snapshot-aware config resolution, the settle-the-tree boot sequence | (library for the bins) | A UI integration is a client-driver plugin, not a loop change and not a capability seam: it consumes the existing `agent/*` event taxonomy and the `dsh-agent` factory. The readline UI is the unstructured analogue of the `acp` bridge and lives INSIDE the stdio app (the `stdio-chat` module of [`stdio-agent/`](stdio-agent/README.md)): it is scaffolding for that one front door, not an independently swappable integration, so it carries no package boundary of its own. +`user-interaction` and `tool-ask-user` live here because asking a human is a UI-backed product affordance, not part of the providerless core spine. The seam remains provider-neutral (`ctx.userInteraction`), while the tool is the model-facing consumer and the app/bridge packages provide concrete providers. + `stdio-agent` and `acp-agent` are the two **app packages**: each composes the [`core/agent-core`](../core/agent-core/README.md) spine with its coupled front-door cluster (and owns the boot `bin`), so a leaf `cordis.yml` is the swappable backends plus one app entry plus any optional product tools. They live in `ui/` because each IS a user-facing front door; the stdout-purity coupling (logger vs. no logger) becomes a property of the artifact rather than a leaf convention. diff --git a/packages/ui/acp-agent/README.md b/packages/ui/acp-agent/README.md index 36e794f92c..ee3a995eaa 100644 --- a/packages/ui/acp-agent/README.md +++ b/packages/ui/acp-agent/README.md @@ -11,8 +11,10 @@ stdout is the ACP JSON-RPC channel, so the cluster is defined as much by what it | Plugin | Why | |---|---| | `@deepseek-ai/dsh-agent-core` | the spine, pre-creating **no** agents (ACP `session/new` creates them on demand) | +| `@deepseek-ai/dsh-user-interaction` | the human question/answer seam used by clients that can complete ACP elicitation requests | | `@deepseek-ai/dsh-session-persistence-jsonl` | durable JSONL session log (the bridge advertises `loadSession`) | -| `@deepseek-ai/dsh-acp` | the bridge that owns stdout for JSON-RPC | +| `@deepseek-ai/dsh-acp` | the bridge that owns stdout for JSON-RPC and provides ACP-backed user answers when a leaf explicitly exposes a user-question tool | +| ~~`@deepseek-ai/dsh-tool-ask-user`~~ | **omitted by default** — ACP elicitation support is still client-dependent, so leaves must opt in deliberately | | ~~console logger~~ | **omitted** — it writes to stdout and would corrupt the protocol frames ([the stdout-purity footgun](../acp/README.md)) | | ~~`hmr`~~ | **omitted** — the editor owns the subprocess | diff --git a/packages/ui/acp-agent/package.json b/packages/ui/acp-agent/package.json index e8b4f3723b..51eb0ea3b1 100644 --- a/packages/ui/acp-agent/package.json +++ b/packages/ui/acp-agent/package.json @@ -36,6 +36,7 @@ "@deepseek-ai/dsh-acp": "^0.0.1", "@deepseek-ai/dsh-agent-core": "^0.0.1", "@deepseek-ai/dsh-session-persistence-jsonl": "^0.0.1", + "@deepseek-ai/dsh-user-interaction": "^0.0.1", "cordis": "^4.0.0-rc.6", "schemastery": "^3.17.0" }, @@ -47,6 +48,7 @@ "@deepseek-ai/dsh-agent-core": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-user-interaction": "workspace:^", "cordis": "^4.0.0-rc.6", "schemastery": "^3.17.0" } diff --git a/packages/ui/acp-agent/src/index.ts b/packages/ui/acp-agent/src/index.ts index 898ec9a509..18490ac668 100644 --- a/packages/ui/acp-agent/src/index.ts +++ b/packages/ui/acp-agent/src/index.ts @@ -35,6 +35,7 @@ import z from 'schemastery' import * as acp from '@deepseek-ai/dsh-acp' import * as agentCore from '@deepseek-ai/dsh-agent-core' import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' export const name = 'acp-agent' @@ -79,6 +80,7 @@ export function apply(ctx: Context, config: Config): void { ...config.persona !== undefined ? { persona: config.persona } : {}, ...config.toolOrder !== undefined ? { toolOrder: config.toolOrder } : {}, }) + ctx.plugin(UserInteractionService) ctx.plugin(SessionPersistenceJsonl, { root: config.persistenceRoot ?? './.sessions' }) ctx.plugin(acp, { model: config.model }) } diff --git a/packages/ui/acp-agent/tests/acp-agent.spec.ts b/packages/ui/acp-agent/tests/acp-agent.spec.ts index 7e1de1226f..6e2f202859 100644 --- a/packages/ui/acp-agent/tests/acp-agent.spec.ts +++ b/packages/ui/acp-agent/tests/acp-agent.spec.ts @@ -30,6 +30,8 @@ describe('dsh-acp-agent composition', () => { expect(ctx.get('sessions')).toBeDefined() expect(ctx.get('sessionPersistence')).toBeDefined() expect(ctx.get('agentLoop')).toBeDefined() + expect(ctx.get('userInteraction')).toBeDefined() + expect(ctx.get('tools')?.get('ask_user_question')).toBeUndefined() // No pre-created agents — ACP session/new creates them on demand. expect(ctx.get('agents')!.list()).toHaveLength(0) await ctx.fiber.dispose() diff --git a/packages/ui/acp-agent/tsconfig.json b/packages/ui/acp-agent/tsconfig.json index 6cc211087c..13009a2e5c 100644 --- a/packages/ui/acp-agent/tsconfig.json +++ b/packages/ui/acp-agent/tsconfig.json @@ -26,6 +26,12 @@ { "path": "../../core/agent-core" }, + { + "path": "../user-interaction" + }, + { + "path": "../tool-ask-user" + }, { "path": "../../session-persistence/session-persistence-jsonl" } diff --git a/packages/ui/acp/README.md b/packages/ui/acp/README.md index 60363566b7..49abfbff6a 100644 --- a/packages/ui/acp/README.md +++ b/packages/ui/acp/README.md @@ -8,7 +8,7 @@ It is a **client-driver / UI plugin**, the structured analogue of the readline ` `apply(ctx, config)` — wires an `AgentSideConnection` (from `@agentclientprotocol/sdk`) to `process.stdin`/`process.stdout` and implements the ACP `Agent` method surface. -`inject: ['agents', 'sessions', 'sessionPersistence', 'tools']` — programs against the interface packages only (never `dsh-agent-loop`). `sessionPersistence` is required because `initialize` advertises `loadSession: true`; `tools` lets a tool own how its calls render (`presentCall`/`presentResult`) — the bridge looks the definition up by name and falls back to a generic presentation when a tool declares none (see Tool-call presentation). +`inject: ['agents', 'sessions', 'sessionPersistence', 'tools', 'userInteraction']` — programs against the interface packages only (never `dsh-agent-loop`). `sessionPersistence` is required because `initialize` advertises `loadSession: true`; `tools` lets a tool own how its calls render (`presentCall`/`presentResult`) — the bridge looks the definition up by name and falls back to a generic presentation when a tool declares none (see Tool-call presentation). `userInteraction` lets agent-owned `ask_user_question` calls become ACP form elicitations routed to the owning session. ### Config @@ -30,6 +30,7 @@ The `initialize` handshake reports a fixed server identity (`agentInfo: { name: | `session/prompt` | `agent.send()` | supports ACP `text` and `resource_link` blocks; rejects image/audio/embedded resource and empty prompts; one in-flight prompt PER session (independent); settles on the OWNING turn's end (a turn that ends in `error` rejects the RPC) | | `session/cancel` | `agent.cancel()` | the queue-aware cancel: aborts a running step, clears queued + steering work, and drops a turn about to start, then settles the prompt `cancelled` — for ONLY that session (a cancel never touches another session's stream or prompt) | | `session/update` | `session/event` | `agent_message_chunk` (text-delta), `agent_thought_chunk` (reasoning-delta), `user_message_chunk` (load replay), `tool_call`/`tool_call_update` (the render intent — a `card`-tagged `ToolCallView`/`ToolResultView` — owned by the TOOL via `presentCall`/`presentResult`, which the bridge switches on to build the wire shape — see Tool-call presentation) | +| `elicitation/create` | `ctx.userInteraction.ask()` | maps `ask_user_question` questions to ACP form elicitations; option descriptions are shown in enum titles, `multi_select` uses ACP array enums, optionless requests use a required `custom` field, and a non-empty custom answer overrides any selected choice | ## Multi-session diff --git a/packages/ui/acp/acp-feature-support.md b/packages/ui/acp/acp-feature-support.md index d37c9b1eaf..6162fae137 100644 --- a/packages/ui/acp/acp-feature-support.md +++ b/packages/ui/acp/acp-feature-support.md @@ -47,7 +47,7 @@ These are capabilities the bridge would *drive* on the editor. The harness runs | `terminal/wait_for_exit` | S | ❌ | ❌ | ❌ | As above. | | `terminal/kill` | S | ❌ | ❌ | ❌ | As above. | | `terminal/release` | S | ❌ | ❌ | ❌ | As above. | -| `elicitation/create` · `elicitation/complete` | U | ❌ | ✅ | ⚠️ | Structured user-input forms. Claude calls the `unstable_*` elicitation methods (to surface MCP server elicitations); Codex does NOT — its `CodexElicitationHandler` maps elicitations onto `session/request_permission` instead. | +| `elicitation/create` · `elicitation/complete` | U | ⚠️ | ✅ | ⚠️ | The bridge drives `unstable_createElicitation` for `ask_user_question` form prompts (session-scoped, no URL-mode flow yet). Claude calls the `unstable_*` elicitation methods for MCP server elicitations; Codex maps elicitations onto `session/request_permission`. | ## 3. Capabilities @@ -140,7 +140,7 @@ The bridge rejects unsupported prompt blocks rather than silently dropping them Ranked by how commonly the reference adapters ship them and how much UX they unlock: -1. **Permission gate** — `session/request_permission` + permission options. Tracked `TODO(rfc010-permission-gate)`; the reverse map is already wired. Foundational, and a prerequisite for modes. +1. **Permission gate** — `session/request_permission` + permission options. Tracked `TODO(rfc010-permission-gate)`; the reverse map is already wired and shared with `ask_user_question` routing. Foundational, and a prerequisite for modes. 2. **Session lifecycle** — `session/list` + `session/delete` (the persistence layer already lists), then `session/resume` / `session/close`. 3. **Modes / config options / model selection** — coupled to the permission gate. 4. **Agent plan** (`sessionUpdate: 'plan'`) — surface the loop's plan as structured entries. diff --git a/packages/ui/acp/package.json b/packages/ui/acp/package.json index cdc952558c..4ebc8485ce 100644 --- a/packages/ui/acp/package.json +++ b/packages/ui/acp/package.json @@ -32,6 +32,7 @@ "@deepseek-ai/dsh-session": "^0.0.1", "@deepseek-ai/dsh-session-persistence": "^0.0.1", "@deepseek-ai/dsh-tools": "^0.0.1", + "@deepseek-ai/dsh-user-interaction": "^0.0.1", "cordis": "^4.0.0-rc.6" }, "devDependencies": { @@ -49,6 +50,8 @@ "@deepseek-ai/dsh-tool-fs": "workspace:^", "@deepseek-ai/dsh-tool-todo": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", + "@deepseek-ai/dsh-tool-ask-user": "workspace:^", + "@deepseek-ai/dsh-user-interaction": "workspace:^", "cordis": "^4.0.0-rc.6" } } diff --git a/packages/ui/acp/src/index.ts b/packages/ui/acp/src/index.ts index e11133aa36..b5e03d772d 100644 --- a/packages/ui/acp/src/index.ts +++ b/packages/ui/acp/src/index.ts @@ -47,6 +47,9 @@ import { type AuthenticateRequest, type CancelNotification, type ContentBlock as AcpContentBlock, + type CreateElicitationRequest, + type ElicitationContentValue, + type EnumOption, type InitializeRequest, type InitializeResponse, type LoadSessionRequest, @@ -71,6 +74,14 @@ import type { ToolCallView, ToolRegistry, ToolResultView, TerminalResultView } f // Side-effect type import: declaration-merges `ctx.sessionPersistence` onto // Context (the bridge injects it and reads `list()` for load cwd validation). import type {} from '@deepseek-ai/dsh-session-persistence' +import { + UserInteractionError, + type AskUserQuestionAnswer, + type AskUserQuestionAnswerItem, + type AskUserQuestionItem, + type AskUserQuestionOption, + type AskUserQuestionRequest, +} from '@deepseek-ai/dsh-user-interaction' import { acpPromptToText, harnessBlockToAcpContent, @@ -84,7 +95,7 @@ export const name = 'acp' // because `initialize` advertises `loadSession: true`. `tools` lets a tool own // how its calls render (`presentCall`/`presentResult`); the bridge looks up the // definition by name and falls back to a generic presentation when absent. -export const inject = ['agents', 'sessions', 'sessionPersistence', 'tools'] +export const inject = ['agents', 'sessions', 'sessionPersistence', 'tools', 'userInteraction'] /** * Build an ACP "invalid params" error whose human detail rides in the message. @@ -111,6 +122,116 @@ function sameWorkspaceCwd(left: string, right: string): boolean { return resolvePath(left) === resolvePath(right) } +function optionDescription(option: AskUserQuestionOption): string { + return option.description === undefined + ? option.label + : `${option.label}: ${option.description}` +} + +function requireStringContent( + content: Record | null | undefined, + key: string, +): string | undefined { + const value = content?.[key] + return typeof value === 'string' && value.trim().length > 0 ? value : undefined +} + +function askAbortError(): UserInteractionError { + return new UserInteractionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED') +} + +function withAbort(promise: Promise, signal: AbortSignal | undefined): Promise { + if (signal === undefined) return promise + if (signal.aborted) return Promise.reject(askAbortError()) + return new Promise((resolve, reject) => { + const onAbort = (): void => { + signal.removeEventListener('abort', onAbort) + reject(askAbortError()) + } + signal.addEventListener('abort', onAbort, { once: true }) + promise.then( + (value) => { + signal.removeEventListener('abort', onAbort) + resolve(value) + }, + (error: unknown) => { + signal.removeEventListener('abort', onAbort) + reject(new Error(String(error), { cause: error })) + }, + ) + }) +} + +function elicitationForQuestion( + sessionId: SessionId, + question: AskUserQuestionItem, + options: AskUserQuestionOption[], +): CreateElicitationRequest { + const title = question.header ?? 'Question' + if (options.length === 0) { + return { + sessionId, + mode: 'form', + message: question.question, + requestedSchema: { + type: 'object', + title, + properties: { + custom: { type: 'string', title: question.question }, + }, + required: ['custom'], + }, + } + } + + const choiceOptions: EnumOption[] = options.map(option => ({ + const: option.label, + title: optionDescription(option), + })) + const choice = question.multiSelect === true + ? { + type: 'array' as const, + title: question.question, + description: 'Choose one or more options, or fill a custom answer below.', + items: { + anyOf: choiceOptions, + }, + } + : { + type: 'string' as const, + title: question.question, + description: 'Choose one option, or fill a custom answer below.', + oneOf: choiceOptions, + } + return { + sessionId, + mode: 'form', + message: question.question, + requestedSchema: { + type: 'object', + title, + properties: { + choice, + custom: { + type: 'string', + title: 'Custom answer', + description: 'Optional free-form answer. Leave empty to use the selected option.', + }, + }, + required: [], + }, + } +} + +function stringArrayContent( + content: Record | null | undefined, + key: string, +): string[] { + const value = content?.[key] + if (Array.isArray(value)) return value.filter((item): item is string => typeof item === 'string' && item.length > 0) + return typeof value === 'string' && value.length > 0 ? [value] : [] +} + /** Plugin config: the agent template ACP sessions are created from. */ export interface AcpConfig { /** Model name for created agents (must have a registered adapter). */ @@ -211,6 +332,7 @@ export function apply(ctx: Context, config: AcpConfig): void { const sessionPersistence = ctx.sessionPersistence const logger = ctx.logger const tools = ctx.tools + const userInteraction = ctx.userInteraction // A new ToolPresenter per session (and a throwaway per load replay), each given // this warn sink so a throwing tool presenter is logged, not propagated. const makePresenter = (agent?: Agent): ToolPresenter => new ToolPresenter(tools, (message) => { logger.warn(message) }, agent) @@ -241,6 +363,42 @@ export function apply(ctx: Context, config: AcpConfig): void { // `notify` never observes it unset — no undefined guard needed. let conn: AgentSideConnection + userInteraction.registerProvider({ + async ask(request: AskUserQuestionRequest): Promise { + if (request.agent === undefined) { + throw new UserInteractionError('ACP user questions must come from an agent-owned request', 'NO_AGENT') + } + const sessionId = bySession.get(request.agent) + if (sessionId === undefined) { + throw new UserInteractionError('ACP user question has no matching session', 'NO_SESSION') + } + const answers: AskUserQuestionAnswerItem[] = [] + for (const question of request.questions) { + const options = question.options ?? [] + const response = await withAbort(conn.unstable_createElicitation( + elicitationForQuestion(sessionId, question, options), + ), request.signal).catch((error: unknown) => { + if (error instanceof UserInteractionError) throw error + throw new UserInteractionError('ACP elicitation request failed', 'ASK_FAILED', { cause: error }) + }) + if (response.action !== 'accept') { + throw new UserInteractionError('ask_user_question was cancelled by the user', 'ASK_CANCELLED') + } + const custom = requireStringContent(response.content, 'custom') + const selected = stringArrayContent(response.content, 'choice') + if (custom === undefined && selected.length === 0) { + throw new UserInteractionError('ask_user_question returned no answer', 'NO_ANSWER') + } + answers.push({ + id: question.id, + selected: custom === undefined ? selected : [], + ...custom !== undefined ? { custom } : {}, + }) + } + return { answers } + }, + }) + /** * Reject any RPC after the bridge has torn down. The `AgentSideConnection` * receive loop can outlive the plugin fiber — under an ACP-only HMR reload the diff --git a/packages/ui/acp/tests/bridge.spec.ts b/packages/ui/acp/tests/bridge.spec.ts index 1e7e9ae511..be05a09644 100644 --- a/packages/ui/acp/tests/bridge.spec.ts +++ b/packages/ui/acp/tests/bridge.spec.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' import { AgentId } from '@deepseek-ai/dsh-agent' -import { makeBridgeHarness, textResponse, type BridgeHarness } from './harness.ts' +import { makeBridgeHarness, textResponse, toolCallResponse, type BridgeHarness } from './harness.ts' /** * End-to-end bridge specs over an in-memory transport: a real @@ -53,6 +53,209 @@ describe('acp bridge', () => { expect(text).toBe('hello there') }) + it('routes ask_user_question through ACP form elicitation and continues with the selected option', async () => { + harness = await makeBridgeHarness({ + storageDir, + withAskUser: true, + script: [ + toolCallResponse('ask-1', 'ask_user_question', { + questions: [{ + id: 'language', + header: 'Project config', + question: 'Which language should I use?', + options: [ + { label: 'TypeScript', description: 'Good for UI apps' }, + { label: 'Python', description: 'Good for scripts' }, + ], + }], + }), + textResponse('Python it is.'), + ], + }) + harness.onElicitation = () => ({ action: 'accept', content: { choice: 'Python' } }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + + const result = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'ask me' }] }) + + expect(result.stopReason).toBe('end_turn') + expect(harness.elicitationRequests).toHaveLength(1) + expect(harness.elicitationRequests[0]).toMatchObject({ + sessionId, + mode: 'form', + message: 'Which language should I use?', + requestedSchema: { + title: 'Project config', + properties: { + choice: { + oneOf: [ + { const: 'TypeScript', title: 'TypeScript: Good for UI apps' }, + { const: 'Python', title: 'Python: Good for scripts' }, + ], + }, + custom: { type: 'string' }, + }, + required: [], + }, + }) + const toolResult = harness.ctx.agents.get(AgentId(sessionId))!.session.events.find(event => event.type === 'tool/result') + const toolResultBlock = toolResult?.type === 'tool/result' ? toolResult.data.content[0] : undefined + const toolResultText = toolResultBlock?.type === 'text' ? toolResultBlock.text : undefined + expect(toolResultText).toBe('{"answers":[{"id":"language","selected":["Python"]}]}') + }) + + it('routes optionless ask_user_question through an ACP free-form answer field', async () => { + harness = await makeBridgeHarness({ + storageDir, + withAskUser: true, + script: [ + toolCallResponse('ask-1', 'ask_user_question', { + questions: [{ id: 'name', question: 'What should I name it?' }], + }), + textResponse('Name recorded.'), + ], + }) + harness.onElicitation = () => ({ action: 'accept', content: { custom: 'apollo' } }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + + await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'ask me' }] }) + + expect(harness.elicitationRequests[0]).toMatchObject({ + requestedSchema: { + properties: { custom: { type: 'string', title: 'What should I name it?' } }, + required: ['custom'], + }, + }) + const toolResult = harness.ctx.agents.get(AgentId(sessionId))!.session.events.find(event => event.type === 'tool/result') + expect(JSON.stringify(toolResult)).toContain('apollo') + }) + + it('supports ACP custom answers alongside choices', async () => { + harness = await makeBridgeHarness({ storageDir, withAskUser: true }) + harness.onElicitation = () => ({ action: 'accept', content: { custom: 'Use Zig' } }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(AgentId(sessionId))! + + const result = await harness.ctx.userInteraction.ask({ + agent, + questions: [{ + id: 'language', + question: 'Which language?', + options: [{ label: 'TypeScript' }], + }], + }) + + expect(result).toEqual({ answers: [{ id: 'language', selected: [], custom: 'Use Zig' }] }) + expect(harness.elicitationRequests[0]).toMatchObject({ + requestedSchema: { + properties: { + choice: { + description: 'Choose one option, or fill a custom answer below.', + oneOf: [{ const: 'TypeScript', title: 'TypeScript' }], + }, + custom: { type: 'string' }, + }, + required: [], + }, + }) + }) + + it('treats ACP custom answers as overriding selected choices', async () => { + harness = await makeBridgeHarness({ storageDir, withAskUser: true }) + harness.onElicitation = () => ({ action: 'accept', content: { choice: 'TypeScript', custom: 'Use Zig' } }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(AgentId(sessionId))! + + await expect(harness.ctx.userInteraction.ask({ + agent, + questions: [{ + id: 'language', + question: 'Which language?', + options: [{ label: 'TypeScript' }], + }], + })).resolves.toEqual({ answers: [{ id: 'language', selected: [], custom: 'Use Zig' }] }) + }) + + it('supports ACP multi-select answers', async () => { + harness = await makeBridgeHarness({ storageDir, withAskUser: true }) + harness.onElicitation = () => ({ action: 'accept', content: { choice: ['Tests', 'Docs'] } }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(AgentId(sessionId))! + + await expect(harness.ctx.userInteraction.ask({ + agent, + questions: [{ + id: 'targets', + question: 'Pick', + options: [{ label: 'Tests' }, { label: 'Docs' }], + multiSelect: true, + }], + })).resolves.toEqual({ answers: [{ id: 'targets', selected: ['Tests', 'Docs'] }] }) + }) + + it('reports ACP ask-user routing and answer failures as structured errors', async () => { + harness = await makeBridgeHarness({ storageDir, withAskUser: true }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(AgentId(sessionId))! + + await expect(harness.ctx.userInteraction.ask({ questions: [{ id: 'x', question: 'No agent?' }] })) + .rejects.toMatchObject({ name: 'UserInteractionError', code: 'NO_AGENT' }) + await expect(harness.ctx.userInteraction.ask({ agent: { id: 'other' } as typeof agent, questions: [{ id: 'x', question: 'No session?' }] })) + .rejects.toMatchObject({ code: 'NO_SESSION' }) + + harness.onElicitation = () => ({ action: 'cancel' }) + await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Cancel?' }] })) + .rejects.toMatchObject({ code: 'ASK_CANCELLED' }) + + harness.onElicitation = () => ({ action: 'accept', content: {} }) + await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Empty?' }] })) + .rejects.toMatchObject({ code: 'NO_ANSWER' }) + + harness.onElicitation = () => { throw new Error('client boom') } + await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Client fails?' }], signal: new AbortController().signal })) + .rejects.toMatchObject({ code: 'ASK_FAILED' }) + }) + + it('aborts ACP ask-user requests before and while waiting for elicitation', async () => { + harness = await makeBridgeHarness({ storageDir, withAskUser: true }) + await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) + const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }) + const agent = harness.ctx.agents.get(AgentId(sessionId))! + + const alreadyAborted = new AbortController() + alreadyAborted.abort() + await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Already?' }], signal: alreadyAborted.signal })) + .rejects.toMatchObject({ code: 'ASK_ABORTED' }) + + let abortedReads = 0 + const racingAbort = { + get aborted() { return abortedReads++ > 0 }, + addEventListener() {}, + removeEventListener() {}, + dispatchEvent() { return false }, + onabort: null, + reason: undefined, + throwIfAborted() {}, + } as AbortSignal + await expect(harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Raced?' }], signal: racingAbort })) + .rejects.toMatchObject({ code: 'ASK_ABORTED' }) + + let release: ((value: { action: 'accept'; content: { custom: string } }) => void) | undefined + harness.onElicitation = () => new Promise((resolve) => { release = resolve }) + const pendingAbort = new AbortController() + const ask = harness.ctx.userInteraction.ask({ agent, questions: [{ id: 'x', question: 'Pending?' }], signal: pendingAbort.signal }) + await new Promise(resolve => setImmediate(resolve)) + pendingAbort.abort() + + await expect(ask).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + release?.({ action: 'accept', content: { custom: 'too late' } }) + }) + it('allows multiple concurrent sessions, each with a distinct id', async () => { harness = await makeBridgeHarness({ storageDir, script: [] }) await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} }) diff --git a/packages/ui/acp/tests/harness.ts b/packages/ui/acp/tests/harness.ts index 39d77fe624..a24c7aa145 100644 --- a/packages/ui/acp/tests/harness.ts +++ b/packages/ui/acp/tests/harness.ts @@ -29,11 +29,15 @@ import { ndJsonStream, type Agent as AcpAgent, type Client, + type CreateElicitationRequest, + type CreateElicitationResponse, type RequestPermissionRequest, type RequestPermissionResponse, type SessionNotification, type Stream, } from '@agentclientprotocol/sdk' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' +import * as ToolAskUser from '@deepseek-ai/dsh-tool-ask-user' import * as AcpPlugin from '../src/index.ts' import { type AcpConfig } from '../src/index.ts' @@ -121,6 +125,10 @@ export interface BridgeHarness { permissionRequests: RequestPermissionRequest[] /** Decide each permission request's outcome (default: cancelled). */ onPermission: (req: RequestPermissionRequest) => RequestPermissionResponse + /** Elicitation requests the bridge issued for ask_user_question. */ + elicitationRequests: CreateElicitationRequest[] + /** Decide each elicitation response (default: cancel). */ + onElicitation: (req: CreateElicitationRequest) => CreateElicitationResponse | Promise /** If set, the client's sessionUpdate throws this (tests notify error path). */ onSessionUpdateError: (() => void) | undefined /** @@ -164,6 +172,8 @@ export async function makeBridgeHarness(options: { * implementation over a mock in tests"). */ withBash?: boolean + /** Plug the REAL `ask_user_question` tool and ACP user-interaction provider. */ + withAskUser?: boolean /** * Plug the REAL `dsh-tool-todo` tool so a test can drive `todo_write` through * the bridge and assert the resulting `plan` sessionUpdate — the shipping @@ -190,6 +200,10 @@ export async function makeBridgeHarness(options: { await ctx.plugin(AgentRegistry) await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(SessionPersistenceJsonl, { root: options.storageDir }) + await ctx.plugin(UserInteractionService) + if (options.withAskUser) { + await ctx.plugin(ToolAskUser) + } if (options.withBash) { await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 }) await ctx.plugin(ToolBash) @@ -226,6 +240,7 @@ export async function makeBridgeHarness(options: { const updates: CapturedUpdate[] = [] const sessionUpdates: { sessionId: string; update: CapturedUpdate }[] = [] const permissionRequests: RequestPermissionRequest[] = [] + const elicitationRequests: CreateElicitationRequest[] = [] const harness: BridgeHarness = { ctx, adapter, @@ -233,6 +248,8 @@ export async function makeBridgeHarness(options: { sessionUpdates, permissionRequests, onPermission: () => ({ outcome: { outcome: 'cancelled' } }), + elicitationRequests, + onElicitation: () => ({ action: 'cancel' }), onSessionUpdateError: undefined, client: undefined as unknown as ClientSideConnection, acpFiber: undefined as unknown as BridgeHarness['acpFiber'], @@ -258,6 +275,10 @@ export async function makeBridgeHarness(options: { permissionRequests.push(params) return Promise.resolve(harness.onPermission(params)) }, + unstable_createElicitation(params: CreateElicitationRequest): Promise { + elicitationRequests.push(params) + return Promise.resolve(harness.onElicitation(params)) + }, }) // Wire the bridge (agent side) and the client (test side). The test config diff --git a/packages/ui/acp/tsconfig.json b/packages/ui/acp/tsconfig.json index 5989363d7f..9c2358c455 100644 --- a/packages/ui/acp/tsconfig.json +++ b/packages/ui/acp/tsconfig.json @@ -29,6 +29,9 @@ { "path": "../../core/tools" }, + { + "path": "../user-interaction" + }, { "path": "../../session-persistence/session-persistence" } diff --git a/packages/ui/stdio-agent/README.md b/packages/ui/stdio-agent/README.md index 5fb0bbe78c..a299e2a94a 100644 --- a/packages/ui/stdio-agent/README.md +++ b/packages/ui/stdio-agent/README.md @@ -13,6 +13,8 @@ A terminal chat always wants the same cluster, so the package owns it rather tha | `@cordisjs/plugin-logger-console` | the console logger — stdout is just the terminal here, so logging to it is correct (the ACP app must NOT have this) | | `@deepseek-ai/dsh-agent-core` | the spine, pre-creating a `main` agent from this app's `model` and carrying its `persona` | | `@deepseek-ai/dsh-session-persistence-jsonl` | durable JSONL session log under `persistenceRoot` | +| `@deepseek-ai/dsh-user-interaction` | the human question/answer seam used by confirmation tools | +| `@deepseek-ai/dsh-tool-ask-user` | the model-facing `ask_user_question` tool | | `stdio-chat` (in-package module) | the readline UI, bound to the `main` agent | `@cordisjs/plugin-hmr` (the dev/demo edit-reload loop) is deliberately a **leaf** entry, NOT baked in here: it is a Loader-only, subprocess-only dev plugin — its constructor throws without `node --expose-internals` + a live `loader`, and the in-process test tier cannot even import it (so a package whose `apply` statically pulled it in could never carry the per-file coverage gate). Unlike the console logger, a stray `hmr` is not a stdout-purity footgun, so leaving it at the leaf costs no safety. The `demo:echo` / `demo:repl` leaves load it and pass `--expose-internals`. diff --git a/packages/ui/stdio-agent/package.json b/packages/ui/stdio-agent/package.json index b8cf84cac4..39630862d8 100644 --- a/packages/ui/stdio-agent/package.json +++ b/packages/ui/stdio-agent/package.json @@ -39,6 +39,8 @@ "@deepseek-ai/dsh-agent-core": "^0.0.1", "@deepseek-ai/dsh-session": "^0.0.1", "@deepseek-ai/dsh-session-persistence-jsonl": "^0.0.1", + "@deepseek-ai/dsh-tool-ask-user": "^0.0.1", + "@deepseek-ai/dsh-user-interaction": "^0.0.1", "cordis": "^4.0.0-rc.6", "schemastery": "^3.17.0" }, @@ -53,6 +55,8 @@ "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-tool-ask-user": "workspace:^", + "@deepseek-ai/dsh-user-interaction": "workspace:^", "cordis": "^4.0.0-rc.6", "schemastery": "^3.17.0" } diff --git a/packages/ui/stdio-agent/src/index.ts b/packages/ui/stdio-agent/src/index.ts index 7d36db373e..58408486ea 100644 --- a/packages/ui/stdio-agent/src/index.ts +++ b/packages/ui/stdio-agent/src/index.ts @@ -45,6 +45,8 @@ import { AgentId } from '@deepseek-ai/dsh-agent' import { SessionId } from '@deepseek-ai/dsh-session' import * as agentCore from '@deepseek-ai/dsh-agent-core' import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' +import * as toolAskUser from '@deepseek-ai/dsh-tool-ask-user' import * as uiStdio from './stdio-chat.ts' export const name = 'stdio-agent' @@ -107,5 +109,7 @@ export function apply(ctx: Context, config: Config): void { }], }) ctx.plugin(SessionPersistenceJsonl, { root: config.persistenceRoot ?? './.sessions' }) + ctx.plugin(UserInteractionService) + ctx.plugin(toolAskUser) ctx.plugin(uiStdio, { welcome: config.welcome ?? 'ready.', agent: 'main' }) } diff --git a/packages/ui/stdio-agent/src/stdio-chat.ts b/packages/ui/stdio-agent/src/stdio-chat.ts index 78b0a5ae5b..4c37f40d37 100644 --- a/packages/ui/stdio-agent/src/stdio-chat.ts +++ b/packages/ui/stdio-agent/src/stdio-chat.ts @@ -20,9 +20,17 @@ import type { Readable, Writable } from 'node:stream' import type { Context } from 'cordis' import z from 'schemastery' import { AgentId } from '@deepseek-ai/dsh-agent' +import { + UserInteractionError, + type AskUserQuestionAnswer, + type AskUserQuestionAnswerItem, + type AskUserQuestionItem, + type AskUserQuestionOption, + type AskUserQuestionRequest, +} from '@deepseek-ai/dsh-user-interaction' export const name = 'ui-stdio' -export const inject = ['agents'] +export const inject = ['agents', 'userInteraction'] /** Serializable plugin configuration (cordis-native, schemastery). */ export interface Config { @@ -57,6 +65,20 @@ function isTTYPair(input: Readable, output: Writable): boolean { return Boolean((input as { isTTY?: boolean }).isTTY && (output as { isTTY?: boolean }).isTTY) } +interface PendingQuestion { + request: AskUserQuestionRequest + questionIndex: number + answers: AskUserQuestionAnswerItem[] + resolve(answer: AskUserQuestionAnswer): void + reject(error: unknown): void + onAbort: () => void +} + +type OptionSelection = + | { kind: 'selected'; options: AskUserQuestionOption[] } + | { kind: 'custom' } + | { kind: 'invalid' } + /** * The plugin body, parameterized over its I/O runtime. `apply` is the thin * production wrapper that binds the real `process` streams; tests call this @@ -154,6 +176,8 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt let submittedWork = false let sawRunning = false let exitTimer: ReturnType | undefined + let activeQuestion: PendingQuestion | undefined + const questionQueue: PendingQuestion[] = [] const maybeExit = (): void => { if (disposed || !stdinClosed) return @@ -180,7 +204,152 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt if (status === 'idle') maybeExit() }) + const activeQuestionItem = (pending: PendingQuestion): AskUserQuestionItem => + pending.request.questions[pending.questionIndex] as AskUserQuestionItem + + const renderQuestion = (pending: PendingQuestion): void => { + const question = activeQuestionItem(pending) + const options = question.options ?? [] + output.write('\n') + output.write(question.header ? `[${question.header}] ${question.question}\n` : `${question.question}\n`) + options.forEach((option, index) => { + output.write(` ${index + 1}. ${option.label}\n`) + if (option.description) output.write(` ${option.description}\n`) + }) + output.write('> ') + } + + const removeAbortListener = (pending: PendingQuestion): void => { + pending.request.signal?.removeEventListener('abort', pending.onAbort) + } + + const startNextQuestion = (): void => { + if (activeQuestion !== undefined) return + const pending = questionQueue.shift() + if (pending === undefined) return + // The queue never contains an aborted pending ask: the seam rejects an + // already-aborted request synchronously, and queued asks attach their + // abort listener before enqueueing. + activeQuestion = pending + renderQuestion(pending) + } + + const disposeQuestion = (pending: PendingQuestion): void => { + removeAbortListener(pending) + pending.reject(new UserInteractionError('ask_user_question was interrupted before the user answered', 'ASK_ABORTED')) + } + + const disposePendingQuestions = (): void => { + if (activeQuestion !== undefined) { + disposeQuestion(activeQuestion) + activeQuestion = undefined + } + for (const pending of questionQueue.splice(0)) { + disposeQuestion(pending) + } + } + + const finishQuestion = (pending: PendingQuestion): void => { + activeQuestion = undefined + removeAbortListener(pending) + pending.resolve({ answers: pending.answers }) + output.write('\n') + startNextQuestion() + } + + const answerCurrentQuestion = (pending: PendingQuestion, answer: AskUserQuestionAnswerItem): void => { + pending.answers.push(answer) + pending.questionIndex += 1 + if (pending.questionIndex >= pending.request.questions.length) { + finishQuestion(pending) + return + } + renderQuestion(pending) + } + + const selectedOptions = (text: string, options: AskUserQuestionOption[], multiSelect: boolean): OptionSelection => { + if (text === '') return { kind: 'invalid' } + if (!multiSelect) { + if (!/^\d+$/.test(text)) return { kind: 'custom' } + const selected = options[Number(text) - 1] + return selected === undefined ? { kind: 'invalid' } : { kind: 'selected', options: [selected] } + } + const indices = text.split(/[,\s]+/).filter(Boolean) + if (indices.length === 0) return { kind: 'invalid' } + if (indices.some(part => !/^\d+$/.test(part))) return { kind: 'custom' } + const uniqueIndices = [...new Set(indices)] + const selected = uniqueIndices.map(part => options[Number(part) - 1]) + return selected.some(option => option === undefined) + ? { kind: 'invalid' } + : { kind: 'selected', options: selected as AskUserQuestionOption[] } + } + + const answerQuestion = (line: string): void => { + const pending = activeQuestion as PendingQuestion + const question = activeQuestionItem(pending) + + const text = line.trim() + const options = question.options ?? [] + const selection = options.length > 0 + ? selectedOptions(text, options, question.multiSelect ?? false) + : { kind: text === '' ? 'invalid' : 'custom' } as OptionSelection + if (selection.kind === 'selected') { + answerCurrentQuestion(pending, { id: question.id, selected: selection.options.map(option => option.label) }) + return + } + + if (selection.kind === 'custom' && text !== '') { + answerCurrentQuestion(pending, { id: question.id, selected: [], custom: text }) + return + } + + output.write(options.length > 0 + ? 'Please enter one of the option numbers' + + (question.multiSelect ? ' (comma or space separated)' : '') + + ' or a custom answer' + + '.\n> ' + : 'Please enter an answer.\n> ') + } + + const disposeUserInteractionProvider = ctx.userInteraction.registerProvider({ + ask(request) { + if (disposed || stdinClosed) { + return Promise.reject( + new UserInteractionError('ask_user_question cannot be answered because stdin is closed', 'ASK_ABORTED'), + ) + } + return new Promise((resolve, reject) => { + const pending: PendingQuestion = { + request, + questionIndex: 0, + answers: [], + resolve, + reject, + onAbort: () => { + if (activeQuestion === pending) { + activeQuestion = undefined + disposeQuestion(pending) + startNextQuestion() + return + } + // If it is not active, this listener can only fire while the ask + // remains queued; settled asks remove the listener first. + questionQueue.splice(questionQueue.indexOf(pending), 1) + disposeQuestion(pending) + }, + } + request.signal?.addEventListener('abort', pending.onAbort, { once: true }) + questionQueue.push(pending) + startNextQuestion() + }) + }, + }) + reader.on('line', (line) => { + if (activeQuestion !== undefined) { + answerQuestion(line) + return + } const text = line.trim() if (!text) return const agent = ctx.agents.get(agentId) @@ -199,12 +368,15 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt // Fires for BOTH stdin EOF and plugin disposal (reader.close() below); // `disposed` guards teardown so HMR/dispose never exits the process. stdinClosed = true + if (!disposed) disposePendingQuestions() maybeExit() }) output.write(`${welcome}\n> `) return () => { disposed = true if (exitTimer !== undefined) clearTimeout(exitTimer) + disposePendingQuestions() + disposeUserInteractionProvider() disposeStatusListener() reader.close() } diff --git a/packages/ui/stdio-agent/tests/readline.spec.ts b/packages/ui/stdio-agent/tests/readline.spec.ts index ae3c480756..a958c435c1 100644 --- a/packages/ui/stdio-agent/tests/readline.spec.ts +++ b/packages/ui/stdio-agent/tests/readline.spec.ts @@ -19,6 +19,7 @@ function fakeContext(): Context { // The UI seeds its label map from the registry at install; this suite only // exercises readline terminal-mode selection, so an empty roster suffices. agents: { list: vi.fn(() => []) }, + userInteraction: { registerProvider: vi.fn(() => vi.fn()) }, } as unknown as Context } diff --git a/packages/ui/stdio-agent/tests/stdio-agent.spec.ts b/packages/ui/stdio-agent/tests/stdio-agent.spec.ts index 34ba201040..1f5a01a5b6 100644 --- a/packages/ui/stdio-agent/tests/stdio-agent.spec.ts +++ b/packages/ui/stdio-agent/tests/stdio-agent.spec.ts @@ -37,6 +37,8 @@ describe('dsh-stdio-agent app', () => { expect(ctx.get('agents')).toBeDefined() expect(ctx.get('agentLoop')).toBeDefined() expect(ctx.get('sessionPersistence')).toBeDefined() + expect(ctx.get('userInteraction')).toBeDefined() + expect(ctx.get('tools')?.get('ask_user_question')).toBeDefined() // The pre-created `main` agent the UI drives. expect(ctx.get('agents')?.get(AgentId('main'))).toBeDefined() await ctx.fiber.dispose() @@ -92,7 +94,7 @@ describe('dsh-stdio-agent app', () => { }) } const assembly = await ctx.get('systemPrompt')!.assemble() - expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha']) + expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'ask_user_question']) await ctx.fiber.dispose() }) diff --git a/packages/ui/stdio-agent/tests/stdio-chat.spec.ts b/packages/ui/stdio-agent/tests/stdio-chat.spec.ts index 090b77ac64..93683d0768 100644 --- a/packages/ui/stdio-agent/tests/stdio-chat.spec.ts +++ b/packages/ui/stdio-agent/tests/stdio-chat.spec.ts @@ -1,10 +1,11 @@ -import { Readable } from 'node:stream' +import { Readable, Writable } from 'node:stream' import { describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { ContentBlock, StreamChunk } from '@deepseek-ai/dsh-llm' import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' import { createStdioChat, type Config, type StdioRuntime } from '../src/stdio-chat.ts' /** @@ -79,10 +80,11 @@ const CONFIG: Config = { welcome: 'hi there', agent: 'main' } async function setup(config: Config = CONFIG, runtimeOver: Partial = {}) { const ctx = new Context() await ctx.plugin(AgentRegistry) + await ctx.plugin(UserInteractionService) const { runtime, input, out, exit } = makeRuntime(runtimeOver) const fiber = await ctx.plugin(Object.assign((inner: Context) => { createStdioChat(inner, config, runtime) - }, { inject: ['agents'] })) + }, { inject: ['agents', 'userInteraction'] })) return { ctx, fiber, input, out, exit } } @@ -105,6 +107,30 @@ describe('createStdioChat rendering', () => { // And it drives the default agent id 'main'. }) + it('detects readline terminal mode from both stream TTY flags', async () => { + for (const [inputTTY, outputTTY] of [[true, false], [true, true]] as const) { + const ctx = new Context() + await ctx.plugin(AgentRegistry) + await ctx.plugin(UserInteractionService) + let text = '' + const output = new Writable({ + write(chunk, _encoding, callback) { + text += String(chunk) + callback() + }, + }) as Writable & { isTTY?: boolean } + const { runtime } = makeRuntime({ output }) + ;(runtime.input as Readable & { isTTY?: boolean }).isTTY = inputTTY + output.isTTY = outputTTY + const fiber = await ctx.plugin(Object.assign((inner: Context) => { + createStdioChat(inner, CONFIG, runtime) + }, { inject: ['agents', 'userInteraction'] })) + + expect(text).toContain('hi there') + await fiber.dispose() + } + }) + it('renders text-delta chunks verbatim', async () => { const { ctx, out } = await setup() ctx.emit('session/event', makeSession('main'), chunkEvent({ type: 'text-delta', index: 0, text: 'hello' })) @@ -160,12 +186,13 @@ describe('createStdioChat rendering', () => { // of the raw session id. const ctx = new Context() await ctx.plugin(AgentRegistry) + await ctx.plugin(UserInteractionService) const agent = makeAgent('main') ctx.agents.register(agent) // registered BEFORE the UI plugin below const { runtime, out } = makeRuntime() await ctx.plugin(Object.assign((inner: Context) => { createStdioChat(inner, CONFIG, runtime) - }, { inject: ['agents'] })) + }, { inject: ['agents', 'userInteraction'] })) ctx.emit('session/event', makeSession('main'), { type: 'turn/start', seq: 1, time: 0, data: { turn: 5, trigger: { kind: 'message' } }, } as SessionEvent) @@ -264,6 +291,347 @@ describe('createStdioChat rendering', () => { }) describe('createStdioChat input', () => { + it('answers a pending user question instead of sending the line to the agent', async () => { + const { ctx, input, out } = await setup() + const agent = makeAgent('main', 'idle') + ctx.agents.register(agent) + + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'confirm', + header: 'Confirm', + question: 'Proceed with the edit?', + options: [{ label: 'Yes', description: 'Apply the edit now.' }], + }], + }) + await new Promise(r => setImmediate(r)) + input.feed('Use a smaller change') + + await expect(answer).resolves.toEqual({ answers: [{ id: 'confirm', selected: [], custom: 'Use a smaller change' }] }) + expect(agent.sent).toEqual([]) + expect(out.text()).toContain('[Confirm] Proceed with the edit?') + expect(out.text()).toContain('1. Yes') + expect(out.text()).toContain('Apply the edit now.') + }) + + it('answers a pending user question by numeric option selection', async () => { + const { ctx, input } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'mode', + question: 'Which mode?', + options: [ + { label: 'Safe' }, + { label: 'Fast' }, + ], + }], + }) + await new Promise(r => setImmediate(r)) + input.feed('2') + + await expect(answer).resolves.toEqual({ + answers: [{ id: 'mode', selected: ['Fast'] }], + }) + }) + + it('renders options in input order and selects by displayed number', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'topic', + question: 'Which topic?', + options: [ + { label: 'Hobbies' }, + { label: 'Work', description: 'Questions about current projects.' }, + { label: 'Casual', description: 'Easy conversation.' }, + ], + }], + }) + await new Promise(r => setImmediate(r)) + + expect(out.text()).toContain([ + 'Which topic?', + ' 1. Hobbies', + ' 2. Work', + ' Questions about current projects.', + ' 3. Casual', + ' Easy conversation.', + ].join('\n')) + input.feed('3') + + await expect(answer).resolves.toEqual({ + answers: [{ id: 'topic', selected: ['Casual'] }], + }) + }) + + it('answers a multi-select question with multiple numeric selections', async () => { + const { ctx, input } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'targets', + question: 'What should I update?', + options: [{ label: 'Tests' }, { label: 'Docs' }, { label: 'Code' }], + multiSelect: true, + }], + }) + await new Promise(r => setImmediate(r)) + input.feed('1 1, 3') + + await expect(answer).resolves.toEqual({ + answers: [{ id: 'targets', selected: ['Tests', 'Code'] }], + }) + }) + + it('accepts non-numeric multi-select input as a custom answer', async () => { + const { ctx, input } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'targets', + question: 'What should I update?', + options: [{ label: 'Tests' }, { label: 'Docs' }], + multiSelect: true, + }], + }) + await new Promise(r => setImmediate(r)) + input.feed('the release notes') + + await expect(answer).resolves.toEqual({ + answers: [{ id: 'targets', selected: [], custom: 'the release notes' }], + }) + }) + + it('asks every question in a batch and returns answers by id', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [ + { id: 'language', question: 'Which language?', options: [{ label: 'Python' }, { label: 'TypeScript' }] }, + { id: 'note', question: 'Any note?' }, + ], + }) + await new Promise(r => setImmediate(r)) + input.feed('2') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('\nAny note?\n') + input.feed('ship today') + + await expect(answer).resolves.toEqual({ + answers: [ + { id: 'language', selected: ['TypeScript'] }, + { id: 'note', selected: [], custom: 'ship today' }, + ], + }) + }) + + it('re-prompts when option input is invalid', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'mode', + question: 'Which mode?', + options: [{ label: 'Safe' }], + multiSelect: true, + }], + }) + await new Promise(r => setImmediate(r)) + input.feed('2') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('Please enter one of the option numbers (comma or space separated) or a custom answer.') + input.feed('1') + + await expect(answer).resolves.toEqual({ + answers: [{ id: 'mode', selected: ['Safe'] }], + }) + }) + + it('re-prompts when single-select option input is out of range', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'mode', + question: 'Which mode?', + options: [{ label: 'Safe' }], + }], + }) + await new Promise(r => setImmediate(r)) + input.feed('2') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('Please enter one of the option numbers or a custom answer.') + input.feed('1') + + await expect(answer).resolves.toEqual({ + answers: [{ id: 'mode', selected: ['Safe'] }], + }) + }) + + it('re-prompts when multi-select input contains no option numbers', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'mode', + question: 'Which mode?', + options: [{ label: 'Safe' }], + multiSelect: true, + }], + }) + await new Promise(r => setImmediate(r)) + input.feed(',') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('Please enter one of the option numbers (comma or space separated) or a custom answer.') + input.feed('1') + + await expect(answer).resolves.toEqual({ + answers: [{ id: 'mode', selected: ['Safe'] }], + }) + }) + + it('re-prompts when an option question receives an empty answer', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ + questions: [{ + id: 'mode', + question: 'Which mode?', + options: [{ label: 'Safe' }], + }], + }) + await new Promise(r => setImmediate(r)) + input.feed('') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('Please enter one of the option numbers or a custom answer.') + input.feed('1') + + await expect(answer).resolves.toEqual({ + answers: [{ id: 'mode', selected: ['Safe'] }], + }) + }) + + it('re-prompts when a question receives an empty answer', async () => { + const { ctx, input, out } = await setup() + const answer = ctx.userInteraction.ask({ questions: [{ id: 'path', question: 'What should I use?' }] }) + await new Promise(r => setImmediate(r)) + input.feed('') + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('Please enter an answer.') + input.feed('Use defaults') + + await expect(answer).resolves.toEqual({ answers: [{ id: 'path', selected: [], custom: 'Use defaults' }] }) + }) + + it('rejects an active question when its signal aborts', async () => { + const { ctx } = await setup() + const controller = new AbortController() + const answer = ctx.userInteraction.ask({ questions: [{ id: 'continue', question: 'Continue?' }], signal: controller.signal }) + const rejected = expect(answer).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + await new Promise(r => setImmediate(r)) + + controller.abort() + + await rejected + }) + + it('continues to the next queued question when the active question aborts', async () => { + const { ctx, input, out } = await setup() + const controller = new AbortController() + const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }], signal: controller.signal }) + const firstRejected = expect(first).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }] }) + await new Promise(r => setImmediate(r)) + + controller.abort() + await firstRejected + await new Promise(r => setImmediate(r)) + expect(out.text()).toContain('\nSecond?\n') + input.feed('second answer') + + await expect(second).resolves.toEqual({ answers: [{ id: 'second', selected: [], custom: 'second answer' }] }) + }) + + it('skips a queued question whose signal aborted before it became active', async () => { + const { ctx, input, out } = await setup() + const controller = new AbortController() + const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }] }) + const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }], signal: controller.signal }) + await new Promise(r => setImmediate(r)) + + controller.abort() + + await expect(Promise.race([ + second.then( + () => 'resolved', + (error: unknown) => (error as { code?: string }).code, + ), + new Promise((resolve) => { setImmediate(() => { resolve('pending') }) }), + ])).resolves.toBe('ASK_ABORTED') + expect(out.text()).not.toContain('\nSecond?\n') + input.feed('first answer') + await expect(first).resolves.toEqual({ answers: [{ id: 'first', selected: [], custom: 'first answer' }] }) + }) + + it('removes an aborted queued question without promoting later queued work early', async () => { + const { ctx, input, out } = await setup() + const controller = new AbortController() + const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }] }) + const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }], signal: controller.signal }) + const third = ctx.userInteraction.ask({ questions: [{ id: 'third', question: 'Third?' }] }) + await new Promise(r => setImmediate(r)) + + controller.abort() + + await expect(second).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + expect(out.text()).toContain('\nFirst?\n') + expect(out.text()).not.toContain('\nSecond?\n') + expect(out.text()).not.toContain('\nThird?\n') + input.feed('first answer') + await new Promise(r => setImmediate(r)) + + expect(out.text()).toContain('\nThird?\n') + input.feed('third answer') + + await expect(first).resolves.toEqual({ answers: [{ id: 'first', selected: [], custom: 'first answer' }] }) + await expect(third).resolves.toEqual({ answers: [{ id: 'third', selected: [], custom: 'third answer' }] }) + }) + + it('rejects active and queued questions when the UI is disposed', async () => { + const { ctx, fiber } = await setup() + const active = ctx.userInteraction.ask({ questions: [{ id: 'active', question: 'Active?' }] }) + const queued = ctx.userInteraction.ask({ questions: [{ id: 'queued', question: 'Queued?' }] }) + const activeRejected = expect(active).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + await new Promise(r => setImmediate(r)) + + await fiber.dispose() + + await activeRejected + await queuedRejected + }) + + it('rejects active and queued questions when stdin closes before the user answers', async () => { + const { ctx, input, exit } = await setup() + const active = ctx.userInteraction.ask({ questions: [{ id: 'active', question: 'Active?' }] }) + const queued = ctx.userInteraction.ask({ questions: [{ id: 'queued', question: 'Queued?' }] }) + const activeRejected = expect(active).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + await new Promise(r => setImmediate(r)) + + input.finish() + await new Promise(r => setImmediate(r)) + + await activeRejected + await queuedRejected + expect(exit).not.toHaveBeenCalled() + }) + + it('rejects new questions immediately after stdin has closed', async () => { + const { ctx, input, out } = await setup() + input.finish() + await new Promise(r => setImmediate(r)) + const before = out.text() + + const answer = ctx.userInteraction.ask({ questions: [{ id: 'late', question: 'Too late?' }] }) + + await expect(answer).rejects.toMatchObject({ code: 'ASK_ABORTED' }) + expect(out.text()).toBe(before) + }) + it('sends a typed line to an idle agent', async () => { const { ctx, input } = await setup() const agent = makeAgent('main', 'idle') diff --git a/packages/ui/stdio-agent/tsconfig.json b/packages/ui/stdio-agent/tsconfig.json index 8b76352d11..6f30c1558e 100644 --- a/packages/ui/stdio-agent/tsconfig.json +++ b/packages/ui/stdio-agent/tsconfig.json @@ -32,6 +32,12 @@ { "path": "../../core/agent-core" }, + { + "path": "../user-interaction" + }, + { + "path": "../tool-ask-user" + }, { "path": "../../session-persistence/session-persistence-jsonl" } diff --git a/packages/ui/tool-ask-user/README.md b/packages/ui/tool-ask-user/README.md new file mode 100644 index 0000000000..10d4a082ba --- /dev/null +++ b/packages/ui/tool-ask-user/README.md @@ -0,0 +1,20 @@ +# @deepseek-ai/dsh-tool-ask-user + +Model-facing `ask_user_question` tool over `ctx.userInteraction`. It lets the model ask the human a concise question when it needs confirmation, a choice, or missing information before continuing. + +## Tool + +`ask_user_question` accepts: + +- `questions` — required non-empty array of question objects. +- `id` — required stable id on each question, echoed in the answer. +- `question` — required question text for each question. +- `header` — optional short heading. +- `options` — optional choices with `label` and `description`. If recommending a choice, put it first and append `(Recommended)` to that label. +- `multi_select` — whether that question may return more than one selected option. + +The tool calls `ctx.userInteraction.ask()` and returns JSON text shaped as `{ "answers": [{ "id": "...", "selected": ["..."], "custom": "..." }] }`. `selected` contains option labels; `custom` is present only for a free-form answer and overrides selected choices. + +## Role + +This is the consumer package for the user-interaction seam. It does not render UI and does not know how input is collected; it only translates model arguments into `AskUserQuestionRequest` and returns the human answer to the agent loop. diff --git a/packages/ui/tool-ask-user/package.json b/packages/ui/tool-ask-user/package.json new file mode 100644 index 0000000000..c1860f48f0 --- /dev/null +++ b/packages/ui/tool-ask-user/package.json @@ -0,0 +1,38 @@ +{ + "name": "@deepseek-ai/dsh-tool-ask-user", + "description": "Model-facing ask_user_question tool over the ctx.userInteraction seam", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-agent": "^0.0.1", + "@deepseek-ai/dsh-tools": "^0.0.1", + "@deepseek-ai/dsh-user-interaction": "^0.0.1", + "cordis": "^4.0.0-rc.6" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "@deepseek-ai/dsh-user-interaction": "workspace:^", + "cordis": "^4.0.0-rc.6" + } +} diff --git a/packages/ui/tool-ask-user/src/index.ts b/packages/ui/tool-ask-user/src/index.ts new file mode 100644 index 0000000000..2591b28ddd --- /dev/null +++ b/packages/ui/tool-ask-user/src/index.ts @@ -0,0 +1,71 @@ +/** + * Model-facing `ask_user_question` tool over the `ctx.userInteraction` seam. + * The tool pauses until a UI provider returns a human answer, then feeds that + * answer back into the agent loop as an ordinary tool result. + * + * @module @deepseek-ai/dsh-tool-ask-user + */ + +import type { Context } from 'cordis' +import { defineTool } from '@deepseek-ai/dsh-tools' +import '@deepseek-ai/dsh-user-interaction' + +export const name = 'tool-ask-user' +export const inject = ['tools', 'userInteraction'] + +const description = 'Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. ' + + 'Send one or more questions, each with a stable id that will be echoed in the answer.' + +export function apply(ctx: Context): void { + ctx.tools.register(defineTool({ + name: 'ask_user_question', + description, + parameters: { + questions: { + type: 'array', + required: true, + description: 'Questions to ask the user before continuing.', + items: { + type: 'object', + properties: { + id: { type: 'string', required: true, description: 'Stable id for this question; echoed in the answer.' }, + question: { type: 'string', required: true, description: 'The specific question to ask the user.' }, + header: { + type: 'string', + description: 'Optional short heading for the question, such as "Confirm" or "Choose Mode".', + }, + options: { + type: 'array', + description: 'Optional choices to show the user. If you recommend one, put it first and append "(Recommended)" to that label.', + items: { + type: 'object', + properties: { + label: { type: 'string', required: true, description: 'Short user-facing option label.' }, + description: { type: 'string', description: 'One sentence explaining the tradeoff or impact.' }, + }, + }, + }, + multi_select: { + type: 'boolean', + description: 'Whether the user may select more than one option. Defaults to false.', + }, + }, + }, + }, + }, + async execute(args, exec) { + const result = await ctx.userInteraction.ask({ + questions: args.questions.map(question => ({ + id: question.id, + question: question.question, + ...question.header !== undefined ? { header: question.header } : {}, + ...question.options !== undefined ? { options: question.options } : {}, + ...question.multi_select !== undefined ? { multiSelect: question.multi_select } : {}, + })), + ...exec.agent !== undefined ? { agent: exec.agent } : {}, + ...exec.signal !== undefined ? { signal: exec.signal } : {}, + }) + return [{ type: 'text', text: JSON.stringify(result) }] + }, + })) +} diff --git a/packages/ui/tool-ask-user/tests/tool-ask-user.spec.ts b/packages/ui/tool-ask-user/tests/tool-ask-user.spec.ts new file mode 100644 index 0000000000..ceff7df388 --- /dev/null +++ b/packages/ui/tool-ask-user/tests/tool-ask-user.spec.ts @@ -0,0 +1,253 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { CallId } from '@deepseek-ai/dsh-llm' +import type { Agent } from '@deepseek-ai/dsh-agent' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry from '@deepseek-ai/dsh-tools' +import UserInteractionService, { type AskUserQuestionRequest } from '@deepseek-ai/dsh-user-interaction' +import * as toolAskUser from '@deepseek-ai/dsh-tool-ask-user' + +interface OptionSchemaShape { + properties: { + questions: { + items: { + properties: { + options: { + items: { + properties: Record + } + } + } & Record + } + } + } +} + +async function setup() { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(UserInteractionService) + await ctx.plugin(toolAskUser) + return ctx +} + +describe('ask_user_question tool', () => { + it('registers a model-facing tool schema', async () => { + const ctx = await setup() + const schema = ctx.tools.schemas().find(tool => tool.name === 'ask_user_question') + + expect(schema).toMatchObject({ + name: 'ask_user_question', + parameters: { + type: 'object', + properties: { + questions: { type: 'array' }, + }, + required: ['questions'], + }, + }) + const parameters = schema?.parameters as unknown as OptionSchemaShape + expect(parameters.properties.questions.items.properties).toMatchObject({ + id: { type: 'string' }, + question: { type: 'string' }, + header: { type: 'string' }, + options: { type: 'array' }, + multi_select: { type: 'boolean' }, + }) + expect(parameters.properties.questions.items.properties.options.items.properties).toMatchObject({ + label: { type: 'string' }, + description: { type: 'string' }, + }) + expect(parameters.properties.questions.items.properties.options.items.properties).not.toHaveProperty('value') + expect(parameters.properties.questions.items.properties.options.items.properties).not.toHaveProperty('recommended') + expect(parameters.properties.questions.items.properties.options.items.properties).not.toHaveProperty('preview') + }) + + it('asks the registered user-interaction provider and projects structured answers to text', async () => { + const ctx = await setup() + const seen: AskUserQuestionRequest[] = [] + ctx.userInteraction.registerProvider({ + async ask(request) { + seen.push(request) + return { answers: [{ id: 'pkg', selected: ['pnpm'] }] } + }, + }) + + const result = await ctx.tools.execute({ + callId: CallId('ask-1'), + name: 'ask_user_question', + arguments: { + questions: [{ + id: 'pkg', + question: 'Which package manager should I use?', + options: [{ label: 'pnpm', description: 'Use pnpm workspaces.' }], + }], + }, + }) + + expect(result).toMatchObject({ + isError: false, + content: [{ type: 'text', text: '{"answers":[{"id":"pkg","selected":["pnpm"]}]}' }], + }) + expect(seen).toMatchObject([{ + questions: [{ + id: 'pkg', + question: 'Which package manager should I use?', + options: [{ label: 'pnpm', description: 'Use pnpm workspaces.' }], + }], + }]) + }) + + it('passes recommended option labels through without adding schema fields', async () => { + const ctx = await setup() + const seen: AskUserQuestionRequest[] = [] + ctx.userInteraction.registerProvider({ + async ask(request) { + seen.push(request) + return { answers: [{ id: 'pkg', selected: ['pnpm (Recommended)'] }] } + }, + }) + + await ctx.tools.execute({ + callId: CallId('ask-recommended'), + name: 'ask_user_question', + arguments: { + questions: [{ + id: 'pkg', + question: 'Which package manager should I use?', + options: [ + { label: 'pnpm (Recommended)' }, + { label: 'npm' }, + ], + }], + }, + }) + + expect(seen[0]?.questions[0]?.options).toEqual([ + { label: 'pnpm (Recommended)' }, + { label: 'npm' }, + ]) + }) + + it('projects custom answers and multi-select choices', async () => { + const ctx = await setup() + ctx.userInteraction.registerProvider({ + async ask() { + return { + answers: [ + { id: 'targets', selected: ['tests', 'docs'] }, + { id: 'notes', selected: [], custom: 'ship today' }, + ], + } + }, + }) + + const result = await ctx.tools.execute({ + callId: CallId('ask-multi'), + name: 'ask_user_question', + arguments: { + questions: [ + { + id: 'targets', + question: 'What should I update?', + options: [{ label: 'tests' }, { label: 'docs' }], + multi_select: true, + }, + { id: 'notes', question: 'Any note?' }, + ], + }, + }) + + expect(result.content).toEqual([{ + type: 'text', + text: '{"answers":[{"id":"targets","selected":["tests","docs"]},{"id":"notes","selected":[],"custom":"ship today"}]}', + }]) + }) + + it('passes the tool abort signal to the user-interaction request', async () => { + const ctx = await setup() + const seen: AskUserQuestionRequest[] = [] + ctx.userInteraction.registerProvider({ + async ask(request) { + seen.push(request) + return { answers: [{ id: 'continue', selected: ['ok'] }] } + }, + }) + const controller = new AbortController() + + await ctx.tools.execute({ + callId: CallId('ask-2'), + name: 'ask_user_question', + arguments: { questions: [{ id: 'continue', question: 'Continue?' }] }, + signal: controller.signal, + }) + + expect(seen[0]?.signal).toBe(controller.signal) + }) + + it('passes optional header and agent through to the user-interaction request', async () => { + const ctx = await setup() + const seen: AskUserQuestionRequest[] = [] + ctx.userInteraction.registerProvider({ + async ask(request) { + seen.push(request) + return { answers: [{ id: 'continue', selected: ['ok'] }] } + }, + }) + const agent = { id: 'main' } as unknown as Agent + + const result = await ctx.tools.execute({ + callId: CallId('ask-3'), + name: 'ask_user_question', + arguments: { questions: [{ id: 'continue', header: 'Confirm', question: 'Continue?' }] }, + agent, + }) + + expect(result.content).toEqual([{ type: 'text', text: '{"answers":[{"id":"continue","selected":["ok"]}]}' }]) + expect(seen[0]).toMatchObject({ questions: [{ id: 'continue', header: 'Confirm', question: 'Continue?' }], agent }) + }) + + it('returns structured user-interaction errors through tool execution', async () => { + const ctx = await setup() + + const result = await ctx.tools.execute({ + callId: CallId('ask-no-provider'), + name: 'ask_user_question', + arguments: { questions: [{ id: 'continue', question: 'Continue?' }] }, + }) + + expect(result).toMatchObject({ + isError: true, + error: { name: 'UserInteractionError', code: 'NO_PROVIDER' }, + }) + }) + + it('returns a structured error for empty question batches', async () => { + const ctx = await setup() + + const result = await ctx.tools.execute({ + callId: CallId('ask-empty'), + name: 'ask_user_question', + arguments: { questions: [] }, + }) + + expect(result).toMatchObject({ + isError: true, + error: { name: 'UserInteractionError', code: 'EMPTY_QUESTIONS' }, + }) + }) + + it('unregisters the tool when its plugin fiber is disposed', async () => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(UserInteractionService) + const fiber = await ctx.plugin(toolAskUser) + expect(ctx.tools.get('ask_user_question')).toBeDefined() + + await fiber.dispose() + + expect(ctx.tools.get('ask_user_question')).toBeUndefined() + }) +}) diff --git a/packages/ui/tool-ask-user/tsconfig.json b/packages/ui/tool-ask-user/tsconfig.json new file mode 100644 index 0000000000..c779bad37f --- /dev/null +++ b/packages/ui/tool-ask-user/tsconfig.json @@ -0,0 +1,36 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../../core/tools" + }, + { + "path": "../user-interaction" + } + ] +} diff --git a/packages/ui/user-interaction/README.md b/packages/ui/user-interaction/README.md new file mode 100644 index 0000000000..6377c2b7ef --- /dev/null +++ b/packages/ui/user-interaction/README.md @@ -0,0 +1,24 @@ +# @deepseek-ai/dsh-user-interaction + +Abstract user-interaction seam. It owns `ctx.userInteraction`, the service a model-facing tool or permission plugin uses when it needs to pause work and ask the human for a decision. + +## Service: `UserInteractionService` (ctx key: `userInteraction`) + +### Public API + +- `ctx.userInteraction.registerProvider(provider): () => void` Register the UI-side provider. Only one provider may be active in a context; disposal unregisters it. +- `ctx.userInteraction.ask(request): Promise` Ask the active provider and wait for the answer. + +### Key Types + +- `AskUserQuestionRequest` — `{ questions: [{ id, question, header?, options?, multiSelect? }], agent?, signal? }`. +- `AskUserQuestionOption` — `{ label, description? }`. +- `AskUserQuestionAnswer` — `{ answers: [{ id, selected, custom? }] }`. +- `UserInteractionProvider` — UI implementation with `ask(request)`. +- `UserInteractionError` — `HarnessError` subclass with codes such as `EMPTY_QUESTIONS`, `NO_PROVIDER`, `DUPLICATE_PROVIDER`, and `ASK_ABORTED`. + +When an answer includes `custom`, `selected` is empty; custom text is an override rather than a supplement to selected choices. + +## Role + +This is the interface package. Model-facing consumers such as `@deepseek-ai/dsh-tool-ask-user` depend on this seam; UI front doors such as the `stdio-agent` readline module and the `acp` bridge provide the provider. The loop stays unchanged: a tool call simply awaits a promise, and the tool result resumes the normal agent loop. diff --git a/packages/ui/user-interaction/package.json b/packages/ui/user-interaction/package.json new file mode 100644 index 0000000000..f333195ac7 --- /dev/null +++ b/packages/ui/user-interaction/package.json @@ -0,0 +1,34 @@ +{ + "name": "@deepseek-ai/dsh-user-interaction", + "description": "Abstract user-interaction seam (ctx.userInteraction) for asking the human during agent runs", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-agent": "^0.0.1", + "@deepseek-ai/dsh-llm": "^0.0.1", + "cordis": "^4.0.0-rc.6" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "cordis": "^4.0.0-rc.6" + } +} diff --git a/packages/ui/user-interaction/src/index.ts b/packages/ui/user-interaction/src/index.ts new file mode 100644 index 0000000000..f9c1616ade --- /dev/null +++ b/packages/ui/user-interaction/src/index.ts @@ -0,0 +1,128 @@ +/** + * User-interaction seam (`ctx.userInteraction`): a UI-backed service for + * pausing an agent tool call until the human answers a question. The model- + * facing tool lives in `@deepseek-ai/dsh-tool-ask-user`; UI packages provide + * the single active provider. + * + * @module @deepseek-ai/dsh-user-interaction + */ + +import { Context, Service } from 'cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { HarnessError } from '@deepseek-ai/dsh-llm' + +declare module 'cordis' { + interface Context { + userInteraction: UserInteractionService + } +} + +/** One selectable answer offered to the user. */ +export interface AskUserQuestionOption { + /** User-facing label. */ + label: string + /** Optional extra context rendered by capable UIs. */ + description?: string +} + +/** One question in an ask_user_question request. */ +export interface AskUserQuestionItem { + /** Stable model-provided question id, echoed in the answer. */ + id: string + /** The question to display. */ + question: string + /** Optional short heading/group label. */ + header?: string + /** Optional choices the UI can render as a menu. */ + options?: AskUserQuestionOption[] + /** Whether more than one option may be selected. Defaults to single-select. */ + multiSelect?: boolean +} + +/** Request for a human answer. */ +export interface AskUserQuestionRequest { + /** Questions to display. */ + questions: AskUserQuestionItem[] + /** Calling agent, when the request came from an agent tool call. */ + agent?: Agent + /** Abort signal for the owning tool/step. */ + signal?: AbortSignal +} + +/** Answer to one question. */ +export interface AskUserQuestionAnswerItem { + /** The answered question id. */ + id: string + /** Selected option labels. Empty when the answer is purely custom text. */ + selected: string[] + /** Optional free-text "Other" answer. */ + custom?: string +} + +/** The human's answer. */ +export interface AskUserQuestionAnswer { + /** Structured answers keyed by question id. */ + answers: AskUserQuestionAnswerItem[] +} + +/** UI-side provider for user questions. */ +export interface UserInteractionProvider { + ask(request: AskUserQuestionRequest): Promise +} + +/** Stable error taxonomy for user-interaction failures. */ +export class UserInteractionError extends HarnessError { + constructor(message: string, code: string, options?: ErrorOptions) { + super(message, code, options) + this.name = 'UserInteractionError' + } +} + +/** `ctx.userInteraction`: one active UI provider plus an `ask()` surface. */ +export class UserInteractionService extends Service { + private provider: UserInteractionProvider | undefined + + constructor(ctx: Context) { + super(ctx, 'userInteraction') + } + + /** + * Register the UI provider. Only one provider may be active in a context. + * + * @param provider UI-side implementation that collects answers. + * @returns Disposer that unregisters this provider. + */ + registerProvider(provider: UserInteractionProvider): () => void { + const dispose = this.ctx.effect(function* (this: UserInteractionService) { + if (this.provider !== undefined) { + throw new UserInteractionError('a user-interaction provider is already registered', 'DUPLICATE_PROVIDER') + } + this.provider = provider + yield () => { + this.provider = undefined + } + }.bind(this), 'userInteraction.registerProvider()') + return () => void dispose() + } + + /** + * Ask the active UI provider and wait for the user's answer. + * + * @param request Questions, owner agent, and abort signal. + * @returns The answer chosen or typed by the human. + */ + async ask(request: AskUserQuestionRequest): Promise { + if (request.signal?.aborted) { + throw new UserInteractionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED') + } + if (request.questions.length === 0) { + throw new UserInteractionError('ask_user_question requires at least one question', 'EMPTY_QUESTIONS') + } + if (this.provider === undefined) { + throw new UserInteractionError('no user-interaction provider is registered', 'NO_PROVIDER') + } + return this.provider.ask(request) + } +} + +export default UserInteractionService diff --git a/packages/ui/user-interaction/tests/user-interaction.spec.ts b/packages/ui/user-interaction/tests/user-interaction.spec.ts new file mode 100644 index 0000000000..adfbc9d4bb --- /dev/null +++ b/packages/ui/user-interaction/tests/user-interaction.spec.ts @@ -0,0 +1,86 @@ +import { describe, expect, it, vi } from 'vitest' +import { Context } from 'cordis' +import UserInteractionService, { + UserInteractionError, + type AskUserQuestionRequest, + type UserInteractionProvider, +} from '@deepseek-ai/dsh-user-interaction' + +function provider(answer = 'approved'): UserInteractionProvider & { seen: AskUserQuestionRequest[] } { + const seen: AskUserQuestionRequest[] = [] + return { + seen, + async ask(request) { + seen.push(request) + return { answers: [{ id: request.questions[0]?.id ?? 'missing', selected: [answer] }] } + }, + } +} + +describe('UserInteractionService', () => { + it('delegates ask requests to the registered provider', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + const p = provider('yes') + ctx.userInteraction.registerProvider(p) + + const result = await ctx.userInteraction.ask({ questions: [{ id: 'confirm', question: 'Proceed?' }] }) + + expect(result).toEqual({ answers: [{ id: 'confirm', selected: ['yes'] }] }) + expect(p.seen).toEqual([{ questions: [{ id: 'confirm', question: 'Proceed?' }] }]) + }) + + it('rejects ask requests when no provider is registered', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + + await expect(ctx.userInteraction.ask({ questions: [{ id: 'confirm', question: 'Proceed?' }] })) + .rejects.toMatchObject({ name: 'UserInteractionError', code: 'NO_PROVIDER' }) + }) + + it('registers providers with HMR-safe disposal', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + const p = provider() + const dispose = ctx.userInteraction.registerProvider(p) + + dispose() + dispose() + + await expect(ctx.userInteraction.ask({ questions: [{ id: 'confirm', question: 'Proceed?' }] })) + .rejects.toMatchObject({ code: 'NO_PROVIDER' }) + }) + + it('rejects duplicate providers instead of replacing the active UI', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + ctx.userInteraction.registerProvider(provider('first')) + + expect(() => ctx.userInteraction.registerProvider(provider('second'))) + .toThrow(UserInteractionError) + }) + + it('fails before reaching the provider when the signal is already aborted', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + const p = { ask: vi.fn(async () => ({ answers: [{ id: 'confirm', selected: ['too late'] }] })) } + ctx.userInteraction.registerProvider(p) + const controller = new AbortController() + controller.abort() + + await expect(ctx.userInteraction.ask({ questions: [{ id: 'confirm', question: 'Proceed?' }], signal: controller.signal })) + .rejects.toMatchObject({ code: 'ASK_ABORTED' }) + expect(p.ask).not.toHaveBeenCalled() + }) + + it('rejects empty question batches before reaching the provider', async () => { + const ctx = new Context() + await ctx.plugin(UserInteractionService) + const p = { ask: vi.fn(async () => ({ answers: [] })) } + ctx.userInteraction.registerProvider(p) + + await expect(ctx.userInteraction.ask({ questions: [] })) + .rejects.toMatchObject({ name: 'UserInteractionError', code: 'EMPTY_QUESTIONS' }) + expect(p.ask).not.toHaveBeenCalled() + }) +}) diff --git a/packages/ui/user-interaction/tsconfig.json b/packages/ui/user-interaction/tsconfig.json new file mode 100644 index 0000000000..178ff39f3f --- /dev/null +++ b/packages/ui/user-interaction/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../llm/llm" + } + ] +} diff --git a/packages/util/README.md b/packages/util/README.md index ae73c8125f..45afe7b0a9 100644 --- a/packages/util/README.md +++ b/packages/util/README.md @@ -5,5 +5,8 @@ Zero-dependency primitives shared across the other groups. A package lands here | Package | Role | |---|---| | `brand/` | The type-only `Branded` nominal-typing primitive (no runtime code, no harness deps) | +| `timeout/` | The timing/classification half of a timeout — `clampTimeout`/`deadline`/`timeoutOf`/`TimeoutReason` (pure functions, no harness deps); termination stays in each capability | `dsh-brand` is the canonical case: it owns ONLY the `Branded` helper, so a capability package can brand the ids it owns (`dsh-bash`'s `BashTaskId`/`OwnerToken`, `dsh-session`'s `SessionId`, …) by depending on `dsh-brand` alone, without pulling in an unrelated package just to reach `Branded`. + +`dsh-timeout` follows the same shape for the timeout family: `dsh-bash` and `dsh-web-fetch-local` each fuse a caller's cancellation with a deadline and later classify "timed out" vs "cancelled" by depending on `dsh-timeout` alone. It deliberately owns only the timing/classification half — the *termination* (SIGKILL a process group, tear down a fetch socket) stays in each capability, because no shared layer can own every capability's kill (see [the timeout-library RFC](../../docs/rfc/implemented/architecture/2026-07-06-timeout-deadline-library.md)). diff --git a/packages/util/timeout/README.md b/packages/util/timeout/README.md new file mode 100644 index 0000000000..db2b06ba53 --- /dev/null +++ b/packages/util/timeout/README.md @@ -0,0 +1,42 @@ +# dsh-timeout + +The **timing-and-classification** half of a timeout — a zero-dependency library of pure functions (no runtime harness deps) shared by every capability that clamps a caller's timeout hint, arms a deadline, and later has to tell "timed out" apart from "cancelled". + +It owns **no termination**. The signal it hands out only *notifies*; actually stopping the work stays in each capability, because that mechanism differs — bash SIGKILLs an OS process group, web tears down a `fetch` socket — and no shared layer can own all of them. This is the boundary the [RFC](../../../docs/rfc/implemented/architecture/2026-07-06-timeout-deadline-library.md) draws: share the timing/classification, keep the hard kill local. + +It is a **library, not a service or plugin**: no `ctx`, registers nothing, holds no state, emits no events. A "timeout service" would have to understand how to stop every capability's work — exactly the knowledge a microkernel keeps out of shared layers. + +## Surface + +```ts +import { clampTimeout, deadline, timeoutOf, TimeoutReason } from '@deepseek-ai/dsh-timeout' +``` + +| Export | Role | +|---|---| +| `clampTimeout(requested, def, max, name?)` | Validate the caller's optional positive-finite hint, fill from `def`, cap at `max`. Throws (with `name`) on a non-positive/non-finite hint. | +| `deadline(upstream, timeoutMs, code)` | Fuse `upstream` cancellation with a timeout into one `AbortSignal` (`AbortSignal.any`); the timeout carries a `TimeoutReason`. `[Symbol.dispose]` clears the timer. | +| `timeoutOf(signal \| { reason }, code?)` | Recover the `TimeoutReason` from an aborted signal/error, else `undefined` — the timeout-vs-cancel classifier. Pass `code` to match only THIS deadline's timer (see nesting below). | +| `TimeoutReason` | The internal reason (`code` + `timeoutMs`) stamped on a timeout abort. Not a public error — providers translate it into their own error/field. | + +## The `timeoutMs <= 0` sentinel + +`0` is the **internal** "no timeout" value for backend-owned background work (bash `start()`): `deadline()` arms no timer and forwards only `upstream`; with no upstream either, it returns a never-aborting signal plus a no-op disposer, so every caller keeps one call shape. External request hints validate as **positive finite** via `clampTimeout` before they reach `deadline`, so `0` is never a model-/plugin-facing "disable timeout" value. + +## Usage shape + +```ts ignore-check +// Scope-lifetime consumer (foreground bash, one fetch): `using` disposes the timer. +using d = deadline(upstream, timeoutMs, 'BASH_TIMEOUT') +const outcome = await runWork({ signal: d.signal }) // work listens on d.signal and terminates itself +const timedOut = timeoutOf(d.signal, 'BASH_TIMEOUT') !== undefined // classify the first abort, scoped to OUR code +const aborted = d.signal.aborted && !timedOut // mutually exclusive: timeout won, or cancel did +``` + +The signal only *notifies* — the caller MUST attach its own termination (`d.signal.addEventListener('abort', kill)`, or hand `d.signal` to `fetch`). Racing a promise against a timer would resolve the tool-call while the child process or socket leaks on; handing out a signal forces a real termination path to exist. + +Pass your own `code` to `timeoutOf` so classification composes under nesting: when the `upstream` you were handed is *itself* a deadline signal (a future `tools/execute` middleware arming a per-call deadline), `AbortSignal.any` preserves the outer `TimeoutReason` if the outer timer fires first. Scoping to your `code` makes a foreign timeout read as an ordinary upstream cancel — the correct classification from your capability's view — instead of your own timeout firing when your local timer never expired. + +## What does NOT get a timeout + +Local file `read`/`write`/`edit` take no `timeoutMs`: a syscall is best-effort-abortable at most, a timeout could not force `fsync`/`rename` to stop, and adding one would be an implicit default that violates explicit-over-implicit. See [`fs/`](../../fs/README.md). diff --git a/packages/util/timeout/package.json b/packages/util/timeout/package.json new file mode 100644 index 0000000000..150a155324 --- /dev/null +++ b/packages/util/timeout/package.json @@ -0,0 +1,30 @@ +{ + "name": "@deepseek-ai/dsh-timeout", + "description": "Zero-dependency timeout/deadline primitive: clampTimeout, deadline, timeoutOf, TimeoutReason (timing + classification only, no termination)", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "cordis": "^4.0.0-rc.6" + }, + "devDependencies": { + "cordis": "^4.0.0-rc.6" + } +} diff --git a/packages/util/timeout/src/index.ts b/packages/util/timeout/src/index.ts new file mode 100644 index 0000000000..ed95a877d3 --- /dev/null +++ b/packages/util/timeout/src/index.ts @@ -0,0 +1,162 @@ +/** + * The timing-and-classification half of a timeout — a zero-dependency library + * of pure functions shared by every capability that clamps a caller's timeout + * hint, arms a deadline, and later has to tell "timed out" apart from + * "cancelled". It owns NO termination: the returned {@link deadline} signal only + * NOTIFIES; actually stopping the work (SIGKILL a process group, tear down a + * fetch socket, …) stays in each capability's implementation, because that + * mechanism differs per capability and no shared layer can own all of them. + * + * This is deliberately a library, not a cordis service or plugin: it takes no + * `ctx`, registers nothing, holds no cross-call state, and emits no events. A + * "timeout service" would have to understand how to stop every capability's + * work — exactly the knowledge a microkernel keeps out of shared layers. + * + * The four exports and their division of labor: + * - {@link clampTimeout} — validate a caller's optional positive hint, fill the + * backend default, cap at the backend max (pure arithmetic + the shared + * positive-finite request contract). + * - {@link deadline} — fuse upstream cancellation with a timeout into one + * `AbortSignal`, the timeout carrying an identifiable {@link TimeoutReason}; + * `[Symbol.dispose]` clears the timer. + * - {@link timeoutOf} — classify an aborted signal (or error): a + * {@link TimeoutReason} means the timeout fired, anything else (or nothing) + * means it did not. + * - {@link TimeoutReason} — the internal classification reason; providers + * translate it into their own public error/result shape before returning. + * + * @module @deepseek-ai/dsh-timeout + */ + +/** + * The internal reason attached to a timeout abort so consumers can classify it + * after the fact. It carries the failing `code` (each capability's own string — + * `BASH_TIMEOUT`, `WEB_FETCH_TIMEOUT`, …) and the `timeoutMs` that elapsed. + * + * It is an INTERNAL classification reason, not a public error: providers + * translate it into their seam-specific error code or result field (via + * {@link timeoutOf}) before returning to callers. Native `AbortSignal.timeout()` + * yields a fixed `TimeoutError` indistinguishable across timeout kinds; this + * type is identifiable and carries the code/duration. + */ +export class TimeoutReason extends Error { + override name = 'TimeoutReason' + + /** + * @param code Capability-owned timeout code (e.g. `BASH_TIMEOUT`). + * @param timeoutMs The deadline that elapsed, in milliseconds. + */ + constructor(readonly code: string, readonly timeoutMs: number) { + super(`${code} after ${timeoutMs}ms`) + } +} + +/** + * Validate a caller's optional timeout hint, fill it from the backend default, + * then cap at the backend max. The shared positive-finite request contract: + * a supplied `requested` must be a positive finite number or this throws — + * `0` is NOT a caller-facing "disable timeout" value (that sentinel is internal + * to {@link deadline}). A missing `requested` falls back to `def`. + * + * @param requested The caller's optional hint; validated when present. + * @param def The backend default applied when `requested` is absent. + * @param max The backend upper bound the result is capped to. + * @param name Field name used in the thrown message (so the caller sees which input was bad). + * @returns The effective timeout in milliseconds: `min(requested ?? def, max)`. + */ +export function clampTimeout( + requested: number | undefined, + def: number, + max: number, + name = 'timeoutMs', +): number { + if (requested !== undefined && (!Number.isFinite(requested) || requested <= 0)) { + throw new Error(`${name} must be a positive finite number`) + } + return Math.min(requested ?? def, max) +} + +/** A deadline signal plus the cleanup that clears its timer (dispose-once). */ +export interface Deadline { + /** Aborts on upstream cancellation OR on timeout (the timeout carries a {@link TimeoutReason}). */ + readonly signal: AbortSignal + /** Clear the timer. Safe to call once; `using` calls it at scope exit. */ + [Symbol.dispose](): void +} + +/** + * Build a deadline signal that aborts on upstream cancellation OR on timeout, + * with the timeout carrying an identifiable {@link TimeoutReason} (unlike + * native `AbortSignal.timeout()`, whose fixed `TimeoutError` is opaque). It is + * `AbortSignal.any([upstream, ])` — the single primitive that fuses + * two abort sources — with the reason and a disposable timer added on top. + * + * `timeoutMs <= 0` is the INTERNAL "no timeout" sentinel for backend-owned + * background work: arm no timer and forward only the upstream signal; with no + * upstream either, return a never-aborting signal so callers keep one call + * shape. External request hints validate as positive finite via + * {@link clampTimeout} before reaching here, so `0` never arrives from a model + * or plugin. + * + * The returned object's `[Symbol.dispose]` clears the timer — use `using` for a + * scope-lifetime consumer, or call it manually for an event-lifetime one. The + * signal only NOTIFIES; the caller must attach its own termination (kill the + * process group, abort the fetch, …). + * + * @param upstream The caller's cancellation signal, if any, fused into the result. + * @param timeoutMs Deadline in milliseconds; `<= 0` means "no timeout" (arm no timer). + * @param code Capability-owned code stamped onto the timeout's {@link TimeoutReason}. + * @returns The fused {@link Deadline} (signal + timer cleanup). + */ +export function deadline( + upstream: AbortSignal | undefined, + timeoutMs: number, + code: string, +): Deadline { + if (timeoutMs <= 0) { + // No timeout (background work): forward only the upstream signal, or a + // never-aborting one when there is no upstream. No timer, so dispose is a + // no-op — the empty method keeps the one call shape for every caller. + return { signal: upstream ?? new AbortController().signal, [Symbol.dispose]() {} } + } + + const timer = new AbortController() + const id = setTimeout(() => { timer.abort(new TimeoutReason(code, timeoutMs)) }, timeoutMs) + return { + // AbortSignal.any adopts the reason of whichever source aborts FIRST, so a + // race resolves to a single cause: timeoutOf() reads TimeoutReason only + // when the timeout won, and upstream-wins leaves an ordinary abort reason. + signal: upstream !== undefined ? AbortSignal.any([upstream, timer.signal]) : timer.signal, + [Symbol.dispose]() { clearTimeout(id) }, + } +} + +/** + * Recover the {@link TimeoutReason} from an aborted signal (or any object with a + * `reason`), else `undefined`. This is the classification half: a provider + * calls it on the deadline signal after an abort to decide whether the cause + * was its timeout (translate to the capability's timeout error/field) or an + * ordinary upstream cancellation (`undefined` → the cancel path). + * + * Pass `code` to scope the match to THIS deadline's timer. It matters under + * nesting: when the `upstream` handed to {@link deadline} is itself a deadline + * signal (e.g. a future `tools/execute` middleware arming a per-call deadline), + * `AbortSignal.any` preserves the OUTER `TimeoutReason` if the outer timer fires + * first. Without `code`, the inner capability would misclassify that outer + * timeout as its own (`timedOut:true` / `WEB_FETCH_TIMEOUT`) though its local + * timer never expired; with `code`, a foreign timeout reads as `undefined` and + * falls through to the upstream-cancel path, which is the correct classification + * from the inner capability's view. Omit `code` only to ask "was this ANY + * timeout" (a generic middleware that owns no single code). + * + * @param x An {@link AbortSignal} or any `{ reason }` carrier (e.g. a caught abort error). + * @param code When provided, only a {@link TimeoutReason} with this exact `code` matches. + * @returns The matching {@link TimeoutReason}, else `undefined`. + */ +export function timeoutOf(x: AbortSignal | { reason?: unknown }, code?: string): TimeoutReason | undefined { + // AbortSignal.reason is typed `any`; pin it to `unknown` so no `any` leaks and + // the instanceof narrows cleanly for both a signal and a bare reason carrier. + const reason: unknown = x.reason + if (!(reason instanceof TimeoutReason)) return undefined + return code === undefined || reason.code === code ? reason : undefined +} diff --git a/packages/util/timeout/tests/timeout.spec.ts b/packages/util/timeout/tests/timeout.spec.ts new file mode 100644 index 0000000000..588317f48d --- /dev/null +++ b/packages/util/timeout/tests/timeout.spec.ts @@ -0,0 +1,185 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { clampTimeout, deadline, timeoutOf, TimeoutReason } from '@deepseek-ai/dsh-timeout' + +describe('TimeoutReason', () => { + it('is an Error carrying the code and elapsed ms', () => { + const reason = new TimeoutReason('BASH_TIMEOUT', 100) + expect(reason).toBeInstanceOf(Error) + expect(reason.name).toBe('TimeoutReason') + expect(reason.code).toBe('BASH_TIMEOUT') + expect(reason.timeoutMs).toBe(100) + expect(reason.message).toBe('BASH_TIMEOUT after 100ms') + }) +}) + +describe('clampTimeout', () => { + it('fills the default when the hint is absent', () => { + expect(clampTimeout(undefined, 120_000, 600_000)).toBe(120_000) + }) + + it('caps the hint at max', () => { + expect(clampTimeout(999_999, 120_000, 600_000)).toBe(600_000) + }) + + it('keeps a valid hint under the cap', () => { + expect(clampTimeout(5_000, 120_000, 600_000)).toBe(5_000) + }) + + it('caps the default itself when the default exceeds max', () => { + // min(def, max) applies even with no hint — a misconfigured backend never + // exceeds its own cap. + expect(clampTimeout(undefined, 900_000, 600_000)).toBe(600_000) + }) + + it('rejects a non-finite hint with the caller-provided name', () => { + expect(() => clampTimeout(Number.NaN, 100, 200, 'bash-local: request.timeoutMs')) + .toThrow(/bash-local: request\.timeoutMs must be a positive finite number/) + expect(() => clampTimeout(Number.POSITIVE_INFINITY, 100, 200)) + .toThrow(/timeoutMs must be a positive finite number/) + }) + + it('rejects a non-positive hint', () => { + expect(() => clampTimeout(0, 100, 200)).toThrow(/must be a positive finite number/) + expect(() => clampTimeout(-1, 100, 200)).toThrow(/must be a positive finite number/) + }) +}) + +describe('deadline — timeout arm', () => { + afterEach(() => { vi.useRealTimers() }) + + it('aborts on timeout with a TimeoutReason after the elapsed ms', () => { + vi.useFakeTimers() + using d = deadline(undefined, 100, 'BASH_TIMEOUT') + expect(d.signal.aborted).toBe(false) + vi.advanceTimersByTime(100) + expect(d.signal.aborted).toBe(true) + const reason = timeoutOf(d.signal) + expect(reason).toBeInstanceOf(TimeoutReason) + expect(reason?.code).toBe('BASH_TIMEOUT') + expect(reason?.timeoutMs).toBe(100) + }) + + it('[Symbol.dispose] clears the timer so no abort fires afterward', () => { + vi.useFakeTimers() + const d = deadline(undefined, 100, 'BASH_TIMEOUT') + d[Symbol.dispose]() + vi.advanceTimersByTime(1_000) + expect(d.signal.aborted).toBe(false) + expect(timeoutOf(d.signal)).toBeUndefined() + }) +}) + +describe('deadline — fuse with upstream', () => { + it('aborts on upstream cancellation, classified as NOT a timeout', () => { + const upstream = new AbortController() + using d = deadline(upstream.signal, 60_000, 'BASH_TIMEOUT') + upstream.abort('user cancelled') + expect(d.signal.aborted).toBe(true) + expect(timeoutOf(d.signal)).toBeUndefined() + }) + + it('cancel wins when it fires before the timeout', () => { + vi.useFakeTimers() + try { + const upstream = new AbortController() + using d = deadline(upstream.signal, 100, 'BASH_TIMEOUT') + upstream.abort('user cancelled') // fires first, before the 100ms timer + vi.advanceTimersByTime(200) + expect(d.signal.aborted).toBe(true) + // AbortSignal.any adopts the FIRST source's reason: cancel won, so no + // TimeoutReason even though the timer later elapsed. + expect(timeoutOf(d.signal)).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + it('timeout wins when it fires before upstream cancellation', () => { + vi.useFakeTimers() + try { + const upstream = new AbortController() + using d = deadline(upstream.signal, 100, 'WEB_FETCH_TIMEOUT') + vi.advanceTimersByTime(150) // past the 100ms deadline: the timer fires first + expect(d.signal.aborted).toBe(true) + expect(timeoutOf(d.signal)?.code).toBe('WEB_FETCH_TIMEOUT') + // A later upstream abort is a no-op on the already-aborted fused signal: + // AbortSignal.any keeps the FIRST cause, so the timeout classification stands. + upstream.abort('too late') + expect(timeoutOf(d.signal)?.code).toBe('WEB_FETCH_TIMEOUT') + } finally { + vi.useRealTimers() + } + }) + + it('forwards a pre-aborted upstream signal immediately', () => { + const upstream = new AbortController() + upstream.abort('already gone') + using d = deadline(upstream.signal, 60_000, 'BASH_TIMEOUT') + expect(d.signal.aborted).toBe(true) + expect(timeoutOf(d.signal)).toBeUndefined() + }) +}) + +describe('deadline — timeoutMs <= 0 (no-timeout sentinel)', () => { + afterEach(() => { vi.useRealTimers() }) + + it('arms no timer and forwards only the upstream signal', () => { + vi.useFakeTimers() + const upstream = new AbortController() + using d = deadline(upstream.signal, 0, 'BASH_TIMEOUT') + vi.advanceTimersByTime(1_000_000) + expect(d.signal.aborted).toBe(false) // no timer ever armed + upstream.abort('kill') + expect(d.signal.aborted).toBe(true) + expect(timeoutOf(d.signal)).toBeUndefined() // never a timeout + }) + + it('returns a never-aborting signal with a no-op disposer when there is no upstream', () => { + vi.useFakeTimers() + const d = deadline(undefined, 0, 'BASH_TIMEOUT') + expect(() => { d[Symbol.dispose]() }).not.toThrow() + vi.advanceTimersByTime(1_000_000) + expect(d.signal.aborted).toBe(false) + expect(timeoutOf(d.signal)).toBeUndefined() + }) + + it('treats a negative timeout the same as zero', () => { + const d = deadline(undefined, -5, 'BASH_TIMEOUT') + expect(d.signal.aborted).toBe(false) + d[Symbol.dispose]() + }) +}) + +describe('timeoutOf', () => { + it('classifies a bare reason carrier that holds a TimeoutReason', () => { + const reason = new TimeoutReason('WEB_FETCH_TIMEOUT', 50) + expect(timeoutOf({ reason })).toBe(reason) + }) + + it('returns undefined for a non-timeout reason', () => { + expect(timeoutOf({ reason: new Error('other') })).toBeUndefined() + expect(timeoutOf({ reason: 'user cancelled' })).toBeUndefined() + expect(timeoutOf({})).toBeUndefined() + }) + + it('matches only the requested code when one is given', () => { + const reason = new TimeoutReason('BASH_TIMEOUT', 100) + expect(timeoutOf({ reason }, 'BASH_TIMEOUT')).toBe(reason) + expect(timeoutOf({ reason }, 'WEB_FETCH_TIMEOUT')).toBeUndefined() + }) +}) + +describe('deadline — nested deadlines', () => { + it("does not misclassify an outer deadline's timeout as the inner code", () => { + // The upstream handed to the inner deadline is ITSELF a deadline that has + // already timed out (outer). AbortSignal.any preserves the outer reason; + // scoping timeoutOf to the inner code keeps the inner capability from + // reporting the outer timeout as its own — it reads as an upstream cancel. + const outer = new AbortController() + outer.abort(new TimeoutReason('OUTER_TIMEOUT', 30)) + using inner = deadline(outer.signal, 60_000, 'BASH_TIMEOUT') + expect(inner.signal.aborted).toBe(true) + expect(timeoutOf(inner.signal, 'BASH_TIMEOUT')).toBeUndefined() // not ours → upstream-cancel path + expect(timeoutOf(inner.signal)?.code).toBe('OUTER_TIMEOUT') // but IS a timeout, unscoped + }) +}) diff --git a/packages/util/timeout/tsconfig.json b/packages/util/timeout/tsconfig.json new file mode 100644 index 0000000000..749cb0208e --- /dev/null +++ b/packages/util/timeout/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [] +} diff --git a/packages/web/tool-web/README.md b/packages/web/tool-web/README.md index d8a2e266a9..ab1326a21e 100644 --- a/packages/web/tool-web/README.md +++ b/packages/web/tool-web/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-tool-web -The model-facing web tool suite — `web_search` and `web_fetch` — over the [web capability seam](../web/README.md) (`ctx.web`). It owns model-facing concerns only: tool names, JSON schemas, snake_case argument names, prompt sections, the result-count bound, result formatting, HTML→markdown presentation, and `presentCall`. All web access goes through `ctx.web`; this package never imports a concrete provider. +The model-facing web tool suite — `web_search` and `web_fetch` — over the [web capability seam](../web/README.md) (`ctx.web`). It owns model-facing concerns only: tool names, JSON schemas, snake_case argument names, prompt sections, the result-count bound, result formatting, HTML→markdown presentation, and `presentCall`. All web access goes through `ctx.web`; this package never imports a concrete provider. Neither tool exposes a model-facing timeout — each tool's cooperative tool-call budget is declared here via config (`fetchTimeoutMs`/`searchTimeoutMs`, attached as `ToolDefinition.timeoutMs`) and enforced by [`@deepseek-ai/dsh-timeout-policy`](../../timeout/timeout-policy/README.md) (a `tools/execute` wrapper); each tool just forwards `exec.signal` to the seam. Each tool is registered independently; a product that wants only one disables the other via config (`{ search: false }` / `{ fetch: false }`). @@ -9,7 +9,7 @@ Each tool is registered independently; a product that wants only one disables th | Tool | Args | Behavior | |---|---|---| | `web_search` | `query` (string) | Discovery. Returns an optional answer plus source URLs. `max_results` is **not** model-facing — the tool sets the bound (the `searchMaxResults` config, default 8) and passes it to the seam. | -| `web_fetch` | `url` (string), `timeout_ms` (number, optional) | Retrieves a specific URL. HTML bodies are rendered to markdown-ish text; text bodies pass through. A non-2xx status is reported, not an error. | +| `web_fetch` | `url` (string) | Retrieves a specific URL. HTML bodies are rendered to markdown-ish text; text bodies pass through. A non-2xx status is reported, not an error. The tool-call timeout is deployment policy (`dsh-timeout-policy`), not a model argument. | ## Config @@ -18,6 +18,10 @@ Each tool is registered independently; a product that wants only one disables th | `search` | `true` | Register `web_search`. | | `fetch` | `true` | Register `web_fetch`. | | `searchMaxResults` | `8` | Upper bound on sources returned by one `web_search` call (the seam truncates a longer provider list and flags it). | +| `fetchTimeoutMs` | `30000` | Cooperative tool-call timeout budget (ms) for `web_fetch`. | +| `searchTimeoutMs` | `30000` | Cooperative tool-call timeout budget (ms) for `web_search`. | + +`fetchTimeoutMs`/`searchTimeoutMs` declare each tool's cooperative timeout budget (attached as `ToolDefinition.timeoutMs`), enforced by [`@deepseek-ai/dsh-timeout-policy`](../../timeout/timeout-policy/README.md); the model-facing schema exposes no timeout argument. ```yaml - id: tool-web diff --git a/packages/web/tool-web/package.json b/packages/web/tool-web/package.json index 8c22afa9a8..80fd69dbc3 100644 --- a/packages/web/tool-web/package.json +++ b/packages/web/tool-web/package.json @@ -37,6 +37,7 @@ "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", + "@deepseek-ai/dsh-timeout-policy": "workspace:^", "@deepseek-ai/dsh-web": "workspace:^", "@deepseek-ai/dsh-web-fetch-local": "workspace:^", "@deepseek-ai/dsh-web-search-exa": "workspace:^", diff --git a/packages/web/tool-web/src/fetch.ts b/packages/web/tool-web/src/fetch.ts index 9c9243e90f..571ce00797 100644 --- a/packages/web/tool-web/src/fetch.ts +++ b/packages/web/tool-web/src/fetch.ts @@ -3,6 +3,13 @@ * Execution goes through `ctx.web` — this module owns the model-facing schema, * argument validation, and PRESENTATION (HTML→markdown, truncation formatting), * while the fetch provider owns safe retrieval (transport, redirects, caps). + * + * The model-facing schema exposes NO timeout knob: the tool-call budget is + * deployment policy DECLARED via this package's `fetchTimeoutMs` config (attached + * as `ToolDefinition.timeoutMs`) and ENFORCED by `@deepseek-ai/dsh-timeout-policy` + * (a `tools/execute` wrapper), matching the reference-agent `WebFetch` shape. This + * tool just forwards the (possibly deadline-derived) `exec.signal` to `ctx.web`; + * the provider keeps its own timeout only as a resource backstop for direct callers. */ import type { Context } from 'cordis' @@ -15,18 +22,17 @@ import type {} from '@deepseek-ai/dsh-system-prompt' import { htmlToMarkdown } from './html.ts' /** - * Validate value constraints the schema DSL can't express: a non-blank `url`, - * and a positive `timeout_ms` when present. Throws a plain `Error` otherwise. + * Validate value constraints the schema DSL can't express: a non-blank `url`. + * Throws a plain `Error` otherwise. No timeout parameter — the tool-call budget + * is deployment policy declared via `fetchTimeoutMs` config and enforced by + * `@deepseek-ai/dsh-timeout-policy`, not a model argument. * * @param args - the schema-validated `web_fetch` arguments. - * @returns the arguments renamed to the seam's camelCase request fields. + * @returns the arguments as the seam's request fields. */ -export function parseFetchArgs(args: { url: string; timeout_ms?: number }): { url: string; timeoutMs?: number } { +export function parseFetchArgs(args: { url: string }): { url: string } { if (args.url.trim().length === 0) throw new Error('url must be a non-empty string') - if (args.timeout_ms !== undefined && (!Number.isFinite(args.timeout_ms) || args.timeout_ms <= 0)) { - throw new Error('timeout_ms must be a positive number') - } - return { url: args.url, ...args.timeout_ms !== undefined ? { timeoutMs: args.timeout_ms } : {} } + return { url: args.url } } /** @@ -67,7 +73,7 @@ export function formatFetchOutput(result: WebFetchResult): string { * @param args - the raw tool arguments; only `url` feeds the view. * @returns the generic card view (`kind: 'fetch'`) shown while the call runs. */ -export function presentFetchCall(args: { url: string; timeout_ms?: number }): GenericCallView { +export function presentFetchCall(args: { url: string }): GenericCallView { return { card: 'generic', title: args.url, kind: 'fetch', rawInput: args.url } } @@ -76,8 +82,10 @@ export function presentFetchCall(args: { url: string; timeout_ms?: number }): Ge * * @param ctx - context whose `tools` and `systemPrompt` registries receive the * registrations; both are effect-scoped and unregister on plugin dispose. + * @param timeoutMs - the cooperative tool-call budget (ms) attached as the tool's + * `ToolDefinition.timeoutMs` for `@deepseek-ai/dsh-timeout-policy` to enforce. */ -export function applyWebFetchTool(ctx: Context): void { +export function applyWebFetchTool(ctx: Context, timeoutMs: number): void { ctx.systemPrompt.section({ name: 'tool:web_fetch', order: 111, @@ -89,12 +97,12 @@ export function applyWebFetchTool(ctx: Context): void { description: 'Fetch the content of a specific HTTP(S) URL and return it decoded to text.', parameters: { url: { type: 'string', required: true, description: 'The HTTP(S) URL to fetch.' }, - timeout_ms: { type: 'number', description: 'Optional fetch timeout in milliseconds (capped by the provider).' }, }, + timeoutMs, async execute(args, exec): Promise { const input = parseFetchArgs(args) const result = await ctx.web.fetch( - { url: input.url, ...input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {} }, + { url: input.url }, exec.signal ? { signal: exec.signal } : undefined, ) return [{ type: 'text', text: formatFetchOutput(result) }] diff --git a/packages/web/tool-web/src/index.ts b/packages/web/tool-web/src/index.ts index 78b6a4bdf3..0f948eacb6 100644 --- a/packages/web/tool-web/src/index.ts +++ b/packages/web/tool-web/src/index.ts @@ -33,7 +33,10 @@ export const name = 'tool-web' /** Services required by the web tool suite. */ export const inject = ['tools', 'web', 'systemPrompt'] -/** Plugin config: which web tools to register, and the `web_search` source cap. */ +/** Default cooperative tool-call timeout budget (ms) for the web tools. */ +export const DEFAULT_WEB_TOOL_TIMEOUT_MS = 30_000 + +/** Plugin config: which web tools to register, the source cap, and per-tool budgets. */ export interface Config { /** Register `web_search`. Defaults to true. */ search?: boolean @@ -41,12 +44,18 @@ export interface Config { fetch?: boolean /** Upper bound on sources returned by one `web_search` call. */ searchMaxResults?: number + /** Cooperative timeout budget (ms) for `web_fetch`. Defaults to 30000. */ + fetchTimeoutMs?: number + /** Cooperative timeout budget (ms) for `web_search`. Defaults to 30000. */ + searchTimeoutMs?: number } export const Config: z = z.object({ search: z.boolean().default(true), fetch: z.boolean().default(true), searchMaxResults: z.number().default(WEB_SEARCH_MAX_RESULTS), + fetchTimeoutMs: z.number().default(DEFAULT_WEB_TOOL_TIMEOUT_MS), + searchTimeoutMs: z.number().default(DEFAULT_WEB_TOOL_TIMEOUT_MS), }) /** The shape after schemastery applies its defaults to every field. */ @@ -61,7 +70,10 @@ function assertPositiveInteger(name: string, value: number): void { /** * Register the enabled web tools. `search`/`fetch` default to true; a product - * that wants only one disables the other in config. The tools' disposers are + * that wants only one disables the other in config. Each tool's cooperative + * timeout budget (`fetchTimeoutMs`/`searchTimeoutMs`, default 30000) is resolved + * here and attached to the tool as `ToolDefinition.timeoutMs` for + * `@deepseek-ai/dsh-timeout-policy` to enforce. The tools' disposers are * fiber-scoped (the effect-based registries clean up on dispose), so no manual * teardown is needed. */ @@ -69,6 +81,8 @@ export function apply(ctx: Context, config: Config): void { // schemastery (Config) has already filled every defaulted field. const resolved = config as ResolvedConfig assertPositiveInteger('searchMaxResults', resolved.searchMaxResults) - if (resolved.search) applyWebSearchTool(ctx, resolved.searchMaxResults) - if (resolved.fetch) applyWebFetchTool(ctx) + assertPositiveInteger('fetchTimeoutMs', resolved.fetchTimeoutMs) + assertPositiveInteger('searchTimeoutMs', resolved.searchTimeoutMs) + if (resolved.search) applyWebSearchTool(ctx, resolved.searchMaxResults, resolved.searchTimeoutMs) + if (resolved.fetch) applyWebFetchTool(ctx, resolved.fetchTimeoutMs) } diff --git a/packages/web/tool-web/src/search.ts b/packages/web/tool-web/src/search.ts index 3776940cde..a7587d328b 100644 --- a/packages/web/tool-web/src/search.ts +++ b/packages/web/tool-web/src/search.ts @@ -92,8 +92,10 @@ export function presentSearchCall(args: { query: string }): GenericCallView { * registrations; both are effect-scoped and unregister on plugin dispose. * @param maxResults - the deployment's source cap, sent as every seam * request's `maxResults`. + * @param timeoutMs - the cooperative tool-call budget (ms) attached as the tool's + * `ToolDefinition.timeoutMs` for `@deepseek-ai/dsh-timeout-policy` to enforce. */ -export function applyWebSearchTool(ctx: Context, maxResults: number): void { +export function applyWebSearchTool(ctx: Context, maxResults: number, timeoutMs: number): void { ctx.systemPrompt.section({ name: 'tool:web_search', order: 110, @@ -106,6 +108,7 @@ export function applyWebSearchTool(ctx: Context, maxResults: number): void { parameters: { query: { type: 'string', required: true, description: 'The search query.' }, }, + timeoutMs, async execute(args, exec): Promise { const input = parseSearchArgs(args) const result = await ctx.web.search( diff --git a/packages/web/tool-web/tests/integration.spec.ts b/packages/web/tool-web/tests/integration.spec.ts index 50ae6c5624..de804e2bcd 100644 --- a/packages/web/tool-web/tests/integration.spec.ts +++ b/packages/web/tool-web/tests/integration.spec.ts @@ -1,10 +1,11 @@ /** * Integration: the real fetch backend (`dsh-web-fetch-local`) + a real search * provider (`dsh-web-search-exa`) + the real seam (`dsh-web`) + the model tool - * (`dsh-tool-web`), exercised through `ctx.tools.execute()` — nothing bypasses - * the tool registry. Fetch hits a real loopback HTTP server (verifying the - * WORLD); search runs the real Exa provider over a stubbed global `fetch` (the - * network is the one boundary we mock). + * (`dsh-tool-web`) + the tool-call timeout policy (`dsh-timeout-policy`), + * exercised through `ctx.tools.execute()` — nothing bypasses the tool registry. + * Fetch hits a real loopback HTTP server (verifying the WORLD); search runs the + * real Exa provider over a stubbed global `fetch` (the network is the one + * boundary we mock). */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -18,6 +19,7 @@ import WebService from '@deepseek-ai/dsh-web' import * as WebFetchLocal from '@deepseek-ai/dsh-web-fetch-local' import * as WebSearchExa from '@deepseek-ai/dsh-web-search-exa' import * as ToolWeb from '@deepseek-ai/dsh-tool-web' +import * as TimeoutPolicy from '@deepseek-ai/dsh-timeout-policy' type Handler = (req: IncomingMessage, res: ServerResponse) => void @@ -39,6 +41,11 @@ beforeEach(async () => { await ctx.plugin(WebService, { searchProvider: WebSearchExa.EXA_PROVIDER_ID, fetchProvider: WebFetchLocal.LOCAL_FETCH_PROVIDER_ID }) await ctx.plugin(WebFetchLocal, {}) await ctx.plugin(WebSearchExa, { apiKey: 'exa-key', baseURL: 'https://api.exa.test' }) + // The shipped deployment shape: the tool-call budget is declared by tool-web + // config (default 30s, attached as ToolDefinition.timeoutMs) and enforced by + // the zero-config timeout-policy plugin, set above the provider backstop so the + // policy normally wins. + await ctx.plugin(TimeoutPolicy) fiber = await ctx.plugin(ToolWeb) }) @@ -96,3 +103,70 @@ describe('web_search integration over the real Exa provider', () => { expect(out.content.map(b => b.text).join('')).toContain('[Result](https://result.test)') }) }) + +describe('tool-call timeout policy over the migrated web tools', () => { + it('neither model schema exposes a timeout parameter after the migration', () => { + const byName = new Map(ctx.tools.schemas().map(s => [s.name, s])) + const fetchParams = byName.get('web_fetch')!.parameters as { properties: Record } + const searchParams = byName.get('web_search')!.parameters as { properties: Record } + expect(Object.keys(fetchParams.properties)).toEqual(['url']) + expect('timeout_ms' in fetchParams.properties).toBe(false) + expect(Object.keys(searchParams.properties)).toEqual(['query']) + }) +}) + +describe('tool-call timeout returns TOOL_TIMEOUT (deadline wins over a slow fetch)', () => { + let slowServer: Server + let slowBase: string + let openSockets: ServerResponse[] + let tctx: Context + let tfiber: Awaited> + + beforeEach(async () => { + // A server that never responds: it holds the connection open until the + // client aborts. The cooperative deadline (via exec.signal → the fetch + // provider → undici) is what ends the call. + openSockets = [] + slowServer = createServer((_req, res) => { openSockets.push(res) }) + await new Promise(resolve => slowServer.listen(0, '127.0.0.1', resolve)) + slowBase = `http://127.0.0.1:${(slowServer.address() as AddressInfo).port}` + + tctx = new Context() + await tctx.plugin(SystemPrompt) + await tctx.plugin(ToolRegistry) + await tctx.plugin(WebService, { fetchProvider: WebFetchLocal.LOCAL_FETCH_PROVIDER_ID }) + // Provider backstop well ABOVE the tool-call budget, so the policy wins. + await tctx.plugin(WebFetchLocal, { timeoutMs: 30_000, maxTimeoutMs: 60_000 }) + await tctx.plugin(TimeoutPolicy) + // The tool-call budget is declared by tool-web config, enforced by the policy. + tfiber = await tctx.plugin(ToolWeb, { fetchTimeoutMs: 50 }) + }) + + afterEach(async () => { + for (const res of openSockets) res.destroy() + await tfiber.dispose() + await new Promise(resolve => slowServer.close(() => { resolve() })) + }) + + it('returns a structured TOOL_TIMEOUT (not the provider WEB_FETCH_TIMEOUT) when the tool-call budget wins', async () => { + const out = await tctx.tools.execute({ callId: CallId('slow-1'), name: 'web_fetch', arguments: { url: slowBase } }) + expect(out.isError).toBe(true) + // The outer tool-call deadline won: TOOL_TIMEOUT, owned by dsh-timeout-policy, + // NOT the provider's own WEB_FETCH_TIMEOUT (its 30s backstop never fired). + expect(out.error?.code).toBe('TOOL_TIMEOUT') + const text = out.content.map(b => (b.type === 'text' ? b.text : '')).join('') + expect(text).toContain('timed out after 50ms') + }) + + it('the provider backstop still protects a DIRECT ctx.web.fetch() call (no tool-call policy in that path)', async () => { + // A direct seam caller does not go through tools/execute, so the tool-call + // policy never applies; the provider's OWN timeout is the only budget. A + // short per-request hint proves the provider backstop is intact and classifies + // as WEB_FETCH_TIMEOUT (the provider-owned code), never TOOL_TIMEOUT. + const err = await tctx.web.fetch({ url: slowBase, timeoutMs: 50 }).then( + () => undefined, + (e: unknown) => e as { code?: string }, + ) + expect(err?.code).toBe('WEB_FETCH_TIMEOUT') + }) +}) diff --git a/packages/web/tool-web/tests/tool-web.spec.ts b/packages/web/tool-web/tests/tool-web.spec.ts index 924e0aaeb2..4bb2728df7 100644 --- a/packages/web/tool-web/tests/tool-web.spec.ts +++ b/packages/web/tool-web/tests/tool-web.spec.ts @@ -110,10 +110,9 @@ describe('fetch formatting', () => { expect(renderBody({ kind: 'html', content: '

y

' })).toBe('y') }) - it('validates url and timeout', () => { + it('validates url (non-empty), no timeout parameter', () => { expect(() => parseFetchArgs({ url: ' ' })).toThrow('non-empty') - expect(() => parseFetchArgs({ url: 'https://a.test', timeout_ms: -1 })).toThrow('positive') - expect(parseFetchArgs({ url: 'https://a.test', timeout_ms: 5 })).toEqual({ url: 'https://a.test', timeoutMs: 5 }) + expect(parseFetchArgs({ url: 'https://a.test' })).toEqual({ url: 'https://a.test' }) }) it('presents a fetch call as a fetch-kind card titled by the url', () => { @@ -249,7 +248,7 @@ describe('tool-web execution through the real registry', () => { expect('default' in ToolWeb).toBe(false) }) - it('executes web_fetch, forwarding timeout_ms and the abort signal to the seam', async () => { + it('executes web_fetch, forwarding the url (no timeout param) and the abort signal to the seam', async () => { const seen: { request?: { url: string; timeoutMs?: number }; signal?: AbortSignal | undefined } = {} const fetchProvider = { id: 'stub-fetch', @@ -262,13 +261,35 @@ describe('tool-web execution through the real registry', () => { } const { ctx, fiber } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider }) const controller = new AbortController() - const out = await ctx.tools.execute({ callId: CallId('fetch-1'), name: 'web_fetch', arguments: { url: 'https://a.test', timeout_ms: 1234 }, signal: controller.signal }) + const out = await ctx.tools.execute({ callId: CallId('fetch-1'), name: 'web_fetch', arguments: { url: 'https://a.test' }, signal: controller.signal }) expect(out.isError).toBe(false) - expect(seen.request).toEqual({ url: 'https://a.test', timeoutMs: 1234 }) + // The model schema exposes no timeout: the tool forwards only the url; the + // tool-call budget is owned by dsh-timeout-policy over exec.signal. + expect(seen.request).toEqual({ url: 'https://a.test' }) expect(seen.signal).toBe(controller.signal) await fiber.dispose() }) + it('executes web_fetch with no caller signal (forwards undefined to the seam)', async () => { + const seen: { signal?: AbortSignal | undefined; passedExec?: boolean } = {} + const fetchProvider = { + id: 'stub-fetch', + status: () => available, + fetch: (request: { url: string }, exec?: { signal?: AbortSignal }) => { + seen.passedExec = exec !== undefined + seen.signal = exec?.signal + return Promise.resolve({ providerId: 'stub-fetch', url: request.url, statusCode: 200, body: { kind: 'text' as const, content: 'ok' }, truncated: false }) + }, + } + const { ctx, fiber } = await mountTools({ webConfig: { fetchProvider: 'stub-fetch' }, fetchProvider }) + // No signal on the execution: the tool passes `undefined` (not `{ signal: undefined }`). + const out = await ctx.tools.execute({ callId: CallId('fetch-2'), name: 'web_fetch', arguments: { url: 'https://a.test' } }) + expect(out.isError).toBe(false) + expect(seen.passedExec).toBe(false) + expect(seen.signal).toBeUndefined() + await fiber.dispose() + }) + it('executes web_search, forwarding the abort signal to the seam', async () => { const seen: { signal?: AbortSignal | undefined } = {} const provider: WebSearchProvider = { @@ -328,3 +349,31 @@ describe('searchMaxResults is plugin config', () => { .rejects.toThrow(/tool-web: searchMaxResults must be a positive integer/) }) }) + +describe('tool-call timeout budget is plugin config', () => { + it('attaches the default 30s budget to web_fetch and web_search', async () => { + const { fiber, ctx } = await mountTools() + expect(ctx.tools.get('web_fetch')?.timeoutMs).toBe(30_000) + expect(ctx.tools.get('web_search')?.timeoutMs).toBe(30_000) + await fiber.dispose() + }) + + it('honors per-tool timeout overrides from config', async () => { + const { fiber, ctx } = await mountTools({ config: { fetchTimeoutMs: 60_000, searchTimeoutMs: 10_000 } }) + expect(ctx.tools.get('web_fetch')?.timeoutMs).toBe(60_000) + expect(ctx.tools.get('web_search')?.timeoutMs).toBe(10_000) + await fiber.dispose() + }) + + it.each([ + ['fetchTimeoutMs', { fetchTimeoutMs: 0 }], + ['searchTimeoutMs', { searchTimeoutMs: -5 }], + ])('rejects a non-positive-integer %s at load', async (key, config) => { + const ctx = new Context() + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(WebService, {}) + await expect(ctx.plugin(ToolWeb, config)) + .rejects.toThrow(new RegExp(`tool-web: ${key} must be a positive integer`)) + }) +}) diff --git a/packages/web/tool-web/tsconfig.json b/packages/web/tool-web/tsconfig.json index 463a18dee9..5226425ec6 100644 --- a/packages/web/tool-web/tsconfig.json +++ b/packages/web/tool-web/tsconfig.json @@ -12,6 +12,7 @@ { "path": "../../llm/llm" }, { "path": "../../core/tools" }, { "path": "../../core/system-prompt" }, + { "path": "../../timeout/timeout-policy" }, { "path": "../web" } ] } diff --git a/packages/web/web-fetch-local/README.md b/packages/web/web-fetch-local/README.md index 58db557581..9c2ef0030f 100644 --- a/packages/web/web-fetch-local/README.md +++ b/packages/web/web-fetch-local/README.md @@ -6,7 +6,9 @@ This is an **implementation** package: it registers a provider into `ctx.web`, i ## Responsibility split -The provider owns **safe resource retrieval**: URL validation, HTTP transport, redirect policy, timeout, abort propagation, byte caps, charset decoding, content-type classification, and binary rejection. `@deepseek-ai/dsh-tool-web` owns **presentation** (HTML→markdown, truncation formatting). A non-2xx HTTP response is a *result* (status code + decoded body), not an error; `WebError` is reserved for failures to safely retrieve or represent the resource. +The provider owns **safe resource retrieval**: URL validation, HTTP transport, redirect policy, a resource-backstop timeout, abort propagation, byte caps, charset decoding, content-type classification, and binary rejection. `@deepseek-ai/dsh-tool-web` owns **presentation** (HTML→markdown, truncation formatting). A non-2xx HTTP response is a *result* (status code + decoded body), not an error; `WebError` is reserved for failures to safely retrieve or represent the resource. + +The provider's `timeoutMs`/`maxTimeoutMs` is a **resource backstop** for direct `ctx.web.fetch()` callers and misconfigured deployments — it is NOT the model-facing tool-call budget. The tool-call budget for `web_fetch` is deployment policy owned by [`@deepseek-ai/dsh-timeout-policy`](../../timeout/timeout-policy/README.md), which arms a per-call deadline on `exec.signal`. A shipped web-tool deployment sets the provider backstop **above** the `tool-timeout` budget, so the tool-call policy normally wins for model calls (returning `TOOL_TIMEOUT`); when the outer deadline signal reaches this provider first, it classifies as `WEB_ABORTED` and the outer wrapper replaces the result with `TOOL_TIMEOUT`. The provider's own `WEB_FETCH_TIMEOUT` only fires for a direct seam caller whose own budget elapsed. ## Transport hygiene @@ -24,8 +26,8 @@ The provider owns **safe resource retrieval**: URL validation, HTTP transport, r | `maxUrlLength` | `2048` | Maximum accepted request URL length. | | `maxResponseBytes` | `5_000_000` | Maximum response body size in bytes. | | `maxBodyChars` | `100_000` | Maximum decoded body length in characters. | -| `timeoutMs` | `30_000` | Default fetch timeout. | -| `maxTimeoutMs` | `120_000` | Upper bound for a per-request timeout override. | +| `timeoutMs` | `30_000` | Default fetch timeout — a resource backstop for direct `ctx.web.fetch()` callers, not the model-facing tool-call budget (that is `dsh-timeout-policy`). | +| `maxTimeoutMs` | `120_000` | Upper bound for a per-request timeout override (direct callers). | | `maxRedirects` | `5` | Maximum same-origin redirect hops (`0` follows none). | | `userAgent` | `deepseek-harness/…` | `User-Agent` header. | diff --git a/packages/web/web-fetch-local/package.json b/packages/web/web-fetch-local/package.json index 8d9a599a52..9b847db6f3 100644 --- a/packages/web/web-fetch-local/package.json +++ b/packages/web/web-fetch-local/package.json @@ -22,6 +22,7 @@ ], "license": "BSD-3-Clause", "peerDependencies": { + "@deepseek-ai/dsh-timeout": "^0.0.1", "@deepseek-ai/dsh-web": "^0.0.1", "cordis": "^4.0.0-rc.6" }, @@ -29,6 +30,7 @@ "schemastery": "^3.18.0" }, "devDependencies": { + "@deepseek-ai/dsh-timeout": "workspace:^", "@deepseek-ai/dsh-web": "workspace:^", "cordis": "^4.0.0-rc.6" } diff --git a/packages/web/web-fetch-local/src/provider.ts b/packages/web/web-fetch-local/src/provider.ts index 2175a62770..ed332c4508 100644 --- a/packages/web/web-fetch-local/src/provider.ts +++ b/packages/web/web-fetch-local/src/provider.ts @@ -21,6 +21,7 @@ import { WebError } from '@deepseek-ai/dsh-web' import type { WebFetchBody, WebFetchProvider, WebFetchRequest, WebFetchResult, WebProviderStatus } from '@deepseek-ai/dsh-web' +import { clampTimeout, deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' import { classifyContentType, decoderForCharset, isSameOrigin, parseCharset, validateFetchUrl } from './policy.ts' /** Resolved provider limits (the plugin's schemastery Config supplies defaults). */ @@ -56,35 +57,25 @@ export class LocalFetchProvider implements WebFetchProvider { } async fetch(request: WebFetchRequest, exec?: { readonly signal?: AbortSignal }): Promise { - const timeoutMs = request.timeoutMs !== undefined - ? Math.min(request.timeoutMs, this.limits.maxTimeoutMs) - : this.limits.timeoutMs + if (exec?.signal?.aborted) throw new WebError('web fetch aborted', 'WEB_ABORTED') + const timeoutMs = clampTimeout(request.timeoutMs, this.limits.timeoutMs, this.limits.maxTimeoutMs) - // One controller drives both the caller's abort and our own timeout, so the - // network request and the streaming read both stop on either. - const controller = new AbortController() - const onAbort = (): void => { controller.abort() } - if (exec?.signal !== undefined) { - if (exec.signal.aborted) throw new WebError('web fetch aborted', 'WEB_ABORTED') - exec.signal.addEventListener('abort', onAbort, { once: true }) - } - const timer = setTimeout(() => { controller.abort(new WebError('web fetch timed out', 'WEB_FETCH_TIMEOUT')) }, timeoutMs) - - try { - return await this.followAndRead(request.url, controller) - } finally { - clearTimeout(timer) - if (exec?.signal !== undefined) exec.signal.removeEventListener('abort', onAbort) - } + // One deadline signal fuses the caller's abort with our own timeout, so the + // network request and the streaming read both stop on either. The timeout + // abort carries a TimeoutReason we recover afterward to classify the cause + // (translateAbortOrNetwork), instead of hand-rolling a controller + timer + + // reason-recovery dance. + using d = deadline(exec?.signal, timeoutMs, 'WEB_FETCH_TIMEOUT') + return await this.followAndRead(request.url, d.signal) } /** Follow same-origin redirects up to the hop cap, then read the final response. */ - private async followAndRead(initialUrl: string, controller: AbortController): Promise { + private async followAndRead(initialUrl: string, signal: AbortSignal): Promise { let currentUrl = validateFetchUrl(initialUrl, this.limits.maxUrlLength) let redirectsFollowed = 0 for (;;) { - const response = await this.requestOnce(currentUrl, controller) + const response = await this.requestOnce(currentUrl, signal) if (isRedirectStatus(response.status)) { // The redirect budget is enforced BEFORE this hop's target is resolved @@ -127,20 +118,20 @@ export class LocalFetchProvider implements WebFetchProvider { continue } - return await this.readBody(response, currentUrl, controller.signal) + return await this.readBody(response, currentUrl, signal) } } - private async requestOnce(url: URL, controller: AbortController): Promise { + private async requestOnce(url: URL, signal: AbortSignal): Promise { try { return await fetch(url, { method: 'GET', redirect: 'manual', headers: { 'user-agent': this.limits.userAgent, 'accept': 'text/html,application/xhtml+xml,text/*;q=0.9,application/json;q=0.8' }, - signal: controller.signal, + signal, }) } catch (error: unknown) { - throw translateAbortOrNetwork(error, controller.signal) + throw translateAbortOrNetwork(error, signal) } } @@ -255,24 +246,18 @@ function resolveRedirect(location: string, base: URL): URL { } /** - * Translate a thrown fetch/stream error into a `WebError`. Our own - * `WEB_FETCH_TIMEOUT` (passed to `controller.abort(reason)`) and any other - * already-typed `WebError` pass through; an `AbortError` becomes `WEB_ABORTED`, - * UNLESS the abort was our timeout — the body-read reader surfaces a generic - * `AbortError` rather than the abort reason, so we recover the timeout's - * `WebError` from `signal.reason`; anything else is a transport/network failure - * (`WEB_PROVIDER_ERROR`). + * Translate a thrown fetch/stream error into a `WebError`, classified by the + * deadline signal rather than the error's shape (which differs by phase: the + * request-phase `fetch` rejects with the abort reason, while the read-phase + * reader surfaces a bare `AbortError`). `timeoutOf(signal, 'WEB_FETCH_TIMEOUT')` + * recovering OUR reason means our timeout fired (`WEB_FETCH_TIMEOUT`); any other + * abort — an upstream cancel, or a foreign/outer deadline's timeout under + * nesting — is `WEB_ABORTED`; a throw with the signal NOT aborted is a + * transport/network failure (`WEB_PROVIDER_ERROR`). */ -function translateAbortOrNetwork(error: unknown, signal?: AbortSignal): WebError { - if (error instanceof WebError) return error - if (error instanceof DOMException && error.name === 'AbortError') { - // A timeout abort carries its WebError as the signal reason; honor the - // WEB_FETCH_TIMEOUT contract instead of reporting a generic cancellation. - // (Node rejects WITH the reason — the WebError branch above — so this only - // fires on a runtime that surfaces a bare AbortError while reason is set.) - /* v8 ignore next */ - if (signal?.reason instanceof WebError) return signal.reason - return new WebError('web fetch aborted', 'WEB_ABORTED', { cause: error }) - } +function translateAbortOrNetwork(error: unknown, signal: AbortSignal): WebError { + const timeout = timeoutOf(signal, 'WEB_FETCH_TIMEOUT') + if (timeout !== undefined) return new WebError('web fetch timed out', 'WEB_FETCH_TIMEOUT', { cause: timeout }) + if (signal.aborted) return new WebError('web fetch aborted', 'WEB_ABORTED', { cause: error }) return new WebError(`web fetch failed: ${String(error)}`, 'WEB_PROVIDER_ERROR', { cause: error }) } diff --git a/packages/web/web-fetch-local/tsconfig.json b/packages/web/web-fetch-local/tsconfig.json index aa7c949fec..c6fb75a5c1 100644 --- a/packages/web/web-fetch-local/tsconfig.json +++ b/packages/web/web-fetch-local/tsconfig.json @@ -17,6 +17,9 @@ { "path": "../../../vendor/schemastery" }, + { + "path": "../../util/timeout" + }, { "path": "../web" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 196191201e..a32a70d33b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -93,6 +93,9 @@ importers: '@deepseek-ai/dsh-bash': specifier: workspace:^ version: link:../bash + '@deepseek-ai/dsh-timeout': + specifier: workspace:^ + version: link:../../util/timeout cordis: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) @@ -133,6 +136,19 @@ importers: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/code-runtime/code-runtime-worker: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + devDependencies: + '@deepseek-ai/dsh-code-runtime': + specifier: workspace:^ + version: link:../code-runtime + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/compact/compact: devDependencies: '@deepseek-ai/dsh-llm': @@ -175,6 +191,43 @@ importers: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/cordis/tool-cordis: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + devDependencies: + '@cordisjs/plugin-loader': + specifier: ^1.0.0-rc.4 + version: 1.0.0-rc.4(cordis@4.0.0-rc.6) + '@cordisjs/plugin-timer': + specifier: workspace:^ + version: link:../../../vendor/timer + '@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-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-scope': + specifier: workspace:^ + version: link:../../core/scope + '@deepseek-ai/dsh-session': + specifier: workspace:^ + version: link:../../core/session + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/core/agent: devDependencies: '@deepseek-ai/dsh-brand': @@ -408,6 +461,34 @@ importers: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/guard/repeat-tool-guard: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + devDependencies: + '@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-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-session': + specifier: workspace:^ + version: link:../../core/session + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/hooks/hook-protocol: devDependencies: '@deepseek-ai/dsh-bash': @@ -852,6 +933,21 @@ importers: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/timeout/timeout-policy: + devDependencies: + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-timeout': + specifier: workspace:^ + version: link:../../util/timeout + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/todo/tool-todo: devDependencies: '@deepseek-ai/dsh-agent': @@ -918,6 +1014,9 @@ importers: '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt + '@deepseek-ai/dsh-tool-ask-user': + specifier: workspace:^ + version: link:../tool-ask-user '@deepseek-ai/dsh-tool-bash': specifier: workspace:^ version: link:../../bash/tool-bash @@ -930,6 +1029,9 @@ importers: '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools + '@deepseek-ai/dsh-user-interaction': + specifier: workspace:^ + version: link:../user-interaction cordis: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) @@ -957,6 +1059,9 @@ importers: '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt + '@deepseek-ai/dsh-user-interaction': + specifier: workspace:^ + version: link:../user-interaction cordis: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@vendor+include)(@cordisjs/plugin-loader@vendor+loader) @@ -1008,6 +1113,12 @@ importers: '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt + '@deepseek-ai/dsh-tool-ask-user': + specifier: workspace:^ + version: link:../tool-ask-user + '@deepseek-ai/dsh-user-interaction': + specifier: workspace:^ + version: link:../user-interaction cordis: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@vendor+include)(@cordisjs/plugin-loader@vendor+loader) @@ -1015,12 +1126,51 @@ importers: specifier: ^3.17.0 version: 3.18.0 + packages/ui/tool-ask-user: + devDependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + '@deepseek-ai/dsh-user-interaction': + specifier: workspace:^ + version: link:../user-interaction + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + + packages/ui/user-interaction: + devDependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/util/brand: devDependencies: cordis: specifier: ^4.0.0-rc.6 version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/util/timeout: + devDependencies: + cordis: + specifier: ^4.0.0-rc.6 + version: 4.0.0-rc.6(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.4) + packages/web/tool-web: dependencies: schemastery: @@ -1039,6 +1189,9 @@ importers: '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt + '@deepseek-ai/dsh-timeout-policy': + specifier: workspace:^ + version: link:../../timeout/timeout-policy '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools @@ -1074,6 +1227,9 @@ importers: specifier: ^3.18.0 version: 3.18.0 devDependencies: + '@deepseek-ai/dsh-timeout': + specifier: workspace:^ + version: link:../../util/timeout '@deepseek-ai/dsh-web': specifier: workspace:^ version: link:../web diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index f579169ab0..4d7d0802c7 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -105,11 +105,26 @@ const dshBinPackageFiles = [ 'src', ] as const +// Packages that ship a worker-thread entry as a sibling runtime bundle +// (lib/worker.js, its own tsdown entry): the bootstrap is loaded via +// `new Worker(new URL('./worker.js', import.meta.url))`, so it cannot live +// inside the index bundle and must be published alongside it. +const workerEntryPackages = new Set(['@deepseek-ai/dsh-code-runtime-worker']) + +const dshWorkerPackageFiles = [ + 'lib/index.js', + 'lib/worker.js', + 'lib/types/**/*.d.ts', + 'lib/types/**/*.d.ts.map', + 'src', +] as const + function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean { return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index]) } function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] { + if (manifest.name && workerEntryPackages.has(manifest.name)) return dshWorkerPackageFiles return manifest.bin ? dshBinPackageFiles : dshPackageFiles } diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 33217097b2..e1cea8a2b7 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -1,11 +1,11 @@ { - "AGENTS.md": 1691, + "AGENTS.md": 1802, "docs/AGENTS.md": 1315, "docs/architecture.md": 1790, "docs/cordis-primer.md": 550, "docs/defensive-patterns.md": 550, "docs/testing.md": 800, - "examples/AGENTS.md": 610, + "examples/AGENTS.md": 653, "packages/AGENTS.md": 450, - "packages/README.md": 605 + "packages/README.md": 660 } diff --git a/scripts/gen-cordis-api.ts b/scripts/gen-cordis-api.ts new file mode 100644 index 0000000000..34583d2ead --- /dev/null +++ b/scripts/gen-cordis-api.ts @@ -0,0 +1,247 @@ +/** + * Generate (and verify) the runtime cordis API catalog the `cordis_inspect` + * tool serves to the model: packages/cordis/tool-cordis/src/api-catalog.ts. + * + * The artifact is the machine-readable sibling of docs/cordis-catalog: it + * reuses `collectServices` / `collectEvents` from `gen-cordis-catalog.ts` (the + * same JSDoc-completeness-enforcing AST walk), so the API the model reads at + * runtime and the API the docs render cannot diverge. Emitted as a typed + * TypeScript data module (not JSON): it compiles under the package tsconfig, + * passes lint and the export-JSDoc gate, and is trivially covered by import. + * + * The data is trimmed for a model-facing text surface: per service the + * `ctx.` name, the first sentence of the class doc, and the raw method + * signatures; per event the name, `@mode`, signature, and first sentence of + * doc; the SHAPES of every exported interface/type-alias the service + * signatures reference (transitively — so a model can see that e.g. a + * `BashRunResult.stdout` is `{ text, truncated }`, not a string); plus the + * curated inherited `ctx` surface shared with the docs catalog. Source + * pointers are dropped (a `file:line` means nothing to the model) and entries + * are sorted deterministically. + * + * `tsx scripts/gen-cordis-api.ts` → write the artifact + * `tsx scripts/gen-cordis-api.ts --check` → exit 1 if the committed file is + * stale (CI / pre-push gate) + */ + +import { globSync, readFileSync, writeFileSync } from 'node:fs' +import { resolve } from 'node:path' +import ts from 'typescript' +import { collectEvents, collectServices, INHERITED_SERVICES } from './gen-cordis-catalog.ts' + +const root = resolve(import.meta.dirname, '..') +const OUT = 'packages/cordis/tool-cordis/src/api-catalog.ts' + +/** Declarations longer than this render as a truncated stub — a shape the model cannot skim teaches nothing. */ +const MAX_DECL_CHARS = 1500 + +/** The first sentence of a (possibly multi-line) JSDoc prose block. */ +function firstSentence(doc: string): string { + const line = doc.split('\n', 1)[0] ?? '' + const match = /^(.*?[.!?])(?:\s|$)/.exec(line) + return (match?.[1] ?? line).trim() +} + +/** Render a string as a single-quoted, lint-clean TS literal. */ +function quote(value: string): string { + return `'${value.replace(/\\/g, '\\\\').replace(/'/g, '\\\'').replace(/\n/g, '\\n')}'` +} + +/** + * Every exported `interface` / `type` declaration under `packages///src`, + * printed without comments, keyed by name. A name declared in more than one + * package (e.g. each plugin's `Config`) is ambiguous and dropped entirely — + * serving the wrong package's shape is worse than serving none. + */ +function collectTypeDecls(scanRoot: string = root): Map { + const printer = ts.createPrinter({ removeComments: true }) + const decls = new Map() + const ambiguous = new Set() + for (const rel of globSync('packages/*/*/src/*.ts', { cwd: scanRoot }).sort()) { + const abs = resolve(scanRoot, rel) + const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true) + for (const stmt of sf.statements) { + if (!ts.isInterfaceDeclaration(stmt) && !ts.isTypeAliasDeclaration(stmt)) continue + if (!(stmt.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)) continue + const name = stmt.name.text + if (decls.has(name)) { + ambiguous.add(name) + continue + } + const printed = printer.printNode(ts.EmitHint.Unspecified, stmt, sf).replace(/\r/g, '') + decls.set(name, printed.length > MAX_DECL_CHARS + ? `${printed.slice(0, MAX_DECL_CHARS)} /* …truncated — full shape in source */` + : printed) + } + } + for (const name of ambiguous) decls.delete(name) + return decls +} + +/** + * The transitive closure of type names referenced by the seed texts: every + * collected declaration whose name appears (word-bounded) in a seed or in an + * already-included declaration, sorted by name. + */ +function referencedTypes(seeds: string[], decls: Map): { name: string; declaration: string }[] { + const included = new Map() + let frontier = seeds + while (frontier.length > 0) { + const next: string[] = [] + for (const [name, declaration] of decls) { + if (included.has(name)) continue + const pattern = new RegExp(`\\b${name}\\b`) + if (frontier.some(text => pattern.test(text))) { + included.set(name, declaration) + next.push(declaration) + } + } + frontier = next + } + return [...included].map(([name, declaration]) => ({ name, declaration })).sort((a, b) => a.name.localeCompare(b.name)) +} + +/** Render the whole generated module (pure, deterministic given sorted collector output). */ +function render(): string { + const services = collectServices() + const events = collectEvents().sort((a, b) => a.name.localeCompare(b.name)) + const types = referencedTypes(services.flatMap(service => service.methods), collectTypeDecls()) + const lines: string[] = [ + '/**', + ' * Generated by scripts/gen-cordis-api.ts — do not edit by hand; run', + ' * `pnpm run gen-cordis-api` to regenerate (freshness-gated by', + ' * `pnpm run verify-cordis-api` in doc-sync).', + ' *', + ' * The machine-readable cordis API catalog `cordis_inspect` serves to the', + ' * model: harness services (summary + public method signatures), harness', + ' * events (mode + signature), and the inherited `ctx` surface. Produced by', + ' * the same AST walk as docs/cordis-catalog, so this data and the rendered', + ' * docs cannot diverge.', + ' *', + ' * @module @deepseek-ai/dsh-tool-cordis/api-catalog', + ' */', + '', + '/** One harness `ctx.` service: its one-line summary and public method signatures. */', + 'export interface ServiceApiEntry {', + ' /** The `ctx.` name, e.g. `tools`. */', + ' key: string', + ' /** First sentence of the service class JSDoc. */', + ' summary: string', + ' /** Public method signatures, bodies stripped, in source order. */', + ' methods: readonly string[]', + '}', + '', + '/** One harness event: its dispatch mode, exact signature, and one-line summary. */', + 'export interface EventApiEntry {', + ' /** The scoped event name, e.g. `agent/status`. */', + ' name: string', + ' /** The dispatch mode from the declaration\'s `@mode` tag. */', + ' mode: string', + ' /** The exact listener signature, whitespace-normalized. */', + ' signature: string', + ' /** First sentence of the event JSDoc. */', + ' summary: string', + '}', + '', + '/** One inherited (cordis core + loader/hmr/timer) `ctx` member group with its summary. */', + 'export interface InheritedApiEntry {', + ' /** The `ctx` member name(s), e.g. `ctx.on / ctx.once`. */', + ' name: string', + ' /** One-line summary of what the member does. */', + ' summary: string', + '}', + '', + '/** One named type shape the service signatures reference. */', + 'export interface TypeApiEntry {', + ' /** The exported type/interface name, e.g. `BashRunResult`. */', + ' name: string', + ' /** The full declaration text, comments stripped. */', + ' declaration: string', + '}', + '', + '/** Every harness `ctx.` service, sorted by key. */', + 'export const SERVICE_API: readonly ServiceApiEntry[] = [', + ] + for (const service of services) { + lines.push(' {') + lines.push(` key: ${quote(service.key)},`) + lines.push(` summary: ${quote(firstSentence(service.doc))},`) + if (service.methods.length === 0) { + lines.push(' methods: [],') + } else { + lines.push(' methods: [') + for (const method of service.methods) lines.push(` ${quote(method)},`) + lines.push(' ],') + } + lines.push(' },') + } + lines.push( + ']', + '', + '/** Every harness event, sorted by name. */', + 'export const EVENT_API: readonly EventApiEntry[] = [', + ) + for (const event of events) { + lines.push(' {') + lines.push(` name: ${quote(event.name)},`) + lines.push(` mode: ${quote(event.mode)},`) + lines.push(` signature: ${quote(event.signature)},`) + lines.push(` summary: ${quote(firstSentence(event.doc))},`) + lines.push(' },') + } + lines.push( + ']', + '', + '/** Shapes of every exported type the SERVICE_API signatures reference (transitively), sorted by name. */', + 'export const TYPE_API: readonly TypeApiEntry[] = [', + ) + for (const type of types) { + lines.push(' {') + lines.push(` name: ${quote(type.name)},`) + lines.push(` declaration: ${quote(type.declaration)},`) + lines.push(' },') + } + lines.push( + ']', + '', + '/** The inherited `ctx` surface (cordis core + loader/hmr/timer), in curated order. */', + 'export const INHERITED_CTX_API: readonly InheritedApiEntry[] = [', + ) + for (const inherited of INHERITED_SERVICES) { + lines.push(` { name: ${quote(inherited.name)}, summary: ${quote(inherited.summary)} },`) + } + lines.push(']', '') + return lines.join('\n') +} + +/** CLI entry: default writes the artifact, `--check` fails if the committed + * copy is stale. Guarded behind an entry-point check so importing this module + * for tests neither regenerates the committed file nor calls process.exit. */ +function main(): void { + const content = render() + if (process.argv.includes('--check')) { + let committed: string | null = null + try { + committed = readFileSync(resolve(root, OUT), 'utf8') + } catch { + // Only ENOENT (not yet generated) is expected; a present-but-unreadable + // file is not a state this repo produces. Either way the remedy is the + // same — regenerate — so treat a read failure as "stale". + committed = null + } + if (committed === content) { + console.log(`gen-cordis-api: ${OUT} is up to date.`) + process.exit(0) + } + console.error(`gen-cordis-api: ${OUT} is stale. Run \`pnpm run gen-cordis-api\` and commit ${OUT}.`) + process.exit(1) + } + + writeFileSync(resolve(root, OUT), content) + console.log(`gen-cordis-api: wrote ${OUT}.`) +} + +// Run only when invoked as a script, not when imported by a test. +if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) { + main() +} diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 6220006ede..9b8141807e 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -327,7 +327,7 @@ const INHERITED_EVENTS: InheritedEntry[] = [ { name: 'loader/patch-context', summary: 'A context is being patched during a reload.', source: 'vendor/loader/src/index.ts:27' }, ] -const INHERITED_SERVICES: InheritedEntry[] = [ +export const INHERITED_SERVICES: InheritedEntry[] = [ { name: 'ctx.on / ctx.once', summary: 'Register an event listener (disposable).', source: 'vendor/cordis/src/events.ts:29' }, { name: 'ctx.emit / ctx.parallel / ctx.serial / ctx.bail / ctx.waterfall', summary: 'Dispatch an event (sync / awaited / first-bail / veto-chain).', source: 'vendor/cordis/src/events.ts:29' }, { name: 'ctx.plugin / ctx.inject', summary: 'Load a plugin / declare required services.', source: 'vendor/cordis/src/registry.ts:144' }, diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index a61bfca763..fa717e80af 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -75,6 +75,7 @@ const GROUP_ORDER = [ 'subagent', 'web', 'todo', + 'cordis', 'hooks', 'session-persistence', 'support', @@ -121,9 +122,18 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'tools', title: 'Tool registry and execution waterfall', mode: 'core', - consumers: ['agent-loop', 'tool-bash', 'tool-fs', 'tool-subagent', 'tool-todo', 'tool-web', 'acp'], + consumers: ['agent-loop', 'tool-ask-user', 'tool-bash', 'tool-cordis', 'tool-fs', 'tool-subagent', 'tool-todo', 'tool-web', 'acp'], note: 'Registers tool definitions, exposes schemas to the prompt, and routes calls through tools/pre-execute and tools/post-execute.', }, + { + key: 'userInteraction', + pkg: 'user-interaction', + title: 'Human question/answer seam', + mode: 'seam', + implementations: ['stdio-agent', 'acp'], + consumers: ['tool-ask-user', 'stdio-agent', 'acp'], + note: 'UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise.', + }, { key: 'agents', pkg: 'agent', @@ -154,7 +164,7 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'code-runtime', title: 'Code-execution seam', mode: 'seam', - implementations: [], + implementations: ['code-runtime-worker'], consumers: [], note: 'Runs one model-written program against host-provided async bindings; backends differ by substrate and language (the Code Mode RFC specifies the worker-thread backend and the tool-registry consumer).', }, @@ -413,6 +423,14 @@ const APP_EXAMPLES = [ config: 'examples/coding-agent/cordis.yml', summary: 'The coding REPL demo adds the real DeepSeek adapter, filesystem tools, todo_write, compaction, and both subagent transports on top of the stdio app package.', }, + { + id: 'cordis', + rel: 'examples/cordis-agent/composition.md', + title: 'Cordis Agent App Composition', + label: 'examples/cordis-agent', + config: 'examples/cordis-agent/cordis.yml', + summary: 'The self-referential demo puts @deepseek-ai/dsh-tool-cordis on the coding spine, letting the agent inspect its own runtime and mount/unmount plugins into it.', + }, { id: 'acp', rel: 'examples/acp-agent/composition.md', @@ -670,7 +688,7 @@ function renderToolPipeline(): string { const maintenance = 'curated Mermaid flow; exact tool schemas and event signatures live in generated catalogs' return [ ...generatedHeader('Tool Execution Pipeline'), - 'This graph shows where policy, hooks, sandboxing, filesystem guards, result rewriting, and UI rendering fit without changing the loop. The key extension points are the `tools/pre-execute` and `tools/post-execute` waterfalls.', + 'This graph shows where policy, hooks, sandboxing, filesystem guards, result rewriting, and UI rendering fit without changing the loop. The key extension points are the `tools/pre-execute`, `tools/execute`, and `tools/post-execute` waterfalls.', '', '```mermaid', 'flowchart TD', @@ -679,6 +697,7 @@ function renderToolPipeline(): string { ' presentCall["UI pending card
presentCall(args)"]', ` pre["${mermaidCode('tools/pre-execute')} waterfall
hooks, permission, sandbox"]`, ' denied["deny or ask
tool body skipped"]', + ` around["${mermaidCode('tools/execute')} waterfall
timeout, retry, metrics (around dispatch)"]`, ' toolBody["Registered tool execute() body"]', ` fsGate["${mermaidCode('fs/write-intent')} or ${mermaidCode('fs/edit-intent')}
tool-fs mutations only"]`, ` owned["Tool-owned session events
${mermaidCode('todo/write')}, ${mermaidCode('fs/observed')}, ${mermaidCode('hook/invoked')}, ${mermaidCode('hook/result')}"]`, @@ -689,19 +708,21 @@ function renderToolPipeline(): string { ' model --> toolCall', ' toolCall --> presentCall', ' toolCall --> pre', - ' pre -->|allow| toolBody', + ' pre -->|allow| around', + ' around --> toolBody', ' pre -->|deny or ask| denied', ' denied --> post', ' toolBody --> fsGate', ' fsGate --> toolBody', ' toolBody --> owned', - ' toolBody --> post', + ' toolBody --> around', + ' around --> post', ' post --> context', ' post --> toolResult', ' toolResult --> presentResult', '```', '', - 'Filesystem read-before-edit checks live below `tool-fs` on the `fs/*` event gate, while hook bridges and future permission prompts live on the generic tool waterfalls. That split lets the same hooks observe bash, fs, web, todo, and subagent calls without coupling those tools to one policy service.', + 'Filesystem read-before-edit checks live below `tool-fs` on the `fs/*` event gate; hook bridges and future permission prompts live on the generic pre/post tool waterfalls; and around-dispatch concerns like the tool-call timeout policy (`@deepseek-ai/dsh-timeout-policy`) wrap core dispatch on `tools/execute`. That split lets the same hooks observe bash, fs, web, todo, and subagent calls without coupling those tools to one policy service.', '', ...maintenanceFooter(maintenance), ].join('\n') @@ -755,6 +776,7 @@ function renderIndex(docs: GraphDoc[]): string { 'docs/capability-seams.md': 'capability seams and core services', 'examples/echo-agent/composition.md': 'echo-agent app composition', 'examples/coding-agent/composition.md': 'coding-agent app composition', + 'examples/cordis-agent/composition.md': 'cordis-agent app composition', 'examples/acp-agent/composition.md': 'acp-agent app composition', 'docs/event-producer-consumer.md': 'event producer/consumer matrix', 'docs/agent-lifecycle.md': 'agent turn and step lifecycle', @@ -765,6 +787,7 @@ function renderIndex(docs: GraphDoc[]): string { 'docs/capability-seams.md': 'hybrid generated', 'examples/echo-agent/composition.md': 'hybrid generated', 'examples/coding-agent/composition.md': 'hybrid generated', + 'examples/cordis-agent/composition.md': 'hybrid generated', 'examples/acp-agent/composition.md': 'hybrid generated', 'docs/event-producer-consumer.md': 'hybrid generated', 'docs/agent-lifecycle.md': 'curated', diff --git a/scripts/gen-module-graph.ts b/scripts/gen-module-graph.ts index b84701c819..dc66dc843e 100644 --- a/scripts/gen-module-graph.ts +++ b/scripts/gen-module-graph.ts @@ -45,7 +45,9 @@ const GROUP_ORDER = [ 'compact', 'subagent', 'web', + 'timeout', 'todo', + 'cordis', 'hooks', 'session-persistence', 'support', diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 24739e1388..c261f69834 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -41,12 +41,15 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry from '@deepseek-ai/dsh-tools' import LocalBashExecutor from '@deepseek-ai/dsh-bash-local' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' import WebService from '@deepseek-ai/dsh-web' import * as WebSearchExa from '@deepseek-ai/dsh-web-search-exa' import * as WebFetchLocal from '@deepseek-ai/dsh-web-fetch-local' import SubagentService from '@deepseek-ai/dsh-subagent' import * as SubagentMock from '@deepseek-ai/dsh-subagent-mock' +import * as ToolAskUser from '@deepseek-ai/dsh-tool-ask-user' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' +import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis' import * as ToolFs from '@deepseek-ai/dsh-tool-fs' import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent' @@ -100,6 +103,19 @@ interface ToolPackage { * guard proves it is exhaustive against the on-disk glob. */ const TOOL_PACKAGES: ToolPackage[] = [ + { + pkg: '@deepseek-ai/dsh-tool-ask-user', + dir: 'tool-ask-user', + source: 'packages/ui/tool-ask-user/src/index.ts', + requires: ['ctx.tools', 'ctx.userInteraction'], + writes: ['tool/call', 'tool/result after a UI/provider answers the question'], + async mount(ctx) { + await ctx.plugin(UserInteractionService) + await ctx.plugin(ToolAskUser) + }, + note: + 'ask_user_question pauses the tool call until the active UI provider returns a human answer.', + }, { pkg: '@deepseek-ai/dsh-tool-bash', dir: 'tool-bash', @@ -113,6 +129,18 @@ const TOOL_PACKAGES: ToolPackage[] = [ note: 'The bash/bash_output/bash_kill tools are model-facing consumers of the bash executor seam.', }, + { + pkg: '@deepseek-ai/dsh-tool-cordis', + dir: 'tool-cordis', + source: 'packages/cordis/tool-cordis/src/index.ts', + requires: ['ctx.tools'], + writes: ['tool/call', 'tool/result', 'live plugin-tree mutations (mount/unmount)'], + async mount(ctx) { + await ctx.plugin(ToolCordis) + }, + note: + 'Ships in examples/cordis-agent only (a deliberate opt-in — mounted code gets the real ctx, see docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins the model mounts may register ADDITIONAL model-visible tools at runtime; the request-header ToolsDelta logs those tool-set changes.', + }, { pkg: '@deepseek-ai/dsh-tool-fs', dir: 'tool-fs', diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 51b634267e..1c62de0851 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -311,6 +311,7 @@ function builtBinSmokeGate(): Gate { 'vitest.e2e.config.ts', 'packages/ui/stdio-agent/tests/built-bin.e2e.ts', 'packages/ui/acp-agent/tests/built-bin.e2e.ts', + 'packages/code-runtime/code-runtime-worker/tests/built-lib.e2e.ts', ], { label: 'built-bin smoke', needs: ['build'], diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 613280ee1b..2d498e8b64 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -48,6 +48,14 @@ { "doc": "docs/core-data-structures/tools.md", "symbol": "StructuredSchemaNode", "source": "packages/core/tools/src/json-schema.ts" }, { "doc": "docs/core-data-structures/tools.md", "symbol": "StructuredOutputSchema", "source": "packages/core/tools/src/json-schema.ts" }, + { "doc": "docs/core-data-structures/user-interaction.md", "symbol": "AskUserQuestionOption", "source": "packages/ui/user-interaction/src/index.ts" }, + { "doc": "docs/core-data-structures/user-interaction.md", "symbol": "AskUserQuestionItem", "source": "packages/ui/user-interaction/src/index.ts" }, + { "doc": "docs/core-data-structures/user-interaction.md", "symbol": "AskUserQuestionRequest", "source": "packages/ui/user-interaction/src/index.ts" }, + { "doc": "docs/core-data-structures/user-interaction.md", "symbol": "AskUserQuestionAnswerItem", "source": "packages/ui/user-interaction/src/index.ts" }, + { "doc": "docs/core-data-structures/user-interaction.md", "symbol": "AskUserQuestionAnswer", "source": "packages/ui/user-interaction/src/index.ts" }, + { "doc": "docs/core-data-structures/user-interaction.md", "symbol": "UserInteractionProvider", "source": "packages/ui/user-interaction/src/index.ts" }, + { "doc": "docs/core-data-structures/user-interaction.md", "symbol": "UserInteractionError", "source": "packages/ui/user-interaction/src/index.ts" }, + { "doc": "docs/core-data-structures/bash.md", "symbol": "BashExecRequest", "source": "packages/bash/bash/src/types.ts" }, { "doc": "docs/core-data-structures/bash.md", "symbol": "BashExecSpec", "source": "packages/bash/bash/src/types.ts" }, { "doc": "docs/core-data-structures/bash.md", "symbol": "BashRunResult", "source": "packages/bash/bash/src/types.ts" }, diff --git a/tsconfig.base.json b/tsconfig.base.json index ea1d804ba5..b4a4e116d8 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -46,9 +46,12 @@ "./packages/code-runtime/*/src", "./packages/fs/*/src", "./packages/compact/*/src", + "./packages/guard/*/src", "./packages/subagent/*/src", "./packages/web/*/src", + "./packages/timeout/*/src", "./packages/todo/*/src", + "./packages/cordis/*/src", "./packages/hooks/*/src", "./packages/session-persistence/*/src", "./packages/ui/*/src", diff --git a/tsconfig.build.json b/tsconfig.build.json index b2cb30885d..882b590009 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -11,6 +11,7 @@ { "path": "./vendor/hmr" }, { "path": "./vendor/logger-console" }, { "path": "./packages/util/brand" }, + { "path": "./packages/util/timeout" }, { "path": "./packages/llm/llm" }, { "path": "./packages/core/session" }, { "path": "./packages/core/scope" }, @@ -19,11 +20,14 @@ { "path": "./packages/session-persistence/session-persistence-sqlite" }, { "path": "./packages/core/system-prompt" }, { "path": "./packages/core/agent" }, + { "path": "./packages/ui/user-interaction" }, { "path": "./packages/core/tools" }, + { "path": "./packages/ui/tool-ask-user" }, { "path": "./packages/core/agent-loop" }, { "path": "./packages/core/agent-core" }, { "path": "./packages/bash/bash" }, { "path": "./packages/code-runtime/code-runtime" }, + { "path": "./packages/code-runtime/code-runtime-worker" }, { "path": "./packages/compact/compact" }, { "path": "./packages/compact/compact-basic" }, { "path": "./packages/llm/llm-deepseek" }, @@ -40,6 +44,7 @@ { "path": "./packages/web/web-search-deepseek" }, { "path": "./packages/web/web-fetch-local" }, { "path": "./packages/web/tool-web" }, + { "path": "./packages/timeout/timeout-policy" }, { "path": "./packages/support/invariants" }, { "path": "./packages/ui/acp" }, { "path": "./packages/ui/acp-agent" }, @@ -55,6 +60,8 @@ { "path": "./packages/subagent/subagent-fork" }, { "path": "./packages/subagent/subagent-acp" }, { "path": "./packages/todo/tool-todo" }, + { "path": "./packages/guard/repeat-tool-guard" }, + { "path": "./packages/cordis/tool-cordis" }, { "path": "./packages/hooks/hook-protocol" }, { "path": "./packages/hooks/hooks-claude" }, { "path": "./packages/hooks/hooks-codex" } diff --git a/tsconfig.json b/tsconfig.json index 24e81fac15..64861f47de 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,6 +22,7 @@ { "path": "./vendor/hmr" }, { "path": "./vendor/logger-console" }, { "path": "./packages/util/brand" }, + { "path": "./packages/util/timeout" }, { "path": "./packages/llm/llm" }, { "path": "./packages/core/session" }, { "path": "./packages/core/scope" }, @@ -30,11 +31,14 @@ { "path": "./packages/session-persistence/session-persistence-sqlite" }, { "path": "./packages/core/system-prompt" }, { "path": "./packages/core/agent" }, + { "path": "./packages/ui/user-interaction" }, { "path": "./packages/core/tools" }, + { "path": "./packages/ui/tool-ask-user" }, { "path": "./packages/core/agent-loop" }, { "path": "./packages/core/agent-core" }, { "path": "./packages/bash/bash" }, { "path": "./packages/code-runtime/code-runtime" }, + { "path": "./packages/code-runtime/code-runtime-worker" }, { "path": "./packages/llm/llm-deepseek" }, { "path": "./packages/llm/llm-pi-ai" }, { "path": "./packages/bash/bash-local" }, @@ -51,6 +55,7 @@ { "path": "./packages/web/web-search-deepseek" }, { "path": "./packages/web/web-fetch-local" }, { "path": "./packages/web/tool-web" }, + { "path": "./packages/timeout/timeout-policy" }, { "path": "./packages/support/invariants" }, { "path": "./packages/ui/acp" }, { "path": "./packages/ui/acp-agent" }, @@ -66,6 +71,8 @@ { "path": "./packages/subagent/subagent-fork" }, { "path": "./packages/subagent/subagent-acp" }, { "path": "./packages/todo/tool-todo" }, + { "path": "./packages/guard/repeat-tool-guard" }, + { "path": "./packages/cordis/tool-cordis" }, { "path": "./packages/hooks/hook-protocol" }, { "path": "./packages/hooks/hooks-claude" }, { "path": "./packages/hooks/hooks-codex" } diff --git a/vitest.config.ts b/vitest.config.ts index 4200b5c7f4..11d1454b08 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -31,7 +31,12 @@ export default defineConfig({ // can't import one without booting it, so they are driven by the keyless // Loader-path smoke (a real subprocess) instead of the in-process unit // suite — the same reason `examples/start.ts` sat out of coverage scope. - exclude: ['packages/*/*/src/types.ts', 'packages/*/*/src/bin.ts'], + // `worker.ts` files are the same class as bin.ts: self-executing + // worker-thread entrypoints that only ever run inside a spawned isolate + // the v8 provider cannot observe. They stay thin glue over in-process- + // tested logic (bootstrap.ts) and are pinned by real-worker integration + // tests. + exclude: ['packages/*/*/src/types.ts', 'packages/*/*/src/bin.ts', 'packages/*/*/src/worker.ts'], // 100% or it doesn't merge (docs/testing.md: excessive tests are welcome). // Per-file so a well-covered big file can't subsidize a bare one. // Every v8 ignore comment must carry a reason — see the quality-gates RFC