Files
deepseek-harness/packages/workflow/tool-workflow
涂轶翔 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
The model-facing workflow tool: run a JavaScript orchestration script that fans out subagents, for users and maintainers choosing or configuring model-driven orchestration. package-reference

@deepseek-ai/dsh-tool-workflow

English | 中文

Summary

dsh-tool-workflow lets a model run JavaScript orchestration that delegates to many subagents and returns a final JSON value. Use it only when the user explicitly requests a workflow or large multi-agent orchestration; prefer plain subagent calls for one or two delegations. Foreground execution waits for all work; cancellation or abnormal completion returns an error rather than partial success. run_in_background: true returns an owned job id immediately and exposes live output. Deployments can rename the tool with toolName and cap rendered results with maxResultChars.

Table of Contents


Use this package

The workflow tool runs a model-authored orchestration script that fans work out across many subagents and returns the script's final JSON value. Use it only when the user explicitly asks for a workflow or for large multi-agent orchestration — an audit over many files, a migration, multi-angle research; for one or two delegations, prefer plain subagent calls.

Calling the tool

The model submits three parameters plus one flag: meta (required identity data: name, description, and optional whenToUse and phases), script (required plain JavaScript body — no export const meta statement; its parameter description carries the body rules and the tool description carries the hook contract), args (optional JSON object exposed to the script as the args global; wrap a bare list in a field so the wire schema stays honest), and run_in_background (optional; present only while enableRunInBackground holds).

A foreground success returns the envelope { kind: 'foreground', runId, agentsStarted, result }, rendered to the model as workflow "<name>" completed (<count> agent<optional-s>). followed by Return value: and the pretty-printed JSON. A workflow that cannot start — a script parse or meta validation failure — returns an error the model can correct from. Cancelling the calling step returns the tool runtime's AbortError ABORTED result; any other cancellation and execution failures return Error: workflow run was cancelled (WorkflowError CANCELLED) or Error: workflow run failed: <error> (WorkflowError with the fatal code that ended the run, such as AGENT_CAP, or RUN_FAILED without one); partial output is never reported as success.

What to expect during a run

While the script runs, the parent turn waits: the tool starts the run, awaits its result, and always disposes it, so the script and its children reach quiescence on every path — including cancellation, which is bridged from the parent step's abort signal. The model sees one final outcome, never intermediate child messages; the children's own work stays out of the parent conversation.

Background runs

run_in_background: true returns { kind: 'background', jobId, runId } immediately: the run is registered on ctx.jobs as an owned workflow job, so the session-header job list streams its phase(), log(), and member lifecycle lines live from the job's output ring, and the row's progress line tracks the current phase. No tool-step signal reaches the run — job_kill, the list's stop control, and owner teardown are what cancel it. Settlement is the job's settlement: a completed run carries the same rendered return value as the job's result (the completion notice announces it, the model's first job_output after settlement carries it once), a cancelled run settles killed with the kill reason, and a failed run settles failed with the script's failure message. Without a live job registry and a controller serving the caller the call fails, naming the missing composition pieces.

Config

Field Default Meaning
toolName workflow The model-facing tool name to register.
maxResultChars 50000 Rendered-result ceiling; longer JSON is truncated with a notice.
enableRunInBackground true Expose run_in_background; disabled calls are also rejected.

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


Understand the implementation

Implementation internals — click to expand

This section explains how the consumer is split from the engine and how the run lifecycle and records work; observable behavior is fully covered in Use this package.

Design concept

The consumer owns the model-facing schema, the tool:<toolName> system-prompt guidance, and the result envelope; script parsing, execution, caps, and cancellation live behind ctx.workflowEngine, while the PTC engine shares Node process confinement with run_code. Usage guidance ships with the tool plugin as a prompt section, never in the deployment persona.

Run lifecycle

execute starts the run and awaits run.result inside a try/finally that always disposes the run. exec.signal is bridged to run.cancel(), including the already-aborted-before-start case. A non-completed stop reason maps to an isError result reporting the reason, rethrowing the caller's abort reason when exec.signal aborted and otherwise throwing a WorkflowError; completion renders { kind, runId, agentsStarted, result }, with the Native renderer truncating only that projection at maxResultChars.

Background lifecycle

A background call registers the run through jobs.start inside the job starter, so a synchronous engine rejection registers nothing and admission preflight runs before the engine spawns. The job's done chains from run.result: dispose (a disposal failure is warned, never rejected into the registry), stop the mirrors, then map the stop reason onto the job outcome. The ring mirror (src/record.ts) subscribes workflow/phase, workflow/log, and member events once per plugin and routes them into the tracked runs' JobHandle faces (append for lines, updateProgress for the phase); a straggling event after settlement finds no tracked run, and an append against a settled job drops inside the registry.

