Files
deepseek-harness/packages/subagent/tool-subagent
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00
..

description, kind
description kind
Model-facing subagent delegation tool for users and maintainers configuring, composing, or debugging delegation over a subagent provider. package-reference

@deepseek-ai/dsh-tool-subagent

English | 中文

Summary

Use this package to give an agent a named tool that delegates work to a configured backend. Every call starts a managed activation and returns the child's name; the runtime owns completion notices and cleanup. Local children support messages and restoration, while external backends execute one task and return their final answer through the completion notice. Supported backends can expose approved child LLM routes. Each instance can select a child preset and depth limit.

Table of Contents


Use this package

The child starts in the caller's workspace directory; the tool takes no directory argument. Existing children retain their own directories when the caller's directory changes.

Mount one instance per delegation target, each with a distinct toolName. The tool exists exactly while its provider does, so sibling load order and provider reloads never strand it.

Minimal configuration

Load the subagent service, an in-process or remote backend, and this tool; then name the provider. This composition exposes a subagent tool that delegates to the spawn backend:

- name: '@deepseek-ai/dsh-subagent'
- name: '@deepseek-ai/dsh-subagent-spawn-in-process'
- name: '@deepseek-ai/dsh-tool-subagent'
  config:
    provider: spawn
    toolName: subagent
Field Default Meaning
provider required Provider name on ctx.subagents (e.g. spawn, fork, acp)
toolName subagent Model-facing tool name; distinct for every loaded instance
modelSelection false Expose optional child route fields; requires provider agentOptions support
modelDiscovery false Register list_subagent_models; enable on one instance per tool scope
agentOptions — Configured child provider, model, adapter-owned reasoningEffort, and positive maxTokens defaults; requires provider agentOptions support and overlays any provider-owned route defaults
agentPreset — Default independent child preset id; requires in-process spawn
allowedAgentPresets — Non-empty preset-id allowlist exposed as the model's optional agent_preset enum; must include agentPreset when both are set
maxDepth Host setting (1) Absolute delegation-depth cap (0 forbids delegation); 'provider-managed' sends no cap to an out-of-process provider

The generated configuration catalog is the exhaustive source for every accepted field and its JSDoc.

Managed delegation

The optional name argument names the child, unique among the caller's children and cannot be lead; omission selects agent-1, agent-2, and so on. The subagent runtime owns the name rule and its errors. Every call returns started subagent <name> after the runtime accepts the child, where <name> is the child's full name from the root, such as reviewer/checker. Top-level calls persist { kind: 'activation', name: <name> } in result presentation metadata; nested Code dispatches retain it in the corresponding tool/ptc-dispatch event's meta field. It does not wait for the child's result. The activation owns the work independently of the completed tool call; the runtime sends a completion notice and releases execution resources.

For every backend, the runtime automatically delivers the completion notice if the calling Agent is still online when the child finishes. The notice includes the final answer unless the child sent that Agent a message just before finishing. Local Spawn and Fork children can also send messages, accept more work through send_message while active, or resume after settling. Codex, Claude Code, ACP, and DSH SDK backends do not accept follow-up messages.

maxDepth caps recursion (0 forbids delegation); omission reads the current Host subagent.maxDepth setting, initially 1, at each delegation. A numeric depth requires a provider with the depthLimit capability; 'provider-managed' leaves the budget to an out-of-process provider. The tool stays visible at the cap; each attempted start checks the calling agent's current depth and rejects with an errored result.

Selecting a child preset

Set agentPreset to give every child an independent preset by default. Set allowedAgentPresets to let the model choose an id through agent_preset; without this allowlist, the model cannot override the configured choice. Only in-process spawn supports these options; fork and external backends reject them.

Duplicate or empty preset ids fail at load. The selected preset is resolved when a call starts the child; an unknown or unloadable preset returns an errored tool result without starting a child. Creating a parent Agent or switching its preset does not resolve child references. Without either selection field, the tool does not require the preset service. An omitted model choice uses the configured agentPreset, or joins the parent's current preset revision when no default is configured. Any explicit id mounts the currently available revision, even when it matches the parent's id.

Compose persona and tools in the preset plugin list. Tool configuration containing persona or toolFilter fails at load with a migration error. Local children use the shared preset restoration rules.

Selecting a child LLM

Set modelSelection: true to expose optional provider, model, and reasoning_effort fields; instances without it reject selection fields. Set modelDiscovery: true on one instance per tool scope to register list_subagent_models; it defaults off independently of modelSelection. A second discovery owner in the same scope fails to register. Discovery follows its owning plugin instance, remains available when its delegation provider is absent, and is removed when that instance unloads. Web and Desktop presets enable discovery and route fields on spawn and leave both disabled on fork. Explicit selection by a model-selectable delegation tool and each discovery call read the Host’s /model-selection-settings service, so a settings edit applies to the next call in every running, restored, and child Session. When enabled, discovery and explicit selection permit its exact route list. When it is disabled or not mounted, they permit only the parent Agent’s current effective provider/model and its supported efforts. An enabled setting with an empty, malformed, or repeated route list rejects each call that reads it with SubagentError code INVALID_MODEL_SELECTION_SETTINGS. Ordinary delegation and tools with model selection disabled do not read the route list; a disabled Host setting also leaves the list unread. Sessions record no authorization; earlier subagent/model-selection-policy events are ignored. Route fields require a backend that advertises agentOptions; in-process Spawn and Fork and DSH SDK qualify, while ACP, Codex, and Claude Code fail the mount.

