@linxin666/dsh-liangshen 0.4.15 → 0.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.i18n.yaml CHANGED
@@ -2,5 +2,5 @@
2
2
  # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
3
  # after editing either side, bring the other along and re-record with:
4
4
  # node scripts/verify-docs.mjs --write <dir>
5
- README.md: a68926e6fca13dfe03fdaeceb56e0b85c66e5928
6
- README.zh.md: 43b0bf7271777c24dc35ada07a88d7ad20a114a9
5
+ README.md: b7b445df406c3e0dc02a84c8b1f2009f8873fdd4
6
+ README.zh.md: 2e9e928f90adf09e88860875bc89a1cbea16b9bd
package/README.md CHANGED
@@ -27,13 +27,13 @@ LiangShen mode therefore keeps the whole session on one presentation, chosen by
27
27
 
28
28
  1. `minimal-prompt` narrows every assembled prompt to the persona section — the one-line persona, the mode's standing working discipline (close a repeated hypothesis after two reasoning passes and call an inspection tool instead of speculating; think only about the next concrete operation rather than pre-rehearsing code; emit multiple tool calls concurrently in a single turn for independent inspections; treat shell processes as ephemeral with no directory persistence across calls and use compound commands or explicit workdir for subdirectories; verify against actual tool output during execution; YAGNI and PDCA; no redundant comments), and one appended orientation line, `Your working directory is <cwd>.` read from the session header — so the harness identity, web-surface, tool-guidance, file-reference, and structured-output sections do not reach the model by default; plan mode's `plan:policy` is kept, because that section is the only thing that enforces plan mode (its exit tool stays registered in every mode);
29
29
  2. AGENTS.md-style workspace instructions reach the model through `instructionSource`: by default (`host`) the preset appends no section of its own and leaves the harness's own delivery of those instructions untouched, so they arrive as its user-role messages — one persistent baseline plus incremental additions, replacements, and removals as directories are touched; under `system-prompt` they join the system prompt itself: at assembly time `minimal-prompt` reads the harness's baseline chain (`$DSH_HOME/AGENTS.md`, then `AGENTS.md` / `CLAUDE.md` and their `.local` overlays from the project root down to the session cwd) and appends the content as one `workspace-instructions` section after the stable prefix, under a byte budget that omits broadest files first and truncates the most specific last; the read happens on every assembly, so file edits propagate without durable messages, and the harness's own agent-instructions injections are dropped instead of duplicating the prompt. Subdirectory dynamic rules will subsequently support registered file tools (including `str_replace_editor`) and `run_code` sub-calls reaching target directories; arbitrary bash or program code is not parsed, and automatic discovery of file accesses performed directly within shell commands is not guaranteed;
30
- 3. the wire keeps one presentation for the entire session, selected by `presentation`: `ptc` (the default) collapses the wire to `run_code` with every other tool reached through the generated SDK, and `native` carries the assembled native roster; `ptc` needs a mounted code runtime — without one the plugin declares no presentation at all and the session simply runs the native surface. The legacy `ptcPresentation` key maps onto `ptc`/`native` with a deprecation warning, and the retired `anchorTools` first-turn narrowing no longer engages — setting it warns;
30
+ 3. the wire keeps one presentation for the entire session, selected by `presentation`: `ptc` (the default) collapses the wire to `run_code` with every other tool reached through the generated SDK, and `native` carries the assembled native roster; `ptc` needs a mounted code runtime — without one no PTC executor can be mounted, so the session simply runs the native surface. The legacy `ptcPresentation` key maps onto `ptc`/`native` with a deprecation warning, and the retired `anchorTools` first-turn narrowing no longer engages — setting it warns;
31
31
  4. `tool-catalog` appends the tool list as a durable user message after the user's message, preserving complete input and output key parameter semantics (`descriptionMaxLength: 200` caps only the one-line summaries). The plugin carries a hand-written one-line summary for each host builtin this preset mounts: a curated tool renders that line whole, so a length cut never slices off the sentence that says what the tool is for, and `descriptionMaxLength` remains the fallback for every tool the table does not name. It names exactly the tools the current request opens — the native roster, or the SDK-reachable projection under `ptc` — and, under tool paging, adds one-line summaries for the namespaces whose tools are held back. Under `ptc` the summaries name namespaces that are genuinely unreachable — neither listed in the request's `tools:sdk` section nor callable from inside a `run_code` program — until `tool_activate`; It republishes only when that surface changes or the published copy left the visible surface (a compaction, a resume);
32
32
  5. gentle tool paging ships on (`pagedToolPatterns: ['mcp__*']`): matching MCP tools stay off the wire and out of the generated SDK, announced as namespace summaries in the catalog, until the model activates one through `tool_activate({ namespace })` — the namespace returns from the next request on, at most three stay active (a fourth evicts the least recently used back to summary). Activation state is rebuilt from the durable event stream across compactions and resumes;
33
- 6. a minimal working-context line — plan-mode state, active paged namespaces, and in-progress todos — is injected at the tail of the latest message only when its sources are readable, keeping current state inside the model's local attention window; runtime contexts (the sandbox and approval snapshots) and the skill catalog flow as in Standard mode;
33
+ 6. a minimal working-context line — plan-mode state, active paged namespaces, in-progress todos, and the key-fact register — is injected at the tail of the latest message only when its sources are readable, keeping current state inside the model's local attention window; runtime contexts (the sandbox and approval snapshots) and the skill catalog flow as in Standard mode;
34
34
  7. the catalog groups the tools of an activated paged family under a `namespace `<name>` (activated):` heading instead of scattering one server's tools through the alphabetical list, while every non-paged tool keeps its flat entry;
