Repository navigation
ptc
The design-level companion to the Subagent Design page — the two-axis role model that makes
execute_codeexecutor-only — to the Subagent System README — the runtime and API reference whose role table lists the tool — and to the Tool Sandbox page — the confinement stack thatterminal,python_repl, and PTC'sexecute_coderesolve. This page documents what PTC is, why a script executes in a separate process, how it reaches real tools, what the containment actually guarantees, and where it is honestly weaker than an OS sandbox.
Source of truth: agent/tools/ptc/**, config/features/agent_side/ptc.py, config/features/agent_side/tools_timeouts.py, agent/tools/subagent/types/functional_role.py, agent/tools/subagent/spawn/core.py, agent/tools/subagent/spawn/system_prompt.py, agent/tools/pub_base/env_scrub.py, agent/tools/pub_base/sandbox.py, and tests/agent/tools/ptc/**. Every statement below was verified against that code.
- Overview
- Design Rationale
- Protocol and Artifacts
- Replay and Prefill
- Security Model
- Configuration
- Limitations
- Failure Modes
- Test Map
- Related Documentation
Programmatic Tool Calling (PTC) is the capability behind the execute_code tool: the model writes one Python script, and that script calls Sherry's real tools synchronously through generated wrappers. It targets the shapes a turn-by-turn tool loop handles badly — three or more tool calls with processing logic between them, loop- and branch-shaped tool use, and large tool outputs that should be filtered before they ever enter the model context.
| Question | Answer |
|---|---|
| Who can call it? | Only the executor functional role; the gate is PTC_ROLES, so the main agent and every other functional role never receive the tool |
| Where does the script run? | In a separate Python child process, spawned per invocation with its own process group, so a timeout kills the group |
| How does the script reach tools? |
from sherry_tools import ... — a generated stub whose every wrapper is one newline-delimited JSON request over a loopback TCP socket to the parent RPC server |
| Whose session do tools run in? | The child's own child_session_key, bound when the tool is constructed and injected into every RPC dispatch — never a script argument |
| What comes back? | One JSON envelope with status (ok / timeout / error / budget_exceeded / sandbox_unavailable), output, error, exit_code, tool_calls_made, and a bounded calls_log of per-call previews |
A script is ordinary Python plus the generated wrappers — no async, no context object, one synchronous call per tool:
from sherry_tools import json_parse, read_file
raw = read_file("README.md")
print(json_parse(raw)["total_lines"])executor child agent
└─ execute_code(code)
└─ run_ptc: RPC listener + temp dir + sherry_tools.py stub + wrapper script
└─ python child process (restricted builtins, scrubbed env, own process group)
└─ from sherry_tools import read_file
└─ one-shot TCP to 127.0.0.1:<ephemeral port>
└─ parent event loop → real BaseTool.ainvoke(session_id=<child key>)
A separate process, not an in-process exec. "Restricted builtins" and a "scrubbed environment" are only meaningful when the interpreter is disposable. The parent installs a reduced __builtins__ namespace in the child and passes env=scrub_env() to a process it can SIGKILL. A wall-clock budget needs a killable process group; an accidental infinite loop, a crash, or a fork bomb stays inside the child. In-process exec would share the parent's globals and could not be terminated that way.
A bridge, not tool objects. Real tools are async BaseTools that need the parent event loop, the provider configuration, and a session to resolve state against — the opposite of what belongs in a disposable interpreter. The generated stub sends arguments over the socket, and the parent dispatches each request onto its own loop with asyncio.run_coroutine_threadsafe, so a blocking child never blocks the parent's async work.
The division of labor with python_repl. Both surfaces execute model-authored Python with a mirrored restricted-builtins set and the same scrub_env, and both resolve the child cwd from the session's project directory (ROOT_DIR only when no binding exists). They differ in shape: python_repl runs one snippet under a 30-second budget with no tool access, while execute_code runs a longer script (120-second budget) that can synchronously call up to 50 real tools. That extra reach is exactly why PTC is executor-only, and why it adds a process group, an RPC bridge, a call budget, and an import allowlist. The executor role keeps python_repl; PTC is additive, not a replacement. Both also resolve the same OS-native sandbox backend: the PTC child argv is wrapped exactly like a sandbox=True python_repl call (see the Tool Sandbox page), with auto degrading and required refusing as described under Limitations.
One named gate for the tool face. PTC_ROLES — a single set in agent/tools/subagent/types/functional_role.py containing executor — is read by both the injection site (spawn/core.py, after the role allow/deny policy) and the prompt builder (spawn/system_prompt.py, one PTC guidance section). The tool face and its prompt section therefore cannot drift apart, and the executor role definition file stays free of PTC-specific wiring.
A fail-closed tool set. build_ptc_tool filters the child's available tools through the allowlist and removes execute_code itself. Listing a tool the executor does not carry is harmless; the intersection is what is enforced, and sessions_spawn / sessions_yield / sessions_kill / sessions_steer / memory / skill_manage / question are never eligible.
Seven modules, one responsibility each:
| Artifact | Responsibility |
|---|---|
tool.py |
Defines ExecuteCodeTool (execute_code), binds the child session, intersects available_tools with ptc_allowed_tools, and renders the model-facing description from the live tool schemas |
runner.py |
run_ptc orchestrates one invocation: start the RPC server, create the temp dir, generate sherry_tools.py, write the wrapper script, generate a one-time RPC token, wrap the child argv with the OS-native sandbox backend, spawn the child, capture and truncate its output, then clean up |
rpc_server.py |
The loopback TCP listener: parses one JSON request per line, authenticates every frame against the per-run token, enforces the per-script call budget, and dispatches each call onto the parent event loop |
stub_generator.py |
Derives ToolStub specs from each tool's tool_call_schema and renders the sherry_tools.py module — one synchronous wrapper per tool plus local helpers; the RPC call reads the token from SHERRY_PTC_RPC_TOKEN rather than embedding it |
builtins.py |
Owns the child's reduced builtin namespace and the import allowlist, and renders both into the wrapper script |
scripts.py |
Resolves ptc__<plan_key>__<step_id>.py under a skill's top-level scripts/; fail-open on ambiguity, escape, or size |
compiler.py |
Turns one step's verified evidence into replay source; static import/syntax validation only, never executes the script |
The wire protocol is one JSON object per line, in both directions:
{"tool": "read_file", "args": {"file_path": "README.md"}, "token": "<one-time token>"}
{"ok": true, "result": "..."}
{"ok": false, "error": "PTC call budget exhausted", "code": "PTCCallBudgetExceeded"}Signature fidelity. Stub parameters come from tool_call_schema, not args_schema, so arguments the framework injects (such as session_id) never appear as callable parameters. A required field renders as a required parameter; an optional field renders with its default as a Python literal, and a default with no literal form falls back to None — the real tool re-validates every call anyway. The generated module also carries three local helpers that never touch the RPC bridge: json_parse (a lenient json.loads), shell_quote (shlex.quote), and retry (exponential backoff).
Artifacts and lifecycle. Each invocation gets a fresh sherry_ptc_* temp directory holding sherry_tools.py and the wrapper script; the child's only path addition is PYTHONPATH=<tmpdir>. The child environment also carries the per-run RPC token in SHERRY_PTC_RPC_TOKEN, which the generated stub reads and sends on every request; the token is generated with secrets.token_urlsafe, lives only in memory, and is never written to sherry_tools.py or any other file. When a backend is usable the child argv is additionally wrapped by backend.wrap(argv, env, writable_roots, allow_network=True) (the sandboxed path in Tool Sandbox); the process is still spawned with start_new_session=True, so a timeout SIGKILLs the whole group. The wrapper captures the user script's stdout and stderr into buffers, prints a single JSON envelope to the real stdout, and the runner classifies it into the status field. The finally block stops the RPC server, joins its thread, removes the temp directory, and re-kills the child if it somehow survived.
Child session. spawn/core.py passes the run's child_session_key as the tool's session, and rpc_server.py injects it into each ainvoke call via the runnable config. A script cannot supply or spoof a session: session_id is not a tool parameter at all.
A second, system-triggered use of run_ptc replays a verified TaskFlow step. It is not execute_code: the LLM does not choose the script, write it at replay time, or run the step.
plan completion
└─ skill review passes
└─ (ptc_prefill_enabled) compile one script per successful step:
skills/auto/<owning-skill>/scripts/ptc__<plan_key>__<step_id>.py
TaskFlow step spawn
└─ _execute_subagent_scoped
└─ executor only: resolve plan_key + step_id, find exactly one script
├─ run_ptc(role-filtered tools_map, child session, cwd=spawned cwd)
│ ├─ ok + exit 0 + non-empty stdout + all calls_log ok + schema ok
│ │ → skip _build_child_agent / LLM / goal loop; stdout is the result
│ └─ otherwise → render [PTC Pre-run Progress] → normal React
└─ no script / ambiguity / unsafe id / non-executor → normal React
Trigger. The replay is triggered by the normal TaskFlow step spawn, not by a tool call and not by skill review itself. The prefill hook is in _execute_subagent_scoped before _build_child_agent; the master switch is PTC["ptc_prefill_enabled"] (shipped False). It runs only for functional_role in PTC_ROLES (executor). The plan key is derived from the root main session (run.controller_session_key, normalized), because a nested spawn's immediate requester can be a child key.
Success contract. status == "ok", exit_code == 0, non-empty output, a non-empty calls_log, and every logged call ok is True. If the spawn carries output_schema, the output must also pass validate_structured_output. A hit does not build a child agent, create a checkpointer, call the completion judge, or run the goal loop; the script's stdout becomes result_text and the run finalizes with handoff=None.
Failure contract. Any miss appends a [PTC Pre-run Progress] block to the child's initial user message and starts normal React. The block lists the completed prefix (side effects are real; do not redo) and the first failed call. calls_log records both raised tool errors and tools that returned ToolMessage(status="error"); entries are bounded, JSON-safe previews, not full results. A script that catches a tool error still counts as failed for replay progress.
Script ownership and lookup. The compiler returns source only; the caller validates it statically and writes it through skill_manage(action="write_file") into the changed skill's top-level scripts/. Lookup is a filesystem scan under AUTO_SKILLS_DIR/**/scripts/ for the exact basename: zero hits, multiple hits, path escape, a symlink, an unsafe step_id, or an oversized file all mean React, never a guess. compiler.py owns the prompt/static validation; scripts.py owns lookup/read.
Known limits. Replay is executor-only, so PTC's role boundary is not widened. The MVP does not journal across a step retry: a re-spawned step may repeat script side effects. A script can be stale after the plan or code changes; the observation switch exists to measure that before enabling the path. PTC handles tool-call-level prefill; LDW owns step-level journal replay.
The controls below are capability reduction, not an OS boundary — the honest position is stated in Limitations.
-
Environment scrubbing. The child environment starts from
scrub_env(): variable names containingKEY,TOKEN,SECRET,PASSWORD,CREDENTIAL,PASSWD,AUTH,DSN,WEBHOOK,BEARER, orAPIKEY(case-insensitive) are dropped, Sherry's own*_API_KEYvariables are denied explicitly, and critical names such asPATHare kept by exact-name precedence. The runner then adds onlyPYTHONPATH,PYTHONUNBUFFERED, and the per-run RPC token (SHERRY_PTC_RPC_TOKEN). -
Restricted builtins. The wrapper executes user code with a reduced
__builtins__:open,exec,eval,compile,globals,locals,input, andbreakpointare absent, as areexit,quit, andhelp.print, collection types, andgetattr-family introspection helpers remain. -
Guarded imports.
__import__is not removed wholesale — the import bytecode needs it — but it is replaced by a guard that resolves only the allowlist (sherry_tools,json,re,math,time,csv,datetime,collections,itertools,functools,statistics,string,textwrap,decimal,random,fractions,heapq,bisect).import osraisesImportError;jsonandsherry_toolspass. -
Per-script tool-call budget. The RPC server refuses the 51st call: the budget check runs before dispatch, exceeding it raises
PTCCallBudgetExceeded, and the envelope's status becomesbudget_exceeded. An unknown tool name is rejected without consuming budget. -
Wall-clock timeout and process-group kill. The child runs under
ptc_timeout_seconds(120 s). On expiry the runner SIGKILLs the whole process group (start_new_session=True), so grandchildren die with it, then captures whatever output the pipes still hold and reportsstatus: "timeout". -
Output caps. stdout is truncated at 50 KB and stderr at 10 KB, each with an explicit
...[truncated N bytes]marker, before the envelope reaches the model. -
Loopback-only RPC with a one-time token. The listener binds an ephemeral port on
127.0.0.1; the constructor refuses0.0.0.0,::, and the empty host outright, and the bound address is re-checked before it is handed to the child. Every request frame must also carry the per-run token the child reads fromSHERRY_PTC_RPC_TOKEN; the server compares it in constant time, and a missing or wrong token makes it drop the connection immediately, without a response, so a stray local process can neither invoke tools nor learn whether a guess was close. -
Child-session isolation. Every dispatched tool call carries the child's
session_idin its runnable config, so tools resolve state against the child session. The parent session is never exposed through PTC. -
Anti-recursion and privilege exclusion.
execute_codeis not in its own allowlist, and the spawn, memory, skill-management, and question tools are excluded by configuration — a script cannot spawn agents, manage skills, or ask the user from inside the sandbox. -
Main-agent invisibility. No PTC builder is registered in
_MAIN_TOOLS_BUILDERS; the tool is constructed only inside child-agent assembly, and only when the role is inPTC_ROLES. -
High-risk gate on every inner call. The RPC dispatch applies the same decision table
ToolGuardrailsuses (pub_base/high_risk_gate.py): the executed-operation ledger, the keyword registry and the recorded approvals. A refused call is recorded in the script'scalls_logas a failed step, so the prefill falls back to React where the normal approval flow runs — a script can never approve itself, and a refusal cannot be silently swallowed. Ordinary tools (read/write/patch/search/web) short-circuit on metadata and never open the ledger. The compile step skips a step whose evidence matches a blocker, so a script that could only fail at replay is not written at all; the escape switchHIGH_RISK_GUARD["replay_path_gate_enabled"]restores the pre-gate behaviour.
| Key | Default | Governs |
|---|---|---|
ptc_timeout_seconds |
120 | Wall-clock budget for one script, and the per tool-call dispatch window |
ptc_max_tool_calls |
50 | Tool calls one script may dispatch before the budget error |
ptc_max_stdout_bytes |
50000 | stdout retained from the child before truncation |
ptc_max_stderr_bytes |
10000 | stderr retained from the child before truncation |
ptc_allowed_tools |
read_file, write_file, patch_file, terminal, search_files, web_search
|
Allowlist intersected with the child's available tools |
ptc_prefill_enabled |
False |
Enables skill-review script compilation and spawn-side PTC prefill; keep off during the observation pass |
extraction.flow_extraction_enabled (Presets & Role → Advanced) |
True |
User-facing flow-replay switch; gates the COMPILE half (PTC + LDW) globally and is read-only per session. Replaying an existing script is not gated |
ptc_script_max_bytes |
20480 |
Maximum compiled script read from a skill's scripts/ directory |
ptc_compile_max_attempts |
2 |
Compiler attempts on JSON/syntax misses; compilation never executes the script |
The object lives in config/features/agent_side/ptc.py; the shared per-tool registry in config/features/agent_side/tools_timeouts.py also declares ptc_timeout_seconds with the same 120-second default, while the runner's timeout comes from the PTC object. PTC adds no pip dependency: its implementation is the standard library plus the already-present LangChain and loguru packages.
-
It is not an OS-level sandbox on its own. The restricted namespace and the import guard constrain what a literal script can name, but
getattrand the other introspection builtins remain available, so a determined script can walk reachable objects and reach capabilities beyond its literal surface. That is the restricted-namespace tier — the same tier as the existingpython_replwrapper builtins. On top of it, the child argv is now wrapped by the same OS-native sandbox backendterminalandpython_replresolve (bubblewrap on Linux, Seatbelt on macOS) whenever a usable one exists, so it gains their write containment and read-shield. Two honest caveats remain: withSANDBOX_POLICY=auto(the default) and no usable backend the run degrades to unsandboxed after exactly one loguru warning; and PTC passesallow_network=True, so bwrap adds--share-netbeside--unshare-all— the child must reach the parent's loopback RPC listener, and a private network namespace would make the tool bridge unreachable. The write/read sandbox is unchanged. See Tool Sandbox for the backends themselves. - Timeout cancellation is best effort. When a tool call exceeds its dispatch window the server cancels the future it holds, but a coroutine already executing on the parent loop may still run to completion; the script receives a timeout error while the tool's side effects may continue.
-
Every invocation pays setup. There is no warm pool: each
execute_codecall creates a temp directory, generates the stub, starts an RPC thread and a fresh interpreter, and tears everything down. A single trivial call costs a process launch. -
The child's working directory is the session's project directory.
ExecuteCodeTool._resolve_cwd()uses the session binding, and spawn-side replay forwardsrun.spawned_cwd;ROOT_DIRis only the unbound fallback, so relative paths follow the project the executor is working in. - Output caps are lossy by design. Beyond 50 KB of stdout or 10 KB of stderr the tail is replaced by a byte-count marker; a script that prints a large table gets a truncated one.
- Envelope-dependent reporting. If the interpreter fails before the wrapper prints its envelope, there is no structured output to parse; the runner surfaces the raw stderr as the error and stdout may be empty.
-
The RPC token is not a cross-user boundary. The listener now requires the one-time token, so a local process that cannot read it can no longer invoke tools or even complete a request. But the token travels through the child's environment, so any same-user process that can read
/proc/<pid>/environduring the script's short lifetime can still recover it; the token defends against unrelated local processes, not against a same-user attacker. The listener also still binds loopback only and lives only for the duration of one script.
| Failure | Observable | Degradation |
|---|---|---|
| Budget exhausted |
status: "budget_exceeded", error naming PTCCallBudgetExceeded
|
Further calls keep failing; the script may catch the error, and the parent turn still receives the partial output |
| Wall-clock timeout |
status: "timeout", a negative exit_code from the SIGKILL |
The process group is dead; partial stdout and stderr are captured up to the caps; the parent turn continues normally |
| Sandbox required but unavailable |
status: "sandbox_unavailable", error naming SANDBOX_POLICY=required
|
The run is refused before any child is spawned; the parent turn gets an actionable hint to install bubblewrap / set SANDBOX_POLICY=auto
|
| Output truncation |
output or error ends with ...[truncated N bytes]
|
The script completed; only the copy returned to the model is clipped |
| Tool error | RPC response {"ok": false, "error": "TypeError: ..."}
|
The stub raises RuntimeError; a script may catch it, and an uncaught one lands in the envelope's error
|
| Import denied | ImportError: import of 'os' is not allowed in PTC |
The script may catch it; uncaught, it lands in the envelope's error
|
| RPC disconnect | Stub raises RuntimeError: PTC RPC connection closed before a response arrived
|
The server returns to accept and serves a reconnecting child; a script that does not retry fails with the error envelope |
| Unknown tool name | RPC response {"ok": false, "error": "unknown tool: ..."}
|
The call is rejected without consuming budget, so the script can fall back to another tool |
| Interpreter-level failure | No envelope; raw stderr becomes error, status: "error"
|
stdout may be empty; the model sees the interpreter's own message instead of a structured report |
| Area | Tests |
|---|---|
| Tool surface: identity, allowlist intersection, bound session, anti-recursion | tests/agent/tools/ptc/test_tool.py |
| Stub generation: signature matching against real schemas, injected-argument exclusion, local helpers | tests/agent/tools/ptc/test_stub_generator.py |
| RPC protocol: loopback refusal, JSON round-trip, budget, tool errors, reconnect, stop | tests/agent/tools/ptc/test_rpc_server.py |
| RPC token handshake: correct / missing / wrong, immediate connection close on rejection | tests/agent/tools/ptc/test_rpc_auth.py |
Sandbox policy mapping: backend wrap, required refusal, auto degrade with one warning, off
|
tests/agent/tools/ptc/test_sandbox_integration.py |
| Runner hardening: per-run token uniqueness, token absent from the generated stub file, backend wrap applied to the child argv, the single degrade warning | tests/agent/tools/ptc/test_runner_hardening.py |
| Child process: end-to-end tool call, restricted builtins, import gate, timeout kill, truncation, env scrubbing, temp-dir cleanup | tests/agent/tools/ptc/test_runner.py |
| Role grid: executor injection, the other four roles, prompt guidance, main-registry isolation | tests/agent/tools/ptc/test_integration.py |
| Replay calls_log: success, raised tool error, error-returning tool, budget failure, JSON-safe previews | tests/agent/tools/ptc/test_calls_log.py |
| Replay lookup: unique/none/ambiguous/nested/symlink/unsafe/size | tests/agent/tools/ptc/test_replay_scripts.py |
| Replay compiler: JSON contract, static validation, retry | tests/agent/tools/ptc/test_compiler.py |
| Skill-review compile handoff: owning skill, skip, disabled flag | tests/agent/middlewares/test_skill_review_ptc_compile.py |
| Spawn prefill: executor gate, success skip, schema miss, React progress | tests/agent/tools/subagent/test_ptc_prefill.py |
| Hermetic replay end to end: a skill-owned script runs through the real PTC child + prefill | tests/full/test_ptc_replay_e2e.py |
Real-LLM end to end: an executor child chooses execute_code and reads a file over RPC |
tests/agent/tools/subagent/test_ptc_executor_e2e.py |
The PTC suites run in the hermetic groups (unit, integration, module); the replay e2e is hermetic and runs a real PTC child with a fake tool. The end-to-end file is the only llm_e2e test: it is deselected by default, runs in the dedicated real-LLM job, and proves the actual model path — the child must call execute_code, the captured envelope must report a dispatched RPC call, and the printed line count must match a count computed from the file at test time, which the sandbox cannot produce without read_file because open is absent there.
| Page | What it covers |
|---|---|
| Subagent Design | The two-axis role model (depth role × functional role) and why execute_code is an executor-only face |
| Subagent System README | Runtime and API reference: spawn pipeline, role table with the tool list, and registry behavior |
| Tool Sandbox | Environment scrubbing and the OS-native isolation that terminal, python_repl, and PTC's execute_code resolve — including the auto degradation and required refusal PTC inherits |
Generated from the repository's wiki/ tree. Source