Durable session records

For a root transport execution (exec.parent absent), the tool projects the run into the calling Agent's Session with four log-only events: run-start after start() returns, member starts and endings filtered by run.id, then run-end only after the result is available and disposal reaches quiescence. Nested transport calls execute normally but write no record. The first failed Session append disables later recording for that run with one warning, leaving either no record or a legal continuous prefix without changing the tool result or cleanup.

The engine's workflow/phase and workflow/log events have no per-line durable surface from this tool: the session log deliberately records run and member lifecycle only, and the Web transcript derives from those records. A background run's lines reach a human through the job observation record instead, which is transient by design.

Render intent

Decided up front per the render-intent Agent Note: a generic card titled workflow: <meta.name>, read directly from args.meta.name — presentation is a pure function of args — with the script text carried as rawInput. The result keeps the generic card.

Source map

File Role
src/index.ts Plugin entry: tool registration, run lifecycle, background job registration, recorder wiring
src/record.ts Background runs' live-progress mirror into the job's output ring
src/types.ts The four log-only record event payloads and their SessionEventMap declaration

Further Exploration

Read these pages when the tool-level contract is not enough. They move from the shared workflow model to the engine and the comparable delegation tool.


Model Experience

System prompt

What the model sees

Every parent request in this plugin's registration scope receives the workflow guidance below. A scoped tool restriction can hide the schema without removing this independently registered guidance.

Workflow guidance
Use the <toolName> tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.

Token effect

Small fixed guidance cost per request while the plugin is active.

KV Cache effect

Prefix-stable while the plugin scope and guidance text are unchanged. Activation or disposal may invalidate reuse from this prompt section.

Tool schema

What the model sees

When visible, the generated default workflow schema carries the complete JavaScript hook and metadata contract; toolName can rename the definition, and the model submits script, metadata, and optional args.

Token effect

Substantial fixed schema cost on each request where the tool is visible.

KV Cache effect

Prefix-stable while toolName, definition, and visibility are unchanged. Renaming, plugin lifecycle, or scoped restrictions may invalidate reuse from this schema.

Tool-call history and result

What the model sees

The full model-written script, metadata, and args remain in the assistant tool call. A foreground success is exactly workflow "<name>" completed (<count> agent<optional-s>)., newline, Return value:, newline, and pretty-printed data-dependent JSON; a cap adds … [truncated: <omitted> more characters] on a new line. A background acceptance is exactly workflow "<name>" started in the background as job <jobId>. Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill., and the same rendered value later reaches the model through the job's completion notice and job_output. Failures after a caller abort render the abort reason; other failures are exactly Error: workflow run was cancelled, optionally suffixed (<error>), Error: workflow run failed: <error-or-unknown error>, or defensively Error: workflow run ended abnormally (<reason>); a call without an owning agent becomes Error: workflow tool requires a calling agent (exec.agent was undefined) (ToolContextUnavailableError). Intermediate child messages are omitted.

Token effect

Call tokens can be large and remain until compaction. Result rendering is capped by maxResultChars; child-model tokens are separate from the parent's retained context.

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 the tool does not yet support. They are current constraints, not a task backlog.

  • A background run reports no intermediate value to the model — job_output before settlement returns status only; the return value arrives whole at completion, and cancellation still discards partial output.
  • args must be an object and Native result text is bounded — callers wrap top-level arrays and scalars in a field; the canonical workflow result stays complete, while JSON beyond maxResultChars is truncated in the model-facing projection rather than stored behind a retrieval handle.
  • Workflow policy is fixed per tool registration — provider selection, caps, and tool name are deployment config, not model-call arguments.
  • Durable records are top-level and observational — nested PTC mode dispatches are not recorded, and a recording failure intentionally degrades to an incomplete prefix rather than changing execution.
  • No recorded-session scenario replays a background run yet — unit and real-engine composition suites cover the path; the snapshot tree pins only the schema and prompt text.

Dev Note

Working context for maintainers — click to expand

This Dev Note is working context for maintainers: open directions that are not decided. It is explicitly non-authoritative — shipped behavior, limits, and accepted rationale live in the sections above, the package code, and the linked Agent Notes.

Open directions: storing truncated JSON behind a retrieval handle instead of clipping the projection; recording nested dispatches beyond the top level; a recorded-session scenario for the background path.