* 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
description, kind
| description | kind |
|---|---|
| Program-based tool execution, generated SDKs, and nested-call limits. | package-reference |
@deepseek-ai/dsh-tool-executor-ptc
English | 中文
Summary
Use this executor when models should call tools through run_code programs. Mount a compatible PTC runtime and tool registry first. Scoped restrictions determine the generated SDK; only run_code is directly callable. Configure the total tool-call limit per program and concurrency for parallel-safe subcalls.
Table of Contents
- Use this package
- Understand the implementation
- Further Exploration
- Model Experience
- Known Limitations and Deferred Work
- Dev Note
Use this package
Add this row to a composition with dsh-tools mounted. The nearest scoped executor selects tool behavior; one scope permits only one executor.
- name: '@deepseek-ai/dsh-tool-executor-ptc'
config:
maxSubCallsPerMinute: 1024
maxParallelSubCalls: 10
Root run_code calls are exclusive and execute serially. maxParallelSubCalls limits parallel-safe nested calls within each program and defaults to 10; it must be a positive integer, with 1 selecting serial execution. Exclusive calls form barriers.
maxSubCallsPerMinute defaults to 1024 and must be a positive integer. Each run_code gets floor(resolved timeoutMs / 60000 × maxSubCallsPerMinute) tool-call attempts: the default Node timeout of two minutes allows 2048. Runtime defaults and timeout caps apply before this calculation; no deadline means no finite call allowance. This is a total allowance, not a rolling window, so calls may happen in a burst. All tool bindings share the count, including queued calls, invalid arguments, and failed tools. The next attempt terminates the entire program through the runtime abort path, cancels active subcalls, and abandons queued calls before returning CODE_RUN_FAILED. As with a timeout, catching a binding error cannot keep the program running; retained runtime state is discarded. Completed tool effects remain, and the next program starts a fresh count.
PtcRuntime providers must report language: 'typescript'. The selected executor rejects other languages during prompt assembly and execution, without falling back to native tools; the /run-code factory rejects them when creating a program tool. Schema reads and execution also validate the current provider. The executor generates a TypeScript SDK and tool schema; the provider supplies execution.
Tool calls retain their declared JSON return values. Passing an unchanged object or array result directly to inspect displays the tool's final text-only output. Fields, copies, modified results, and results nested inside another value use ordinary Node formatting. Use inspect({ ...result }) for an object's raw structure or inspect(result.lines) for selected fields. Scalar results use ordinary formatting; Images and mixed text/image outputs follow the image rules below.
This package declares ctx.ptcRuntime and ctx.systemPrompt as required injections; Agent-owned programs need ctx.workingDirectory. The executor activates only after its runtime is available and withdraws when that runtime unloads. An enabled PTC executor without a runtime stops application startup. A withdrawn PTC selection never falls back to native execution.
Shared dispatch events and the ptc-mode message-source declaration live in @deepseek-ai/dsh-tool-executor-ptc/types; Client code imports the same declarations through @deepseek-ai/dsh-tool-executor-ptc/client. Both entries exclude Host service declarations. Host policy extensions use import type from the package entry for PtcDispatchLog and tools/ptc-dispatch-log without mounting the executor.
The /run-code entry exports createRunCodeTool for plugins that register a named program tool alongside native tools. Supply an explicit runtime and the complete private ToolDefinition list, then register the returned definition in the owning scope. Programs can call only that list, even when the Agent can call other native tools; the private definitions do not enter the tool registry. Nested calls retain normal approvals, guards, dispatch logs, screenshots, deferred context, and turn completion. RunCodeConfig exposes the same validated call-allowance and concurrency settings as this executor.
The caller owns the supplied runtime and must keep it available until the factory's context finishes disposal. For runtimes that retain state or enforce a sandbox, disposal cancels active Agent programs and waits for nested calls; Agent disposal releases its retained environment. Environment initialization belongs to the supplied runtime's registration API; register it before exposing the program tool. The factory appends runtime syntax and execution guidance to the caller's description; the caller supplies instructions for the private bindings.
Understand the implementation
Implementation internals — click to expand
The executor receives the entire raw call batch and owns parsing, scheduling, cancellation, and optional model-step logging. It reuses the shared invocation pipeline for policy, tool bodies, and result notifications. After abort, it waits for started work and returns ordered error results for skipped calls. Unloading the executor aborts active Agent-owned programs whose runtime supports sandboxing or retains state, and waits for their nested calls to settle. Accepted batches still settle through that executor, potentially with cancellation errors.
PTC mode
The PTC executor exposes the reserved run_code transport and a deterministic TypeScript SDK. Each SDK binding captures a frozen ToolSchema and passes it through the scheduler to its execution context. Before policy, a started call records only pairing ids, name, and normalized arguments; its settle event preserves the rendered result, optional presentation metadata, and structured error. Metadata is projected from that call’s canonical value and frozen; it changes neither the program value nor model content. Description and parameters remain transient and never enter Session events or SDK output. Calls are scheduled through a per-run pool that reuses the native concurrency contract. Under ptc alone, a model-direct call naming a program-only SDK tool resolves to UNKNOWN_TOOL before policy — the announced surface and the callable surface stay the same. Intermediate binding values are execution-local; only the outer run_code result has a hard size cap.
Text inspection reuses the completed pipeline's output.render result after content policies. It neither executes the tool nor renders it again. Replacements made only for the dispatch log do not change the program's inspection text.
New sub-calls use <parent>:ptc:<n> ids. Consumers treat these ids as opaque and correlate events by exact equality; restored historical ids retain their original bytes. The PTC mode decision owns durable naming and restoration rules.
TypeScript bindings for read_image and CUA screenshot operations return an Image with a readable path, width, and height. Other tool values are substituted all or nothing: when { type: 'image', attachment } entries reference every image of the finalized result and the program can read each one, those entries become Images, as admitted MCP image blocks do, and the result's text and images reach the model only through inspect; otherwise the value stays raw and the complete result content reaches the model as additional context. Passing it to inspect places its durable attachment among the captured text in the run_code result. Images nested in arrays and objects are displayed with their containing value. On program failure, inspected output accompanies the original diagnostic; outer result replacements remain authoritative. If an output policy removes a screenshot or read_image image, the binding rejects with ToolCallError and includes the retained text notice. Additional contexts retain their producing tool’s attribution.
run_code and tools created by createRunCodeTool report outputTruncated: true when captured output or diagnostic text was truncated. With the Node runtime, display-output overflow discards subsequent output while execution continues under the original timeout and cancellation rules. A normally completed program remains a successful tool result, with a truncation notice directing the model to read current state without repeating completed actions. A later failure keeps its actual error kind and truncation notice. Retained images and settled subcall records remain available.
When the caller cancels and the runtime reports abort, run_code waits for cleanup and returns the native tool cancellation result: AbortError / ABORTED, with Error: tool call aborted as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in turn/end, including a hook's reason. Runtime failures retain CODE_RUN_FAILED and their diagnostics, even if the caller also cancels. A runtime rejection keeps a PtcRuntimeError code and otherwise becomes CODE_RUN_FAILED with the rejection as cause. A blank description, an invalid timeoutMs, or timeoutMs or sandbox_permissions on a runtime that does not support it fails as ToolArgsError with INVALID_ARGS; a call after executor disposal fails with CODE_RUN_UNAVAILABLE; and a missing runtime, workingDirectory, or sandboxPolicy fails as ToolContextUnavailableError. Cancellation can discard retained runtime state and does not undo completed tool effects.
run_code accepts timeoutMs when the mounted runtime supports an override; its schema reports the configured default and maximum, and the runtime's usage instructions. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider sandbox_permissions mode requires a non-empty justification and approval before the program starts. The schema asks the model to write that reason in the current user's language. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. Retained PTC environments follow the standing file policy. PTC observes committed Session mode changes and immediately cancels affected calls in all Node modes. Later PTC calls wait for their nested-tool cleanup before resolving the latest policy. The runtime owns process invalidation and cleanup; permission setters remain synchronous. One-time escalations omit the state owner and complete in a temporary environment; standing variables remain available to ordinary calls.
Custom host integrations retain their PtcExecutor instance and call reset(agent) to clear that Agent's environment; reset is not a model tool or SDK binding. It requires a state-retaining runtime, cancels active calls, invokes release(agent), and waits for process and started nested-tool cleanup without requiring the program to respond. Before admitting new programs, it queues Program environment reset; retained variables cleared. Completed tool effects remain. The notice is logged when consumed; cancellation or Agent disposal can discard it after state is cleared. Concurrent resets share cleanup. Missing or unsupported runtimes reject without blocking admission. Cleanup or notice-admission failure throws CodeResetFailedError; later programs report CodeRunFailedError with host-reset guidance until an explicit retry succeeds. Reset does not undo completed tool effects.
src/index.ts— Scoped registration, tool descriptions, batch execution and host environment reset.src/ptc-calls.ts— Call admission and cancellation; reset waits for runtime release and nested-tool cleanup before admitting new calls.
Further Exploration
Model Experience
PTC mode schema and system prompt
What the model sees
PTC mode exposes the generated run_code schema, the SDK instructions below, and the generated exact TypeScript SDK block. The schema lists code before description; this is presentation order, not an enforced JSON member order. REPL and Script runtimes share the generic tool description and SDK instructions; their executionInstructions supply syntax and state rules. The TypeScript SDK declares inspect(...values) and uses it in the bash example for every execution mode. The instructions identify generated declarations as program-only bindings. When the current bash parameter schema accepts the example arguments, they also show a complete run_code call around tools.bash(...). The tools:sdk section uses first-party order 5000 and disables prompt-variable interpolation, preserving literal {{…}} text in tool descriptions and schemas in TypeScript programs. Under ptc, the prompt also carries the tools:ptc-only rule earlier in the first-party order, so the model reads which tools it may call before it reads what each one is for. Exhausting the tool-call allowance returns a failed run_code result with the limit, rejected call number, termination notice, and possible infinite-loop warning. Runtime cleanup diagnostics and captured output remain visible. TypeScript programs show selected values with inspect(...values). Each argument is rendered independently. The executor omits function returns and final expression values. The Node provider retains the complete native console and captures its stdout and stderr writes; model instructions direct programs to use inspect.
TypeScript PTC mode SDK instructions with bash
## Writing code for run_code
`run_code` takes two required arguments: `code`, the body of an async TypeScript function (erasable syntax only — no `enum` or namespaces; type annotations are advisory, the code runs type-stripped), and `description`, a short summary of what the program does. The declarations below are SDK bindings for this program. A declaration does not make its name a directly callable tool; only names supplied as separate tool schemas may be called directly. When no separate `bash` schema is supplied, invoke a declared `bash` binding inside `run_code`:
`run_code({ code: "inspect(await tools.bash({ description: 'Show current directory', command: 'pwd' }))", description: "Show current directory" })`
Inside the program:
- Call tools as `await tools.name(args)` — quoted access for exotic names: `tools["my-tool"](args)`. Every call resolves to its declared value, which may be an Image. Tool arguments must be lossless JSON.
- A FAILED tool call rejects with `ToolCallError`, whose `toolName` identifies the failed tool and whose `message` is human-readable — `try/catch` it to handle and continue.
- Independent read-only calls MAY overlap under `Promise.all` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`.
- Show selected values and images with `inspect(...values)`; every other intermediate result stays out of the conversation, so extract just what you need.
Program-only SDK bindings:
Tool-call allowance exhausted
Error: code run failed (abort): run_code exceeded its limit of 2048 tool calls (1024 per minute of its timeout); call 2049 was not dispatched. The run_code program may contain an infinite loop. Check loop termination or split the work into smaller run_code calls.
Token effect
Fixed per-request cost proportional to the visible definitions. PTC mode trades end-tool schemas for generated SDK text plus one transport schema rather than promising a universal reduction. The allowance adds no SDK or schema text; its diagnostic contributes tokens through the failed run's result.
KV Cache effect
Prefix-stable while the PTC mode selection, generated SDK, transport schema, and visible tool set are unchanged. Mode or filter changes may invalidate reuse from the first changed prompt or schema token. Changing maxSubCallsPerMinute does not change prompt or schema tokens.
Registered program tools
What the model sees
A factory-created tool presents its caller-supplied name and description with the same program parameters, runtime instructions, and result rendering as run_code. Its private bindings do not produce direct tool schemas or an SDK prompt section. The consumer owns its binding guidance.
Token effect
One program tool schema joins the existing native schemas. The caller's binding guidance adds its own prompt cost; intermediate values remain outside model history unless the program emits them or a nested tool defers context.
KV Cache effect
The schema remains stable while the caller's description and runtime settings remain unchanged. Initialization runs inside the runtime and does not add program source to model requests.
Known Limitations and Deferred Work
These constraints apply to the host integration and accepted calls.
- Program Images need a value reference — read_image, CUA screenshots, and values whose
{ type: 'image', attachment }entries reference every result image yieldImages; other image-producing tools keep their declared values and automatically attach their pictures as additional model context. - Program Images require attachment path mapping — the filesystem must map stored host attachments to readable program paths.
fs-sshhas no such mapping, so read_image and CUA image adaptation rejects in that composition, while value-referenced images stay raw JSON and reach the model as additional context. - No built-in reset control — the shipped Loader plugin does not expose its executor instance through a service, GUI control or SDK endpoint. Hosts needing reset must mount and retain
PtcExecutorin their own composition; that integration owns retries after a failed reset. - PTC mode uses TypeScript, and presentation is per agent rather than per tool — PTC execution requires
ctx.ptcRuntime.language === 'typescript'; within one agent no tool can be native-only while another is ptc-only. - PTC mode intermediate values are execution-local and unbounded by bytes — they cannot be reconstructed from session replay and may exhaust process or worker memory; only the outer
run_codeoutput has the worker's configurable hard cap. - State depends on the runtime: the default backend starts fresh; Node
persistent-in-memoryexecution and Script mode withscriptPersistence: trueretain memory per live Agent. Agent disposal awaits release. Restart and execution failures can clear memory; model-visible guidance explains how to recreate missing variables. Programs and results remain in the Session log, without serializing live objects.
Dev Note
Working context for maintainers — click to expand
None.