A call supplies provider and model together; reasoning_effort requires both fields in the same call. An effort-only call rejects before route lookup or child creation. Omitting all three fields preserves configured child defaults and their existing fallback behavior. Static provider.agentRouteDefaults, when present, form the provider/model baseline; tool configuration and model fields overlay it before route-aware effort merging and exact-route preflight. Providers without these defaults use compatible values from the parent's latest logged request, then the parent's creation options before its first request, while retaining the configured maxTokens. An explicit provider/model pair without an effort clears configured and inherited effort, even when the route is unchanged, so the selected model resolves its default. The live LLM adapter validates the effective route before child creation. Catalog membership remains advisory, so a model can use an unlisted id when its adapter accepts it.


Understand the implementation

Implementation internals — click to expand

This section explains how the tool mirrors provider lifecycle and settles runs; the observable behavior is covered in Use this package.

Design concept

One instance is one provider plus one tool name. The plugin registers its definition in the owning composition while the provider is present and disposes it when the provider leaves. Each preset revision owns one shared registration, including tools with preset selection. Agents inherit its definitions; switching presets changes scope ancestry without reinstalling tools. Discovery belongs to the instance configured with modelDiscovery and reads the same current Host setting as the delegation executor. A numeric maxDepth or configured LLM selection unsupported by the provider fails the mount. Multiple distinctly named delegation tools may expose model selection in one scope.

Activation ownership

The tool calls ctx.subagents.startActivation() with parent delivery selected. The runtime owns startup cancellation, execution, outcome reporting, and cleanup. A startup failure is an errored tool result. Rejections before startup are coded: a missing calling Agent, llm service, or effective parent route throws ToolContextUnavailableError; an unpaired route field throws ToolArgsError, and an empty route field counts as omitted; and SubagentError reports a disabled selection (MODEL_SELECTION_DISABLED, PRESET_SELECTION_DISABLED), a preset outside the allowlist (PRESET_NOT_ALLOWED), a route the current Host setting does not authorize (MODEL_ROUTE_NOT_ALLOWED), invalid enabled model-selection settings (INVALID_MODEL_SELECTION_SETTINGS), an LLM provider unknown to discovery (LLM_PROVIDER_NOT_FOUND), or a provider replaced during route preflight (PROVIDER_CHANGED). When the caller can call list_subagent_models, unpaired-field and unauthorized-route rejections tell the model to call it. Failures after publication arrive through the completion notice, with diagnostics and partial output preserved by the runtime.

Result acknowledgement

The canonical tool result is { kind: 'activation', name }. It contains no execution Promise or final output; programmatic consumers that need to await results use the subagent service directly.

Context-sensitive wording

The tool's description derives from provider.inheritsParentContext: a fresh child gets "it does not see this conversation" wording, a forked child gets "it does not see the current in-flight turn" wording, so the model never restates or omits context that does not exist.

Source map

File Role
src/index.ts Tool registration, provider lifecycle mirroring, activation requests
src/preset-selection.ts Preset defaults, model allowlist, and selection guidance
src/model-selection.ts Request/config merge and live LLM route preflight
src/model-selection-settings.ts Host-owned opt-in setting read at each delegation and discovery call
src/model-selection-state.ts Declaration of the retired Session policy event, kept so released Session logs stay readable
src/list-models.ts list_subagent_models runtime discovery tool

Further Exploration

Read these pages when the package-level contract is not enough; they move from the tool's runtime behavior to the seam it delegates over and the adjacent child tools.


Model Experience

Tool schema

What the model sees

The generated default subagent schema appears under the configured tool name while its provider exists. An instance with modelSelection adds provider, model, and reasoning_effort in every Session. The provider description tells the model to set the fields only when the task needs a different model and names the omitted-field route: the parent's current model and effort, or the default configured for the tool or backend. It names list_subagent_models as the source of provider ids when the same instance enables modelDiscovery. allowedAgentPresets adds the agent_preset enum and guidance for the default or inherited selection. Context inheritance and continuation support determine task and follow-up descriptions. Agent restrictions apply to inherited preset delegation tools in schemas, execution, and guidance, including when historical toolFilter overrides are restored; sibling Agents remain unaffected. Preset-selection guidance depends only on the tool configuration, so it does not depend on other presets’ declaration order.

Token effect

Fixed schema cost per parent request, including the optional name field; modelSelection adds three optional route fields, while preset selection adds one enum parameter and default guidance. Each tool instance adds one schema; visible delegation tools share one short system-prompt section.

KV Cache effect