35
35
  8. `maxResidentTokens` (default 8000) estimates the always-on-wire surface and warns once when it is crossed, naming the heaviest tools and `pagedToolPatterns` as the remedy. The threshold was re-estimated for V4.1 (its KV cache is a quarter of V4-Flash's, so the same schema load occupies a quarter of the sparse-index slots and the budget moved from 6000 to 8000), still calibrated above the shipped roster so only real growth trips it. The guard never truncates: silently dropping a tool the session needs would trade a measurable context cost for an unmeasurable capability loss.
36
- 9. a key-fact register (`fact_register`) lets the model pin a hard user constraint, a confirmed decision, or a failed path as one short line; the register is folded from the durable event stream and rides the `[Working Context: ...]` line — the surface that lands inside the guaranteed local attention window every step — as the counter to V4.1's long-session forgetting.
36
+ 9. a key-fact register (`fact_register`) lets the model pin a hard user constraint, a confirmed decision, or a failed path as one short line; the register is folded from the durable event stream and rides the `[Working Context: ...]` line — the surface that lands inside the guaranteed local attention window every step — as the counter to V4.1's long-session forgetting. Both wire shapes feed that one fold: `ptc` records the call as a `tool/ptc-dispatch` (object arguments, own `isError`), `native` as a `tool/call` (JSON-string arguments), and a dispatch that reported an error is never applied.
37
37
 
38
38
  ## Security model
39
39
 
@@ -66,7 +66,7 @@ The preset-local plugins are configured in `agent.cordis.yml`:
66
66
  | `instructionSource` | `host` | Where workspace instructions reach the model. `host` (the default) appends no section of its own and leaves the harness's agent-instructions injection untouched, so the instructions arrive as the harness's own user-role messages: one persistent baseline plus incremental additions, replacements, and removals as directories are touched; `system-prompt` reads the AGENTS.md-style chain at assembly time and appends it to the system prompt (the harness's own injections are dropped); `hint` replaces the first injection with a one-time non-imperative reference-file hint and drops later ones. |
67
67
  | `instructionMaxBytes` | `65536` | Byte budget for the rendered workspace-instructions section, used only in `system-prompt` mode: broadest files are omitted first, the most specific file is truncated last. |
68
68
  | `descriptionMaxLength` | `200` | Cap for one tool's one-line summary in the injected catalog, applied to every tool the curated table does not name. A curated host builtin renders its hand-written line whole. Complete key parameter semantics remain fully preserved. |
69
- | `presentation` | `ptc` | Wire presentation for the whole session. `ptc` (the shipped default) collapses the wire to `run_code` with every other tool reached through the generated SDK; `native` keeps the assembled native roster. The plugin declares the value on each agent scope through `agent.ctx.tools.presentAs` as soon as the scope exists, and the composition mounts the official `@deepseek-ai/dsh-tool-executor-ptc` row for PTC execution. Switching to `native` disables that executor row so the declaration and execution stay in the same mode. A deployment with no PTC runtime, a declined declaration, or a scope that cannot reach the API keeps the native surface and warns once. The removed `both` mode is not accepted: an old profile naming it fails registration, so migrate the key to `ptc` or `native`. |
69
+ | `presentation` | `ptc` | Wire presentation for the whole session. `ptc` (the shipped default) collapses the wire to `run_code` with every other tool reached through the generated SDK; `native` keeps the assembled native roster. The settings overlay writes the value into the composition: the official `@deepseek-ai/dsh-tool-executor-ptc` row stays mounted for `ptc` and is disabled for `native`, so that row IS the wire (0.2.2 retired the per-scope `agent.ctx.tools.presentAs` declaration). A deployment with no PTC runtime keeps the native surface. The removed `both` mode is not accepted: an old profile naming it fails registration, so migrate the key to `ptc` or `native`. |
70
70
  | `pagedToolPatterns` | `['mcp__*']` | Gentle paging ships on: matching MCP tools are held back from the wire and the generated SDK until activated through `tool_activate({ namespace })`. Held-back namespaces appear in the catalog as one-line summaries. At most three paged namespaces stay active at once, rebuilt from the event stream. |
71
71
  | `maxResidentTokens` | `8000` | Estimated-token ceiling for the always-on-wire surface (the serialized schemas at roughly four characters per token), re-estimated for V4.1's compressed KV cache and still calibrated above the shipped roster so it flags real growth rather than the factory configuration. Crossing it warns once, names the heaviest tools, and points at `pagedToolPatterns`; it never truncates the roster. |
72
72
  | `ptcPresentation` | (retired) | Legacy alias: `true` maps to `presentation: 'ptc'` and `false` to `'native'`, both with a deprecation warning. |
@@ -117,7 +117,7 @@ When validating mode behavior and evaluating performance, verification tiers mus
117
117
  | --- | --- | --- |
118
118
  | `enabled` | `true` | Master switch: when false, the preset is not declared and the announcement does not run. |
119
119
  | `announceToAgent` | `false` | Opt-in: when true, a system-prompt section announces the plugin. Off by default so agent system prompts stay clean. |
120
- | `presentation` | `ptc` | Wire presentation of the preset this plugin declares. The value is written into the `tool-catalog` row, whose declaration through `agent.ctx.tools.presentAs` IS the wire: `ptc` collapses it to `run_code`, `native` keeps the assembled roster, and the catalog text describes the surface that declaration produces. A change re-declares the preset as soon as the Host commits it, so the next session picks it up; a session that already started keeps the composition it declared. The removed `both` mode is rejected at registration — migrate an old profile to `ptc` or `native`. |
120
+ | `presentation` | `ptc` | Wire presentation of the preset this plugin declares. The value is written into the `tool-catalog` row and drives the composition: the `@deepseek-ai/dsh-tool-executor-ptc` row it enables IS the wire, so `ptc` collapses it to `run_code` and `native` keeps the roster, and the catalog text describes the surface that composition produces. A change re-declares the preset as soon as the Host commits it, so the next session picks it up; a session that already started keeps the composition it declared. The removed `both` mode is rejected at registration — migrate an old profile to `ptc` or `native`. |
121
121
  | `dispatcher` | `true` | Identity switch: when true (the shipped default), the declared preset appends the dispatcher rules section after the persona — complexity triage (L0/L1 direct, L2 through the full flow), the R0.5 compatibility gate that separates the legacy Agent Teams runtime (spawn_teammate plus team-scoped coordination tools) from the current one (a shared task board over ordinary subagents), an interview before planning on an L2 task, the Lead & Dispatch identity with its three execution topologies (Lead-Core, Hybrid, Fan-out) chosen by coupling against parallel ROI, the R9 plan pipeline (plan mode is the user's switch: inside it the plan is explored, written, and submitted through `exit_plan_mode`; outside it the dispatcher plans and then executes), delegation with layer-by-layer review and acceptance, and task tracking in `todo_write` — then a local English supplement with the interview additions, one rule that keeps the task board a tracking surface rather than a dispatch path, and one that keeps a pinned fact an anchor rather than current state. The block is maintained in this repository: it was re-extracted on 2026-10-18 and re-synced on 2026-11-02 against 0.55.0 and again on 2026-11-03 against 0.56.0 plus that package's unreleased Agent Teams pass (twenty-five anti-patterns; the R1 execution topologies; the Lead & Dispatch identity; R2's Harness 0.2.2 note that an explicit route may still be limited to the parent route; R8 restated against the planned direct execution R1 authorizes; R6's fix-and-reverify duty on a Lead-Core or Hybrid core; R0.5 rewritten for the current built-in team, whose only addition over plain subagents is a shared task board that stays bookkeeping under the R5 brief; R2's three allowlist states; R8's withdrawn empty-allowlist fallback; R6's record-backed re-dispatch count, non-penalized hand_back and UI Before/After evidence gate; R7's per-turn sweep and clause deletion test; R5's [Limits] rule that every cap states what it bounds, in what unit, the cap, and whether it accumulates, plus the [Compact Delta Brief] default; R0's impact-not-effort stop; the standing subagent contract, report protocol and coordinator-only tool list; and R9, adapted so plan mode stays the user's switch—this deployment mounts no enter_plan_mode row, and the dispatcher never asks the user for it); the text is written one decision sentence per rule (upstream's compact register, which took the block from about 35,000 to 24,600 characters while every correction and addition stayed), corrections are applied in place rather than appended as a contradicting second copy, `DISPATCHER_RULES_PROVENANCE` records every correction and every addition along with the upstream commit it came from, `DISPATCHER_RULES_PROVENANCE.omissions` records the two upstream entries this preset deliberately does not carry, because each names a tool it does not mount (the `dispatch_ledger` tool and the `enter_plan_mode`/`leave_plan_mode` rows), and `node tools/check-dispatcher-rules.mjs` reports drift against an installed copy of the origin package. Switching it off returns the session to the bare persona with its working discipline. It is orthogonal to `presentation`: `presentation` decides the tool surface, `dispatcher` decides the identity and the process discipline. |
122
122
 
123
123
  All fields are editable in the web settings surface (plugin config) or through the profile patch (`dsh plugin` / `cordis.patch.yml`). Under the 0.1.7 settings contract a plugin's own Config IS its settings page: the Host serves one form per profile entry (the entry id `liangshen`, or the aggregate's generated `web-ui-liangshen` row) and every field is declared `volatile()`, so a write is committed into the running plugin instead of remounting its row. The preset-shaping presentation field then reaches a session through the declaration: the plugin applies the committed values to the composition rows of `presets/liangshen/agent.cordis.yml` and re-declares the preset, so the settings surface — not the bundled file — is what the operator's sessions actually run. A row or key the composition does not carry is never invented: the overlay only narrows the shipped configuration. A change applies to sessions created after it; a session that already started keeps the composition it declared, because the registry refuses to recompose a started conversation.
@@ -134,7 +134,7 @@ All fields are editable in the web settings surface (plugin config) or through t
134
134
  - Paged tools (default pattern `mcp__*`) stay off the wire until the model activates their namespace through `tool_activate`; at most three paged namespaces are active at once, activating a fourth evicts the least recently used one back to its summary, and activation state is rebuilt from the durable event stream after compactions and resumes. Under `ptc` the page also restricts the scope's tool registry, so an unactivated namespace is unreachable from inside a `run_code` program too;
135
135
  - The working-context line is injected only when its sources (plan-mode state, active paged namespaces, in-progress todos) are readable, and omitted otherwise;
136
136
  - Tool results are pruned once they exceed 4096 characters, keeping a 2048-character head and a 1024-character tail (guarding the sparse-index slots while preserving the error tail and exit code), so oversized outputs do not crowd the context;
137
- - `run_code` needs a mounted PTC runtime (the shipped web and headless compositions mount `@deepseek-ai/dsh-ptc-runtime-node` as the `ptc-runtime` row); without one, `ptc` declares nothing and the session runs the native surface;
137
+ - `run_code` needs a mounted PTC runtime (the shipped web and headless compositions mount `@deepseek-ai/dsh-ptc-runtime-node` as the `ptc-runtime` row); without one no PTC executor can be mounted, so the session runs the native surface;
138
138
  - The spawn delegation row enables child-model selection (`modelSelection: true` with `modelDiscovery: true`), so the settings page's subagent model-selection toggle is honored under this preset: the model sees `provider` / `model` / `reasoning_effort` on `subagent` and the `list_subagent_models` discovery tool, and an explicit route is checked against the Session's allowed list (without a recorded policy the effective route falls back to the parent's); the row also keeps the pre-split spelling `modelSelectionSettings: true`, because the SDK pinned in `devDependencies` reads only that key while the harness checkout this repository runs against no longer declares it, and each generation reads the key it knows while the other stays inert;
139
139
  - Exactly one delegation row in a composition scope may enable discovery. The upstream `modelDiscovery` flag registers `list_subagent_models` under a fixed tool name in the scope the row composes into, and the registry refuses a second registration of that name in one scope, so a second discovery owner fails the whole session instead of adding a second opt-in. The fork row therefore ships without it (as the builtin Standard, PTC, and Cordis presets ship it, which leave the route fields off there too), and the composition test counts the discovery owners structurally;
140
140
  - The `subagent-routes` row is the child-route guard. Once a Session recorded an allowed-route list, every delegation the row polices must resolve to an authorized route: an explicit `provider`/`model` pair on `subagent`, or the caller's own route on `subagent_fork` (and any teammate creator), whose inherited route is checked precisely because the tool cannot choose one. A refusal names the routes that would work; a route named on an inherit-only tool is refused as an override attempt; and a tool mounted without route fields is policed through the route its child would inherit instead of being asked for a pair no call could satisfy. The guard fails open on every fact it cannot read (no recorded policy, no session registry, no registry probe), so a Host that cannot answer keeps the harness's own delegation behavior, and `enabled: false` on the row turns it off entirely;
package/README.zh.md CHANGED
@@ -27,13 +27,13 @@ DeepSeek V4.1 Flash 的后训练直接对齐其原生 DSML 工具调用面,官
27
27
 
28
28
  1. `minimal-prompt` 把每次组装出的提示词收窄到 persona 一段——一行 persona、本模式的固定工作纪律(同一假设的思考推演不超过两轮,缺少事实时立即闭合思考并调用检查工具而非空想;思考只决定下一步具体操作,不预演完整代码实现;多处独立检查或搜索在单轮内并发发射多个工具调用;Shell 为无状态进程,跨调用目录不保留,子目录操作使用复合命令或显式 workdir;正确性一律在执行阶段以工具实际输出验证;YAGNI 与 PDCA;不写冗余注释)、以及一行从会话头读取的方位信息 `Your working directory is <cwd>.`——因此 harness identity、web surface、工具用法、文件引用与结构化输出等 section 默认不会到达模型;plan mode 的 `plan:policy` 保留,因为该 section 是 plan mode 唯一的执行依据(它的退出工具在任何模式下都保持注册);
29
29
  2. AGENTS.md 类工作区指令经 `instructionSource` 送达模型:默认(`host`)下 preset 不追加任何自有段,也不改动宿主自己的送达,工作区指令以宿主的 user 角色消息抵达——一条持久基线,加上触碰目录后的增量、替换与移除;`system-prompt` 下它们直接进入系统提示词本身:组装时 `minimal-prompt` 读取 harness 的基线链(`$DSH_HOME/AGENTS.md`,再从项目根到会话 cwd 沿途的 `AGENTS.md` / `CLAUDE.md` 及其 `.local` 覆盖层),把内容作为一段 `workspace-instructions` 追加在稳定前缀之后,受字节预算约束——放不下时先省略最宽的文件、最后才截断最具体的文件;读取在每次组装时都发生,文件改动无需持久消息即可在下次请求生效,harness 自己的 agent-instructions 注入则被丢弃以免与提示词重复。工作区子目录动态规则后续将支持注册文件工具(含 `str_replace_editor`)及 `run_code` 内子调用触达的目录;不解析任意 bash/program 代码,不保证 shell 自行文件访问的自动发现;
30
- 3. wire 在整个会话中保持由 `presentation` 选定的同一种呈现:`ptc`(出厂默认)把 wire 收拢为 `run_code`、其余工具经生成的 SDK 调用;`native` 携带组装出的原生清单;`ptc` 需要挂载的 code runtime;没有时插件不做声明,会话直接运行原生工具面。旧键 `ptcPresentation` 映射到 `ptc`/`native` 并发出弃用告警,已退役的 `anchorTools` 首回合收窄不再生效——设置它会收到告警;
30
+ 3. wire 在整个会话中保持由 `presentation` 选定的同一种呈现:`ptc`(出厂默认)把 wire 收拢为 `run_code`、其余工具经生成的 SDK 调用;`native` 携带组装出的原生清单;`ptc` 需要挂载的 code runtime;没有时无法挂载 PTC 执行器,会话直接运行原生工具面。旧键 `ptcPresentation` 映射到 `ptc`/`native` 并发出弃用告警,已退役的 `anchorTools` 首回合收窄不再生效——设置它会收到告警;
31
31
  4. `tool-catalog` 把工具清单作为持久 user 消息追加在用户消息之后,保留完整输入输出关键参数语义(`descriptionMaxLength: 200` 仅限制一行摘要长度)。插件为该预设挂载的每个宿主内置工具配有一行手写短描述:被策展的工具直接使用整行策展文,长度截断不会切掉说明工具用途的那句话,`descriptionMaxLength` 只作为未被策展工具的兜底。目录只宣告该次请求实际开放的工具——原生清单,或 `ptc` 下经 SDK 可达的投影——并在分页开启时为被扣留的命名空间附上一行摘要;`ptc` 下这些摘要代表真正不可达的命名空间——既不在该请求的 `tools:sdk` 段中,也不能在 `run_code` 程序内调用——直到 `tool_activate`;只在工具面变化、或已发布副本离开可见面(压缩、恢复)时重发;
32
32
  5. 温和分页出厂开启(`pagedToolPatterns: ['mcp__*']`):匹配的 MCP 工具被扣留在 wire 与生成的 SDK 之外,以命名空间摘要出现在目录中,直到模型经 `tool_activate({ namespace })` 激活——激活的命名空间从下一个请求起重新可达,最多保持三个已激活的分页命名空间(激活第四个时将最久未用的逐回摘要状态)。激活状态从持久事件流重建,压缩与恢复均可还原;
33
- 6. 最小版 working-context 行——plan-mode 状态、已激活的分页命名空间、进行中的 todo——只在其来源可读时注入到最新消息尾部,让当前状态落在模型的局部注意力窗口内;运行时上下文(sandbox 与 approval 快照)与 skill 目录按 Standard 模式正常注入;
33
+ 6. 最小版 working-context 行——plan-mode 状态、已激活的分页命名空间、进行中的 todo、以及关键事实登记簿——只在其来源可读时注入到最新消息尾部,让当前状态落在模型的局部注意力窗口内;运行时上下文(sandbox 与 approval 快照)与 skill 目录按 Standard 模式正常注入;
34
34
  7. 目录把已激活分页家族的工具归在 `namespace `<名称>` (activated):` 标题之下,而不是把一个服务端的工具散落在字母序清单里;未被分页的工具仍保持扁平条目;
35
35
  8. `maxResidentTokens`(默认 8000)估算常驻 wire 面并在超过时告警一次,列出最重的工具并把 `pagedToolPatterns` 指为处置手段。该阈值按 V4.1 的 KV 压缩重新校准(其 KV cache 为 V4-Flash 的 1/4,同样的 schema 负载只占 1/4 的稀疏索引槽位,阈值由 6000 上调至 8000),仍校准在出厂清单之上,用于发现真实增长而非出厂配置本身。该守卫从不截断:静默丢掉会话需要的工具,等于用可度量的上下文成本换取不可度量的能力损失。
36
- 9. 关键事实登记簿(`fact_register`)让模型把用户硬性约束、已确认的架构决策、失败过的路径登记为一行短事实;登记簿从持久事件流折叠,随 `[Working Context: ...]` 行投射——每步都落在保证命中的局部注意力窗口内——以此对抗 V4.1 的长会话遗忘。
36
+ 9. 关键事实登记簿(`fact_register`)让模型把用户硬性约束、已确认的架构决策、失败过的路径登记为一行短事实;登记簿从持久事件流折叠,随 `[Working Context: ...]` 行投射——每步都落在保证命中的局部注意力窗口内——以此对抗 V4.1 的长会话遗忘。两种 wire 形态喂给同一份折叠:`ptc` 下该调用记为 `tool/ptc-dispatch`(对象形态的 arguments、自带的 `isError`),`native` 下记为 `tool/call`(JSON 字符串形态的 arguments),报错的 dispatch 一律不生效。
37
37
 
38
38
  ## 安全模型
39
39
 
@@ -66,7 +66,7 @@ DeepSeek V4.1 Flash 的后训练直接对齐其原生 DSML 工具调用面,官
66
66
  | `instructionSource` | `host` | 工作区指令送达模型的方式。`host`(默认)不追加任何自有段,也不改动宿主的 agent-instructions 注入,工作区指令以宿主自己的 user 角色消息送达:一条持久基线,加上触碰目录后的增量、替换与移除;`system-prompt` 在组装时读取 AGENTS.md 链并追加进系统提示词(harness 自己的注入被丢弃);`hint` 把首次注入替换为一次性的、非命令式的参考文件提示,后续注入丢弃。 |
67
67
  | `instructionMaxBytes` | `65536` | 渲染后的 workspace-instructions 段的字节预算,仅在 `system-prompt` 模式下生效:最宽的文件先被省略,最具体的文件最后被截断。 |
68
68
  | `descriptionMaxLength` | `200` | 注入目录中单个工具一行摘要的长度上限,作用于所有未被策展表覆盖的工具;被策展的宿主内置工具直接使用整行手写短描述。完整关键参数语义保持完整。 |
69
- | `presentation` | `ptc` | 整个会话的 wire 呈现方式。`ptc`(出厂默认)把 wire 收拢为 `run_code`,其余工具经生成的 SDK 调用;`native` 保持组装出的原生清单。插件在 agent scope 一出现时就通过 `agent.ctx.tools.presentAs` 声明该取值,组合同时挂载官方 `@deepseek-ai/dsh-tool-executor-ptc` 行执行 PTC 程序。切换到 `native` 会停用该执行器行,使呈现声明与实际执行保持同一模式。部署没有 PTC runtime、宿主拒绝声明、或 scope 拿不到该 API 时保持原生面并告警一次。已删除的 `both` 取值不被接受:旧 profile 写明它会在注册时被拒绝,请迁移为 `ptc` 或 `native`。 |
69
+ | `presentation` | `ptc` | 整个会话的 wire 呈现方式。`ptc`(出厂默认)把 wire 收拢为 `run_code`,其余工具经生成的 SDK 调用;`native` 保持组装出的原生清单。设置覆盖层把该取值写进组合:`ptc` 时保留官方 `@deepseek-ai/dsh-tool-executor-ptc` 行并借此执行 PTC 程序,`native` 时停用该行——**那一行就是 wire**(0.2.2 已移除按 scope 的 `agent.ctx.tools.presentAs` 声明)。部署没有 PTC runtime 时保持原生面。已删除的 `both` 取值不被接受:旧 profile 写明它会在注册时被拒绝,请迁移为 `ptc` 或 `native`。 |
70
70
  | `pagedToolPatterns` | `['mcp__*']` | 出厂开启温和分页:命中的 MCP 工具被扣留在 wire 与生成的 SDK 之外,直到模型通过 `tool_activate({ namespace })` 激活其命名空间。被扣留的命名空间在目录中以一行摘要出现。最多同时保持三个已激活的分页命名空间,激活状态从持久事件流重建。 |
71
71
  | `maxResidentTokens` | `8000` | 常驻 wire 面的估算 token 上限(按序列化 schema 约四字符一 token),按 V4.1 的 KV 压缩重新校准后仍高于出厂清单,用于发现真实增长而非出厂配置本身。超过时告警一次、列出最重的工具并指向 `pagedToolPatterns`;不会截断工具清单。 |
72
72
  | `ptcPresentation` | (已退役) | 旧别名:`true` 映射为 `presentation: 'ptc'`,`false` 映射为 `'native'`,两者都伴随弃用告警。 |
@@ -117,7 +117,7 @@ dsh plugin --profile web remove @linxin666/dsh-liangshen
117
117
  | --- | --- | --- |
118
118
  | `enabled` | `true` | 总开关:关闭后不声明预设、也不发公告。 |
119
119
  | `announceToAgent` | `false` | 按需开启:开启后向 agent 系统提示注入本插件公告。默认关闭,保持系统提示词干净。 |
120
- | `presentation` | `ptc` | 本插件所声明 preset 的 wire 呈现。取值写进 `tool-catalog` 行,而该行通过 `agent.ctx.tools.presentAs` 的声明**就是** wire:`ptc` 收拢为 `run_code`,`native` 保持组装出的原生清单,目录文本描述的就是该声明产生的面。Host 提交改动后立即重新声明 preset,此后新建的会话即采用新值;已开始的会话保持其已声明的组合。已删除的 `both` 取值在注册时被拒绝——旧 profile 请迁移为 `ptc` 或 `native`。 |
120
+ | `presentation` | `ptc` | 本插件所声明 preset 的 wire 呈现。取值写进 `tool-catalog` 行并驱动组合:它启用的 `@deepseek-ai/dsh-tool-executor-ptc` 行**就是** wire,`ptc` 因此收拢为 `run_code`、`native` 保持原生清单,目录文本描述的就是该组合产生的面。Host 提交改动后立即重新声明 preset,此后新建的会话即采用新值;已开始的会话保持其已声明的组合。已删除的 `both` 取值在注册时被拒绝——旧 profile 请迁移为 `ptc` 或 `native`。 |
121
121
  | `dispatcher` | `true` | 身份开关:开启时(出厂默认)所声明的 preset 在 persona 之后追加调度者规则段——复杂度分诊(L0/L1 直接执行,L2 走完整流程)、区分两代 Agent Teams 的 R0.5 兼容性闸门(legacy 运行期带 spawn_teammate 并顶替协调工具,现行运行期只是在原生子代理之上加一块共享任务板)、L2 任务先澄清访谈再规划、Lead & Dispatch 身份与按「耦合度 × 并行收益」三选一的执行拓扑(Lead-Core / Hybrid / Fan-out)、R9 计划模式管线(计划模式是用户的开关:已经在该模式里就只读探索、写计划、经 `exit_plan_mode` 提交;不在就照常规划后执行,不向用户索要这个模式)、派发子代理并逐层审查与验收,以及落在 `todo_write` 的任务跟踪——其后是本地英文补充:访谈类新增内容,加上让任务看板停在做跟踪的表面、而不是派发路径的那一条,以及让登记的事实保持为锚点、而不是当前状态的那一条。这个块在本仓维护:2026-10-18 重新抽取,2026-11-02 按 0.55.0 同步,2026-11-03 再按 0.56.0 及该包尚未发布的 Agent Teams 改动同步一次(二十五条反模式;R1 的三套执行拓扑;Lead & Dispatch 身份;R2 补上 Harness 0.2.2 起显式路由可能仍受父路由限制;R8 改为相对 R1 授权的计划内直执来定义;R6 补上 Lead-Core / Hybrid 主干上「先修后交付」;R0.5 按现行内置 team 重写——它对原生子代理只多加一块共享任务板,且该任务板始终是 R5 任务书之下的记账面;R2 的 allowlist 三态;R8 被撤回的空 allowlist 兜底;R6 记录化的重派次数、不罚 hand_back、以及界面的 Before/After 证据门;R7 每轮扫描即将升级或过期的项,以及删除测试;R5 的 [Limits] 规则——每个上限都写明它约束什么、单位、上限值、以及是否累计,外加 [Compact Delta Brief] 的精简任务书默认形态;R0 的「按影响而非按工作量停手」;常设子代理契约、报告协议与主控专用工具清单;以及 R9——按「计划模式是用户的开关」做了适配:本部署没有 enter_plan_mode 行,调度者也不主动向用户索要它);行文按上游那套精简写法处理——每条规则一句判定,正文从约 35,000 字符压到 24,600 字符,而每一条更正与新增都保留;更正就地应用,而不是作为一条自相矛盾的第二份副本追加;`DISPATCHER_RULES_PROVENANCE` 逐条记录每一次更正与每一处新增,并带上它来自的上游提交;`DISPATCHER_RULES_PROVENANCE.omissions` 记录本预设有意不带的两条上游内容,它们各自指向本预设没挂的工具(`dispatch_ledger` 工具,以及 `enter_plan_mode` / `leave_plan_mode` 两行);`node tools/check-dispatcher-rules.mjs` 对已安装的来源包报告漂移。关闭后回到仅含工作纪律的极简 persona。它与 `presentation` 正交:`presentation` 决定工具面,`dispatcher` 决定身份与流程纪律。 |
122
122
 
123
123
  各字段都可在 Web 设置界面(插件配置)或 profile patch(`dsh plugin` / `cordis.patch.yml`)中编辑。0.1.7 的设置契约下,插件自身的 Config 就是它的设置页:Host 为每个 profile entry 生成一张表单(entry id 为 `liangshen`,聚合安装下为生成的 `web-ui-liangshen` 行),每个字段都声明为 `volatile()`,因此写入被提交进运行中的插件实例,而不是重挂该行。塑造 preset 的 presentation 字段再经声明抵达会话:插件把已提交的取值应用到 `presets/liangshen/agent.cordis.yml` 的对应行并重新声明 preset,因此真正被会话运行的是设置界面的取值,而不是包内文件。组合里没有的行或键绝不会被凭空写入——覆写只会收窄出厂配置。改动对之后新建的会话生效;已开始的会话保持其已声明的组合,因为 registry 拒绝重组已开始的会话。
@@ -134,7 +134,7 @@ dsh plugin --profile web remove @linxin666/dsh-liangshen
134
134
  - 被分页扣留的工具(出厂模式 `mcp__*`)在模型经 `tool_activate` 激活其命名空间之前不进 wire、也不进生成的 SDK;同时最多三个分页命名空间保持激活,激活第四个会把最近最少使用的逐回摘要状态,激活状态在压缩与恢复后从持久事件流重建。`ptc` 下分页同时作用于作用域的工具注册表,未激活的命名空间在 `run_code` 程序内同样不可达;
135
135
  - working-context 行只在其来源(plan-mode 状态、已激活的分页命名空间、进行中的 todo)可读时注入,否则省略;
136
136
  - 工具结果超过 4096 字符即被修剪,保留 2048 字符头部与 1024 字符尾部(守护稀疏索引槽位的同时保住错误尾部与退出码),避免超大输出挤占上下文;
137
- - `run_code` 需要挂载的 PTC runtime(随包发布的 web 与 headless 组合以 `ptc-runtime` 行挂载 `@deepseek-ai/dsh-ptc-runtime-node`);没有时 `ptc` 不做声明,会话运行原生工具面;
137
+ - `run_code` 需要挂载的 PTC runtime(随包发布的 web 与 headless 组合以 `ptc-runtime` 行挂载 `@deepseek-ai/dsh-ptc-runtime-node`);没有时无法挂载 PTC 执行器,会话运行原生工具面;
138
138
  - spawn 委派行已开启子 agent 模型选择(`modelSelection: true` 与 `modelDiscovery: true`),因此设置界面的子智能体模型选择开关在本预设下生效:模型在 `subagent` 上看到 `provider` / `model` / `reasoning_effort` 参数与 `list_subagent_models` 发现工具,显式路由会按会话的允许清单校验(没有已记录的策略时退回父会话当前路由);该行同时保留拆分前的写法 `modelSelectionSettings: true`:`devDependencies` 里钉的 SDK 只认这一个键,而本仓库运行所对的 harness checkout 已不再声明它,两代各读自己认识的键,另一个保持惰性;
139
139
  - 同一组合 scope 内只允许一行委派工具开启发现:上游 `modelDiscovery` 以固定工具名在该行所合入的 scope 中注册 `list_subagent_models`,而注册表拒绝同一 scope 内同名工具的第二次注册,因此第二个开启行会让整个会话创建失败而不是多出一份能力。fork 行因此不带它(官方 Standard、PTC、Cordis 预设同样如此,且它们连路由字段也不开),组合测试按结构统计发现工具的所有者;
140
140
  - `subagent-routes` 行是子路由守卫。一旦会话记录了允许路由清单,本行所管辖的每次委派都必须落到已授权路由上:`subagent` 上显式的 `provider`/`model` 对,或 `subagent_fork`(以及任何创建 teammate 的工具)上调用方自己的路由——后者的继承路由正是因为工具无法自选才需要校验。拒绝时会列出可用路由;在只继承的工具上点名路由会作为越权重路由被拒;没挂路由字段的工具不索要它给不出的参数,而是按子代理将要继承的路由校验。守卫对任何读不到的事实一律放行(未记录策略、无会话注册表、无注册表探针),因此答不出来的宿主保持 harness 原本的委派行为;行上的 `enabled: false` 可整体关闭;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-liangshen",
3
3
  "description": "LiangShen (梁神) agent preset plus its composer lever for the dsh web GUI. The host half declares the bundled preset to the harness's agent-preset registry at activation (declare = enabled), so the preset is selectable for new sessions without writing anything into the harness home; the preset keeps a minimal persona with standing working discipline while the harness's own user-role agent-instructions injection delivers the workspace instructions (the optional `instructionSource: system-prompt` mode lifts them into the prompt instead), and declares one tool presentation for the session's whole lifetime: `ptc` by default (the wire collapses to `run_code` and every other tool is reached through the generated SDK), with `native` as the explicit assembled-roster option. High-fan-out tool families (default `mcp__*`) stay paged out of the wire until the preset's own `tool_activate` tool loads their namespace (LRU cap three, state replayed from the durable session event stream), and the tool catalog — exactly the reachable tools plus paged-out namespace summaries — and a one-line working-context projection travel as durable user messages republished only on change. The browser half adds a slot-machine lever left of the model selector on the new-session screen to toggle the mode. Hot-pluggable via cordis.patch.yml + profile symlink, no dsh source changes.",
4
- "version": "0.4.15",
4
+ "version": "0.4.16",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
7
7
  "engines": {
@@ -5,17 +5,17 @@
5
5
  # presentation declared for the session's whole lifetime instead of a staged
6
6
  # turn boundary.
7
7
  #
8
- # The presentation is the SDK's ToolPresentationMode, picked by the
8
+ # The presentation is the SDK's tool presentation mode, picked by the
9
9
  # tool-catalog row's `presentation` key (default `'ptc'`): `'native'` keeps
10
- # the assembled roster on the wire, and `'ptc'` collapses the wire to the
11
- # single `run_code` transport with every other tool reached from inside the
12
- # program through the generated SDK. The declaration lands once per agent
13
- # scope through agent.ctx.tools.presentAs as early as the scope exists, and
14
- # degrades to the native surface with a one-time warning when the deployment
15
- # has no code runtime or the host declines. The retired anchor-turn staging is
16
- # gone: the legacy `anchorTools` and boolean `ptcPresentation` keys are still
17
- # accepted (the latter mapping true -> 'ptc' and false -> 'native') but only
18
- # warn once.
10
+ # the roster on the wire, and `'ptc'` collapses the wire to the single
11
+ # `run_code` transport with every other tool reached from inside the program
12
+ # through the generated SDK. The settings overlay turns that key into the
13
+ # `tool-executor-ptc` row below, which is what actually decides the wire:
14
+ # 0.2.2 retired `agent.ctx.tools.presentAs`, so no plugin declares it per
15
+ # scope any more, and a deployment with no code runtime keeps the native
16
+ # surface. The retired anchor-turn staging is gone: the legacy `anchorTools`
17
+ # and boolean `ptcPresentation` keys are still accepted (the latter mapping
18
+ # true -> 'ptc' and false -> 'native') but only warn once.
19
19
  #
20
20
  # Gentle tool paging keeps high-fan-out families out of reach until needed:
21
21
  # tools matching `pagedToolPatterns` (default `mcp__*`) stay paged out, the
@@ -187,13 +187,14 @@
187
187
 
188
188
  # ── the wire ────────────────────────────────────────────────────────────────
189
189
  #
190
- # `presentation` on the `tool-catalog` row above IS the wire. The plugin
191
- # declares it on each agent scope through `agent.ctx.tools.presentAs` as soon
192
- # as the scope exists, then re-assembles so the declaration reaches the
193
- # request the model actually receives; `native` keeps the assembled roster,
194
- # `ptc` collapses it to the single `run_code` transport. A deployment with no
195
- # PTC runtime, a host that declines the declaration, or a wire that offers no
196
- # schema projection keeps the native surface and warns once.
190
+ # `presentation` on the `tool-catalog` row above IS the wire, because the
191
+ # settings overlay turns it into the `tool-executor-ptc` row below: a mounted
192
+ # ptc executor collapses the wire to the single `run_code` transport, and the
193
+ # `native` value disables that row so the roster is what the request carries.
194
+ # The catalog reads the same fact back (a `ptc` setting plus a mounted
195
+ # runtime) because no reader can observe the collapse itself: the ptc
196
+ # executor keeps `run_code` outside the registry, so a schema read returns the
197
+ # same list under both modes.
197
198
  #
198
199
  # This cohort splits execution into an agent-scoped executor row. The row below
199
200
  # selects the same official PTC executor as the builtin ptc preset; the settings
@@ -530,8 +531,8 @@
530
531
  fetch: false
531
532
  searchTimeoutMs: 60000
532
533
 
533
- # PTC execution is an agent-scoped plugin in this cohort. The declaration
534
- # overlay disables this row for the native presentation; without it, `presentAs`
535
- # can select the wire but no executor can carry a run_code program.
534
+ # PTC execution is an agent-scoped plugin in this cohort, and this row IS the
535
+ # presentation: the settings overlay disables it for the native presentation.
536
+ # Without that executor the wire has no `run_code` to carry a program.
536
537
  - id: tool-executor-ptc
537
538
  name: '@deepseek-ai/dsh-tool-executor-ptc'
@@ -13,12 +13,13 @@
13
13
  * renders the current facts as one of its fields, republished only on change.
14
14
  *
15
15
  * The register itself is a list of single-line facts, newest last, rebuilt by
16
- * replaying `tool/call` events for this tool from the session log — exactly
17
- * the way the paging activation state replays. A fact is a string the model
18
- * writes; registering a new fact APPENDS, and registering one already present
19
- * is a no-op report. REVOCATION is append-only too: a `revoke` entry removes
20
- * every earlier fact carrying the same tag, so the fold stays deterministic
21
- * after resume and compaction without any process memory.
16
+ * replaying this tool's calls out of the session log — exactly the way the
17
+ * paging activation state replays, and from both wire shapes a session records
18
+ * them in ({@link factRegisterCall}). A fact is a string the model writes;
19
+ * registering a new fact APPENDS, and registering one already present is a
20
+ * no-op report. REVOCATION is append-only too: a `revoke` entry removes every
21
+ * earlier fact carrying the same tag, so the fold stays deterministic after
22
+ * resume and compaction without any process memory.
22
23
  *
23
24
  * The tool is deliberately small: it validates and reports, it does not edit
24
25
  * the context itself. The projection the model sees next step is the fold of
@@ -53,17 +54,52 @@ export const MAX_FACT_CHARS = 160
53
54
  /** Cap the register so the ledger cannot itself flood the local window. */
54
55
  export const MAX_FACTS = 12
55
56
 
57
+ /**
58
+ * The call one event contributes to the fold, or undefined when the event is
59
+ * not a `fact_register` call that took effect.
60
+ *
61
+ * The session records the call in one of two shapes, and which one depends on
62
+ * the presentation the session runs. `native` records a top-level `tool/call`
63
+ * whose `arguments` is the JSON string the model emitted. `ptc` — the shipped
64
+ * default — collapses the wire to `run_code` and reaches every other tool from
65
+ * inside a program, which the runtime records as `tool/ptc-dispatch`: its
66
+ * `arguments` is already an object, and a dispatch that failed carries its own
67
+ * `isError` on the dispatch record (`event.data.isError`), not on the event
68
+ * envelope. Reading only `tool/call` therefore folded an empty register in
69
+ * every factory-default session — pin and revoke both reported success while no
70
+ * `key facts` field ever rendered — which is the same gap `paging.mjs` replays
71
+ * both shapes to avoid.
72
+ *
73
+ * A dispatch that reported an error never took effect, so it contributes
74
+ * nothing: a failed pin must not pin, and a failed revoke must not drop a fact
75
+ * that still stands. `tool/ptc-dispatch-start` only announces a dispatch that
76
+ * has not settled yet, so the event-type check below leaves it out. The
77
+ * `native` half keeps its existing semantics untouched: a `tool/call` is read
78
+ * whatever its `tool/result` later reported, exactly as before this change.
79
+ */
80
+ function factRegisterCall(event) {
81
+ if (event?.type === 'tool/ptc-dispatch') {
82
+ const dispatch = event.data
83
+ if (dispatch?.name !== FACT_LEDGER_TOOL || dispatch?.isError === true) return undefined
84
+ return dispatch
85
+ }
86
+ if (event?.type !== 'tool/call' || event.data?.name !== FACT_LEDGER_TOOL) return undefined
87
+ return event.data
88
+ }
89
+
56
90
  /**
57
91
  * Fold the current fact register from the event stream: every successful
58
- * `fact_register` call appends its fact (or revokes by tag). Facts carry no
59
- * ids — revocation matches on the optional `tag`, and an untagged fact can
60
- * only be revoked by revoking its exact text as the tag of last resort.
92
+ * `fact_register` call appends its fact (or revokes by tag), whichever wire
93
+ * shape recorded it. Facts carry no ids — revocation matches on the optional
94
+ * `tag`, and an untagged fact can only be revoked by revoking its exact text as
95
+ * the tag of last resort.
61
96
  */
62
97
  export function foldFactLedger(events) {
63
98
  const facts = []
64
99
  for (const event of Array.isArray(events) ? events : []) {
65
- if (event?.type !== 'tool/call' || event.data?.name !== FACT_LEDGER_TOOL) continue
66
- let args = event.data?.arguments
100
+ const data = factRegisterCall(event)
101
+ if (data === undefined) continue
102
+ let args = data.arguments
67
103
  if (typeof args === 'string') {
68
104
  try { args = JSON.parse(args) } catch { args = undefined }
69
105
  }
@@ -1,22 +1,25 @@
1
1
  /**
2
- * tool-catalog — the model-visible tool surface for LiangShen mode: one
3
- * presentation declaration per session, gentle tool paging for high-fan-out
2
+ * tool-catalog — the model-visible tool surface for LiangShen mode: the
3
+ * presentation this composition renders, gentle tool paging for high-fan-out
4
4
  * namespaces, and the durable catalog message.
5
5
  *
6
- * PRESENTATION: the `presentation` config picks how this session's tools sit
7
- * on the wire, matching the SDK's ToolPresentationMode:
8
- * - `native`: the assembled native roster, no code transport;
6
+ * PRESENTATION: the `presentation` config names the transport the session
7
+ * carries, matching the SDK's tool presentation modes:
8
+ * - `native`: the native roster, no code transport;
9
9
  * - `ptc` (default): the wire collapses to the single `run_code` transport
10
10
  * and every other tool is reached from inside the program through the
11
11
  * generated SDK.
12
12
  *
13
- * The declaration happens once per agent scope (agent.ctx.tools.presentAs) as
14
- * early as the scope exists — there is no turn-boundary staging: the retired
15
- * anchor-turn mechanism is gone, and the legacy `anchorTools` key is accepted
16
- * but ignored with a one-time warning. The legacy boolean `ptcPresentation`
17
- * maps onto the enum (true -> 'ptc', false -> 'native') with a one-time
18
- * deprecation warning. A missing code runtime or a declined declaration keeps
19
- * the native surface with a one-time warning.
13
+ * The preset composition is what actually selects it: `src/composition.ts`
14
+ * enables or disables the `tool-executor-ptc` row from the same setting, and
15
+ * that row is what installs the executor whose `describe()` decides the wire
16
+ * (0.2.2 retired `ctx.tools.presentAs`, the old per-scope declaration, so this
17
+ * plugin no longer declares anything). A deployment with no code runtime keeps
18
+ * the native surface, and the catalog says so. There is no turn-boundary
19
+ * staging: the retired anchor-turn mechanism is gone, and the legacy
20
+ * `anchorTools` key is accepted but ignored with a one-time warning. The legacy
21
+ * boolean `ptcPresentation` maps onto the enum (true -> 'ptc', false ->
22
+ * 'native') with a one-time deprecation warning.
20
23
  *
21
24
  * TOOL PAGING: tools whose names match `pagedToolPatterns` (default
22
25
  * `['mcp__*']`) stay off the wire until their namespace is activated through
@@ -26,25 +29,27 @@
26
29
  * process-memory state. At most a few namespaces stay active; the LRU
27
30
  * eviction falls out of the same replay.
28
31
  *
29
- * Paging is enforced in TWO places, because the wire is not the only surface a
30
- * tool can be reached through:
31
- * - the wire partition below (resident tools returned, paged tools lifted) and
32
- * - a per-scope registry restriction (agent.ctx.tools.restrict) that removes
33
- * the paged names exactly as the wire does.
34
- * The second one is what makes paging real under the `ptc` presentation,
35
- * where the wire has already collapsed to the single `run_code` transport and
36
- * every other tool is reached from inside a program. Under a collapsed wire
37
- * the visible set is the whole surface: it renders the `tools:sdk` prompt
38
- * section and it is what a program may dispatch to, so filtering the assembled
39
- * `tools` array alone would withhold nothing the model can observe. The
40
- * restriction is derived from the same pattern match as the partition
41
- * (`withheldToolNames`) and is lifted before a new one is applied, so repeated
42
- * collections do not accumulate filters.
32
+ * Paging is enforced in ONE place: a per-scope registry restriction
33
+ * (agent.ctx.tools.restrict) that removes the paged names from every scoped
34
+ * reader, the request's own wire included.
43
35
  *
44
- * WHICH PRESENTATION PAGES WHAT: the registry restriction is installed for
45
- * `ptc` alone, because a collapsed wire is the one presentation where the
46
- * scope's registry IS the whole reachable surface. `native` carries no
47
- * program at all, so the wire partition is the whole of paging there.
36
+ * The wire cannot be filtered by a listener any more. Since 0.2.2 the
37
+ * `system-prompt/assemble` waterfall transforms a `PromptPresentation` that
38
+ * carries no tool array at all: the harness collects the tool providers BEFORE
39
+ * the waterfall runs and merges the authoritative `tools` back AFTER it, so a
40
+ * listener can neither observe nor rewrite what the request carries. The
41
+ * registry is the surface every tool declaration is projected from — the
42
+ * native roster the executor renders and the set a program may dispatch to —
43
+ * so one restriction pages both presentations, and the wire partition that
44
+ * used to page the `native` roster is gone with the array it filtered.
45
+ *
46
+ * READING THE SURFACE: the catalog describes the request's own tool set, read
47
+ * as `tools.schemas(agent, context.toolSet)` while assembling. The assemble
48
+ * context's `toolSet` is the step's admitted selection — the fact a listener
49
+ * cannot recover from the assembly value — and `schemas()` reads through the
50
+ * scope's restriction, so the catalog lists exactly what the wire carries. An
51
+ * unreadable projection is NOT an empty one: the catalog keeps its last
52
+ * published state rather than announcing a session with no tools.
48
53
  *
49
54
  * TIMING: that restriction is installed from OUTSIDE the assembly waterfall.
50
55
  * `SystemPrompt.assemble()` collects the tool providers and calls every
@@ -83,7 +88,6 @@ import {
83
88
  inactiveNamespaces,
84
89
  integerAtLeast,
85
90
  namespaceOf,
86
- partitionWireTools,
87
91
  replayActivations,
88
92
  summarizeInactive,
89
93
  validatePagedToolPatterns,
@@ -115,7 +119,7 @@ const pagedSurfaceBySession = new WeakMap()
115
119
  /**
116
120
  * Publish (or, with `undefined`, retract) one scope's paged namespaces.
117
121
  * @param agent - agent scope the partition belongs to.
118
- * @param surface - namespace-keyed namespaces, as `partitionWireTools` returns.
122
+ * @param surface - namespace-keyed namespaces, as `inactiveNamespaces` returns.
119
123
  */
120
124
  function publishPagedSurface(agent, surface) {
121
125
  if (agent === undefined || agent === null) return
@@ -558,38 +562,6 @@ export function renderCatalogText(entries, presentation = 'native', inactive = [
558
562
  ].join('\n')
559
563
  }
560
564
 
561
- /**
562
- * Overlay the registry projection onto each wire entry, keyed by name, so the
563
- * catalog describes complete argument semantics even when the assembly's own
564
- * tool object carries a thinner definition.
565
- *
566
- * A tool the projection NAMES is authoritative for the parameter field,
567
- * including its absence: a projected entry that declares no parameters means
568
- * the tool takes no declared arguments, and the wire's placeholder object
569
- * (`{ type: 'object', properties: {} }`) would otherwise render the misleading
570
- * `Record<string, JsonValue>` signature. A tool the projection does not name
571
- * keeps the wire's own definition, and so does every entry when no projection
572
- * is readable at all.
573
- */
574
- export function mergeProjectedSchemas(wireTools, projection) {
575
- if (!Array.isArray(projection) || projection.length === 0) return wireTools
576
- const byName = new Map()
577
- for (const schema of projection) {
578
- if (typeof schema?.name === 'string' && schema.name !== '') byName.set(schema.name, schema)
579
- }
580
- return wireTools.map((tool) => {
581
- const projected = byName.get(tool?.name)
582
- if (projected === undefined) return tool
583
- const merged = { ...tool }
584
- if (projected.parameters === undefined) delete merged.parameters
585
- else merged.parameters = projected.parameters
586
- if (typeof projected.description === 'string' && projected.description.length > 0) {
587
- merged.description = projected.description
588
- }
589
- return merged
590
- })
591
- }
592
-
593
565
  /** Build the durable catalog message for one entry list. */
594
566
  export function createCatalogMessage(entries, presentation = 'native', inactive = []) {
595
567
  return {
@@ -662,7 +634,7 @@ function withoutMessage(decision, id) {
662
634
  return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
663
635
  }
664
636
 
665
- /** Register the presentation declaration, the wire paging, and the per-step catalog injection. */
637
+ /** Register the registry paging and the per-step catalog injection. */
666
638
  export function apply(ctx, config) {
667
639
  const descriptionMaxLength = integerAtLeast(
668
640
  name,
@@ -711,11 +683,6 @@ export function apply(ctx, config) {
711
683
  // Session to agent mapping for lifecycle events
712
684
  const agentBySession = new WeakMap()
713
685
 
714
- // Presentation declaration tracking per agent scope (one declaration each)
715
- const agentDeclared = new WeakSet()
716
- const agentDeclareFailed = new WeakSet()
717
- const agentDisposers = new WeakMap()
718
-
719
686
  // Registry-level paging state, one entry per agent scope: the names the live
720
687
  // restriction withholds and the exact disposer that lifts it. Keyed by agent
721
688
  // so two sessions assembling at once cannot lift each other's filter, and
@@ -736,15 +703,17 @@ export function apply(ctx, config) {
736
703
 
737
704
  /**
738
705
  * Recompute one agent scope's page from the durable session event stream and
739
- * make the registry match it: `deny` masks exactly the names the wire
740
- * partition would withhold, so the scope still inherits everything else.
706
+ * make the registry match it: `deny` masks exactly the names the paged
707
+ * namespaces carry, so the scope still inherits everything else.
741
708
  * Scoped registrations are exempt by the registry's own rule, so
742
709
  * preset-owned tools can never be filtered away by this.
743
710
  *
744
- * The restriction is what paging MEANS under a collapsed `ptc` wire, where
745
- * filtering the assembled `tools` array changes nothing a program can reach.
746
- * It also stores the namespaces it withheld, so the catalog and the live
747
- * restriction are read from ONE fact instead of two computations.
711
+ * The restriction is what paging MEANS in both presentations now that the
712
+ * waterfall carries no tool array: the registry is the surface every tool
713
+ * declaration is projected from, so the native roster and the program
714
+ * bindings lose the paged names together. It also stores the namespaces it
715
+ * withheld, so the catalog and the live restriction are read from ONE fact
716
+ * instead of two computations.
748
717
  *
749
718
  * Called OUTSIDE the assembly waterfall, deliberately: see
750
719
  * {@link syncBeforeAssembly} for why an in-waterfall sync cannot fix the
@@ -769,7 +738,7 @@ export function apply(ctx, config) {
769
738
  // nothing left to withhold. Silent on an unreadable surface: a sync may
770
739
  // run before the registry is populated, and "no tools yet" is not the
771
740
  // assembly-path emergency that warning describes.
772
- const fullSurface = quietSchemas(agent) ?? []
741
+ const fullSurface = readSurface(agent, undefined, { quiet: true }) ?? []
773
742
  if (fullSurface.length === 0) return undefined
774
743
  // Publish before the withhold decision: with every namespace already active
775
744
  // there is nothing to restrict, and the activation tool must still know the
@@ -809,23 +778,18 @@ export function apply(ctx, config) {
809
778
  * request's own SDK section still lists it. Syncing before the providers are
810
779
  * collected is what keeps the two consistent from the FIRST `ptc` request.
811
780
  *
812
- * GATED ON THE WIRE ACTUALLY COLLAPSING, not on the configuration asking for
813
- * it. Both halves of that gate matter, and each covers a deployment where
814
- * paging at the registry would be wrong:
815
- * - `presentation === 'ptc'` is what the operator configured, and it is the
816
- * only presentation whose registry is the whole reachable surface;
817
- * - `agentDeclared.has(agent)` is the scope's own declaration actually
818
- * landing, which is NOT the same as `transportReady()`. A deployment with
819
- * no mounted code runtime (and one whose host declines the declaration)
820
- * keeps the native wire: the assembled array carries paging by itself, and
821
- * a registry restriction installed anyway would strip the paged families
822
- * from that request's native wire — the first request would lose tools it
823
- * is supposed to have, and the catalog would announce namespaces as
824
- * withheld that nothing withheld.
781
+ * EVERY SCOPE IS PAGED, in both presentations. Before 0.2.2 the native
782
+ * roster was filtered in the waterfall itself — the listener returned a
783
+ * narrowed `tools` array — so a registry restriction there would have been
784
+ * redundant, and a deployment whose wire never collapsed (no code runtime, a
785
+ * declined declaration) had to keep it off entirely. The harness now merges
786
+ * its own provider-owned `tools` back after the waterfall, so that return
787
+ * value is discarded: the registry is the only place a page can exist, and a
788
+ * scope left unpaged would hand the model every paged family it was supposed
789
+ * to activate first.
825
790
  */
826
791
  const syncBeforeAssembly = (agent) => {
827
- if (agent === undefined || presentation !== 'ptc') return undefined
828
- if (!agentDeclared.has(agent)) return undefined
792
+ if (agent === undefined) return undefined
829
793
  return syncScopePaging(agent)
830
794
  }
831
795
 
@@ -834,65 +798,16 @@ export function apply(ctx, config) {
834
798
  // The 0.1.6 cohort renamed the service face from `codeRuntime` to
835
799
  // `ptcRuntime` (package `@deepseek-ai/dsh-code-runtime` became
836
800
  // `@deepseek-ai/dsh-ptc-runtime`); the old key is gone, so reading it would
837
- // silently disable PTC staging for every session.
838
- const transportReady = () => presentation !== 'native' && ctx.get('ptcRuntime') !== undefined
839
-
840
- /**
841
- * Declare this agent scope's presentation through the public
842
- * agent.ctx.tools.presentAs(mode). One declaration per scope; a refusal is
843
- * permanent for the agent, a wire miss is retryable.
844
- */
845
- const declarePresentation = (agent) => {
846
- if (!transportReady() || agent === undefined) return false
847
- if (agentDeclared.has(agent)) return true
848
- if (agentDeclareFailed.has(agent)) return false
849
-
850
- const tools = agent?.ctx?.tools
851
- if (tools === undefined || typeof tools.presentAs !== 'function') {
852
- // No composition row replaces this declaration: `presentAs` is how a
853
- // preset selects its wire, so a scope that cannot reach it runs the
854
- // native surface no matter what `presentation` says. Report it once
855
- // instead of leaving the operator's setting silently unapplied.
856
- agentDeclareFailed.add(agent)
857
- warnOnce('runtime', 'no scoped tools view to declare the presentation through — keeping the native tool surface')
858
- return false
859
- }
860
-
861
- try {
862
- const disposer = tools.presentAs(presentation)
863
- agentDeclared.add(agent)
864
- if (typeof disposer === 'function') {
865
- agentDisposers.set(agent, disposer)
866
- }
867
- return true
868
- } catch (err) {
869
- agentDeclareFailed.add(agent)
870
- warnOnce('runtime', `the "${presentation}" presentation was declined: ${err instanceof Error ? err.message : String(err)} — keeping the native tool surface`)
871
- return false
872
- }
873
- }
874
-
875
- /**
876
- * Abort/revert the declaration if active, restoring the native presentation.
877
- */
878
- const revertPresentation = (agent, reason, retryable = false) => {
879
- if (agent === undefined) return
880
- const disposer = agentDisposers.get(agent)
881
- if (typeof disposer === 'function') {
882
- try {
883
- disposer()
884
- } catch {
885
- // Ignore disposer error
886
- }
887
- agentDisposers.delete(agent)
888
- }
889
- agentDeclared.delete(agent)
890
- // A declaration the host itself refused is permanent for this agent. One that
891
- // merely failed to reach a wire is not: the next assembly may declare again,
892
- // and latching it would strand the session on the native surface.
893
- if (!retryable) agentDeclareFailed.add(agent)
894
- warnOnce('runtime', `${reason} — keeping the native tool surface`)
895
- }
801
+ // silently disable program presentation for every session.
802
+ //
803
+ // This is the ONE fact that decides what the request carries, because no
804
+ // reader can observe the collapse itself: the petc executor keeps `run_code`
805
+ // outside the registry (`describe()` returns it, `tools.schemas()` never
806
+ // does), so a `schemas()` read returns the same roster under both
807
+ // presentations. The composition enables the `tool-executor-ptc` row from
808
+ // exactly this setting (see `src/composition.ts`), so the configured
809
+ // presentation plus a mounted runtime IS the wire.
810
+ const collapsedTransport = () => presentation !== 'native' && ctx.get('ptcRuntime') !== undefined
896
811
 
897
812
  /**
898
813
  * Read visible tool schemas from the public tools.schemas(agent) API.
@@ -911,71 +826,59 @@ export function apply(ctx, config) {
911
826
  }
912
827
 
913
828
  /**
914
- * Read the scope's model-facing surface without the assembly path's warning.
915
- * Returns undefined when no projection is readable at all.
829
+ * Read the model-facing surface one scope offers this step, without the
830
+ * reserved transport (the catalog never lists run_code as an entry).
831
+ *
832
+ * `toolSet` is the assemble context's step admission: passing it narrows the
833
+ * read to exactly the tools this request may carry, conditionally registered
834
+ * ones excluded. Omitted, the read covers every registered definition, which
835
+ * is what the paging sync needs to compute its page.
836
+ *
837
+ * An EMPTY list and an UNREADABLE registry are different facts, and the
838
+ * return type keeps them apart: `[]` means this scope really offers no tool,
839
+ * `undefined` means nothing could be read (a deployment without the registry,
840
+ * a projection that threw). A caller that treats the second as the first
841
+ * announces "no tools" to a session that has them — the defect issue #2016
842
+ * reports.
843
+ *
844
+ * @param agent - agent scope the surface is read for.
845
+ * @param toolSet - the step's admitted selection, or undefined for every definition.
846
+ * @param options - `quiet` suppresses the diagnostic of an unreadable registry.
847
+ * @returns the visible schemas minus run_code, or undefined when unreadable.
916
848
  */
917
- const quietSchemas = (agent) => {
849
+ const readSurface = (agent, toolSet, options) => {
918
850
  const tools = resolveToolsService(agent)
919
851
  if (tools === undefined) return undefined
920
852
  for (const method of ['schemas', 'sdkSchemas']) {
921
853
  if (typeof tools[method] !== 'function') continue
922
854
  try {
923
- const schemas = tools[method](agent)
855
+ const schemas = tools[method](agent, toolSet)
924
856
  if (Array.isArray(schemas)) return schemas.filter(entry => entry?.name && entry.name !== 'run_code')
925
- } catch {
926
- // Try the next source; an unreadable registry is not fatal here.
927
- }
928
- }
929
- return undefined
930
- }
931
-
932
- const publicSchemas = (agent) => {
933
- const tools = resolveToolsService(agent)
934
- if (tools === undefined) return undefined
935
- if (typeof tools.schemas === 'function') {
936
- try {
937
- const schemas = tools.schemas(agent)
938
- if (Array.isArray(schemas) && schemas.length > 0) {
939
- const filtered = schemas.filter(t => t?.name && t.name !== 'run_code')
940
- return filtered.length > 0 ? filtered : undefined
941
- }
942
- return undefined
943
- } catch {
944
- warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
945
- return undefined
946
- }
947
- }
948
- // Test harness compatibility stub
949
- if (typeof tools.sdkSchemas === 'function') {
950
- try {
951
- const schemas = tools.sdkSchemas(agent)
952
- if (Array.isArray(schemas) && schemas.length > 0) {
953
- const filtered = schemas.filter(t => t?.name && t.name !== 'run_code')
954
- return filtered.length > 0 ? filtered : undefined
857
+ } catch (err) {
858
+ if (options?.quiet !== true) {
859
+ // Its own key, so an unreadable projection never swallows the
860
+ // declaration warning that explains what replaced it.
861
+ warnOnce('surface', `no tool schemas available (${err instanceof Error ? err.message : String(err)}) — the catalog keeps its last published state`)
955
862
  }
956
- } catch {
957
- warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
958
863
  return undefined
959
864
  }
960
865
  }
961
866
  return undefined
962
867
  }
963
868
 
964
- // Early lifecycle hook: declare the presentation and page the scope as soon
965
- // as it exists.
869
+ // Early lifecycle hook: page the scope as soon as it exists.
966
870
  //
967
871
  // The 0.1.6 cohort folded the former `agent/session-start` into the async
968
872
  // serial `agent/created`, which carries the same payload object and runs
969
873
  // before the first prompt assembly; the host waits for this listener, so the
970
- // declaration is already in place when that assembly reads the presentation.
874
+ // page is already in place when that assembly collects its tool providers.
971
875
  //
972
876
  // The payload is destructured ON PURPOSE: `agent/created` passes its payload
973
877
  // OBJECT as the first argument, not the agent itself. Reading that parameter
974
- // as the agent yields an object with no `session` and no `ctx`, so the
975
- // declaration is skipped and paging silently never engages.
878
+ // as the agent yields an object with no `session` and no `ctx`, so paging
879
+ // would silently never engage.
976
880
  ctx.on('agent/created', ({ agent }) => {
977
881
  if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
978
- if (transportReady()) declarePresentation(agent)
979
882
  // The session log is readable here, and this runs before the first turn
980
883
  // assembles a prompt, so a scope created over an existing (resumed)
981
884
  // session is paged before its FIRST assembly rather than one request late.
@@ -1004,166 +907,86 @@ export function apply(ctx, config) {
1004
907
  return next()
1005
908
  }, { prepend: true })
1006
909
 
1007
- // Per-agent, not one process-wide flag: two sessions assembling at once would
1008
- // otherwise let one skip the re-assembly the other is running.
1009
- const reassembling = new WeakSet()
1010
-
1011
910
  ctx.on('system-prompt/assemble', async (assembly, context, next) => {
1012
911
  const agent = context?.agent
912
+ // The step's admitted selection, and the one fact about this request's tool
913
+ // set a listener can still read: since 0.2.2 the assembly value carries no
914
+ // tool array, and the providers it is built from are collected before this
915
+ // waterfall runs.
916
+ const toolSet = context?.toolSet
1013
917
 
1014
918
  if (agent !== undefined && agent.session !== undefined) {
1015
919
  agentBySession.set(agent.session, agent)
1016
920
  }
1017
921
 
1018
- if (agent !== undefined && !agentDeclared.has(agent) && transportReady()) {
1019
- // Under 'ptc' a declaration collapses the wire to the single `run_code`
1020
- // transport and lists the tools from their SDK projection. Where no
1021
- // projection can be read at all, declaring would collapse the wire and
1022
- // then have to undo it, losing the native surface on the way out. Stay
1023
- // native instead.
1024
- const projectable = publicSchemas(agent)
1025
- if (presentation === 'ptc' && (projectable === undefined || projectable.length === 0)) {
1026
- warnOnce('runtime', 'no tool schema projection available — keeping the native tool surface')
1027
- } else {
1028
- const declaredNow = declarePresentation(agent)
1029
- // A declaration made here cannot reach THIS assembly: the harness collects
1030
- // the tool providers before the waterfall runs. Re-assemble so the
1031
- // presentation lands on the assembly the model actually receives.
1032
- if (declaredNow && !reassembling.has(agent)) {
1033
- const sp = ctx.get('systemPrompt')
1034
- if (typeof sp?.assemble === 'function') {
1035
- reassembling.add(agent)
1036
- try {
1037
- return await sp.assemble(context)
1038
- } catch (error) {
1039
- warnOnce('runtime', `re-assembling after the presentation declaration failed: ${error instanceof Error ? error.message : String(error)}`)
1040
- } finally {
1041
- reassembling.delete(agent)
1042
- }
1043
- }
1044
- // Nothing re-assembled, so this wire stays native. Presenting a transport
1045
- // the request never names would lie to the model, so drop back to native
1046
- // for this assembly and let the next assembly declare again.
1047
- revertPresentation(agent, `the "${presentation}" declaration did not reach this assembly wire`, true)
1048
- }
1049
- }
1050
- }
1051
-
1052
- // A declaration that just landed here (a scope no lifecycle hook could
1053
- // reach) pages the scope before the re-assembly collects its providers, so
1054
- // that request renders a page-consistent SDK section too. Idempotent: a
1055
- // scope already paged by its lifecycle hook re-derives the same state.
1056
- if (agent !== undefined && agentDeclared.has(agent)) syncBeforeAssembly(agent)
922
+ // Page the scope before the providers are collected; a scope the lifecycle
923
+ // hooks already paged re-derives the same state, so this is idempotent.
924
+ syncBeforeAssembly(agent)
1057
925
 
1058
- // Delegate first: the assembled value stays authoritative for the wire (a
1059
- // presentation declared inside this waterfall reaches the NEXT assembly,
1060
- // which is why a declaration is followed by a re-assembly).
926
+ // The waterfall's transformed value travels on untouched: tool declarations
927
+ // are provider-owned, so there is no array here to filter or restore.
1061
928
  const assembled = await next()
1062
929
 
1063
- const assembledTools = Array.isArray(assembled?.tools) ? assembled.tools : undefined
1064
- const wireOnlyRunCode = assembledTools !== undefined && assembledTools.length > 0 && assembledTools.every(t => t?.name === 'run_code')
1065
-
1066
- // The paging restriction was installed OUTSIDE this waterfall (see
1067
- // {@link syncBeforeAssembly}) because `assemble()` renders the sections and
1068
- // collects the providers before the waterfall runs: installing it here
1069
- // would leave the request it runs for with a catalog that claims a
1070
- // namespace is paged and a `tools:sdk` section that still lists it. What
1071
- // this waterfall does with it is read the SAME state the restriction was
1072
- // built from, so the catalog never describes a different page than the one
1073
- // the registry enforces.
1074
- const pagingState = agent === undefined ? undefined : agentPaging.get(agent)
1075
-
1076
- // Under a collapsed `ptc` wire the registry is the ONLY surface a tool can
1077
- // be reached through, so the page is expressed as a registry restriction.
1078
- // The native wire carries paging by itself on the assembled array. A wire
1079
- // that carries the native roster again (a reverted declaration) must also
1080
- // drop a page left over from a collapsed assembly, or the filter would keep
1081
- // hiding tools that wire just handed back.
1082
- let surface = agent !== undefined ? publicSchemas(agent) : undefined
1083
- // The wire partition replays the durable log itself: `pagingState` exists
1084
- // only where a restriction was installed (the collapsed ptc wire), and the
1085
- // native wire still pages the assembled array from the same event stream.
1086
- const activeNamespaces = new Set(
1087
- replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active,
1088
- )
1089
- if (agent !== undefined && !wireOnlyRunCode && pagingState !== undefined) clearScopePaging(agent)
1090
-
1091
- // If the wire carries only run_code but no projection is readable, revert to
1092
- // native and restore the native wire. The replacement travels in the RETURNED
1093
- // assembly: the waterfall's returned value is the authoritative one, and
1094
- // mutating the object the harness handed downstream would be a side effect no
1095
- // other listener can see.
1096
- let correctedWire
1097
- if (wireOnlyRunCode && (surface === undefined || surface.length === 0)) {
1098
- revertPresentation(agent, 'no tool schema projection available under PTC')
1099
- const nativeSchemas = publicSchemas(agent) ?? []
1100
- surface = nativeSchemas
1101
- correctedWire = nativeSchemas
930
+ // The catalog describes THIS request's surface, read from the registry
931
+ // through the step's admission. `schemas()` reads through the scope's
932
+ // restriction, so the result is exactly the list this request carries: the
933
+ // native roster, or - under a collapsed `ptc` wire - the projection every
934
+ // tool is reached through from inside a program (run_code is the transport,
935
+ // never a catalog entry).
936
+ const surface = agent === undefined ? undefined : readSurface(agent, toolSet)
937
+
938
+ // The presentation this request carries is the one the composition mounted.
939
+ // Nothing in the assembly names it and `schemas()` reads the same roster
940
+ // under both, so the configured mode plus a mounted runtime is the answer -
941
+ // and a mode whose runtime is missing keeps the native wording, because
942
+ // that is the wire an executor-less deployment renders.
943
+ const effectivePresentation = collapsedTransport() ? 'ptc' : 'native'
944
+
945
+ // An unreadable projection is NOT an empty one. Keep the catalog this scope
946
+ // last published instead of rewriting it: recording "this session has no
947
+ // tools" over a read that merely failed is what made the model refuse tools
948
+ // the request was carrying (issue #2016). The one fact that still has to
949
+ // follow the request is the transport, so the wording is corrected above.
950
+ if (agent === undefined) return assembled
951
+ if (surface === undefined) {
952
+ const previous = agentCatalogState.get(agent)
953
+ if (previous !== undefined && previous.presentation !== effectivePresentation) {
954
+ agentCatalogState.set(agent, { ...previous, presentation: effectivePresentation })
955
+ }
956
+ return assembled
1102
957
  }
1103
958
 
1104
- const effectiveWire = correctedWire ?? assembledTools
1105
- const effectiveOnlyRunCode = effectiveWire !== undefined && effectiveWire.length > 0 && effectiveWire.every(t => t?.name === 'run_code')
1106
-
1107
- // The catalog describes the transport this request actually carries, never
1108
- // the configuration's intent: a collapsed wire is 'ptc', and anything else
1109
- // is native.
1110
- const effectivePresentation = effectiveOnlyRunCode ? 'ptc' : 'native'
1111
-
1112
- // Gentle paging: the active namespaces were replayed from the durable event
1113
- // stream above; here the paged-but-inactive tools come off the wire itself.
1114
- // run_code and the resident roster never match the paging patterns.
1115
- const { resident, inactive } = partitionWireTools(effectiveWire, pagedToolPatterns, activeNamespaces)
1116
-
1117
959
  // Diagnostic guard on the always-on-wire surface. It warns rather than
1118
960
  // truncates: silently dropping a tool the session needs would trade a
1119
961
  // measurable context cost for an unmeasurable capability loss.
1120
- const residentTokens = estimateSurfaceTokens(resident)
962
+ const residentTokens = estimateSurfaceTokens(surface)
1121
963
  if (residentTokens > maxResidentTokens) {
1122
964
  // Name the heaviest tools so the remedy is actionable rather than a bare number.
1123
- const heaviest = [...resident]
965
+ const heaviest = [...surface]
1124
966
  .map(tool => ({ name: typeof tool?.name === 'string' ? tool.name : '(unnamed)', tokens: estimateSurfaceTokens([tool]) }))
1125
967
  .sort((left, right) => right.tokens - left.tokens)
1126
968
  .slice(0, 3)
1127
969
  .map(entry => `${entry.name} (${entry.tokens})`)
1128
970
  .join(', ')
1129
- warnOnce('resident-budget', `the resident tool surface is about ${residentTokens} tokens across ${resident.length} tools, over the ${maxResidentTokens}-token budget; heaviest: ${heaviest} — add matching families to pagedToolPatterns so they are held off the wire until activated`)
971
+ warnOnce('resident-budget', `the resident tool surface is about ${residentTokens} tokens across ${surface.length} tools, over the ${maxResidentTokens}-token budget; heaviest: ${heaviest} — add matching families to pagedToolPatterns so they are held off the wire until activated`)
1130
972
  }
1131
973
 
1132
- // The catalog describes this request's ACTUAL surface: with a live page it
1133
- // summarizes exactly the namespaces that page withholds (the same fact the
1134
- // restriction was built from), and otherwise the namespaces the WIRE
1135
- // partition found.
1136
- const catalogInactive = summarizeInactive(
1137
- pagingState?.inactive ?? inactive,
974
+ // The page the registry enforces IS this request's page: the restriction was
975
+ // installed before the providers were collected (see {@link syncBeforeAssembly}),
976
+ // and the surface above already reads through it. A scope whose page could
977
+ // not be installed withholds nothing, so it advertises nothing.
978
+ const pagingState = agentPaging.get(agent)
979
+ const inactiveSummary = summarizeInactive(
980
+ pagingState?.inactive ?? [],
1138
981
  describe => catalogDescription(describe, descriptionMaxLength),
1139
982
  )
1140
983
 
1141
- let entries
1142
- if (effectivePresentation === 'ptc') {
1143
- // Under the collapsed transport the request opens only run_code, so the
1144
- // catalog lists the SDK-reachable projection instead of the wire.
1145
- entries = catalogEntries(surface ?? [], descriptionMaxLength, { patterns: pagedToolPatterns })
1146
- } else {
1147
- const merged = mergeProjectedSchemas(resident, surface)
1148
- entries = catalogEntries(merged, descriptionMaxLength, { patterns: pagedToolPatterns })
1149
- }
1150
- const inactiveSummary = catalogInactive
1151
-
1152
- // Store fresh state on agent
1153
- if (agent !== undefined) {
1154
- agentCatalogState.set(agent, {
1155
- entries,
1156
- presentation: effectivePresentation,
1157
- inactive: inactiveSummary,
1158
- })
1159
- }
1160
-
1161
- if (assembledTools === undefined) return assembled
1162
- // Keep the caller's own assembly object whenever this pass neither corrected
1163
- // a collapsed wire nor lifted a paged tool off it: a needless copy would hand
1164
- // downstream listeners a different object for no behavioral reason.
1165
- const unchanged = correctedWire === undefined && resident.length === assembledTools.length
1166
- return unchanged ? assembled : { ...assembled, tools: resident }
984
+ agentCatalogState.set(agent, {
985
+ entries: catalogEntries(surface, descriptionMaxLength, { patterns: pagedToolPatterns }),
986
+ presentation: effectivePresentation,
987
+ inactive: inactiveSummary,
988
+ })
989
+ return assembled
1167
990
  }, { prepend: true })
1168
991
 
1169
992
  ctx.on('agent/pre-step', async (payload, next) => {