Prefix-stable while provider instances and their configuration are unchanged. Adapter catalog changes do not alter the definition. Shipped fork tools omit model-selection fields to preserve reuse of the inherited parent prefix. A custom fork tool may enable selection; changing its route can prevent prefix reuse.

Model selection and discovery

What the model sees

The optional list_subagent_models definition reads the current Host route setting, falling back to the current parent route when the setting is disabled or absent. Calls reject while the optional ctx.llm service is unavailable. With the setting enabled, provider model lists intersect the advertised catalog with its authorized routes. Otherwise, they resolve only the current parent model, even if the catalog omits it. The discovery tool’s description lists what each argument combination returns; an empty query field counts as omitted. Delegation tools document their own selection fields, defaults, and the discovery source. Exact-model queries accept authorized ids absent from the catalog; unauthorized provider/model lookups fail before adapter access. Catalog or exact-model lookup failures and cancellation reject the call. Execution independently enforces the same setting.

Token effect

One fixed discovery schema is present wherever modelDiscovery is enabled, regardless of the Host setting or the owning instance’s modelSelection option; the shipped Web and Desktop presets include it, while headless, SDK, and ACP profiles do not. Route metadata enters the transcript only when the model calls the tool.

KV Cache effect

The schema is prefix-stable across adapter registration and catalog changes. Each discovery result is appended after the reusable prefix.

System prompt

What the model sees

Visible delegation tools share delegation and collaboration guidance, listing tools in name order and instructing the model to start independent delegations together and keep working while they run, and to end its turn instead of sleeping or polling when only waiting for their results remains. Ending the turn works because a settled child notifies its parent and a notice that reaches an idle parent starts one independent model request; hosts that keep children progressing alternate agent.whenIdle() and waitForChildren(agent) (dsh-subagent, session.ts). Hidden or unavailable tools are omitted; no guidance appears when none are visible. With both subagent and subagent_fork visible and the default concurrency limit of 8, the text is:

Tool-guidance section
Start independent delegations with `subagent` or `subagent_fork` together in one assistant message and continue useful work while they run. The concurrency limit of all the subagents is 8. When only waiting for their results remains, end your turn instead of sleeping or polling; the next result starts a new turn. Collect the subagent results required to complete the task before giving the user a final answer.

Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests.

Token effect

Two guidance paragraphs per parent request with visible delegation tools, listing their names and shared-file coordination rules.

KV Cache effect

Prefix-stable while the visible tool names and configured concurrency limit are unchanged; each prompt assembly reads the current limit.

Runtime depth context

What the model sees

When the calling agent reaches or exceeds a visible tool's effective numeric depth cap, an optional runtime-context snapshot tells it to do the work directly. The cap is resolved again at each request, including after settings changes or session resume. Hidden tools and provider-managed limits contribute no depth text. For a child at depth one with a cap of one:

Depth-limit notice
Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.

Token effect

One short contribution per capped tool joins the user-role runtime-context snapshot. Unchanged snapshots are not appended again; agents below the cap receive no additional text. includeRuntimeContext: false suppresses this notice without changing runtime depth enforcement.

KV Cache effect

Depth changes do not alter the system prompt or tool schemas. Updated runtime context appends after existing history; the provider still enforces the cap if the model attempts delegation.

Start result

What the model sees

The description guidance asks for 3–5 words in the language of the user’s current request. The call retains the task description and prompt. Success returns started subagent <name>; startup rejection, including a duplicate or invalid name, returns an error. Child execution details are delivered separately from this acknowledgement.

Token effect

The prompt and acknowledgement remain in parent history until compaction; child working context remains in the child.

KV Cache effect

Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.

Completion delivery

What the model sees

Answer delivery follows the managed delegation rules above. The returned name addresses the child in send_message, interrupt_agent, and Team task owners; only backends with continuation support accept follow-up messages.

Token effect

Messages and completion notices append to parent history independently of the start acknowledgement. The tool result itself contains no final output.

KV Cache effect

Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.

Known Limitations and Deferred Work

These limits define what this tool does not return or enforce; they are current package constraints.

  • This tool does not wait for results — use the completion notice or child messages. Programmatic result waiting belongs to the subagent service.
  • Preset choices omit descriptions — agent_preset exposes ids and default or inheritance guidance only. The schema does not read candidate preset documents, so registration is independent of their declaration order. Use ids that convey each candidate's purpose.
  • Preset references are checked on delegation — Host-mounted and preset-mounted tools both resolve the target when starting a child. A target can be declared or replaced after tool registration, so loading the tool cannot establish its availability for a later call. Misspelled or unavailable ids remain undetected until selected; that call returns an error.
  • Shipped fork tools omit model selection — their configuration leaves modelSelection disabled to preserve inherited-prefix reuse. Custom fork tools may enable it under the same Host authorization and adapter validation as other delegation tools.
  • Depth caps are fixed per instance — another cap requires another distinctly named tool. Child personas and tools belong to the selected Agent Preset. Explicit LLM selection requires modelSelection and is restricted to the routes the Host setting authorizes at call time, or the current parent route when it is disabled.

Dev Note

Working context for maintainers — click to expand

None.