Turn the subagent extension into the pi-subagent Pi package

Move the extension from ~/.pi/agent/extensions/subagent into this repo
and package it for pi install:

- Sources under src/, entry exposed via the pi manifest in package.json
- Host packages (@earendil-works/*, typebox) stay peer dependencies
- Tests, TLA+ spec, and research notes move along unchanged in behavior
- Gates (.pi/verify.json): typecheck, tests, tlc, smoke — all green
- Install: pi install git:git.rwiesner.com/alex/pi-subagent or local path
This commit is contained in:
alex committed 2026-11-25 13:40:16 +00:00
1 parent 496e6334c9
commit 4deccb95ef
33 files changed
+7180

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
node_modules/
states/
*.log
+8
View File
@@ -0,0 +1,8 @@
{
"gates": [
{ "name": "typecheck", "command": "npm run check", "on_settle": true },
{ "name": "tests", "command": "npm test", "on_settle": true },
{ "name": "tlc", "command": "npm run modelcheck" },
{ "name": "smoke", "command": "npm run smoke" }
]
}
+11
View File
@@ -0,0 +1,11 @@
# Changelog
## [0.1.0] - 2026-11-25
Initial release as a Pi package.
- `subagent` tool: synchronous single, parallel, and chain delegation to named Pi agents in isolated child processes.
- `subagent_async` and `subagent_jobs` tools: start jobs without waiting, then list, get, wait, or cancel them.
- `/subagents` command, footer status line, and persisted job snapshots across reload and resume.
- One shared FIFO scheduler with bounded workers (`PI_SUBAGENT_MAX_WORKERS`), bounded async admission, and process-tree cleanup on shutdown.
- TLA+ spec (`spec/SubagentJobs.tla`) model-checked with TLC; test suite and deterministic verification gates.
+150
View File
@@ -0,0 +1,150 @@
# Pi subagents
Delegate work to named Pi agents in isolated child processes. The extension provides synchronous execution for a result the parent needs immediately and asynchronous jobs for work the parent can retrieve later.
Distributed as a Pi package: the `pi` manifest in `package.json` exposes the extension entry at `src/index.ts`, with host packages (`@earendil-works/*`, `typebox`) declared as peer dependencies.
## Install
```bash
pi install git:git.rwiesner.com/alex/pi-subagent
```
Or from a local checkout:
```bash
pi install /path/to/pi-subagent
```
## Tools
### `subagent` — synchronous
Preserves the original blocking interface. Exactly one invocation shape is required:
```json
{ "agent": "scout", "task": "Inspect the extension lifecycle" }
```
```json
{
"tasks": [
{ "agent": "scout", "task": "Inspect lifecycle" },
{ "agent": "reviewer", "task": "Review the result", "cwd": "../project" }
]
}
```
```json
{
"chain": [
{ "agent": "scout", "task": "Investigate the design" },
{ "agent": "reviewer", "task": "Review this report: {previous}" }
]
}
```
Parallel accepts at most eight tasks. Chain replaces every `{previous}` placeholder with the preceding step’s final output and stops at the first failure.
### `subagent_async` — start without waiting
Accepts the same invocation fields as `subagent`, validates the complete invocation, and returns a job ID immediately. Available in TUI and RPC sessions. Print/JSON calls return an error directing the caller to `subagent`.
```json
{ "tasks": [{ "agent": "scout", "task": "Research storage" }] }
```
Async jobs survive the current tool call and model turn. Completion does **not** inject a message or start a model turn automatically.
### `subagent_jobs` — inspect and control
```json
{ "action": "list", "activeOnly": true }
{ "action": "get", "jobId": "job_0001" }
{ "action": "wait", "jobId": "job_0001", "timeoutSeconds": 30 }
{ "action": "cancel", "jobId": "job_0001" }
```
- `wait` defaults to 30 seconds and accepts values greater than zero up to 300 seconds. Timeout returns `timedOut: true` without changing the job.
- Aborting a wait stops only that wait. Aborting a synchronous invocation cancels that invocation.
- `cancel` is idempotent for terminal jobs. It prevents queued tasks from starting and terminates running process trees.
- Unknown or evicted IDs and malformed requests are management errors. A successfully retrieved `failed`, `cancelled`, or `interrupted` job is not a management-tool error.
Avoid tight polling: use `wait` when the parent cannot proceed without the result.
## Human inspection
```text
/subagents
/subagents job_0001
/subagents cancel job_0001
```
The footer shows the number of active jobs. `/subagents` lists active and retained terminal jobs; the detailed view includes tasks, diagnostics, output, timing, and usage.
## Scheduling and admission
Synchronous and asynchronous work share one FIFO scheduler. At most four child processes run globally by default.
```bash
export PI_SUBAGENT_MAX_WORKERS=8
```
Valid worker values are integers from 1 through 32. Invalid values fall back to four with a warning. A session accepts at most 64 nonterminal async jobs; excess admission fails atomically without spawning work. Cancelling or finishing jobs frees admission capacity.
Before admission, the extension validates all agents and directories. Relative `cwd` values resolve against the caller’s `ctx.cwd`. Agent discovery is performed separately at each task’s resolved directory, so project-local agents follow the task rather than the parent process’s incidental directory.
`agentScope` is `user` by default. Use `project` or `both` for project agents. In an untrusted interactive project, every distinct project-agent source requires confirmation; a trusted session exempts only its own project-agent directory, not foreign directories selected through task `cwd`. `confirmProjectAgents: false` bypasses prompts and should be used only for trusted projects. Noninteractive print/JSON sessions cannot display confirmation prompts and retain the existing no-prompt behavior.
## States and outcomes
Jobs use:
```text
queued → running → succeeded | failed | cancelled | interrupted
↘ cancelling → cancelled
```
Tasks use `queued`, `running`, `succeeded`, `failed`, `cancelled`, and `interrupted`.
- Single mirrors its task outcome.
- Parallel runs all admitted tasks unless cancelled. Any failed task fails the job, while successful results remain available.
- Chain records only executed steps and stops on failure.
- Spawn errors, nonzero exits, error/aborted stop reasons, and termination signals are failures.
- Once cancellation is processed, a later successful process exit cannot change the outcome.
On reload, quit, `/new`, resume, or fork, unfinished jobs become `interrupted`; the extension stops admission and awaits process-tree cleanup. It sends `SIGTERM`, then `SIGKILL` after five seconds when necessary. Normal Pi shutdown awaits this handler. Hard crashes, `SIGKILL`, and forced exits cannot guarantee cleanup.
There is no per-task execution timeout. Work runs until completion, explicit cancellation, or session shutdown.
## Results, history, and usage
Async snapshots retain per-task final output up to 50 KiB and a valid-UTF-8 stderr tail up to 64 KiB, with explicit truncation metadata. Raw message/tool transcripts are retained for synchronous rendering but not for async history.
Pi custom entries persist bounded job snapshots outside model context. Reload/resume restores them for inspection; restored unfinished jobs become `interrupted`, never runnable. `/new` starts empty. `/tree` navigation replaces terminal history from the active branch without disturbing live jobs. Active jobs plus the 50 most recent terminal jobs are retained; oldest terminal history evicts first.
Child token/cost usage is aggregated in snapshots for inspection. It is not automatically added to the parent tool’s usage because repeated `get` and `wait` calls could otherwise double-count it.
## Child runtime
Each task remains a real `pi --mode json -p --no-session` process and inherits the existing model, thinking, tool, context-file, skill, extension, and MCP behavior. Agent markdown bodies are passed as appended system prompts.
Children always receive `--exclude-tools subagent*`, preventing recursive dispatch and worker-pool deadlocks. Other startup isolation is unchanged.
## Development
```bash
npm install --ignore-scripts
npm run check
npm test
npm run modelcheck
npm run smoke
```
`spec/SubagentJobs.tla` models the bounded scheduler and lifecycle. TLC checks worker bounds, legal state invariants, terminal stability, chain ordering, and cancellation/shutdown behavior. Set `TLA2_TOOLS_JAR` if `tla2tools.jar` is not at the local development fallback path.
Tests exercise the manager interface, tool schemas/adapters, real subprocess behavior with a fake Pi executable, generated transition sequences, UTF-8 properties, and persistence. `.pi/verify.json` wires the deterministic gates.
## `pi-durable` evaluation
This implementation intentionally uses Pi-native subprocesses and custom entries, not `@earendil-works/pi-durable`. The pinned comparison and rationale are in [`research/pi-durable-async-subagents.md`](research/pi-durable-async-subagents.md).
+1748
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
{
"name": "pi-subagent",
"version": "0.1.0",
"description": "Synchronous and asynchronous subagents for Pi.",
"type": "module",
"keywords": ["pi-package"],
"files": ["src"],
"pi": {
"extensions": ["./src/index.ts"]
},
"scripts": {
"check": "tsc --noEmit",
"test": "node --test --test-concurrency=1 test/*.test.ts",
"test:manager": "node --test --test-concurrency=1 test/manager.test.ts",
"modelcheck": "java -jar ${TLA2_TOOLS_JAR:-/home/alex/projects/pi-verify/vendor/tla2tools.jar} -cleanup -config spec/SubagentJobs.cfg spec/SubagentJobs.tla",
"smoke": "pi -e . --help >/dev/null"
},
"peerDependencies": {
"@earendil-works/pi-agent-core": "*",
"@earendil-works/pi-ai": "*",
"@earendil-works/pi-coding-agent": "*",
"@earendil-works/pi-tui": "*",
"typebox": "*"
},
"devDependencies": {
"@earendil-works/pi-agent-core": "1.6.0",
"@earendil-works/pi-ai": "1.6.0",
"@earendil-works/pi-coding-agent": "1.6.0",
"@earendil-works/pi-tui": "1.6.0",
"@types/node": "^24.0.0",
"fast-check": "^4.0.0",
"typebox": "^1.4.7",
"typescript": "^5.9.3"
}
}
+303
View File
@@ -0,0 +1,303 @@
# `pi-durable` as a foundation for async subagents
**Pinned upstream commit:** [`e2cb38ac149b440560e1f66da26613bf25f42937`](https://github.com/earendil-works/pi/commit/e2cb38ac149b440560e1f66da26613bf25f42937) (2026-11-25). All upstream line references below are against this commit.
**Host examined:** installed `@earendil-works/pi-coding-agent` 1.6.0. The installed tree does **not** contain `@earendil-works/pi-durable`; the package is published separately (npm latest is 1.6.0), but it is not bundled with the coding agent.
**Assumption:** “Option C” means embedding a `pi-durable` `Harness` inside the Pi extension process to run async jobs while the parent Pi session remains the UI/model loop. It does not mean replacing the Pi CLI with `pi-durable`. If C instead means replacing Pi, the fidelity gaps below become larger, not smaller.
## Executive summary
- `@earendil-works/pi-durable` is a **complete durable in-process agent harness**, not a subprocess supervisor. It owns conversations, model turns, tool calls, submissions, tasks, compaction, and crash recovery, using `pi-ai` for model access and Chord for documents ([README:3-7](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L3-L7), [registry.ts:10](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/registry.ts#L10)).
- Its genuinely useful capabilities for this problem are the **task state machine, ownership/abort tree, explicit waits, park/signal mechanism, task graph, bounded tool output, and crash/restart accounting**. It already has production-shaped implementations and a large test suite for these.
- It **cannot run or supervise the extension’s existing `pi --mode json -p --no-session` children as first-class jobs**. It can spawn a command through its `NodeExecutionEnv`/`bash` tool, but it has no JSON-event supervisor, no per-process job record, and no external-process reconciliation. Its own agent runs in-process.
- Reusing current behavior would require substantial glue: a `Models` adapter, a tool adapter (durable supplies only `read`, `write`, `edit`, `bash`, `powershell`), MCP bridging, Pi-extension bridging, prompt/context-file reconstruction, TUI work, and usage reshaping. These are not “drop-in” APIs.
- Two settled design decisions conflict directly with durable’s model: **the four-process global scheduler** (durable allows one writer per storage and has no cross-process locking) and **session-bound kill-on-reload** (durable is designed to resume interrupted work after a process restart).
- **Recommendation: Option A.** Keep the subprocess design and borrow durable’s state-machine ideas. Do not add `pi-durable` as a dependency now. Option B adds a second store without solving scheduling; Option C replaces the behavior the extension exists to preserve.
## Findings
### 1. What `pi-durable` actually provides
| Capability | What exists | Important limit |
|---|---|---|
| **Execution** | `Harness` over one `Storage`; conversations, submissions, built-in `pi.generation`, `pi.tool`, and `pi.compaction` tasks; hooks, code mode, compaction ([README:92-113](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L92-L113), [registry.ts:10](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/registry.ts#L10)) | In-process. It calls `models.streamSimple()` itself ([generation.ts:811](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/generation.ts#L811)). |
| **Persistence** | Atomic commits of entries, documents, task records, and submissions; Memory, IndexedDB, SQLite, JSONL, Cloudflare DO backends; reopen and resume ([README:115-138](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L115-L138), [README:1020-1051](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L1020-L1051)) | One writer per storage; no cross-process locking ([README:1051](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L1051)). |
| **Cancellation** | `Conversation.abort()`, `Submission.abort()`, `Harness.abortTask()`; abort cascades bottom-up through owned tasks; parked tools get `cancel()` ([README:882-884](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L882-L884), [README:918-952](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L918-L952), [README:427](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L427)) | No forced termination of non-cooperative in-process code; it is an explicit non-goal ([spec.md:7291-7303](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/docs/spec.md#L7291-L7303)). |
| **Waiting** | `Submission.wait()`, `waitForIdle()`, `waitForTask()`; task waits with `allSettled`, `failFast`, `any`; sleeps and signals; tools can park instead of holding a process ([README:214-261](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L214-L261), [README:392-432](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L392-L432), [README:929-954](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L929-L954)) | Waiting is process-local unless the task parks; external processes are not automatically waited on. |
| **Task graph** | `watchTaskGraph()` exposes every live task with owner edge, status, background/abort marks, and owned conversations ([README:956-971](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L956-L971)) | Live tasks only. Completed records are queried through `getTask` and transaction scans (`tx.scanTasks`); `inspect` reports live tasks. I found no task-delete/prune API. |
| **Subagents** | Patterns and runnable examples: a foreground tool creates a task-owned child conversation and waits for its submission ([21-subagent-foreground.ts:41-78](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/test/examples/21-subagent-foreground.ts#L41-L78)); a background manager uses an anchor task plus reporter tasks ([22-subagent-background.ts:57-72](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/test/examples/22-subagent-background.ts#L57-L72), [22-subagent-background.ts:133-212](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/test/examples/22-subagent-background.ts#L133-L212)) | There is no built-in named-subagent manager. It is example/product code built from conversations, tasks, and `SubmissionSettled` signals ([README:924-927](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L924-L927)). The background example’s reporter auto-posts answers to the parent; that is optional product code, not a primitives requirement. An explicit get/list/wait API can omit it. |
| **Crash resume** | Open turns surviving `running` tasks back to `pending`, counts restarts, retries model requests with backoff, and ends repeated crash loops at `restartLimit` ([scheduler.ts:478-518](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/scheduler.ts#L478-L518), [README:263-267](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L263-L267)) | This is recovery of **its own tasks**, not of external subprocesses. A custom tool that spawns a process must implement its own idempotency/reconciliation; replay policy only decides whether the tool reruns ([README:336](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L336)). |
| **Process execution** | `NodeExecutionEnv` can spawn programs, stream stdout/stderr, and kill process trees ([env/node.ts:829-836](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/env/node.ts#L829-L836), [env/node.ts:303-327](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/env/node.ts#L303-L327)) | It is a command environment for tools, not a job supervisor. No JSONL `pi` event parsing, process registry, or orphan reconciliation. |
The test suite is substantial: 107 `*.test.ts` files under `packages/durable/test`, including ownership/abort, task graph, task recovery, nested tools, read-only sessions, and a replay-safe subagent recovery test ([harness-ownership.test.ts:1298-1345](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/test/harness-ownership.test.ts#L1298-L1345)). That supports the scheduler/state-machine parts; it does not establish parity with Pi’s agent runtime.
### 2. Can it run the existing `pi --mode json -p --no-session` subprocesses?
**No, not as a supported or first-class capability.**
`pi-durable` executes an **independent in-process agent harness**. Its built-in generation task resolves a model from `HarnessOptions.models` and calls `runtime.models.streamSimple(...)` ([generation.ts:208-224](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/generation.ts#L208-L224), [generation.ts:811](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/generation.ts#L811)). Its built-in task list is `pi.generation`, `pi.tool`, `pi.compaction`; there is no process/task supervisor task ([registry.ts:10](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/registry.ts#L10)).
You could write a custom durable tool that spawns `pi --mode json -p --no-session`, parses its JSONL, and returns the final answer. But that gives you only:
- a durable `pi.tool` task around the call, with replay policy and output limits;
- no durable record of the child process identity, no process registry, no session-bound ownership, no automatic orphan cleanup;
- on a crash, either the tool reruns (if `replay: "safe"`) or the model gets an `interrupted` result ([README:336](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L336)); the child process itself is outside durable’s state machine.
So durable can **host a subprocess-spawning tool**, but it does not **supervise the extension’s subprocess jobs**. The extension would still own the process registry, JSON event parsing, cancellation, result bounding, and reload cleanup.
### 3. What reuse would require: APIs present versus glue
| Current behavior | `pi-durable` API present | Glue / gap | Assessment |
|---|---|---|---|
| **Agent markdown discovery** (`~/.pi/agent/agents`, project `.pi/agents`) | None. Durable has no agent-file loader. | Keep `agents.ts` discovery and map `AgentConfig` to `AgentChange` (`instructions`, `model`, `thinkingLevel`, `tools`, `cwd`) ([types.ts:556-577](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/types.ts#L556-L577)). | Small/medium glue. Semantics of `instructions` differ from `--append-system-prompt`. |
| **Parent model/provider selection** | `ModelRef { provider, modelId }`; parent `ctx.model` supplies both ([README:481-505](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L481-L505)). | `HarnessOptions.models` requires a full `pi-ai` `Models`, not Pi’s `ModelRegistry` ([types.ts:796-803](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/types.ts#L796-L803)). Pi exposes `ctx.modelRegistry` (a facade with `streamSimple`, `complete`, `find`, auth methods) but not the private `ModelRuntime implements Models` ([model-registry.d.ts:18-45](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/model-registry.d.ts:18), [model-runtime.d.ts:35-36](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/model-runtime.d.ts:35)). | Model ref is easy; the `Models` bridge is real glue and an unsupported private-API risk. |
| **Thinking level** | `AgentState.thinkingLevel`; generation sends `reasoning` unless `"off"`; `thinkingBudgets` exists in stream options ([types.ts:556-559](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/types.ts#L556-L559), [types.ts:650-664](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/types.ts#L650-L664)). | Map `ctx.thinkingLevel`; preserve the current rule that explicit agent models do not inherit the parent thinking level ([index.ts:299-304](/home/alex/.pi/agent/extensions/subagent/index.ts:299)). | Small glue, but behavior must be specified. |
| **Coding tools** | `read`, `write`, `edit`, `bash`, and optionally `powershell` ([README:294-296](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L294-L296), [tools/index.ts:28-36](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/tools/index.ts#L28-L36)). | Pi also has `ls`, `find`, `grep`, and its own tool semantics/renderers. Durable’s built-ins are separate implementations, not Pi’s tools. | Medium/large gap for exact behavior. |
| **MCP** | None. Durable mentions MCP tools only as possible registered tools (`tool_search`, code mode); `@earendil-works/pi-durable` does not depend on `pi-mcp` ([package.json:166-173](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/package.json#L166-L173)). | Connect via `@earendil-works/pi-mcp`, adapt each server/tool to `ToolRegistration`, handle auth, deferred tools, reconnection, naming, images. | Large glue; current child gets MCP automatically. |
| **Pi extensions** | Durable has its own `Extension` shape (tools, sections, hooks, wraps, tasks) ([types.ts:512-526](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/types.ts#L512-L526)). | Pi extensions are `ExtensionAPI` modules with a different lifecycle/context. No adapter exists. | Large glue; custom tools, permission hooks, providers, and UI extensions would not just work. |
| **Context files / skills / system prompt** | Durable’s prompt is sections plus `instructions` ([README:471-479](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L471-L479)). | Pi publicly exports `loadProjectContextFiles()` ([resource-loader.d.ts:65-71](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/resource-loader.d.ts:65)); `buildSystemPrompt()` exists in an internal module but is not a root export ([system-prompt.d.ts:25-70](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/system-prompt.d.ts:25), [index.d.ts:19](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/index.d.ts:19)). You would have to render context files into durable sections and reproduce Pi’s tool snippets/guidelines/skills. | Medium/large glue; exact prompt parity is unlikely without a shared builder. |
| **UI / progress** | Durable has `Conversation.watch()`, `watchTaskGraph()`, `pi.live` docs, and `api.details()` ([README:578-628](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L578-L628), [README:956-968](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L956-L968)). | Build a new TUI job panel/renderers; current code renders child JSON events and tool activity ([index.ts:721-763](/home/alex/.pi/agent/extensions/subagent/index.ts:721)). | Medium/large UI work. |
| **Usage** | `pi.usage` per conversation (`provider/model`, tool name), `harness.usage()` aggregate ([README:1012-1018](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L1012-L1018), [usage.ts:1-45](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/usage.ts#L1-L45)). | Current extension parses child `message_end` events into `input/output/cache/cost/contextTokens/turns` ([index.ts:360-378](/home/alex/.pi/agent/extensions/subagent/index.ts:360)). Map durable’s `Usage` shape and compute context/turns separately. | Small/medium glue. |
| **CWD** | `AgentState.cwd`; environment built per call ([README:531-545](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L531-L545)). | Translate the extension’s per-task `cwd`. | Small. |
| **Recursion disabled** | Child conversations can remove the subagent extension: `configure({ extensions: { remove: [Subagent] } })` ([21-subagent-foreground.ts:58-61](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/test/examples/21-subagent-foreground.ts#L58-L61)). | In the current subprocess path there is no explicit removal: it only passes `--tools` when the agent markdown lists tools ([index.ts:305](/home/alex/.pi/agent/extensions/subagent/index.ts:305)). “Recursion disabled” is a design requirement, not an implemented guarantee today. | Small in durable; must be added to subprocess path. |
| **Bounded results** | Tool output limits default to 2000 lines / 50 KB ([truncate.ts:12-13](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/truncate.ts#L12-L13)); details can be larger if the tool stores them. | Current extension caps parallel summary at 50 KB but keeps full `messages` in details ([index.ts:37](/home/alex/.pi/agent/extensions/subagent/index.ts:37), [index.ts:147-170](/home/alex/.pi/agent/extensions/subagent/index.ts:147)). | Durable’s default aligns with the agreed cap; still need an explicit details bound. |
**Bottom line:** durable has the right *vocabulary* for jobs (agent state, model ref, thinking, cwd, tool filters, ownership, task graph, usage), but not Pi’s runtime. The missing pieces are exactly the ones that make the current extension valuable: full Pi agent boot, MCP, extensions, context files, coding tools, and TUI. The current child is also ephemeral (`--no-session`); durable persists a conversation transcript, which is a feature difference as well as a storage difference ([index.ts:298](/home/alex/.pi/agent/extensions/subagent/index.ts:298)).
### 4. Package maturity, dependencies, storage, multi-process rules, and importability
**Maturity and versioning**
- The package is explicitly **Experimental**: “The API changes without notice between releases” ([README:3](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L3)).
- `package.json` says 1.6.0, but the CHANGELOG at the pinned commit has an **Unreleased** section with breaking changes to tool parks, wraps, hook results, `admit`, signal state, and commit results ([CHANGELOG.md:1-12](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/CHANGELOG.md#L1-L12)). The `v1.6.0` tag is `faac585884ae2c013a6b1400f3e9e77f10b34bac`; published 1.6.0 does not include those Unreleased changes.
- The README is not fully synchronized with source at this commit: the hook example at [README:785](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L785) still shows the old `{ sleep: { ... } }` shape, while `ToolPark` is tagged `{ kind: "sleep" | "wait" }` ([types.ts:265-279](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/types.ts#L265-L279)). Treat examples as version-specific.
- Test coverage is broad (107 test files), including storage conformance, scheduler recovery, read-only views, task graph, child tasks, and subagent recovery. This is meaningful engineering, but the API churn is real.
**Maturity judgment:** engineering maturity is high for task/storage semantics; API maturity is low because the package labels itself experimental and is still making breaking changes on `main` after the 1.6.0 release.
**Engines, dependencies, exports**
- Node `>=22.19.0` ([package.json:163-165](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/package.json#L163-L165)); the host has the same engine floor.
- Runtime dependencies are pinned exactly: `@earendil-works/chord`, `pi-ai`, `pi-codemode`, `pi-schema`, `pi-telemetry` at 1.6.0, plus `@silvia-odwyer/photon` and `diff` ([package.json:166-173](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/package.json#L166-L173)). No `peerDependencies`; npm treats Pi packages as ordinary dependencies and may install separate copies under the extension tree.
- Exports include the root, `/tools`, `/env`, `/env/node`, `/codemode`, `/tool-search`, `/images/*`, `/storage/memory`, `/storage/indexeddb`, `/storage/jsonl`, `/storage/jsonl/node`, `/storage/sqlite`, `/storage/sqlite/node`, `/storage/sqlite/cloudflare`, and `/testing` ([package.json:8-123](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/package.json#L8-L123)). Published files are `dist`, README, and CHANGELOG ([package.json:125-130](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/package.json#L125-L130)).
**Storage options and constraints**
| Backend | Use | Caveat |
|---|---|---|
| Memory | `MemoryStorage` | Nothing persisted. Good for a session-bound prototype, but no crash recovery. |
| IndexedDB | Browser | One owner at a time; use a Web Lock. |
| SQLite | `openNodeSqliteStorage(file)` | WAL + `synchronous = NORMAL`; commits survive process crashes, newest may be lost on power/host failure. |
| JSONL | `openNodeJsonlStorage(dir)` | Append-only; `fsync` optional; read-only viewer mode; keeps whole history in memory. Not for long-running agents. |
| Cloudflare DO | DO SQLite | Only inside a Durable Object. |
Source: [README:1020-1051](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L1020-L1051).
**Multi-process ownership**
- “One process writes a storage at a time; there is no cross-process locking” ([README:1051](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L1051)).
- Read-only viewing is supported: `HarnessOptions.readOnly` refuses writes and scheduling ([types.ts:852-859](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/types.ts#L852-L859)); JSONL must also be opened with storage-level `readOnly` because a writable open repairs files ([README:127](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L127), [README:1051](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L1051)).
- The scheduler is a `TaskScheduler` owned by one `Harness` ([scheduler.ts:318](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/scheduler.ts#L318)). I found no lease, worker registry, or cross-process ownership API.
**Can a normal Pi extension import it?**
Mechanically, yes, as a normal npm dependency:
- Pi’s host-provided list is `pi-ai`, `pi-agent-core`, `pi-coding-agent`, `pi-tui`, `typebox`; `pi-durable` is not on it ([packages.md:104-116](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/packages.md:104)).
- Pi docs say npm dependencies work if you add a `package.json` next to the extension and run `npm install`; imports from `node_modules/` resolve ([extensions.md:168-170](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/extensions.md:168)).
- The current `subagent` implementation files are only `index.ts` and `agents.ts` (plus this `research/` directory); there is no `package.json`/`node_modules`. Adding the dependency is a packaging change.
But it is **not a supported host API**, and there is a real module-identity risk:
- Pi maps only exact host-provided specifiers, including `@earendil-works/pi-ai`, `@earendil-works/pi-ai/models`, `@earendil-works/pi-ai/compat`, and `typebox` ([loader.js:65-88](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/loader.js:65)).
- `pi-durable` imports `@earendil-works/pi-ai/utils/validation`, `/utils/uuid`, `/utils/retry`, `/session-resources`, and similar subpaths that are **not** in that alias map ([tool.ts:13](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/tool.ts#L13), [provider.ts:2](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/provider.ts#L2), [harness.ts:5](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/harness.ts#L5), [generation.ts:13-16](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/generation.ts#L13-L16)). Those will resolve from its installed dependency tree, potentially a second `pi-ai` copy in the same process.
- Pi’s docs warn: “Installed packages load with separate module roots. Do not rely on two packages sharing one dependency instance” ([packages.md:116](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/packages.md:116)).
- `pi-durable` pins `pi-ai` and `chord` to exact 1.6.0, so the extension becomes version-locked to the host release. A host upgrade can strand the extension.
**Judgment:** import is allowed but integration is not first-class. A spike would be required to prove that the duplicate `pi-ai`/`chord` module identities do not break session-resource cleanup, model streaming, or storage. I did not run that spike.
### 5. Options and their consequences
| Criterion | **A. Subprocess design + borrowed durable ideas** | **B. `pi-durable` for job metadata/history only** | **C. Rebuild async around `pi-durable` Harness/tasks** |
|---|---|---|---|
| Current sync `subagent` | Preserved exactly | Preserved exactly | Could stay, but creates two execution engines |
| Async execution | Subprocess per task | Subprocess per task | In-process `pi-durable` agent |
| Current agent markdown, model inheritance, MCP, extensions, context files, TUI | Inherited from child Pi | Inherited from child Pi | Must rebuild/adapt most of it |
| One job per single/parallel/chain invocation | Custom job record | Custom job record + durable records | Durable task tree; needs an umbrella job task |
| Explicit get/list/wait/cancel, no auto model turn | Custom | Custom + durable queries | Durable APIs fit |
| Session-bound, killed on reload/replacement | Natural | Natural if store is cleaned | Conflicts with durable’s resume model |
| Four-process global scheduler | Custom, compatible | Custom; durable’s single-writer store blocks shared metadata | Incompatible with one durable store; needs coordinator or separate stores |
| Bounded metadata/results + Pi custom-entry history | Preserved | Dual history or durable-only history | Durable transcript + Pi history duplicated |
| Recursion disabled | Must add explicit removal to subprocess args | Same | Easy via extension removal |
| Verification | TLA+ scheduler + fake-process tests | Plus storage conformance/dual-store tests | Upstream durable tests + fidelity/integration tests; loses fake-process execution coverage |
| Dependency/operational risk | Lowest | High | Highest |
The capability facts in the table are sourced above; the trade-offs and risk rankings are judgment.
#### Option A — keep subprocess execution, borrow durable ideas
**Preserves:** every settled decision in the brief: sync `subagent` unchanged; add `subagent_async` and `subagent_jobs`; one job per invocation; explicit get/list/wait/cancel with no automatic model turn; jobs survive a turn but are session-bound and killed on reload/session replacement; four-process global scheduler; bounded metadata/results and Pi custom-entry history; subprocess-per-task with current Pi markdown/model/cwd/tools/MCP/extension behavior; recursion disabled; TLA+ and deterministic fake-process tests. Two implementation gaps in the current sync path still need closing: an explicit recursion guard and a hard details/result bound (see §3).
**What to borrow (ideas, not the dependency):**
- A durable job record with a stable ID, idempotency/request ID, parent/child edges, explicit state enum, bounded summary, artifact path, and append-only event history.
- Ownership-tree cancellation: cancel parent → cancel children bottom-up; one job per invocation; background jobs opt out of parent turn-abort but are reachable by an explicit “cancel all” operation.
- Explicit waits and parked states: `queued/running/waiting/succeeded/failed/cancelled/interrupted`, with `wait`/`get` reading committed state rather than relying on in-memory promises.
- Restart/restart-limit accounting for the scheduler, and a session epoch marker so stale jobs are killed rather than resumed after a reload.
- Process-tree kill (durable’s `NodeExecutionEnv` is a useful reference) and orphan reconciliation by PID/start token.
- Bounded tool output: durable’s 2000-line/50 KB default matches the agreed result cap.
**New failure modes / operational requirements:** orphaned child processes after a host crash, PID reuse, process-group kill on POSIX/Windows, async cleanup in `session_shutdown`, a job index that is crash-consistent with Pi custom entries, and a cross-process scheduler lock/lease. These are already implicit in the agreed design; durable does not remove them. The current sync path already sends `SIGTERM`, then `SIGKILL` after 5 s, to the direct child only ([index.ts:408-418](/home/alex/.pi/agent/extensions/subagent/index.ts:408)); async jobs need a process-tree kill.
**Verification:** TLA+ model remains applicable; deterministic fake-process tests remain the primary execution test; add tests for SIGTERM→SIGKILL escalation, process-tree kill, reload/session-replacement cleanup, stale-job reconciliation, and job-store crash recovery.
#### Option B — durable only for metadata/history
**Preserves:** subprocess execution, current fidelity, sync tool, session-bound semantics, four-process scheduler (as a custom component), bounded results, recursion guard.
**Changes/invalidates:** the single-source-of-truth history. You would either keep Pi custom entries and mirror to durable (dual write) or move history to durable and lose Pi-native rendering. Durable’s one-writer rule means the four processes cannot all write its store; only a coordinator could, so it does not solve the shared scheduler. If you use `MemoryStorage`, it does not survive a crash; if you use SQLite/JSONL, you add migration, cleanup, and version-lock obligations.
**New failure modes:** dual-store divergence, durable store migration/version skew, stale metadata after crash, cleanup on reload, extra disk, duplicate `pi-ai`/`chord` modules, and a second set of IDs. The lower-level `createSession()` API can store documents without a Harness/models, but it provides no scheduler, so it is essentially a storage library ([session.ts:143-163](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/session/session.ts#L143-L163)).
**Verification:** durable’s storage conformance suite plus consistency tests between Pi entries and durable docs; still needs all fake-process tests. TLA+ must model both stores or prove one is derived.
**Judgment:** B is only defensible if there is a concrete requirement for durable’s queryable history/task graph that Pi custom entries plus a small sidecar index cannot meet. It adds a large dependency for a metadata problem.
#### Option C — rebuild async around `pi-durable` Harness/tasks
**Preserves:** explicit job semantics, cancellation/ownership tree, waiting/parking, task graph, bounded output, recursion removal, usage accounting, and stronger-than-session persistence if you let it persist.
**Invalidates or puts at risk:**
- **Subprocess-per-task**; the agent runs in the Pi extension process. A tool crash/OOM can take down the parent. Durable explicitly does not force-terminate non-cooperative in-process code ([spec.md:7303](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/docs/spec.md#L7303)).
- **Current agent markdown/model/MCP/extension/context/UI fidelity**; all require adapters or reimplementation (see §3).
- **Four-process global scheduler**; durable has one writer per storage and no cross-process locking ([README:1051](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L1051)). You would need a single coordinator or per-process stores, either of which changes the agreed scheduler.
- **Session-bound kill-on-reload**; durable’s purpose is to resume after a process dies ([README:5](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L5), [README:115-127](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md#L115-L127)). Keeping session-bound semantics requires abort/cleanup on shutdown plus a session epoch that prevents reopen-resume; that is a custom layer on top of durable. Using `MemoryStorage` avoids the store mismatch but discards durable’s crash-resume, leaving only its in-process scheduler.
- **Pi custom-entry history**; durable has its own transcript/store. You would either duplicate or replace Pi history.
- **Fake-process tests**; execution is no longer a process, so those tests no longer cover the async path. You would need fake models/timers/storage plus integration tests.
**New failure modes:** event-loop starvation, in-process memory growth, model/provider auth mismatch, MCP/extension/context gaps, TUI rewrite, usage double-counting (durable warns against reporting a child’s usage in the parent result, since the child’s `pi.usage` already counts it — [spec.md:7131](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/docs/spec.md#L7131)), durable store growth with no prune API, API churn, and duplicate `pi-ai` copies.
**Verification:** upstream durable’s tests cover its scheduler/storage; they do not cover Pi fidelity. You would need golden tests comparing child Pi vs durable output for tool set, system prompt, MCP, extension hooks, usage, and cancellation; provider/auth parity tests; and session-shutdown tests. TLA+ could model the wrapper, but durable’s internal scheduler is upstream’s responsibility.
## Recommendation
**Adopt Option A.** Keep the agreed subprocess design, and borrow durable’s state-machine discipline rather than its package.
This is judgment, based on the sourced facts above:
- The extension’s value is fidelity to a real Pi child: markdown agents, model/provider inheritance, thinking, cwd, tools, MCP, extensions, context files, and TUI. Durable does not provide that runtime; it provides a different one.
- The settled four-process scheduler and session-bound job lifetime are structurally opposed to durable’s single-writer, resume-after-crash model. Bending durable to those decisions costs more than implementing the job state machine directly.
- Durable’s best ideas are portable: request IDs, explicit task states, ownership/abort trees, parks/signals, bounded output, restart limits, task graph views. These can live in a small Pi-native job store and Pi custom entries.
Concretely, for Option A:
1. Keep the current `subagent` tool and `agents.ts` discovery unchanged.
2. Add a Pi-native job record/index with `jobId`, `requestId`, parent/child edges, mode (`single|parallel|chain`), state, timestamps, bounded summary, result artifact path, and error/cancel reason.
3. Implement `subagent_async` to create one job per invocation and spawn children exactly as today; implement `subagent_jobs` as explicit `get/list/wait/cancel` over committed records, with no automatic model turn.
4. Add a session epoch and `session_shutdown` cleanup that kills the process tree and marks jobs `interrupted`; on startup, reconcile stale jobs instead of resuming them.
5. Add explicit recursion guard: never pass the `subagent`/`subagent_async` tools to a child, even when the markdown file omits `tools`.
6. Add a job-event log and task-graph-style view for the TUI, but store it in Pi custom entries plus a small sidecar index, not in a second durable store. Pi custom entries are explicitly durable and do not enter LLM context ([extensions.md:1683-1699](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/extensions.md:1683)).
7. Keep the TLA+ scheduler model and fake-process tests; add process-tree kill, reload, orphan, and job-store crash tests.
**Revisit Option C only if** the product accepts in-process execution and the loss of subprocess isolation, Pi exposes a supported in-process agent harness plus a public `Models` bridge, and the four-process/session-bound constraints are relaxed or replaced by a single-writer coordinator. Until then, C is a rewrite with a large fidelity regression surface. **Option B is not recommended** unless a concrete queryable-history requirement emerges; even then, start with the lower-level `Session`/documents API or a plain SQLite job table, not the full Harness.
## Facts that could not be established
- Whether `pi-durable` can be loaded through Pi’s jiti alias map without a second `pi-ai`/`chord` copy causing runtime problems. No spike was run.
- Whether a complete `Models` adapter can be built from the public `ModelRegistry` without private APIs. No public `Models` instance is exposed to extensions; `ModelRuntime implements Models` but is private ([model-runtime.d.ts:35-36](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/model-runtime.d.ts:35)).
- Exact behavioral parity between durable’s `read/write/edit/bash` and Pi’s tools; not exhaustively diffed.
- The exact API diff between the published 1.6.0 tarball and the pinned main commit. Main has Unreleased breaking changes, so they are not identical; I did not enumerate every difference.
- Whether Pi awaits `session_shutdown` handlers through every exit path (including SIGKILL); docs define the event but not a hard guarantee for uncatchable termination ([extensions.md:601-610](/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/extensions.md:601)).
- Whether durable task records are ever pruned. I found `scanTasks`/`getTask` but no delete/prune API; not exhaustively audited.
- Performance/memory of embedding durable in the Pi process for many concurrent jobs. No benchmark was run.
- Whether a custom durable tool can reliably supervise `pi --mode json` process trees on all platforms without additional process-registry code. Durable’s environment has tree-kill logic, but no job-level reconciliation.
- Whether the current child actually offers the `subagent` tool when the agent markdown omits `tools`. The current code has no explicit removal, but I did not run a child to observe its tool loadout.
## Files and sources
### Upstream `pi-durable` at `e2cb38ac149b440560e1f66da26613bf25f42937`
- [`packages/durable/README.md`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/README.md) — overview, concepts, persist/resume, tools, parks, subagents, child tasks, task graph, usage, storage.
- Experimental: L3
- Concepts: L92-113
- Persist/resume: L115-138
- Signals/sleeps: L214-261
- Failures/recovery: L263-271
- Extensions: L273-292
- Tools/coding tools: L294-305
- Tool replay/crash: L336
- Tools that park: L392-432
- System prompt/agent: L471-505
- Busy conversations: L630-692
- Abort/subagents: L882-928
- Child tasks: L929-954
- Task graph: L956-971
- Usage: L1012-1018
- Storage/multi-process: L1020-1051
- [`packages/durable/package.json`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/package.json) — version, exports, engines, dependencies.
- [`packages/durable/src/harness/types.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/types.ts) — `ToolPark` L265-279; `Extension` L512-526; `AgentState` L556-577; stream options L650-664; `HarnessOptions` L796-859.
- [`packages/durable/src/harness/scheduler.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/scheduler.ts) — `TaskScheduler` L318; recovery L478-518.
- [`packages/durable/src/harness/registry.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/registry.ts) — built-in tasks L10.
- [`packages/durable/src/harness/generation.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/generation.ts) — model resolution L208-224; `streamSimple` L811.
- [`packages/durable/src/harness/usage.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/harness/usage.ts) — `UsageDoc` and aggregation.
- [`packages/durable/src/session/session.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/session/session.ts) — `createSession()` L143-163.
- [`packages/durable/src/tools/index.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/tools/index.ts) — `CodingTools` L28-36.
- [`packages/durable/src/truncate.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/truncate.ts) — default output limits L12-13.
- [`packages/durable/src/env/node.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/src/env/node.ts) — process spawn/tree kill L303-327, L829-836.
- [`packages/durable/docs/spec.md`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/docs/spec.md) — non-goals L7291-7303.
- [`packages/durable/CHANGELOG.md`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/CHANGELOG.md) — Unreleased breaking changes L1-12.
- [`packages/durable/test/examples/21-subagent-foreground.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/test/examples/21-subagent-foreground.ts) — foreground subagent L41-78.
- [`packages/durable/test/examples/22-subagent-background.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/test/examples/22-subagent-background.ts) — background subagents L57-72, L133-212.
- [`packages/durable/test/harness-ownership.test.ts`](https://github.com/earendil-works/pi/blob/e2cb38ac149b440560e1f66da26613bf25f42937/packages/durable/test/harness-ownership.test.ts) — subagent abort/recovery L1154-1170, L1298-1345.
### Host Pi 1.6.0 (installed)
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/extensions.md`
- lifecycle/shutdown: L390-393, L601-610
- available imports/dependencies: L155-170
- `pi.appendEntry`: L1683-1699
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/packages.md`
- host-provided packages and dependency rules: L100-116
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/loader.js`
- jiti aliases: L65-88
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/model-registry.d.ts`
- `ModelRegistry` facade: L18-45
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/model-runtime.d.ts`
- `ModelRuntime implements Models`: L35-36
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/resource-loader.d.ts`
- `loadProjectContextFiles`: L65-71
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/core/system-prompt.d.ts`
- prompt/context/skills options: L25-70 (internal module, not a root export)
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/index.d.ts`
- public exports (includes `loadProjectContextFiles`, not `buildSystemPrompt`): L19-20
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/mcp.md`
- MCP configuration/behavior: L1-100
- `/home/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/docs/cli-integration.md`
- JSON/print mode: L3-40
### Current extension
- `/home/alex/.pi/agent/extensions/subagent/index.ts`
- concurrency/result caps: L34-37
- child args/model/thinking/tools: L298-305
- temp system prompt and task: L331-339
- spawn/JSON parsing/usage: L344-386
- abort/kill: L408-418
- parent model/thinking capture: L483-486
- project-agent trust UI: L518-544
- TUI renderers: L721-763
- `/home/alex/.pi/agent/extensions/subagent/agents.ts`
- `AgentConfig`: L11-18
- markdown discovery: L128-140
- `/home/alex/.pi/agent/extensions/subagent` implementation files: `index.ts` and `agents.ts` (plus this `research/` report); no `package.json` or `node_modules`.
### Other primary sources
- npm package: https://www.npmjs.com/package/@earendil-works/pi-durable/v/1.6.0 (latest 1.6.0; Node >=22.19.0).
- `v1.6.0` tag: [`faac585884ae2c013a6b1400f3e9e77f10b34bac`](https://github.com/earendil-works/pi/tree/faac585884ae2c013a6b1400f3e9e77f10b34bac) (the pinned main commit is later and includes Unreleased changes).
## Answer
**Option A.** `pi-durable` is an excellent source of durable job-state ideas, but it is a different agent runtime, not a supervisor for `pi --mode json` children. Keep the subprocess design, borrow request IDs, explicit task states, ownership/abort trees, bounded results, restart accounting, and a task-graph-style view; implement them in Pi custom entries plus a small job index. Do not adopt durable for execution (C) or metadata (B) unless the four-process/session-bound decisions and the current Pi fidelity requirements are deliberately renegotiated.
+15
View File
@@ -0,0 +1,15 @@
CONSTANT MaxWorkers = 2
INIT Init
NEXT Next
INVARIANT TypeOK
INVARIANT WorkerBound
INVARIANT ChainOrdering
INVARIANT CancellationDrainsQueue
INVARIANT ShutdownStopsWork
INVARIANT SuccessfulJobsHaveSuccessfulTasks
INVARIANT FailedJobsHaveFailedTasks
PROPERTY TerminalJobStability
PROPERTY TerminalTaskStability
+176
View File
@@ -0,0 +1,176 @@
--------------------------- MODULE SubagentJobs ---------------------------
EXTENDS FiniteSets, Naturals
CONSTANT MaxWorkers
Jobs == {"chain", "parallel"}
Tasks == {"chain-1", "chain-2", "parallel-1", "parallel-2"}
JobOf == [t \in Tasks |-> IF t \in {"chain-1", "chain-2"} THEN "chain" ELSE "parallel"]
NoPred == "no-predecessor"
ChainPred == [t \in Tasks |-> IF t = "chain-2" THEN "chain-1" ELSE NoPred]
JobStates == {"queued", "running", "cancelling", "succeeded", "failed", "cancelled", "interrupted"}
TaskStates == {"queued", "running", "succeeded", "failed", "cancelled", "interrupted"}
TerminalJobStates == {"succeeded", "failed", "cancelled", "interrupted"}
TerminalTaskStates == {"succeeded", "failed", "cancelled", "interrupted"}
ASSUME MaxWorkers \in Nat /\ MaxWorkers > 0
VARIABLES jobState, taskState, processRunning, cancelRequested, shuttingDown
vars == <<jobState, taskState, processRunning, cancelRequested, shuttingDown>>
TasksOf(j) == {t \in Tasks : JobOf[t] = j}
ReadyIn(state, t) ==
IF ChainPred[t] = NoPred
THEN TRUE
ELSE state[ChainPred[t]] = "succeeded"
LiveProcesses == {t \in Tasks : processRunning[t]}
TypeOK ==
/\ jobState \in [Jobs -> JobStates]
/\ taskState \in [Tasks -> TaskStates]
/\ processRunning \in [Tasks -> BOOLEAN]
/\ cancelRequested \in [Jobs -> BOOLEAN]
/\ shuttingDown \in BOOLEAN
Init ==
/\ jobState = [j \in Jobs |-> "queued"]
/\ taskState = [t \in Tasks |-> "queued"]
/\ processRunning = [t \in Tasks |-> FALSE]
/\ cancelRequested = [j \in Jobs |-> FALSE]
/\ shuttingDown = FALSE
Start(t) ==
LET j == JobOf[t] IN
/\ ~shuttingDown
/\ ~cancelRequested[j]
/\ jobState[j] \in {"queued", "running"}
/\ taskState[t] = "queued"
/\ ReadyIn(taskState, t)
/\ Cardinality(LiveProcesses) < MaxWorkers
/\ taskState' = [taskState EXCEPT ![t] = "running"]
/\ processRunning' = [processRunning EXCEPT ![t] = TRUE]
/\ jobState' = [jobState EXCEPT ![j] = "running"]
/\ UNCHANGED <<cancelRequested, shuttingDown>>
JobAfterProgress(j) ==
IF \A t \in TasksOf(j) : taskState'[t] = "succeeded"
THEN "succeeded"
ELSE IF
/\ \E t \in TasksOf(j) : taskState'[t] = "failed"
/\ ~\E t \in TasksOf(j) : processRunning'[t]
/\ ~\E t \in TasksOf(j) :
/\ taskState'[t] = "queued"
/\ ReadyIn(taskState', t)
THEN "failed"
ELSE jobState[j]
Complete(t, outcome) ==
LET j == JobOf[t] IN
/\ ~shuttingDown
/\ ~cancelRequested[j]
/\ taskState[t] = "running"
/\ processRunning[t]
/\ outcome \in {"succeeded", "failed"}
/\ taskState' = [taskState EXCEPT ![t] = outcome]
/\ processRunning' = [processRunning EXCEPT ![t] = FALSE]
/\ jobState' = [jobState EXCEPT ![j] = JobAfterProgress(j)]
/\ UNCHANGED <<cancelRequested, shuttingDown>>
Cancel(j) ==
/\ ~shuttingDown
/\ jobState[j] \notin TerminalJobStates \cup {"cancelling"}
/\ cancelRequested' = [cancelRequested EXCEPT ![j] = TRUE]
/\ jobState' = [jobState EXCEPT ![j] = "cancelling"]
/\ taskState' = [t \in Tasks |->
IF JobOf[t] = j /\ taskState[t] = "queued"
THEN "cancelled"
ELSE taskState[t]]
/\ UNCHANGED <<processRunning, shuttingDown>>
ReapCancelled(t) ==
\* Models every late process outcome after cancellation. The raw exit may be
\* success or failure; the committed task outcome remains cancelled.
LET j == JobOf[t] IN
/\ cancelRequested[j]
/\ jobState[j] = "cancelling"
/\ taskState[t] = "running"
/\ processRunning[t]
/\ taskState' = [taskState EXCEPT ![t] = "cancelled"]
/\ processRunning' = [processRunning EXCEPT ![t] = FALSE]
/\ UNCHANGED <<jobState, cancelRequested, shuttingDown>>
FinishCancellation(j) ==
/\ jobState[j] = "cancelling"
/\ ~\E t \in TasksOf(j) : processRunning[t] \/ taskState[t] = "running"
/\ jobState' = [jobState EXCEPT ![j] = "cancelled"]
/\ UNCHANGED <<taskState, processRunning, cancelRequested, shuttingDown>>
Shutdown ==
/\ ~shuttingDown
/\ shuttingDown' = TRUE
/\ jobState' = [j \in Jobs |->
IF jobState[j] \in TerminalJobStates THEN jobState[j] ELSE "interrupted"]
/\ taskState' = [t \in Tasks |->
IF taskState[t] \in TerminalTaskStates THEN taskState[t] ELSE "interrupted"]
/\ UNCHANGED <<processRunning, cancelRequested>>
ReapInterrupted(t) ==
/\ shuttingDown
/\ taskState[t] = "interrupted"
/\ processRunning[t]
/\ processRunning' = [processRunning EXCEPT ![t] = FALSE]
/\ UNCHANGED <<jobState, taskState, cancelRequested, shuttingDown>>
Quiescent ==
/\ \A j \in Jobs : jobState[j] \in TerminalJobStates
/\ \A t \in Tasks : ~processRunning[t]
/\ UNCHANGED vars
Next ==
\/ \E t \in Tasks : Start(t)
\/ \E t \in Tasks : Complete(t, "succeeded")
\/ \E t \in Tasks : Complete(t, "failed")
\/ \E j \in Jobs : Cancel(j)
\/ \E t \in Tasks : ReapCancelled(t)
\/ \E j \in Jobs : FinishCancellation(j)
\/ Shutdown
\/ \E t \in Tasks : ReapInterrupted(t)
\/ Quiescent
WorkerBound == Cardinality(LiveProcesses) <= MaxWorkers
ChainOrdering ==
\A t \in Tasks :
/\ ChainPred[t] \in Tasks
/\ taskState[t] \in {"running", "succeeded", "failed"}
=> taskState[ChainPred[t]] = "succeeded"
CancellationDrainsQueue ==
\A j \in Jobs :
cancelRequested[j] =>
~\E t \in TasksOf(j) : taskState[t] = "queued"
ShutdownStopsWork ==
shuttingDown =>
/\ \A t \in Tasks : taskState[t] \in TerminalTaskStates
/\ \A j \in Jobs : jobState[j] \in TerminalJobStates
SuccessfulJobsHaveSuccessfulTasks ==
\A j \in Jobs :
jobState[j] = "succeeded" =>
\A t \in TasksOf(j) : taskState[t] = "succeeded"
FailedJobsHaveFailedTasks ==
\A j \in Jobs :
jobState[j] = "failed" =>
\E t \in TasksOf(j) : taskState[t] = "failed"
TerminalJobStability ==
\A j \in Jobs : \A state \in TerminalJobStates :
[](jobState[j] = state => [](jobState[j] = state))
TerminalTaskStability ==
\A t \in Tasks : \A state \in TerminalTaskStates :
[](taskState[t] = state => [](taskState[t] = state))
=============================================================================
+157
View File
@@ -0,0 +1,157 @@
/**
* Agent discovery and configuration
*/
import * as fs from "node:fs";
import * as path from "node:path";
import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
export type AgentScope = "user" | "project" | "both";
export interface AgentConfig {
name: string;
description: string;
tools?: string[];
model?: string;
systemPrompt: string;
source: "user" | "project";
filePath: string;
}
export interface AgentDiscoveryResult {
agents: AgentConfig[];
projectAgentsDir: string | null;
}
/**
* Raw agent frontmatter. Values are `unknown` because `parseFrontmatter` runs a
* real YAML parser, so any scalar or collection can appear here.
*
* A type alias rather than an interface: `parseFrontmatter` constrains its
* parameter to `Record<string, unknown>`, and only an alias picks up the
* implicit index signature that satisfies it.
*/
type AgentFrontmatter = {
name?: unknown;
description?: unknown;
tools?: unknown;
model?: unknown;
};
/**
* Normalize a frontmatter `tools` value to a list of tool names.
*
* Both spellings are valid YAML and both are in use:
*
* tools: read, bash # string
* tools: [read, bash] # array
*
* so accept either. Anything else (a number, a map, a nested list) yields no
* tools rather than throwing: this runs inside agent discovery, where a single
* bad file must not take down every other agent in the same directory.
*/
function parseToolList(value: unknown): string[] | undefined {
const raw = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : [];
const tools = raw
.filter((t): t is string => typeof t === "string")
.map((t) => t.trim())
.filter(Boolean);
return tools.length > 0 ? tools : undefined;
}
function loadAgentsFromDir(dir: string, source: "user" | "project"): AgentConfig[] {
const agents: AgentConfig[] = [];
if (!fs.existsSync(dir)) {
return agents;
}
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return agents;
}
for (const entry of entries) {
if (!entry.name.endsWith(".md")) continue;
if (!entry.isFile() && !entry.isSymbolicLink()) continue;
const filePath = path.join(dir, entry.name);
let content: string;
try {
content = fs.readFileSync(filePath, "utf-8");
} catch {
continue;
}
const { frontmatter, body } = parseFrontmatter<AgentFrontmatter>(content);
if (typeof frontmatter.name !== "string" || typeof frontmatter.description !== "string") {
continue;
}
agents.push({
name: frontmatter.name,
description: frontmatter.description,
tools: parseToolList(frontmatter.tools),
model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
systemPrompt: body,
source,
filePath,
});
}
return agents;
}
function isDirectory(p: string): boolean {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
function findNearestProjectAgentsDir(cwd: string): string | null {
let currentDir = cwd;
while (true) {
const candidate = path.join(currentDir, CONFIG_DIR_NAME, "agents");
if (isDirectory(candidate)) return candidate;
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) return null;
currentDir = parentDir;
}
}
export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryResult {
const userDir = path.join(getAgentDir(), "agents");
const projectAgentsDir = findNearestProjectAgentsDir(cwd);
const userAgents = scope === "project" ? [] : loadAgentsFromDir(userDir, "user");
const projectAgents = scope === "user" || !projectAgentsDir ? [] : loadAgentsFromDir(projectAgentsDir, "project");
const agentMap = new Map<string, AgentConfig>();
if (scope === "both") {
for (const agent of userAgents) agentMap.set(agent.name, agent);
for (const agent of projectAgents) agentMap.set(agent.name, agent);
} else if (scope === "user") {
for (const agent of userAgents) agentMap.set(agent.name, agent);
} else {
for (const agent of projectAgents) agentMap.set(agent.name, agent);
}
return { agents: Array.from(agentMap.values()), projectAgentsDir };
}
export function formatAgentList(agents: AgentConfig[], maxItems: number): { text: string; remaining: number } {
if (agents.length === 0) return { text: "none", remaining: 0 };
const listed = agents.slice(0, maxItems);
const remaining = agents.length - listed.length;
return {
text: listed.map((a) => `${a.name} (${a.source}): ${a.description}`).join("; "),
remaining,
};
}
+14
View File
@@ -0,0 +1,14 @@
export const DEFAULT_MAX_WORKERS = 4;
export const MAX_WORKERS_LIMIT = 32;
export function readMaxWorkers(value: string | undefined): { value: number; warning?: string } {
if (value === undefined || value === "") return { value: DEFAULT_MAX_WORKERS };
if (!/^\d+$/.test(value)) {
return { value: DEFAULT_MAX_WORKERS, warning: `Invalid PI_SUBAGENT_MAX_WORKERS="${value}"; using ${DEFAULT_MAX_WORKERS}.` };
}
const parsed = Number(value);
if (parsed < 1 || parsed > MAX_WORKERS_LIMIT) {
return { value: DEFAULT_MAX_WORKERS, warning: `PI_SUBAGENT_MAX_WORKERS must be 1–${MAX_WORKERS_LIMIT}; using ${DEFAULT_MAX_WORKERS}.` };
}
return { value: parsed };
}
+284
View File
@@ -0,0 +1,284 @@
/**
* Synchronous and asynchronous subagents with isolated Pi child processes.
*
* The Pi-facing adapters live here. Orchestration and process lifecycle are in
* manager.ts and runner.ts respectively.
*/
import * as path from "node:path";
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
import {
CONFIG_DIR_NAME,
type ExtensionAPI,
type ExtensionContext,
getAgentDir,
} from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
import { readMaxWorkers } from "./config.ts";
import { formatJob, formatJobList } from "./job-format.ts";
import { SubagentManager } from "./manager.ts";
import { extractJobSnapshots, persistedJob, SUBAGENT_JOB_ENTRY } from "./persistence.ts";
import { InvalidInvocationError, prepareInvocation } from "./prepare.ts";
import {
formatParallelSummary,
getResultOutput,
isFailedResult,
isRunningResult,
renderSubagentCall,
renderSubagentResult,
} from "./render.ts";
import { ProcessRunner } from "./runner.ts";
import { SubagentJobsParams, SubagentParams, type SubagentParamsType } from "./schemas.ts";
import { type JobSnapshot, type PreparedInvocation, type SubagentDetails, type SyncOutcome, type TaskRunner } from "./types.ts";
function textResult(text: string, details?: unknown, isError?: boolean): AgentToolResult<any> {
return { content: [{ type: "text", text }], details, isError };
}
function emptyDetails(params: SubagentParamsType): SubagentDetails {
return {
mode: params.chain !== undefined ? "chain" : params.tasks !== undefined ? "parallel" : "single",
status: "failed",
agentScope: params.agentScope ?? "user",
projectAgentsDir: null,
projectAgentsDirs: [],
results: [],
};
}
function detailsFor(request: PreparedInvocation, outcome: SyncOutcome): SubagentDetails {
return {
mode: request.mode,
status: outcome.status,
agentScope: request.agentScope,
projectAgentsDir: request.projectAgentsDir,
projectAgentsDirs: request.projectAgentsDirs ?? [],
results: outcome.results,
};
}
function syncResult(request: PreparedInvocation, outcome: SyncOutcome): AgentToolResult<SubagentDetails> {
const details = detailsFor(request, outcome);
if (request.mode === "parallel") {
return { content: [{ type: "text", text: formatParallelSummary(outcome.results) }], details };
}
if (request.mode === "chain") {
const failed = outcome.results.find(isFailedResult);
if (failed) {
return {
content: [{ type: "text", text: `Chain stopped at step ${failed.step ?? "?"} (${failed.agent}): ${getResultOutput(failed)}` }],
details,
isError: true,
};
}
return { content: [{ type: "text", text: outcome.results.at(-1)?.output || "(no output)" }], details };
}
const result = outcome.results[0];
if (!result) return { content: [{ type: "text", text: outcome.status }], details, isError: outcome.status === "failed" };
if (isFailedResult(result)) {
return {
content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${getResultOutput(result)}` }],
details,
isError: true,
};
}
return { content: [{ type: "text", text: result.output || "(no output)" }], details };
}
function syncUpdate(request: PreparedInvocation, outcome: SyncOutcome): AgentToolResult<SubagentDetails> {
const terminal = outcome.results.filter((result) => !isRunningResult(result)).length;
let text: string;
if (request.mode === "parallel") text = `Parallel: ${terminal}/${outcome.results.length} done`;
else if (request.mode === "chain") text = `Chain: ${terminal}/${request.tasks.length} steps done`;
else text = outcome.results[0]?.output || "(running...)";
return { content: [{ type: "text", text }], details: detailsFor(request, outcome) };
}
function jobResult(job: JobSnapshot): AgentToolResult<{ job: JobSnapshot }> {
return { content: [{ type: "text", text: formatJob(job) }], details: { job } };
}
export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
const workerConfig = readMaxWorkers(process.env.PI_SUBAGENT_MAX_WORKERS);
let currentContext: ExtensionContext | undefined;
let configurationWarning = workerConfig.warning;
const updateStatus = (ctx: ExtensionContext | undefined = currentContext): void => {
if (!ctx) return;
const active = manager.list(true).length;
ctx.ui.setStatus("subagents", active > 0 ? `subagents: ${active} active` : undefined);
};
const manager = new SubagentManager(taskRunner ?? new ProcessRunner(), {
maxWorkers: workerConfig.value,
onJobChange: (job) => {
updateStatus();
if (!currentContext) return;
try {
pi.appendEntry(SUBAGENT_JOB_ENTRY, persistedJob(currentContext.sessionManager.getSessionId(), job));
} catch {
// Ephemeral sessions and persistence failures do not change job execution.
}
},
});
pi.on("session_start", (_event, ctx) => {
currentContext = ctx;
manager.restore(extractJobSnapshots(ctx.sessionManager.getBranch()));
updateStatus(ctx);
if (configurationWarning) {
ctx.ui.notify(configurationWarning, "warning");
configurationWarning = undefined;
}
});
pi.on("session_shutdown", async () => {
await manager.shutdown();
updateStatus();
currentContext = undefined;
});
pi.on("session_tree", (_event, ctx) => {
currentContext = ctx;
manager.replaceHistory(extractJobSnapshots(ctx.sessionManager.getBranch()));
updateStatus(ctx);
});
pi.registerEntryRenderer(SUBAGENT_JOB_ENTRY, (entry, _options, theme) => {
const job = extractJobSnapshots([entry])[0];
if (!job) return undefined;
return new Text(
theme.fg("muted", "Subagent ") + theme.fg("accent", job.id) + theme.fg("muted", ` ${job.mode} → ${job.status}`),
0,
0,
);
});
pi.registerTool({
name: "subagent",
label: "Subagent (sync)",
description: [
"Synchronously delegate to specialized subagents with isolated context; waits for all results.",
"Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).",
"Use subagent_async when the parent should continue without waiting.",
`Default agent scope is "user" (from ${path.join(getAgentDir(), "agents")}).`,
`To enable project-local agents in ${CONFIG_DIR_NAME}/agents, set agentScope: "both" (or "project").`,
].join(" "),
parameters: SubagentParams,
async execute(_toolCallId, params, signal, onUpdate, ctx) {
let request: PreparedInvocation;
try {
request = await prepareInvocation(params, ctx);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const unknownNonParallel = error instanceof InvalidInvocationError && message.startsWith("Unknown agent:") && params.tasks === undefined;
return textResult(message, emptyDetails(params), unknownNonParallel);
}
const outcome = await manager.runSync(request, {
signal,
onUpdate: onUpdate ? (partial) => onUpdate(syncUpdate(request, partial)) : undefined,
});
return syncResult(request, outcome);
},
renderCall(args, theme) {
return renderSubagentCall(args, theme);
},
renderResult(result, options, theme) {
return renderSubagentResult(result as AgentToolResult<SubagentDetails>, options, theme);
},
});
pi.registerTool({
name: "subagent_async",
label: "Subagent (async)",
description: [
"Start a single, parallel, or chain subagent job and return its job ID immediately.",
"The job survives the current turn but is interrupted on reload or session replacement.",
"Use subagent_jobs with get or wait to retrieve results, list to inspect jobs, or cancel to stop one.",
"Results are pull-based: completion never starts an automatic model turn. Avoid tight polling; use wait with a bounded timeout.",
"Only available in TUI/RPC sessions. Child processes cannot recursively dispatch subagents.",
].join(" "),
parameters: SubagentParams,
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
if (ctx.mode === "print" || ctx.mode === "json") {
return textResult("Async subagents require a TUI/RPC session. Use the synchronous subagent tool in print/JSON mode.", undefined, true);
}
try {
const request = await prepareInvocation(params, ctx);
const job = manager.startAsync(request);
return {
content: [{ type: "text", text: `Started ${request.mode} async job ${job.id} (${job.status}).\nUse subagent_jobs { action: "get" | "wait", jobId: "${job.id}" } to retrieve it.` }],
details: { job },
};
} catch (error) {
return textResult(error instanceof Error ? error.message : String(error), undefined, true);
}
},
renderCall(args, theme) {
return renderSubagentCall(args, theme);
},
renderResult(result) {
const text = result.content[0];
return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
},
});
pi.registerTool({
name: "subagent_jobs",
label: "Subagent jobs",
description: [
"Inspect and control async subagent jobs.",
"Actions: list {activeOnly?}; get {jobId}; wait {jobId, timeoutSeconds? (default 30, max 300)}; cancel {jobId}.",
"Waiting or timing out never cancels a job. Failed/cancelled/interrupted job snapshots are normal retrieval results, not management-tool errors.",
].join(" "),
parameters: SubagentJobsParams,
async execute(_toolCallId, params, signal) {
try {
switch (params.action) {
case "list": {
const jobs = manager.list(params.activeOnly ?? false);
return { content: [{ type: "text", text: formatJobList(jobs) }], details: { jobs } };
}
case "get":
return jobResult(manager.get(params.jobId));
case "wait":
return jobResult(await manager.wait(params.jobId, params.timeoutSeconds, signal));
case "cancel":
return jobResult(manager.cancel(params.jobId));
default:
return textResult("Unknown subagent_jobs action", undefined, true);
}
} catch (error) {
return textResult(error instanceof Error ? error.message : String(error), undefined, true);
}
},
renderResult(result) {
const text = result.content[0];
return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
},
});
pi.registerCommand("subagents", {
description: "List, inspect, or cancel async subagents: /subagents [job-id | cancel job-id]",
handler: async (args, ctx) => {
const parts = args.trim().split(/\s+/).filter(Boolean);
try {
if (parts.length === 0) {
ctx.ui.notify(formatJobList(manager.list()), "info");
return;
}
if (parts.length === 1) {
ctx.ui.notify(formatJob(manager.get(parts[0])), "info");
return;
}
if (parts.length === 2 && parts[0] === "cancel") {
ctx.ui.notify(formatJob(manager.cancel(parts[1])), "info");
return;
}
ctx.ui.notify("Usage: /subagents [job-id | cancel job-id]", "warning");
} catch (error) {
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
}
},
});
}
+41
View File
@@ -0,0 +1,41 @@
import { formatUsageStats } from "./render.ts";
import type { JobSnapshot, TaskSnapshot } from "./types.ts";
function taskOutput(task: TaskSnapshot): string {
if (task.errorMessage) return `Error: ${task.errorMessage}${task.output ? `\n\n${task.output}` : ""}`;
if (task.output) return task.output;
if (task.stderr) return task.stderr;
return task.status === "queued" || task.status === "running" ? "(pending)" : "(no output)";
}
export function formatJob(job: JobSnapshot): string {
const lines = [
`Job ${job.id} — ${job.status}${job.timedOut ? " (wait timed out; job is unchanged)" : ""}`,
`Mode: ${job.mode} · Tasks recorded: ${job.results.length}/${job.plannedTaskCount} · Scope: ${job.agentScope}`,
`Created: ${new Date(job.createdAt).toISOString()}${job.finishedAt ? ` · Finished: ${new Date(job.finishedAt).toISOString()}` : ""}`,
];
if (job.errorMessage) lines.push(`Job error: ${job.errorMessage}`);
for (const [index, task] of job.results.entries()) {
const label = job.mode === "chain" ? `Step ${task.step ?? index + 1}` : `Task ${index + 1}`;
lines.push("", `### ${label}: ${task.agent} — ${task.status}`);
lines.push(`Task: ${task.task}`);
lines.push(taskOutput(task));
if (task.outputTruncated) lines.push(`[Output truncated: ${task.outputBytesOmitted} bytes omitted]`);
if (task.stderrTruncated) lines.push("[stderr truncated; retained the 64 KiB tail]");
if (task.terminationSignal) lines.push(`Termination signal: ${task.terminationSignal}`);
}
const usage = formatUsageStats(job.usage);
if (usage) lines.push("", `Usage (child-reported; not added to parent totals): ${usage}`);
return lines.join("\n");
}
export function formatJobList(jobs: JobSnapshot[]): string {
if (jobs.length === 0) return "No subagent jobs.";
const counts = new Map<string, number>();
for (const job of jobs) counts.set(job.status, (counts.get(job.status) ?? 0) + 1);
const summary = Array.from(counts, ([status, count]) => `${count} ${status}`).join(", ");
return [
`Subagent jobs: ${summary}`,
...jobs.map((job) => `${job.id} ${job.status.padEnd(11)} ${job.mode.padEnd(8)} ${job.results.length}/${job.plannedTaskCount} recorded`),
].join("\n");
}
+589
View File
@@ -0,0 +1,589 @@
import { truncateUtf8Head } from "./output.ts";
import {
emptyUsage,
isTerminalJob,
type InvocationMode,
type JobSnapshot,
type JobStatus,
type ManagerOptions,
type PreparedInvocation,
type PreparedTask,
type RunResult,
type TaskRunner,
type TaskSnapshot,
type TaskStatus,
type UsageStats,
type SyncOutcome,
type SyncRunOptions,
} from "./types.ts";
const DEFAULT_MAX_WORKERS = 4;
const DEFAULT_MAX_ACTIVE_JOBS = 64;
const DEFAULT_HISTORY_LIMIT = 50;
const DEFAULT_WAIT_SECONDS = 30;
const MAX_WAIT_SECONDS = 300;
const ASYNC_OUTPUT_LIMIT_BYTES = 50 * 1024;
interface InternalTask {
prepared: PreparedTask;
snapshot: TaskSnapshot;
controller?: AbortController;
result?: RunResult;
}
interface Execution {
id: string;
request: PreparedInvocation;
status: JobStatus;
plannedTaskCount: number;
tasks: InternalTask[];
createdAt: number;
startedAt?: number;
finishedAt?: number;
errorMessage?: string;
isAsync: boolean;
cancelRequested: boolean;
onUpdate?: (outcome: SyncOutcome) => void;
completion?: Promise<unknown>;
}
interface ScheduledTask {
execution: Execution;
task: InternalTask;
resolve: (result: RunResult) => void;
}
interface Waiter {
resolve: (snapshot: JobSnapshot) => void;
reject: (error: Error) => void;
timer: NodeJS.Timeout;
}
function cloneSnapshot(snapshot: JobSnapshot): JobSnapshot {
return structuredClone(snapshot);
}
function initialTask(prepared: PreparedTask, now: number): InternalTask {
void now;
return {
prepared,
result: {
agent: prepared.agent.name,
agentSource: prepared.agent.source,
task: prepared.task,
cwd: prepared.cwd,
step: prepared.step,
status: "queued",
exitCode: null,
messages: [],
output: "",
stderr: "",
usage: emptyUsage(),
},
snapshot: {
agent: prepared.agent.name,
agentSource: prepared.agent.source,
task: prepared.task,
cwd: prepared.cwd,
step: prepared.step,
status: "queued",
exitCode: null,
output: "",
outputTruncated: false,
outputBytesOmitted: 0,
stderr: "",
stderrTruncated: false,
usage: emptyUsage(),
},
};
}
function failed(result: RunResult): boolean {
return result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal);
}
export class SubagentManager {
private readonly runner: TaskRunner;
private readonly maxWorkers: number;
private readonly maxActiveJobs: number;
private readonly historyLimit: number;
private readonly now: () => number;
private readonly onJobChange?: (snapshot: JobSnapshot) => void;
private readonly jobs = new Map<string, Execution>();
private readonly activeExecutions = new Set<Execution>();
private readonly queue: ScheduledTask[] = [];
private readonly waiters = new Map<string, Set<Waiter>>();
private liveWorkers = 0;
private nextJobId = 1;
private accepting = true;
constructor(runner: TaskRunner, options: ManagerOptions = {}) {
this.runner = runner;
this.maxWorkers = options.maxWorkers ?? DEFAULT_MAX_WORKERS;
this.maxActiveJobs = options.maxActiveJobs ?? DEFAULT_MAX_ACTIVE_JOBS;
this.historyLimit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT;
this.now = options.now ?? Date.now;
this.onJobChange = options.onJobChange;
}
startAsync(request: PreparedInvocation): JobSnapshot {
if (!this.accepting) throw new Error("Subagent manager is shutting down");
const active = Array.from(this.jobs.values()).filter((job) => job.isAsync && !isTerminalJob(job.status)).length;
if (active >= this.maxActiveJobs) throw new Error(`Too many active async jobs (${active}); maximum is ${this.maxActiveJobs}`);
const execution = this.createExecution(request, true);
execution.completion = this.execute(execution).catch((error: unknown) => {
execution.errorMessage = error instanceof Error ? error.message : String(error);
this.finalize(execution, "failed");
});
return this.snapshot(execution);
}
async runSync(request: PreparedInvocation, options: SyncRunOptions = {}): Promise<SyncOutcome> {
if (!this.accepting) throw new Error("Subagent manager is shutting down");
if (options.signal?.aborted) throw new Error("Subagent was aborted");
const execution = this.createExecution(request, false);
execution.onUpdate = options.onUpdate;
const onAbort = () => this.requestCancellation(execution);
options.signal?.addEventListener("abort", onAbort, { once: true });
execution.completion = this.execute(execution).catch((error: unknown) => {
execution.errorMessage = error instanceof Error ? error.message : String(error);
this.finalize(execution, "failed");
});
try {
await execution.completion;
if (execution.cancelRequested) throw new Error("Subagent was aborted");
return this.syncOutcome(execution);
} finally {
options.signal?.removeEventListener("abort", onAbort);
}
}
get(jobId: string): JobSnapshot {
return this.snapshot(this.requireJob(jobId));
}
list(activeOnly = false): JobSnapshot[] {
return Array.from(this.jobs.values())
.filter((job) => job.isAsync && (!activeOnly || !isTerminalJob(job.status)))
.sort((a, b) => b.createdAt - a.createdAt || a.id.localeCompare(b.id))
.map((job) => this.snapshot(job));
}
async wait(jobId: string, timeoutSeconds = DEFAULT_WAIT_SECONDS, signal?: AbortSignal): Promise<JobSnapshot> {
const execution = this.requireJob(jobId);
if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0 || timeoutSeconds > MAX_WAIT_SECONDS) {
throw new Error(`wait timeout must be greater than 0 and at most ${MAX_WAIT_SECONDS} seconds`);
}
if (isTerminalJob(execution.status)) return this.snapshot(execution);
if (signal?.aborted) throw new Error("Wait aborted");
return new Promise<JobSnapshot>((resolve, reject) => {
const waiters = this.waiters.get(jobId) ?? new Set<Waiter>();
this.waiters.set(jobId, waiters);
const waiter: Waiter = {
resolve,
reject,
timer: setTimeout(() => {
waiters.delete(waiter);
waiter.resolve({ ...this.snapshot(execution), timedOut: true });
}, timeoutSeconds * 1000),
};
const onAbort = () => {
clearTimeout(waiter.timer);
waiters.delete(waiter);
reject(new Error("Wait aborted"));
};
if (signal) signal.addEventListener("abort", onAbort, { once: true });
waiter.resolve = (snapshot) => {
clearTimeout(waiter.timer);
if (signal) signal.removeEventListener("abort", onAbort);
resolve(snapshot);
};
waiter.reject = (error) => {
clearTimeout(waiter.timer);
if (signal) signal.removeEventListener("abort", onAbort);
reject(error);
};
waiters.add(waiter);
});
}
restore(snapshots: JobSnapshot[]): void {
for (const saved of snapshots) {
const existing = this.jobs.get(saved.id);
if (existing && this.activeExecutions.has(existing)) continue;
const interrupted = !isTerminalJob(saved.status);
const tasks = saved.results.map((result) => {
const source = result.agentSource === "unknown" ? "user" : result.agentSource;
const prepared: PreparedTask = {
agent: {
name: result.agent,
description: "Restored agent",
systemPrompt: "",
source,
filePath: "",
},
task: result.task,
cwd: result.cwd,
step: result.step,
};
const task = initialTask(prepared, this.now());
task.snapshot = structuredClone(result);
if (interrupted && (task.snapshot.status === "queued" || task.snapshot.status === "running")) {
task.snapshot.status = "interrupted";
task.snapshot.finishedAt = this.now();
}
return task;
});
const execution: Execution = {
id: saved.id,
request: {
mode: saved.mode,
tasks: tasks.map((task) => task.prepared),
agentScope: saved.agentScope,
projectAgentsDir: saved.projectAgentsDir,
projectAgentsDirs: saved.projectAgentsDirs,
dispatchDefaults: {},
},
status: interrupted ? "interrupted" : saved.status,
plannedTaskCount: saved.plannedTaskCount,
tasks,
createdAt: saved.createdAt,
startedAt: saved.startedAt,
finishedAt: interrupted ? this.now() : saved.finishedAt,
errorMessage: interrupted ? "Interrupted by session restart" : saved.errorMessage,
isAsync: true,
cancelRequested: false,
};
this.jobs.set(saved.id, execution);
const match = /^job_(\d+)$/.exec(saved.id);
if (match) this.nextJobId = Math.max(this.nextJobId, Number(match[1]) + 1);
}
this.pruneHistory();
}
replaceHistory(snapshots: JobSnapshot[]): void {
for (const [id, job] of this.jobs) {
if (!this.activeExecutions.has(job)) this.jobs.delete(id);
}
this.restore(snapshots);
}
async shutdown(): Promise<void> {
const active = Array.from(this.activeExecutions);
const completions = active.map((execution) => execution.completion).filter((completion) => completion !== undefined);
if (this.accepting) {
this.accepting = false;
for (const execution of active) {
execution.status = "interrupted";
execution.finishedAt = this.now();
execution.errorMessage = "Session shut down before completion";
for (let index = this.queue.length - 1; index >= 0; index--) {
const scheduled = this.queue[index];
if (scheduled.execution !== execution) continue;
this.queue.splice(index, 1);
scheduled.task.result = this.interruptedResult(scheduled.task);
scheduled.resolve(scheduled.task.result);
}
for (const task of execution.tasks) {
if (task.snapshot.status === "succeeded" || task.snapshot.status === "failed" || task.snapshot.status === "cancelled" || task.snapshot.status === "interrupted") continue;
task.snapshot.status = "interrupted";
task.snapshot.finishedAt = this.now();
task.controller?.abort();
}
this.activeExecutions.delete(execution);
this.emit(execution);
this.resolveWaiters(execution);
this.emitSync(execution);
}
this.pruneHistory();
}
await Promise.allSettled(completions);
}
private interruptedResult(task: InternalTask): RunResult {
return {
...this.cancelledResult(task),
status: "interrupted",
stopReason: "aborted",
errorMessage: "Interrupted by session shutdown",
};
}
cancel(jobId: string): JobSnapshot {
const execution = this.requireJob(jobId);
this.requestCancellation(execution);
return this.snapshot(execution);
}
private requestCancellation(execution: Execution): void {
if (isTerminalJob(execution.status) || execution.status === "cancelling") return;
execution.cancelRequested = true;
execution.status = "cancelling";
for (let index = this.queue.length - 1; index >= 0; index--) {
const scheduled = this.queue[index];
if (scheduled.execution !== execution) continue;
this.queue.splice(index, 1);
scheduled.task.snapshot.status = "cancelled";
scheduled.task.snapshot.finishedAt = this.now();
scheduled.task.result = this.cancelledResult(scheduled.task);
scheduled.resolve(scheduled.task.result);
}
for (const task of execution.tasks) {
if (task.snapshot.status === "running") task.controller?.abort();
}
this.emit(execution);
this.emitSync(execution);
if (!execution.tasks.some((task) => task.snapshot.status === "running")) this.finalize(execution, "cancelled");
}
private cancelledResult(task: InternalTask): RunResult {
return {
agent: task.prepared.agent.name,
agentSource: task.prepared.agent.source,
task: task.prepared.task,
cwd: task.prepared.cwd,
step: task.prepared.step,
exitCode: null,
messages: [],
output: "",
stderr: "",
usage: emptyUsage(),
status: "cancelled",
stopReason: "aborted",
errorMessage: "Cancelled by caller",
};
}
private createExecution(request: PreparedInvocation, isAsync: boolean): Execution {
const id = `job_${String(this.nextJobId++).padStart(4, "0")}`;
const execution: Execution = {
id,
request,
status: "queued",
plannedTaskCount: request.tasks.length,
tasks: (request.mode === "chain" ? request.tasks.slice(0, 1) : request.tasks).map((task) => initialTask(task, this.now())),
createdAt: this.now(),
isAsync,
cancelRequested: false,
};
this.activeExecutions.add(execution);
if (isAsync) {
this.jobs.set(id, execution);
this.emit(execution);
}
return execution;
}
private async execute(execution: Execution): Promise<void> {
if (execution.request.mode === "single") {
const result = await this.schedule(execution, execution.tasks[0]);
this.finalize(execution, failed(result) ? "failed" : "succeeded");
return;
}
if (execution.request.mode === "parallel") {
const results = await Promise.all(execution.tasks.map((task) => this.schedule(execution, task)));
this.finalize(execution, results.some(failed) ? "failed" : "succeeded");
return;
}
let previous = "";
for (let index = 0; index < execution.request.tasks.length; index++) {
if (index > 0) {
const prepared = {
...execution.request.tasks[index],
task: execution.request.tasks[index].task.replace(/\{previous\}/g, previous),
};
execution.tasks.push(initialTask(prepared, this.now()));
}
const result = await this.schedule(execution, execution.tasks[index]);
if (execution.cancelRequested || isTerminalJob(execution.status)) {
this.finalize(execution, "cancelled");
return;
}
if (failed(result)) {
this.finalize(execution, "failed");
return;
}
previous = result.output;
}
this.finalize(execution, "succeeded");
}
private schedule(execution: Execution, task: InternalTask): Promise<RunResult> {
return new Promise((resolve) => {
this.queue.push({ execution, task, resolve });
this.pump();
});
}
private pump(): void {
if (!this.accepting) return;
while (this.liveWorkers < this.maxWorkers && this.queue.length > 0) {
const scheduled = this.queue.shift()!;
const { execution, task } = scheduled;
if (isTerminalJob(execution.status) || execution.cancelRequested) {
const result = execution.status === "interrupted" ? this.interruptedResult(task) : this.cancelledResult(task);
task.snapshot.status = result.status ?? "cancelled";
task.snapshot.finishedAt = this.now();
task.result = execution.isAsync ? { ...result, messages: [] } : result;
scheduled.resolve(result);
this.emit(execution);
this.emitSync(execution);
continue;
}
this.liveWorkers++;
void this.runScheduled(scheduled);
}
}
private async runScheduled(scheduled: ScheduledTask): Promise<void> {
const { execution, task, resolve } = scheduled;
const controller = new AbortController();
task.controller = controller;
task.snapshot.status = "running";
task.snapshot.startedAt = this.now();
if (execution.status === "queued") {
execution.status = "running";
execution.startedAt = this.now();
this.emit(execution);
}
this.emitSync(execution);
try {
const result = await this.runner.run(task.prepared, execution.request.dispatchDefaults, {
signal: controller.signal,
onUpdate: (partial) => {
if (execution.isAsync) return;
partial.status = "running";
task.result = partial;
this.emitSync(execution);
},
});
this.applyResult(execution, task, result);
this.emitSync(execution);
resolve(result);
} catch (error) {
const result: RunResult = {
agent: task.prepared.agent.name,
agentSource: task.prepared.agent.source,
task: task.prepared.task,
cwd: task.prepared.cwd,
step: task.prepared.step,
exitCode: 1,
messages: [],
output: "",
stderr: "",
usage: emptyUsage(),
errorMessage: error instanceof Error ? error.message : String(error),
};
this.applyResult(execution, task, result);
resolve(result);
} finally {
this.liveWorkers--;
this.pump();
}
}
private applyResult(execution: Execution, task: InternalTask, result: RunResult): void {
task.result = execution.isAsync ? { ...result, messages: [] } : result;
if (task.snapshot.status === "interrupted") {
task.result.status = "interrupted";
return;
}
task.snapshot.status = execution.cancelRequested ? "cancelled" : failed(result) ? "failed" : "succeeded";
task.result.status = task.snapshot.status;
task.snapshot.exitCode = result.exitCode;
const output = truncateUtf8Head(result.output, ASYNC_OUTPUT_LIMIT_BYTES);
task.snapshot.output = output.text;
task.snapshot.outputTruncated = output.truncated;
task.snapshot.outputBytesOmitted = output.bytesOmitted;
task.snapshot.stderr = result.stderr;
task.snapshot.stderrTruncated = result.stderrTruncated ?? false;
task.snapshot.usage = { ...result.usage };
task.snapshot.model = result.model;
task.snapshot.stopReason = result.stopReason;
task.snapshot.errorMessage = result.errorMessage;
task.snapshot.terminationSignal = result.terminationSignal;
task.snapshot.finishedAt = this.now();
}
private syncOutcome(execution: Execution): SyncOutcome {
return { status: execution.status, results: execution.tasks.map((task) => task.result!) };
}
private emitSync(execution: Execution): void {
if (execution.isAsync) return;
try {
execution.onUpdate?.(this.syncOutcome(execution));
} catch {
// Observers cannot interrupt scheduling or strand a worker.
}
}
private finalize(execution: Execution, status: JobStatus): void {
if (isTerminalJob(execution.status)) return;
execution.status = execution.cancelRequested && status !== "interrupted" ? "cancelled" : status;
execution.finishedAt = this.now();
this.activeExecutions.delete(execution);
this.emit(execution);
this.emitSync(execution);
this.resolveWaiters(execution);
this.pruneHistory();
}
private resolveWaiters(execution: Execution): void {
const waiters = this.waiters.get(execution.id);
if (!waiters) return;
this.waiters.delete(execution.id);
for (const waiter of waiters) waiter.resolve(this.snapshot(execution));
}
private requireJob(jobId: string): Execution {
const job = this.jobs.get(jobId);
if (!job) throw new Error(`Unknown or evicted subagent job: ${jobId}`);
return job;
}
private snapshot(execution: Execution): JobSnapshot {
const usage: UsageStats = emptyUsage();
for (const task of execution.tasks) {
for (const key of ["input", "output", "cacheRead", "cacheWrite", "cost", "turns"] as const) usage[key] += task.snapshot.usage[key];
usage.contextTokens = Math.max(usage.contextTokens, task.snapshot.usage.contextTokens);
}
return cloneSnapshot({
id: execution.id,
mode: execution.request.mode,
agentScope: execution.request.agentScope,
projectAgentsDir: execution.request.projectAgentsDir,
projectAgentsDirs: execution.request.projectAgentsDirs ?? (execution.request.projectAgentsDir ? [execution.request.projectAgentsDir] : []),
status: execution.status,
plannedTaskCount: execution.plannedTaskCount,
results: execution.tasks.map((task) => task.snapshot),
usage,
createdAt: execution.createdAt,
startedAt: execution.startedAt,
finishedAt: execution.finishedAt,
errorMessage: execution.errorMessage,
});
}
private emit(execution: Execution): void {
if (!execution.isAsync) return;
try {
this.onJobChange?.(this.snapshot(execution));
} catch {
// Persistence/UI observers cannot interrupt scheduling.
}
}
private pruneHistory(): void {
const terminal = Array.from(this.jobs.values())
.filter((job) => job.isAsync && isTerminalJob(job.status))
.sort((a, b) => (a.finishedAt ?? a.createdAt) - (b.finishedAt ?? b.createdAt));
while (terminal.length > this.historyLimit) {
const oldest = terminal.shift()!;
this.jobs.delete(oldest.id);
this.waiters.delete(oldest.id);
}
}
}
+35
View File
@@ -0,0 +1,35 @@
export interface TruncatedText {
text: string;
truncated: boolean;
bytesOmitted: number;
}
function isExactUtf8(buffer: Buffer): boolean {
return Buffer.from(buffer.toString("utf8"), "utf8").equals(buffer);
}
/** Keep a valid-UTF-8 prefix no larger than limit bytes. */
export function truncateUtf8Head(input: string, limit: number): TruncatedText {
const bytes = Buffer.from(input, "utf8");
const cap = Math.max(0, Math.floor(limit));
let end = Math.min(cap, bytes.length);
while (end > 0 && !isExactUtf8(bytes.subarray(0, end))) end--;
return {
text: bytes.subarray(0, end).toString("utf8"),
truncated: end < bytes.length,
bytesOmitted: bytes.length - end,
};
}
/** Keep a valid-UTF-8 suffix no larger than limit bytes. */
export function truncateUtf8Tail(input: string, limit: number): TruncatedText {
const bytes = Buffer.from(input, "utf8");
const cap = Math.max(0, Math.floor(limit));
let start = Math.max(0, bytes.length - cap);
while (start < bytes.length && !isExactUtf8(bytes.subarray(start))) start++;
return {
text: bytes.subarray(start).toString("utf8"),
truncated: start > 0,
bytesOmitted: start,
};
}
+66
View File
@@ -0,0 +1,66 @@
import type { JobSnapshot } from "./types.ts";
export const SUBAGENT_JOB_ENTRY = "subagent-job-v1";
interface PersistedJob {
version: 1;
sessionId: string;
job: JobSnapshot;
}
export function persistedJob(sessionId: string, job: JobSnapshot): PersistedJob {
return { version: 1, sessionId, job: structuredClone(job) };
}
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object";
}
const modes = new Set(["single", "parallel", "chain"]);
const jobStatuses = new Set(["queued", "running", "cancelling", "succeeded", "failed", "cancelled", "interrupted"]);
const taskStatuses = new Set(["queued", "running", "succeeded", "failed", "cancelled", "interrupted"]);
const usageKeys = ["input", "output", "cacheRead", "cacheWrite", "cost", "contextTokens", "turns"] as const;
function validUsage(value: unknown): boolean {
return record(value) && usageKeys.every((key) => typeof value[key] === "number" && Number.isFinite(value[key]));
}
function validTask(value: unknown): boolean {
if (!record(value)) return false;
return typeof value.agent === "string"
&& (value.agentSource === "user" || value.agentSource === "project" || value.agentSource === "unknown")
&& typeof value.task === "string"
&& typeof value.cwd === "string"
&& typeof value.status === "string" && taskStatuses.has(value.status)
&& (typeof value.exitCode === "number" || value.exitCode === null)
&& typeof value.output === "string"
&& typeof value.outputTruncated === "boolean"
&& typeof value.outputBytesOmitted === "number"
&& typeof value.stderr === "string"
&& typeof value.stderrTruncated === "boolean"
&& validUsage(value.usage);
}
function validJob(value: unknown): value is JobSnapshot {
if (!record(value)) return false;
return typeof value.id === "string"
&& typeof value.mode === "string" && modes.has(value.mode)
&& (value.agentScope === "user" || value.agentScope === "project" || value.agentScope === "both")
&& (typeof value.projectAgentsDir === "string" || value.projectAgentsDir === null)
&& Array.isArray(value.projectAgentsDirs) && value.projectAgentsDirs.every((dir) => typeof dir === "string")
&& typeof value.status === "string" && jobStatuses.has(value.status)
&& typeof value.plannedTaskCount === "number" && Number.isInteger(value.plannedTaskCount)
&& typeof value.createdAt === "number" && Number.isFinite(value.createdAt)
&& Array.isArray(value.results) && value.results.every(validTask)
&& validUsage(value.usage);
}
export function extractJobSnapshots(entries: unknown[]): JobSnapshot[] {
const snapshots: JobSnapshot[] = [];
for (const entry of entries) {
if (!record(entry) || entry.type !== "custom" || entry.customType !== SUBAGENT_JOB_ENTRY || !record(entry.data)) continue;
if (entry.data.version !== 1 || !validJob(entry.data.job)) continue;
snapshots.push(structuredClone(entry.data.job));
}
return snapshots;
}
+259
View File
@@ -0,0 +1,259 @@
/**
* Invocation preparation.
*
* Turns a flat `subagent` request into a fully resolved `PreparedInvocation`:
* exactly one mode, one discovered agent per task, absolute task cwds, and the
* dispatch defaults inherited from the calling session.
*
* This module is deliberately effect-free beyond reading agent files and
* asking the UI to confirm project-local agents. It never starts a manager or
* a process, and it validates every task before prompting, so a later invalid
* task cannot leave a half-approved invocation behind.
*/
import * as fs from "node:fs";
import * as path from "node:path";
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
import { type AgentScope, discoverAgents } from "./agents.ts";
import type { SubagentParamsType } from "./schemas.ts";
import type { DispatchDefaults, PreparedInvocation, PreparedTask } from "./types.ts";
const MAX_PARALLEL_TASKS = 8;
/** Thrown when a request does not describe exactly one valid mode. */
export class InvalidInvocationError extends Error {
constructor(message: string) {
super(message);
this.name = "InvalidInvocationError";
}
}
/** Thrown when the user declines to run agents from a project-local directory. */
export class ProjectAgentDeclinedError extends Error {
readonly directory: string;
readonly agents: string[];
constructor(directory: string, agents: string[]) {
super(`Canceled: project-local agents not approved (${directory}: ${agents.join(", ")}).`);
this.name = "ProjectAgentDeclinedError";
this.directory = directory;
this.agents = agents;
}
}
export interface PrepareUIContext {
confirm(title: string, message: string): Promise<boolean>;
}
/**
* The subset of Pi's `ExtensionToolContext` that preparation needs.
*
* Declared structurally so tests can pass a small fake while the real
* `ExtensionToolContext` (which has far more members) remains assignable.
*/
export interface PrepareContext {
cwd: string;
model?: { provider: string; id: string } | undefined;
thinkingLevel?: ThinkingLevel;
hasUI: boolean;
isProjectTrusted(): boolean;
ui: PrepareUIContext;
}
/** Compile-time guard: Pi's real tool context must stay assignable to the fake-friendly shape. */
type AssertTrue<T extends true> = T;
type _ExtensionToolContextIsPrepareContext = AssertTrue<
ExtensionToolContext extends PrepareContext ? true : false
>;
type InvocationMode = PreparedInvocation["mode"];
interface RequestItem {
agent: string;
task: string;
cwd?: string;
}
interface NormalizedRequest {
mode: InvocationMode;
items: RequestItem[];
}
/** Resolve the requested agent scope, defaulting unknown/missing values to "user". */
export function resolveAgentScope(value: unknown): AgentScope {
return value === "user" || value === "project" || value === "both" ? value : "user";
}
function normalizeItem(item: unknown, label: string): RequestItem {
if (item === null || typeof item !== "object") {
throw new InvalidInvocationError(`${label} must be an object with nonempty "agent" and "task".`);
}
const record = item as Record<string, unknown>;
if (typeof record.agent !== "string" || record.agent.trim().length === 0) {
throw new InvalidInvocationError(`${label}.agent must be a nonempty string.`);
}
if (typeof record.task !== "string" || record.task.trim().length === 0) {
throw new InvalidInvocationError(`${label}.task must be a nonempty string.`);
}
if (record.cwd !== undefined && typeof record.cwd !== "string") {
throw new InvalidInvocationError(`${label}.cwd must be a string when provided.`);
}
return { agent: record.agent, task: record.task, cwd: record.cwd ?? undefined };
}
/**
* Pick exactly one mode. Empty arrays and partial single requests are errors,
* not "no mode": silently ignoring them would run something the caller did not
* ask for.
*/
function normalizeRequest(params: SubagentParamsType): NormalizedRequest {
if (params === null || typeof params !== "object") {
throw new InvalidInvocationError("Invalid parameters. Expected a subagent request object.");
}
const hasSingle = params.agent !== undefined || params.task !== undefined;
const hasTasks = params.tasks !== undefined;
const hasChain = params.chain !== undefined;
const modeCount = Number(hasSingle) + Number(hasTasks) + Number(hasChain);
if (modeCount === 0) {
throw new InvalidInvocationError(
"Invalid parameters. Provide exactly one mode: single (agent + task), parallel (tasks), or chain (chain).",
);
}
if (modeCount > 1) {
throw new InvalidInvocationError(
"Invalid parameters. Provide exactly one mode: single (agent + task), parallel (tasks), or chain (chain).",
);
}
if (hasSingle) {
if (
typeof params.agent !== "string" ||
params.agent.trim().length === 0 ||
typeof params.task !== "string" ||
params.task.trim().length === 0
) {
throw new InvalidInvocationError('Single mode requires nonempty "agent" and "task".');
}
return {
mode: "single",
items: [{ agent: params.agent, task: params.task, cwd: params.cwd }],
};
}
if (hasTasks) {
const tasks = params.tasks;
if (!Array.isArray(tasks) || tasks.length === 0) {
throw new InvalidInvocationError('Parallel mode requires a nonempty "tasks" array.');
}
if (tasks.length > MAX_PARALLEL_TASKS) {
throw new InvalidInvocationError(
`Too many parallel tasks (${tasks.length}). Max is ${MAX_PARALLEL_TASKS}.`,
);
}
return {
mode: "parallel",
items: tasks.map((item, index) => normalizeItem(item, `tasks[${index}]`)),
};
}
const chain = params.chain;
if (!Array.isArray(chain) || chain.length === 0) {
throw new InvalidInvocationError('Chain mode requires a nonempty "chain" array.');
}
return {
mode: "chain",
items: chain.map((item, index) => normalizeItem(item, `chain[${index}]`)),
};
}
function resolveTaskCwd(baseCwd: string, itemCwd: string | undefined): string {
const resolved = path.resolve(baseCwd, itemCwd ?? ".");
let stat: fs.Stats;
try {
stat = fs.statSync(resolved);
} catch {
throw new InvalidInvocationError(`Invalid cwd (does not exist): ${resolved}`);
}
if (!stat.isDirectory()) {
throw new InvalidInvocationError(`Invalid cwd (not a directory): ${resolved}`);
}
return resolved;
}
/**
* Prepare a subagent invocation.
*
* All tasks are resolved and validated before any confirmation prompt. On
* success the result is ready to hand to a manager; on failure nothing has
* been started.
*/
export async function prepareInvocation(
params: SubagentParamsType,
ctx: PrepareContext,
): Promise<PreparedInvocation> {
const agentScope = resolveAgentScope(params.agentScope);
const request = normalizeRequest(params);
const tasks: PreparedTask[] = [];
const projectAgentsByDir = new Map<string, Set<string>>();
for (let index = 0; index < request.items.length; index++) {
const item = request.items[index];
const cwd = resolveTaskCwd(ctx.cwd, item.cwd);
// Discovery is per task: agents are a property of the task's effective
// working directory, not of the caller's cwd.
const discovery = discoverAgents(cwd, agentScope);
const agent = discovery.agents.find((candidate) => candidate.name === item.agent);
if (!agent) {
const available = discovery.agents.map((candidate) => `"${candidate.name}"`).join(", ") || "none";
throw new InvalidInvocationError(`Unknown agent: "${item.agent}". Available agents: ${available}.`);
}
if (agent.source === "project" && discovery.projectAgentsDir) {
const names = projectAgentsByDir.get(discovery.projectAgentsDir) ?? new Set<string>();
names.add(agent.name);
projectAgentsByDir.set(discovery.projectAgentsDir, names);
}
const task: PreparedTask = { agent, task: item.task, cwd };
if (request.mode === "chain") task.step = index + 1;
tasks.push(task);
}
const projectAgentsDirs = Array.from(projectAgentsByDir.keys());
const confirmProjectAgents = params.confirmProjectAgents ?? true;
const trustedDiscovery = ctx.isProjectTrusted() ? discoverAgents(ctx.cwd, agentScope) : null;
const trustedProjectAgentsDir = trustedDiscovery?.projectAgentsDir
? fs.realpathSync(trustedDiscovery.projectAgentsDir)
: undefined;
if (agentScope !== "user" && confirmProjectAgents && ctx.hasUI && projectAgentsDirs.length > 0) {
for (const directory of projectAgentsDirs) {
if (trustedProjectAgentsDir && fs.realpathSync(directory) === trustedProjectAgentsDir) continue;
const agents = Array.from(projectAgentsByDir.get(directory) ?? []);
const approved = await ctx.ui.confirm(
"Run project-local agents?",
`Agents: ${agents.join(", ")}\nSource: ${directory}\n\nProject agent prompts are repo-controlled. Only continue for repositories you trust.`,
);
if (!approved) throw new ProjectAgentDeclinedError(directory, agents);
}
}
const dispatchDefaults: DispatchDefaults = {
model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
thinkingLevel: ctx.thinkingLevel,
};
return {
mode: request.mode,
tasks,
agentScope,
projectAgentsDir: projectAgentsDirs[0] ?? null,
projectAgentsDirs,
dispatchDefaults,
};
}
+576
View File
@@ -0,0 +1,576 @@
/**
* Rendering for the synchronous `subagent` tool.
*
* This module is intentionally independent of the tool implementation so the
* call and result views can be reused by other subagent tools. The helpers use
* structural types; `index.ts` can pass Pi's theme and result objects directly.
*/
import * as os from "node:os";
import type { Message } from "@earendil-works/pi-ai";
import { formatReadLineRange, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
import { Container, Markdown, Spacer, Text, type Component } from "@earendil-works/pi-tui";
import { truncateUtf8Head } from "./output.ts";
import type { RunResult, SubagentDetails, TaskStatus, UsageStats } from "./types.ts";
export const PER_TASK_OUTPUT_CAP = 50 * 1024;
export const PARALLEL_OUTPUT_CAP_BYTES = PER_TASK_OUTPUT_CAP;
const COLLAPSED_ITEM_COUNT = 10;
export interface SubagentRenderTheme {
fg(color: any, text: string): string;
bold(text: string): string;
}
export interface SubagentRenderOptions {
expanded?: boolean;
isPartial?: boolean;
}
export interface SubagentCallArgs {
agent?: string;
task?: string;
tasks?: ReadonlyArray<{ agent?: string; task?: string }>;
chain?: ReadonlyArray<{ agent?: string; task?: string }>;
agentScope?: unknown;
}
export interface SubagentResultLike {
content?: ReadonlyArray<{ type?: string; text?: string }>;
details?: (Partial<SubagentDetails> & { results?: readonly RunResult[] }) | undefined;
}
export interface ResultStatusFields {
status?: TaskStatus;
exitCode?: number | null;
stopReason?: string;
terminationSignal?: string;
}
type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, any> };
function resolveAgentScope(value: unknown): "user" | "project" | "both" {
return value === "user" || value === "project" || value === "both" ? value : "user";
}
export function formatTokens(count: number): string {
if (count < 1000) return count.toString();
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
if (count < 1000000) return `${Math.round(count / 1000)}k`;
return `${(count / 1000000).toFixed(1)}M`;
}
export function formatUsageStats(
usage: {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
cost: number;
contextTokens?: number;
turns?: number;
},
model?: string,
): string {
const parts: string[] = [];
if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
if (usage.contextTokens && usage.contextTokens > 0) {
parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
}
if (model) parts.push(model);
return parts.join(" ");
}
export function formatToolCall(
toolName: string,
args: Record<string, unknown>,
themeFg: (color: any, text: string) => string,
): string {
const shortenPath = (p: string) => {
const home = os.homedir();
return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
};
switch (toolName) {
case "bash": {
const command = (args.command as string) || "...";
const preview = command.length > 60 ? `${command.slice(0, 60)}...` : command;
return themeFg("muted", "$ ") + themeFg("toolOutput", preview);
}
case "read": {
const rawPath = (args.file_path || args.path || "...") as string;
const filePath = shortenPath(rawPath);
const lineRange = formatReadLineRange(args.offset, args.limit);
let text = themeFg("accent", filePath);
if (lineRange) {
text += themeFg("warning", lineRange);
}
return themeFg("muted", "read ") + text;
}
case "write": {
const rawPath = (args.file_path || args.path || "...") as string;
const filePath = shortenPath(rawPath);
const content = (args.content || "") as string;
const lines = content.split("\n").length;
let text = themeFg("muted", "write ") + themeFg("accent", filePath);
if (lines > 1) text += themeFg("dim", ` (${lines} lines)`);
return text;
}
case "edit": {
const rawPath = (args.file_path || args.path || "...") as string;
return themeFg("muted", "edit ") + themeFg("accent", shortenPath(rawPath));
}
case "ls": {
const rawPath = (args.path || ".") as string;
return themeFg("muted", "ls ") + themeFg("accent", shortenPath(rawPath));
}
case "find": {
const pattern = (args.pattern || "*") as string;
const rawPath = (args.path || ".") as string;
return themeFg("muted", "find ") + themeFg("accent", pattern) + themeFg("dim", ` in ${shortenPath(rawPath)}`);
}
case "grep": {
const pattern = (args.pattern || "") as string;
const rawPath = (args.path || ".") as string;
return (
themeFg("muted", "grep ") +
themeFg("accent", `/${pattern}/`) +
themeFg("dim", ` in ${shortenPath(rawPath)}`)
);
}
default: {
const argsStr = JSON.stringify(args);
const preview = argsStr.length > 50 ? `${argsStr.slice(0, 50)}...` : argsStr;
return themeFg("accent", toolName) + themeFg("dim", ` ${preview}`);
}
}
}
export function getFinalOutput(messages: readonly Message[] | undefined): string {
if (!messages) return "";
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
if (msg.role === "assistant") {
for (const part of msg.content) {
if (part.type === "text") return part.text;
}
}
}
return "";
}
export function getDisplayItems(messages: readonly Message[] | undefined): DisplayItem[] {
const items: DisplayItem[] = [];
if (!messages) return items;
for (const msg of messages) {
if (msg.role === "assistant") {
for (const part of msg.content) {
if (part.type === "text") items.push({ type: "text", text: part.text });
else if (part.type === "toolCall") items.push({ type: "toolCall", name: part.name, args: part.arguments });
}
}
}
return items;
}
export function isRunningStatus(status: TaskStatus | undefined): boolean {
return status === "queued" || status === "running";
}
export function isFailedStatus(status: TaskStatus | undefined): boolean {
return status === "failed" || status === "cancelled" || status === "interrupted";
}
/**
* Running/queued placeholders have a null exit code but are not failures. For
* every other result, null or nonzero exits are failures, as are explicit
* error/aborted stop reasons, termination signals, and failure statuses.
*/
export function isFailedResult(result: ResultStatusFields): boolean {
if (isRunningStatus(result.status)) return false;
if (isFailedStatus(result.status)) return true;
if (result.exitCode === null || (result.exitCode !== undefined && result.exitCode !== 0)) return true;
return result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal);
}
export function isRunningResult(result: ResultStatusFields): boolean {
return isRunningStatus(result.status);
}
export function isSuccessfulResult(result: ResultStatusFields): boolean {
return !isRunningResult(result) && !isFailedResult(result);
}
interface ResultOutputFields extends ResultStatusFields {
messages?: readonly Message[];
output?: string;
stderr?: string;
errorMessage?: string;
}
export function getResultOutput(result: ResultOutputFields): string {
const output = result.output || getFinalOutput(result.messages);
if (isFailedResult(result)) {
return result.errorMessage || result.stderr || output || "(no output)";
}
return output || "(no output)";
}
/** Apply the model-facing parallel result cap using a valid UTF-8 prefix. */
export function truncateParallelOutput(output: string): string {
const truncated = truncateUtf8Head(output, PER_TASK_OUTPUT_CAP);
if (!truncated.truncated) return output;
return `${truncated.text}\n\n[Output truncated: ${truncated.bytesOmitted} bytes omitted. Full output preserved in tool details.]`;
}
export function formatParallelSummary(results: readonly RunResult[]): string {
const successCount = results.filter(isSuccessfulResult).length;
const summaries = results.map((result) => {
const output = truncateParallelOutput(getResultOutput(result));
const status = isFailedResult(result)
? `failed${result.stopReason && result.stopReason !== "end" ? ` (${result.stopReason})` : ""}`
: isRunningResult(result)
? "running"
: "completed";
return `### [${result.agent}] ${status}\n\n${output}`;
});
return `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n---\n\n")}`;
}
export function renderSubagentCall(args: SubagentCallArgs, theme: SubagentRenderTheme): Component {
const scope = resolveAgentScope(args.agentScope);
if (args.chain && args.chain.length > 0) {
let text =
theme.fg("toolTitle", theme.bold("subagent ")) +
theme.fg("accent", `chain (${args.chain.length} steps)`) +
theme.fg("muted", ` [${scope}]`);
for (let i = 0; i < Math.min(args.chain.length, 3); i++) {
const step = args.chain[i];
const cleanTask = (step.task ?? "").replace(/\{previous\}/g, "").trim();
const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask;
text +=
"\n " +
theme.fg("muted", `${i + 1}.`) +
" " +
theme.fg("accent", step.agent ?? "...") +
theme.fg("dim", ` ${preview}`);
}
if (args.chain.length > 3) text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`;
return new Text(text, 0, 0);
}
if (args.tasks && args.tasks.length > 0) {
let text =
theme.fg("toolTitle", theme.bold("subagent ")) +
theme.fg("accent", `parallel (${args.tasks.length} tasks)`) +
theme.fg("muted", ` [${scope}]`);
for (const t of args.tasks.slice(0, 3)) {
const task = t.task ?? "";
const preview = task.length > 40 ? `${task.slice(0, 40)}...` : task;
text += `\n ${theme.fg("accent", t.agent ?? "...")}${theme.fg("dim", ` ${preview}`)}`;
}
if (args.tasks.length > 3) text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`;
return new Text(text, 0, 0);
}
const agentName = args.agent || "...";
const task = args.task ?? "";
const preview = task ? (task.length > 60 ? `${task.slice(0, 60)}...` : task) : "...";
let text =
theme.fg("toolTitle", theme.bold("subagent ")) +
theme.fg("accent", agentName) +
theme.fg("muted", ` [${scope}]`);
text += `\n ${theme.fg("dim", preview)}`;
return new Text(text, 0, 0);
}
function aggregateUsage(results: readonly RunResult[]): {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
cost: number;
turns: number;
} {
const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
for (const r of results) {
total.input += r.usage.input;
total.output += r.usage.output;
total.cacheRead += r.usage.cacheRead;
total.cacheWrite += r.usage.cacheWrite;
total.cost += r.usage.cost;
total.turns += r.usage.turns;
}
return total;
}
function resultIsRunning(result: RunResult, overallActive: boolean): boolean {
if (isRunningResult(result)) return true;
return overallActive && result.status === undefined && result.exitCode === null;
}
function resultOutput(result: RunResult): string {
return result.output || getFinalOutput(result.messages);
}
export function renderSubagentResult(
result: SubagentResultLike,
options: SubagentRenderOptions,
theme: SubagentRenderTheme,
): Component {
const details = result.details;
const results = details?.results ?? [];
if (!details || results.length === 0) {
const text = result.content?.[0];
return new Text(text?.type === "text" && text.text ? text.text : "(no output)", 0, 0);
}
const mode = details.mode ?? (results.length === 1 ? "single" : "parallel");
const overallActive =
details.status === "queued" || details.status === "running" || details.status === "cancelling";
const expanded = options.expanded ?? false;
const mdTheme = getMarkdownTheme();
const fg = (color: string, text: string) => theme.fg(color, text);
const renderDisplayItems = (items: DisplayItem[], limit?: number) => {
const toShow = limit ? items.slice(-limit) : items;
const skipped = limit && items.length > limit ? items.length - limit : 0;
let text = "";
if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`);
for (const item of toShow) {
if (item.type === "text") {
const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n");
text += `${theme.fg("toolOutput", preview)}\n`;
} else {
text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, fg)}\n`;
}
}
return text.trimEnd();
};
if (mode === "single" && results.length === 1) {
const r = results[0];
const running = resultIsRunning(r, overallActive);
const isError = !running && isFailedResult(r);
const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
const displayItems = getDisplayItems(r.messages);
const finalOutput = resultOutput(r);
if (expanded) {
const container = new Container();
let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
if (isError && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
container.addChild(new Text(header, 0, 0));
if (isError && r.errorMessage) container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
container.addChild(new Spacer(1));
container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
container.addChild(new Text(theme.fg("dim", r.task), 0, 0));
container.addChild(new Spacer(1));
container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
if (displayItems.length === 0 && !finalOutput) {
container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
} else {
for (const item of displayItems) {
if (item.type === "toolCall")
container.addChild(
new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, fg), 0, 0),
);
}
if (finalOutput) {
container.addChild(new Spacer(1));
container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
}
}
const usageStr = formatUsageStats(r.usage, r.model);
if (usageStr) {
container.addChild(new Spacer(1));
container.addChild(new Text(theme.fg("dim", usageStr), 0, 0));
}
return container;
}
let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
if (isError && r.stopReason) text += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
if (isError && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`;
else if (displayItems.length === 0) {
if (finalOutput) {
const preview = finalOutput.split("\n").slice(0, 3).join("\n");
text += `\n${theme.fg("toolOutput", preview)}`;
} else {
text += `\n${theme.fg("muted", "(no output)")}`;
}
} else {
text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`;
if (displayItems.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
}
const usageStr = formatUsageStats(r.usage, r.model);
if (usageStr) text += `\n${theme.fg("dim", usageStr)}`;
return new Text(text, 0, 0);
}
if (mode === "chain") {
const successCount = results.filter((r) => !isFailedResult(r)).length;
const icon = successCount === results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
if (expanded) {
const container = new Container();
container.addChild(
new Text(
icon +
" " +
theme.fg("toolTitle", theme.bold("chain ")) +
theme.fg("accent", `${successCount}/${results.length} steps`),
0,
0,
),
);
for (const r of results) {
const rIcon = isFailedResult(r) ? theme.fg("error", "✗") : theme.fg("success", "✓");
const displayItems = getDisplayItems(r.messages);
const finalOutput = resultOutput(r);
container.addChild(new Spacer(1));
container.addChild(
new Text(`${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0),
);
container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
for (const item of displayItems) {
if (item.type === "toolCall") {
container.addChild(
new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, fg), 0, 0),
);
}
}
if (finalOutput) {
container.addChild(new Spacer(1));
container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
}
const stepUsage = formatUsageStats(r.usage, r.model);
if (stepUsage) container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0));
}
const usageStr = formatUsageStats(aggregateUsage(results));
if (usageStr) {
container.addChild(new Spacer(1));
container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
}
return container;
}
let text =
icon + " " + theme.fg("toolTitle", theme.bold("chain ")) + theme.fg("accent", `${successCount}/${results.length} steps`);
for (const r of results) {
const rIcon = isFailedResult(r) ? theme.fg("error", "✗") : theme.fg("success", "✓");
const displayItems = getDisplayItems(r.messages);
const finalOutput = resultOutput(r);
text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`;
if (displayItems.length === 0) {
if (finalOutput) {
text += `\n${theme.fg("toolOutput", finalOutput.split("\n").slice(0, 3).join("\n"))}`;
} else {
text += `\n${theme.fg("muted", "(no output)")}`;
}
} else {
text += `\n${renderDisplayItems(displayItems, 5)}`;
}
}
const usageStr = formatUsageStats(aggregateUsage(results));
if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
return new Text(text, 0, 0);
}
if (mode === "parallel") {
const running = results.filter((r) => resultIsRunning(r, overallActive)).length;
const successCount = results.filter((r) => !resultIsRunning(r, overallActive) && isSuccessfulResult(r)).length;
const failCount = results.filter((r) => !resultIsRunning(r, overallActive) && isFailedResult(r)).length;
const isRunning = running > 0;
const icon = isRunning
? theme.fg("warning", "⏳")
: failCount > 0
? theme.fg("warning", "◐")
: theme.fg("success", "✓");
const status = isRunning
? `${successCount + failCount}/${results.length} done, ${running} running`
: `${successCount}/${results.length} tasks`;
if (expanded && !isRunning) {
const container = new Container();
container.addChild(
new Text(`${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`, 0, 0),
);
for (const r of results) {
const rIcon = isFailedResult(r) ? theme.fg("error", "✗") : theme.fg("success", "✓");
const displayItems = getDisplayItems(r.messages);
const finalOutput = resultOutput(r);
container.addChild(new Spacer(1));
container.addChild(new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0));
container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
for (const item of displayItems) {
if (item.type === "toolCall") {
container.addChild(
new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, fg), 0, 0),
);
}
}
if (finalOutput) {
container.addChild(new Spacer(1));
container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
}
const taskUsage = formatUsageStats(r.usage, r.model);
if (taskUsage) container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0));
}
const usageStr = formatUsageStats(aggregateUsage(results));
if (usageStr) {
container.addChild(new Spacer(1));
container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
}
return container;
}
let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`;
for (const r of results) {
const rRunning = resultIsRunning(r, overallActive);
const rIcon = rRunning
? theme.fg("warning", "⏳")
: isFailedResult(r)
? theme.fg("error", "✗")
: theme.fg("success", "✓");
const displayItems = getDisplayItems(r.messages);
const finalOutput = resultOutput(r);
text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
if (displayItems.length === 0) {
if (finalOutput) {
text += `\n${theme.fg("toolOutput", finalOutput.split("\n").slice(0, 3).join("\n"))}`;
} else {
text += `\n${theme.fg("muted", rRunning ? "(running...)" : "(no output)")}`;
}
} else {
text += `\n${renderDisplayItems(displayItems, 5)}`;
}
}
if (!isRunning) {
const usageStr = formatUsageStats(aggregateUsage(results));
if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
}
if (!expanded) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
return new Text(text, 0, 0);
}
const text = result.content?.[0];
return new Text(text?.type === "text" && text.text ? text.text : "(no output)", 0, 0);
}
+434
View File
@@ -0,0 +1,434 @@
/**
* Subprocess task runner for Pi subagents.
*
* One ProcessRunner invocation spawns one isolated `pi --mode json` child,
* feeds it the task, and translates its JSONL events into a RunResult.
*/
import { spawn, type ChildProcess } from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { StringDecoder } from "node:string_decoder";
import type { Message } from "@earendil-works/pi-ai";
import {
emptyUsage,
type DispatchDefaults,
type PreparedTask,
type RunOptions,
type RunResult,
type TaskRunner,
} from "./types.ts";
const DEFAULT_KILL_GRACE_MS = 5000;
const DEFAULT_STDERR_LIMIT_BYTES = 64 * 1024;
export interface ProcessInvocation {
command: string;
args: string[];
}
/**
* Options seam for tests and embedders.
*
* `invocation` replaces the real Pi executable resolution, so a test can run
* a fake Node script with the computed arguments. `killGraceMs` shortens the
* SIGTERM -> SIGKILL escalation while preserving production behaviour.
*/
export interface ProcessRunnerOptions {
/** Replace the real Pi executable/argv resolution (for example with a fake Node script). */
invocation?: (args: string[]) => ProcessInvocation;
/** Delay between SIGTERM and SIGKILL when an abort kills the process tree. */
killGraceMs?: number;
/** Maximum number of stderr bytes retained (defaults to 64 KiB). */
stderrLimitBytes?: number;
/** Override platform detection, primarily for tests. */
platform?: NodeJS.Platform;
/** Environment for the child (defaults to the current process environment). */
env?: NodeJS.ProcessEnv;
}
/** Keep the last `limit` bytes without starting inside a UTF-8 code point. */
class BoundedByteTail {
private readonly chunks: Buffer[] = [];
private readonly limit: number;
private length = 0;
private dropped = false;
constructor(limit: number) {
this.limit = limit;
}
push(chunk: Buffer): void {
if (chunk.length === 0) return;
if (this.limit <= 0) {
this.dropped = true;
return;
}
this.chunks.push(chunk);
this.length += chunk.length;
while (this.length > this.limit) {
const first = this.chunks[0];
const overflow = this.length - this.limit;
if (first.length <= overflow) {
this.chunks.shift();
this.length -= first.length;
} else {
this.chunks[0] = first.subarray(overflow);
this.length -= overflow;
}
this.dropped = true;
}
}
read(): { text: string; truncated: boolean } {
if (this.length === 0) return { text: "", truncated: this.dropped };
let buffer = this.chunks.length === 1 ? this.chunks[0] : Buffer.concat(this.chunks, this.length);
let start = 0;
while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) start++;
if (start > 0) {
buffer = buffer.subarray(start);
return { text: buffer.toString("utf8"), truncated: true };
}
return { text: buffer.toString("utf8"), truncated: this.dropped };
}
}
function getPiInvocation(args: string[]): ProcessInvocation {
const currentScript = process.argv[1];
const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
if (currentScript && !isBunVirtualScript && fs.existsSync(currentScript)) {
return { command: process.execPath, args: [currentScript, ...args] };
}
const execName = path.basename(process.execPath).toLowerCase();
const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
if (!isGenericRuntime) {
return { command: process.execPath, args };
}
return { command: "pi", args };
}
function finalAssistantText(messages: Message[]): string {
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index];
if (message.role !== "assistant") continue;
for (const part of message.content) {
if (part.type === "text") return part.text;
}
}
return "";
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function killProcessTree(child: ChildProcess, signal: NodeJS.Signals, platform: NodeJS.Platform): void {
const pid = child.pid;
if (pid === undefined) return;
if (platform === "win32") {
if (signal === "SIGKILL") {
try {
const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
stdio: "ignore",
windowsHide: true,
});
killer.on("error", () => {});
killer.unref();
} catch {
// Best effort: the direct kill below may still work.
}
try {
child.kill("SIGKILL");
} catch {
// Already gone.
}
return;
}
try {
child.kill("SIGTERM");
} catch {
// Already gone.
}
try {
const killer = spawn("taskkill", ["/pid", String(pid), "/T"], {
stdio: "ignore",
windowsHide: true,
});
killer.on("error", () => {});
killer.unref();
} catch {
// Already gone.
}
return;
}
try {
process.kill(-pid, signal);
return;
} catch {
// The process group may already be gone; fall back to the direct child.
}
try {
child.kill(signal);
} catch {
// Already gone.
}
}
async function writePromptToTempFile(agentName: string, prompt: string): Promise<{ dir: string; filePath: string }> {
const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-"));
const safeName = agentName.replace(/[^\w.-]+/g, "_");
const filePath = path.join(dir, `prompt-${safeName}.md`);
try {
await fs.promises.writeFile(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
} catch (error) {
await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => {});
throw error;
}
return { dir, filePath };
}
async function removeTempPrompt(dir: string | undefined, filePath: string | undefined): Promise<void> {
if (filePath) {
try {
await fs.promises.unlink(filePath);
} catch {
// Already gone.
}
}
if (dir) {
try {
await fs.promises.rm(dir, { recursive: true, force: true });
} catch {
// Already gone.
}
}
}
export class ProcessRunner implements TaskRunner {
private readonly invocation: (args: string[]) => ProcessInvocation;
private readonly killGraceMs: number;
private readonly stderrLimitBytes: number;
private readonly platform: NodeJS.Platform;
private readonly env: NodeJS.ProcessEnv;
constructor(options: ProcessRunnerOptions = {}) {
this.invocation = options.invocation ?? getPiInvocation;
this.killGraceMs = Math.max(0, options.killGraceMs ?? DEFAULT_KILL_GRACE_MS);
this.stderrLimitBytes = Math.max(0, Math.floor(options.stderrLimitBytes ?? DEFAULT_STDERR_LIMIT_BYTES));
this.platform = options.platform ?? process.platform;
this.env = options.env ?? process.env;
}
async run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise<RunResult> {
const result: RunResult = {
agent: task.agent.name,
agentSource: task.agent.source,
task: task.task,
cwd: task.cwd,
step: task.step,
exitCode: 0,
messages: [],
output: "",
stderr: "",
stderrTruncated: false,
usage: emptyUsage(),
model: task.agent.model ?? defaults.model,
};
let tempDir: string | undefined;
let promptPath: string | undefined;
try {
if (task.agent.systemPrompt.trim()) {
const temp = await writePromptToTempFile(task.agent.name, task.agent.systemPrompt);
tempDir = temp.dir;
promptPath = temp.filePath;
}
const args = this.buildArgs(task, defaults, promptPath);
return await this.spawnAndCollect(args, task, options, result);
} finally {
await removeTempPrompt(tempDir, promptPath);
}
}
private buildArgs(task: PreparedTask, defaults: DispatchDefaults, promptPath: string | undefined): string[] {
const args: string[] = ["--mode", "json", "-p", "--no-session", "--exclude-tools", "subagent*"];
const inheritsDispatchConfig = !task.agent.model;
const model = task.agent.model ?? defaults.model;
if (model) args.push("--model", model);
if (inheritsDispatchConfig && defaults.thinkingLevel) args.push("--thinking", defaults.thinkingLevel);
if (task.agent.tools && task.agent.tools.length > 0) args.push("--tools", task.agent.tools.join(","));
if (promptPath) args.push("--append-system-prompt", promptPath);
args.push(`Task: ${task.task}`);
return args;
}
private spawnAndCollect(
args: string[],
task: PreparedTask,
options: RunOptions,
result: RunResult,
): Promise<RunResult> {
const invocation = this.invocation(args);
let child: ChildProcess;
try {
child = spawn(invocation.command, invocation.args, {
cwd: task.cwd,
shell: false,
stdio: ["ignore", "pipe", "pipe"],
detached: this.platform !== "win32",
windowsHide: true,
env: this.env,
});
} catch (error) {
result.exitCode = null;
result.errorMessage = errorMessage(error);
return Promise.resolve(result);
}
return new Promise<RunResult>((resolve) => {
const stdoutDecoder = new StringDecoder("utf8");
const stderrTail = new BoundedByteTail(this.stderrLimitBytes);
let stdoutBuffer = "";
let settled = false;
let abortRequested = false;
let killTimer: NodeJS.Timeout | undefined;
const notify = (): void => {
if (!options.onUpdate) return;
try {
const tail = stderrTail.read();
options.onUpdate({
...result,
messages: [...result.messages],
usage: { ...result.usage },
output: finalAssistantText(result.messages),
stderr: tail.text,
stderrTruncated: tail.truncated,
});
} catch {
// An observer must not break the child run.
}
};
const processLine = (line: string): void => {
if (!line.trim()) return;
let event: { type?: unknown; message?: unknown };
try {
event = JSON.parse(line) as { type?: unknown; message?: unknown };
} catch {
return;
}
if (event.type !== "message_end" || !event.message || typeof event.message !== "object") return;
const message = event.message as Message;
result.messages.push(message);
if (message.role === "assistant") {
result.usage.turns++;
const usage = message.usage;
if (usage) {
result.usage.input += usage.input || 0;
result.usage.output += usage.output || 0;
result.usage.cacheRead += usage.cacheRead || 0;
result.usage.cacheWrite += usage.cacheWrite || 0;
result.usage.cost += usage.cost?.total || 0;
result.usage.contextTokens = usage.totalTokens || 0;
}
if (!result.model && message.model) result.model = message.model;
if (message.stopReason) result.stopReason = message.stopReason;
if (message.errorMessage) result.errorMessage = message.errorMessage;
}
notify();
};
const onStdout = (chunk: Buffer): void => {
stdoutBuffer += stdoutDecoder.write(chunk);
const lines = stdoutBuffer.split("\n");
stdoutBuffer = lines.pop() ?? "";
for (const line of lines) processLine(line);
};
const onStderr = (chunk: Buffer): void => {
stderrTail.push(chunk);
};
const onError = (error: Error): void => {
result.errorMessage = error.message;
};
const cleanup = (): void => {
if (killTimer) {
clearTimeout(killTimer);
killTimer = undefined;
}
options.signal.removeEventListener("abort", onAbort);
child.stdout?.removeListener("data", onStdout);
child.stderr?.removeListener("data", onStderr);
child.removeListener("error", onError);
child.removeListener("close", onClose);
};
const finish = (): void => {
if (settled) return;
settled = true;
cleanup();
resolve(result);
};
const onClose = (code: number | null, signal: NodeJS.Signals | null): void => {
stdoutBuffer += stdoutDecoder.end();
if (stdoutBuffer.trim()) processLine(stdoutBuffer);
stdoutBuffer = "";
result.exitCode = code;
result.terminationSignal = signal ?? undefined;
if (abortRequested) {
result.stopReason = "aborted";
result.errorMessage = result.errorMessage ?? "Subagent was aborted";
if (killTimer) {
// The direct child is gone. Make sure descendants in its
// process group do not survive the abort.
killProcessTree(child, "SIGKILL", this.platform);
clearTimeout(killTimer);
killTimer = undefined;
}
}
const stderr = stderrTail.read();
result.stderr = stderr.text;
result.stderrTruncated = stderr.truncated;
result.output = finalAssistantText(result.messages);
finish();
};
const onAbort = (): void => {
if (settled || abortRequested) return;
abortRequested = true;
killProcessTree(child, "SIGTERM", this.platform);
killTimer = setTimeout(() => {
killTimer = undefined;
if (!settled) killProcessTree(child, "SIGKILL", this.platform);
}, this.killGraceMs);
};
child.stdout?.on("data", onStdout);
child.stderr?.on("data", onStderr);
child.once("error", onError);
child.once("close", onClose);
if (options.signal.aborted) onAbort();
else options.signal.addEventListener("abort", onAbort, { once: true });
});
}
}
+93
View File
@@ -0,0 +1,93 @@
/**
* TypeBox request schemas for the subagent tools.
*
* These are the single source of truth for the wire/JSON shape of an
* invocation request. `prepare.ts` consumes the inferred static types; the
* tool registration in `index.ts` can hand the schemas straight to Pi.
*/
import { Type, type Static } from "typebox";
/**
* Which agent directories an invocation may read.
*
* Declared as a union of literals rather than `StringEnum`: under this
* dependency setup `StringEnum` degrades the inferred static type to `string`,
* which would erase the `AgentScope` contract at every call site.
*/
export const AgentScopeSchema = Type.Union(
[Type.Literal("user"), Type.Literal("project"), Type.Literal("both")],
{
description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
default: "user",
},
);
export type AgentScopeValue = Static<typeof AgentScopeSchema>;
export const TaskItem = Type.Object({
agent: Type.String({ description: "Name of the agent to invoke" }),
task: Type.String({ description: "Task to delegate to the agent" }),
cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
});
export type TaskItemType = Static<typeof TaskItem>;
export const ChainItem = Type.Object({
agent: Type.String({ description: "Name of the agent to invoke" }),
task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
});
export type ChainItemType = Static<typeof ChainItem>;
export const SubagentParams = Type.Object({
agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })),
task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })),
tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })),
agentScope: Type.Optional(AgentScopeSchema),
confirmProjectAgents: Type.Optional(
Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true }),
),
cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
});
export type SubagentParamsType = Static<typeof SubagentParams>;
/**
* Parameters for managing async subagent jobs.
*
* A union of objects keyed by a literal `action` discriminant. `timeoutSeconds`
* is bounded by the schema: strictly positive and at most five minutes.
*/
export const SubagentJobsParams = Type.Union(
[
Type.Object({
action: Type.Literal("list"),
activeOnly: Type.Optional(Type.Boolean({ description: "Only return jobs that are still active." })),
}),
Type.Object({
action: Type.Literal("get"),
jobId: Type.String({ description: "Identifier of the job to inspect." }),
}),
Type.Object({
action: Type.Literal("wait"),
jobId: Type.String({ description: "Identifier of the job to wait for." }),
timeoutSeconds: Type.Optional(
Type.Number({
exclusiveMinimum: 0,
maximum: 300,
description: "Maximum seconds to wait (greater than 0, at most 300).",
}),
),
}),
Type.Object({
action: Type.Literal("cancel"),
jobId: Type.String({ description: "Identifier of the job to cancel." }),
}),
],
{ description: "Manage asynchronous subagent jobs: list, get, wait, or cancel." },
);
export type SubagentJobsParamsType = Static<typeof SubagentJobsParams>;
+142
View File
@@ -0,0 +1,142 @@
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
import type { Message } from "@earendil-works/pi-ai";
import type { AgentConfig, AgentScope } from "./agents.ts";
export type InvocationMode = "single" | "parallel" | "chain";
export type JobStatus = "queued" | "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "interrupted";
export type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "cancelled" | "interrupted";
export interface DispatchDefaults {
model?: string;
thinkingLevel?: ThinkingLevel;
}
export interface PreparedTask {
agent: AgentConfig;
task: string;
cwd: string;
step?: number;
}
export interface PreparedInvocation {
mode: InvocationMode;
tasks: PreparedTask[];
agentScope: AgentScope;
projectAgentsDir: string | null;
projectAgentsDirs?: string[];
dispatchDefaults: DispatchDefaults;
}
export interface UsageStats {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
cost: number;
contextTokens: number;
turns: number;
}
export interface RunResult {
agent: string;
agentSource: "user" | "project" | "unknown";
task: string;
cwd: string;
step?: number;
exitCode: number | null;
messages: Message[];
output: string;
stderr: string;
stderrTruncated?: boolean;
usage: UsageStats;
model?: string;
stopReason?: string;
errorMessage?: string;
terminationSignal?: string;
status?: TaskStatus;
}
export interface RunOptions {
signal: AbortSignal;
onUpdate?: (result: RunResult) => void;
}
export interface TaskRunner {
run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise<RunResult>;
}
export interface TaskSnapshot {
agent: string;
agentSource: "user" | "project" | "unknown";
task: string;
cwd: string;
step?: number;
status: TaskStatus;
exitCode: number | null;
output: string;
outputTruncated: boolean;
outputBytesOmitted: number;
stderr: string;
stderrTruncated: boolean;
usage: UsageStats;
model?: string;
stopReason?: string;
errorMessage?: string;
terminationSignal?: string;
startedAt?: number;
finishedAt?: number;
}
export interface JobSnapshot {
id: string;
mode: InvocationMode;
agentScope: AgentScope;
projectAgentsDir: string | null;
projectAgentsDirs: string[];
status: JobStatus;
plannedTaskCount: number;
results: TaskSnapshot[];
usage: UsageStats;
createdAt: number;
startedAt?: number;
finishedAt?: number;
errorMessage?: string;
timedOut?: boolean;
}
export interface SyncOutcome {
status: JobStatus;
results: RunResult[];
}
export interface SubagentDetails {
mode: InvocationMode;
status: JobStatus;
agentScope: AgentScope;
projectAgentsDir: string | null;
projectAgentsDirs: string[];
results: RunResult[];
}
export interface SyncRunOptions {
signal?: AbortSignal;
onUpdate?: (outcome: SyncOutcome) => void;
}
export interface ManagerOptions {
maxWorkers?: number;
maxActiveJobs?: number;
historyLimit?: number;
now?: () => number;
onJobChange?: (snapshot: JobSnapshot) => void;
}
export const TERMINAL_JOB_STATUSES: ReadonlySet<JobStatus> = new Set(["succeeded", "failed", "cancelled", "interrupted"]);
export function isTerminalJob(status: JobStatus): boolean {
return TERMINAL_JOB_STATUSES.has(status);
}
export function emptyUsage(): UsageStats {
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
}
+71
View File
@@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import test from "node:test";
import fc from "fast-check";
import { SubagentManager } from "../src/manager.ts";
import { isTerminalJob, type JobSnapshot, type JobStatus } from "../src/types.ts";
import { FakeRunner, invocation } from "./helpers.ts";
type Action =
| { type: "start"; mode: "single" | "parallel" | "chain" }
| { type: "cancel"; index: number }
| { type: "complete"; fail: boolean };
const action = fc.oneof(
fc.record({ type: fc.constant("start"), mode: fc.constantFrom("single", "parallel", "chain") }),
fc.record({ type: fc.constant("cancel"), index: fc.integer({ min: 0, max: 7 }) }),
fc.record({ type: fc.constant("complete"), fail: fc.boolean() }),
) as fc.Arbitrary<Action>;
function checkInvariants(manager: SubagentManager, ids: string[], runner: FakeRunner, previous: Map<string, JobSnapshot>, shuttingDown: boolean): void {
assert.ok(runner.calls.filter((call) => !call.settled).length <= 2, "global worker bound");
for (const id of ids) {
const current = manager.get(id);
const old = previous.get(id);
if (old && isTerminalJob(old.status)) assert.equal(current.status, old.status, `terminal job ${id} changed`);
for (let index = 0; index < current.results.length; index++) {
const task = current.results[index];
const before = old?.results[index];
if (before && ["succeeded", "failed", "cancelled", "interrupted"].includes(before.status)) {
assert.equal(task.status, before.status, `terminal task ${id}/${index} changed`);
}
if (current.mode === "chain" && index > 0) {
assert.equal(current.results[index - 1].status, "succeeded", "chain step ran before predecessor succeeded");
}
}
if (current.status === "cancelling") assert.equal(current.results.some((task) => task.status === "queued"), false);
if (shuttingDown) assert.equal(isTerminalJob(current.status), true);
previous.set(id, current);
}
}
test("generated start/complete/cancel/shutdown sequences preserve scheduler and lifecycle invariants", async () => {
await fc.assert(fc.asyncProperty(fc.array(action, { minLength: 1, maxLength: 30 }), async (actions) => {
const runner = new FakeRunner(false);
const manager = new SubagentManager(runner, { maxWorkers: 2 });
const ids: string[] = [];
const previous = new Map<string, JobSnapshot>();
let shuttingDown = false;
for (const step of actions) {
if (step.type === "start" && ids.length < 8 && !shuttingDown) {
ids.push(manager.startAsync(invocation(step.mode)).id);
} else if (step.type === "cancel" && ids.length > 0 && !shuttingDown) {
manager.cancel(ids[step.index % ids.length]);
} else if (step.type === "complete") {
const pending = runner.calls.find((call) => !call.settled);
if (pending) runner.complete(pending.task.task, "generated", step.fail ? { exitCode: 1, errorMessage: "generated failure" } : {});
}
await new Promise((resolve) => setImmediate(resolve));
checkInvariants(manager, ids, runner, previous, shuttingDown);
}
shuttingDown = true;
const shutdown = manager.shutdown();
for (const pending of runner.calls.filter((call) => !call.settled)) {
runner.complete(pending.task.task, "late completion", { exitCode: 0 });
}
await shutdown;
checkInvariants(manager, ids, runner, previous, shuttingDown);
assert.throws(() => manager.startAsync(invocation()), /shutting down/);
}), { numRuns: 100 });
});
+14
View File
@@ -0,0 +1,14 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readMaxWorkers } from "../src/config.ts";
test("worker configuration accepts only integers from 1 through 32", () => {
assert.deepEqual(readMaxWorkers(undefined), { value: 4 });
assert.deepEqual(readMaxWorkers("1"), { value: 1 });
assert.deepEqual(readMaxWorkers("32"), { value: 32 });
for (const invalid of ["0", "33", "-1", "1.5", "four", " 4"]) {
const result = readMaxWorkers(invalid);
assert.equal(result.value, 4);
assert.match(result.warning ?? "", /PI_SUBAGENT_MAX_WORKERS/);
}
});
+164
View File
@@ -0,0 +1,164 @@
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import test from "node:test";
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
import registerExtension from "../src/index.ts";
import { extractJobSnapshots } from "../src/persistence.ts";
import { FakeRunner } from "./helpers.ts";
type Execute = (id: string, params: any, signal?: AbortSignal, onUpdate?: unknown, ctx?: ExtensionToolContext) => Promise<AgentToolResult<any>>;
async function harness(initialEntries: unknown[] = []) {
let branch = initialEntries;
const cwd = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-extension-"));
const agentsDir = path.join(cwd, ".pi", "agents");
await fs.promises.mkdir(agentsDir, { recursive: true });
await fs.promises.writeFile(path.join(agentsDir, "scout.md"), "---\nname: scout\ndescription: Test agent\n---\nTest prompt\n");
const runner = new FakeRunner();
const tools = new Map<string, { execute: Execute }>();
const commands = new Map<string, (args: string, ctx: ExtensionToolContext) => Promise<void>>();
const events = new Map<string, (event: any, ctx: ExtensionToolContext) => unknown>();
const entries: unknown[] = [];
const notifications: string[] = [];
const statuses = new Map<string, string | undefined>();
const pi = {
registerTool(definition: { name: string; execute: Execute }) { tools.set(definition.name, definition); },
registerCommand(name: string, definition: { handler: (args: string, ctx: ExtensionToolContext) => Promise<void> }) { commands.set(name, definition.handler); },
registerEntryRenderer() {},
on(name: string, handler: (event: any, ctx: ExtensionToolContext) => unknown) { events.set(name, handler); },
appendEntry(_type: string, data: unknown) { entries.push({ type: "custom", customType: _type, data }); },
};
registerExtension(pi as unknown as ExtensionAPI, runner);
const ctx = {
cwd,
mode: "tui",
hasUI: true,
model: undefined,
thinkingLevel: undefined,
isProjectTrusted: () => true,
ui: {
confirm: async () => true,
notify: (text: string) => { notifications.push(text); },
setStatus: (key: string, text: string | undefined) => { statuses.set(key, text); },
},
sessionManager: {
getBranch: () => branch,
getSessionId: () => "test-session",
},
} as unknown as ExtensionToolContext;
return {
cwd, runner, tools, commands, events, entries, notifications, statuses, ctx,
setBranch: (entries: unknown[]) => { branch = entries; },
};
}
const params = { agent: "scout", task: "test task", agentScope: "project", confirmProjectAgents: false };
test("Pi adapters preserve sync results and expose async failure/cancel/interruption without management errors", async () => {
const h = await harness();
try {
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
const syncPromise = h.tools.get("subagent")!.execute("sync", params, undefined, undefined, h.ctx);
await new Promise((resolve) => setImmediate(resolve));
h.runner.complete("test task", "sync output");
const sync = await syncPromise;
assert.equal(sync.content[0].type, "text");
assert.equal(sync.content[0].type === "text" ? sync.content[0].text : "", "sync output");
assert.notEqual(sync.isError, true);
const started = await h.tools.get("subagent_async")!.execute("async-1", params, undefined, undefined, h.ctx);
const jobId = (started.details as any).job.id as string;
h.runner.complete("test task", "partial", { exitCode: 1, errorMessage: "boom" });
const failed = await h.tools.get("subagent_jobs")!.execute("wait-1", { action: "wait", jobId, timeoutSeconds: 1 }, undefined, undefined, h.ctx);
assert.equal((failed.details as any).job.status, "failed");
assert.notEqual(failed.isError, true);
assert.match(extractJobSnapshots(h.entries).at(-1)?.status ?? "", /failed/);
await h.commands.get("subagents")!("", h.ctx);
assert.match(h.notifications.at(-1) ?? "", new RegExp(jobId));
const second = await h.tools.get("subagent_async")!.execute("async-2", params, undefined, undefined, h.ctx);
const secondId = (second.details as any).job.id as string;
const cancelling = await h.tools.get("subagent_jobs")!.execute("cancel", { action: "cancel", jobId: secondId }, undefined, undefined, h.ctx);
assert.equal((cancelling.details as any).job.status, "cancelling");
assert.notEqual(cancelling.isError, true);
const cancelled = await h.tools.get("subagent_jobs")!.execute("wait-2", { action: "wait", jobId: secondId, timeoutSeconds: 1 }, undefined, undefined, h.ctx);
assert.equal((cancelled.details as any).job.status, "cancelled");
assert.notEqual(cancelled.isError, true);
const third = await h.tools.get("subagent_async")!.execute("async-3", params, undefined, undefined, h.ctx);
const thirdId = (third.details as any).job.id as string;
await h.events.get("session_shutdown")?.({ type: "session_shutdown", reason: "reload" }, h.ctx);
const interrupted = await h.tools.get("subagent_jobs")!.execute("get-3", { action: "get", jobId: thirdId }, undefined, undefined, h.ctx);
assert.equal((interrupted.details as any).job.status, "interrupted");
assert.notEqual(interrupted.isError, true);
const unknown = await h.tools.get("subagent_jobs")!.execute("unknown", { action: "get", jobId: "job_missing" }, undefined, undefined, h.ctx);
assert.equal(unknown.isError, true);
assert.equal(h.runner.aborted.includes("test task"), true);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("async dispatch rejects print/JSON before admission", async () => {
const h = await harness();
try {
for (const mode of ["print", "json"]) {
const ctx = { ...h.ctx, mode } as ExtensionToolContext;
const result = await h.tools.get("subagent_async")!.execute("async", params, undefined, undefined, ctx);
assert.equal(result.isError, true);
assert.match(result.content[0].type === "text" ? result.content[0].text : "", /synchronous subagent/);
}
assert.equal(h.runner.calls.length, 0);
assert.equal(h.entries.length, 0);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("session restart restores persisted interrupted history without starting a child", async () => {
const first = await harness();
let second: Awaited<ReturnType<typeof harness>> | undefined;
try {
await first.events.get("session_start")?.({ type: "session_start", reason: "startup" }, first.ctx);
const started = await first.tools.get("subagent_async")!.execute("async", params, undefined, undefined, first.ctx);
const jobId = (started.details as any).job.id as string;
await first.events.get("session_shutdown")?.({ type: "session_shutdown", reason: "reload" }, first.ctx);
second = await harness(first.entries);
await second.events.get("session_start")?.({ type: "session_start", reason: "reload" }, second.ctx);
const restored = await second.tools.get("subagent_jobs")!.execute("get", { action: "get", jobId }, undefined, undefined, second.ctx);
assert.equal((restored.details as any).job.status, "interrupted");
assert.notEqual(restored.isError, true);
assert.equal(second.runner.calls.length, 0);
} finally {
await fs.promises.rm(first.cwd, { recursive: true, force: true });
if (second) await fs.promises.rm(second.cwd, { recursive: true, force: true });
}
});
test("session_tree replaces history from the active branch", async () => {
const h = await harness();
try {
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
const started = await h.tools.get("subagent_async")!.execute("async", params, undefined, undefined, h.ctx);
const jobId = (started.details as any).job.id as string;
h.runner.complete("test task");
await h.tools.get("subagent_jobs")!.execute("wait", { action: "wait", jobId, timeoutSeconds: 1 }, undefined, undefined, h.ctx);
h.setBranch([]);
await h.events.get("session_tree")?.({ type: "session_tree" }, h.ctx);
const missing = await h.tools.get("subagent_jobs")!.execute("get", { action: "get", jobId }, undefined, undefined, h.ctx);
assert.equal(missing.isError, true);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env node
/**
* Fake child `pi` for ProcessRunner tests.
*
* The runner appends the real Pi CLI arguments after this script path; the
* fake ignores them and selects a scenario from FAKE_PI_MODE. All child
* processes inherit the same environment from the runner.
*/
import { spawn } from "node:child_process";
import * as fs from "node:fs";
const mode = process.env.FAKE_PI_MODE ?? "success";
function emit(event) {
process.stdout.write(`${JSON.stringify(event)}\n`);
}
function assistantMessage(text, options = {}) {
const message = {
role: "assistant",
content: [{ type: "text", text }],
api: "fake",
provider: "fake",
model: options.model ?? "fake-model",
usage: options.usage ?? {
input: 10,
output: 5,
cacheRead: 2,
cacheWrite: 1,
totalTokens: 18,
cost: { input: 0.1, output: 0.1, cacheRead: 0.02, cacheWrite: 0.03, total: 0.25 },
},
stopReason: options.stopReason ?? "stop",
timestamp: Date.now(),
};
if (options.errorMessage) message.errorMessage = options.errorMessage;
return message;
}
function toolResultMessage(text) {
return {
role: "toolResult",
toolCallId: "call_1",
toolName: "read",
content: [{ type: "text", text }],
isError: false,
timestamp: Date.now(),
};
}
function finish(defaultCode = 0) {
process.exitCode = Number(process.env.FAKE_PI_EXIT ?? defaultCode);
}
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
if (mode === "success") {
emit({ type: "agent_start" });
emit({
type: "message_end",
message: assistantMessage("working", {
stopReason: "toolUse",
usage: {
input: 10,
output: 5,
cacheRead: 2,
cacheWrite: 1,
totalTokens: 18,
cost: { input: 0.1, output: 0.1, cacheRead: 0.02, cacheWrite: 0.03, total: 0.25 },
},
}),
});
emit({ type: "message_end", message: toolResultMessage("tool output") });
// Stale legacy shape: the runner must ignore tool_result_end and keep only
// the message_end tool result above.
emit({ type: "tool_result_end", message: toolResultMessage("STALE tool output") });
emit({
type: "message_end",
message: assistantMessage("final answer", {
usage: {
input: 20,
output: 7,
cacheRead: 3,
cacheWrite: 2,
totalTokens: 30,
cost: { input: 0.2, output: 0.3, cacheRead: 0.04, cacheWrite: 0.06, total: 0.75 },
},
}),
});
process.stderr.write(process.env.FAKE_PI_STDERR ?? "");
finish();
} else if (mode === "failure") {
emit({
type: "message_end",
message: assistantMessage("", { stopReason: "error", errorMessage: "model exploded" }),
});
process.stderr.write("diagnostic\n");
finish(7);
} else if (mode === "stderr") {
process.stderr.write("STDERR-START");
const chunk = "é".repeat(10000);
for (let index = 0; index < 8; index++) process.stderr.write(chunk);
process.stderr.write("STDERR-END");
finish();
} else if (mode === "wait") {
fs.writeFileSync(process.env.FAKE_PI_READY_FILE, String(process.pid));
setInterval(() => {}, 1000);
} else if (mode === "tree-term") {
const readyFile = process.env.FAKE_PI_READY_FILE;
const parentSignalFile = process.env.FAKE_PI_PARENT_SIGNAL_FILE;
const childReadyFile = process.env.FAKE_PI_CHILD_READY_FILE;
const childSignalFile = process.env.FAKE_PI_CHILD_SIGNAL_FILE;
const childPidFile = process.env.FAKE_PI_CHILD_PID_FILE;
process.on("SIGTERM", () => {
fs.appendFileSync(parentSignalFile, "SIGTERM\n");
});
const childScript = `
const fs = require("node:fs");
process.on("SIGTERM", () => {
fs.appendFileSync(process.env.FAKE_PI_CHILD_SIGNAL_FILE, "SIGTERM\\n");
});
fs.writeFileSync(process.env.FAKE_PI_CHILD_READY_FILE, String(process.pid));
setInterval(() => {}, 1000);
`;
const child = spawn(process.execPath, ["-e", childScript], {
env: process.env,
stdio: "ignore",
});
if (child.pid && childPidFile) fs.writeFileSync(childPidFile, String(child.pid));
const deadline = Date.now() + 5000;
while (!fs.existsSync(childReadyFile) && Date.now() < deadline) {
await delay(10);
}
fs.writeFileSync(
readyFile,
JSON.stringify({ parentPid: process.pid, childPid: child.pid }),
);
setInterval(() => {}, 1000);
} else {
process.stderr.write(`unknown FAKE_PI_MODE: ${mode}\n`);
process.exitCode = 2;
}
+85
View File
@@ -0,0 +1,85 @@
import type { AgentConfig } from "../src/agents.ts";
import type { PreparedInvocation, RunResult, TaskRunner, RunOptions } from "../src/types.ts";
export const agent: AgentConfig = {
name: "scout",
description: "Test agent",
systemPrompt: "Test prompt",
source: "user",
filePath: "/tmp/scout.md",
};
export function invocation(mode: PreparedInvocation["mode"] = "single"): PreparedInvocation {
const count = mode === "single" ? 1 : 2;
return {
mode,
agentScope: "user",
projectAgentsDir: null,
dispatchDefaults: {},
tasks: Array.from({ length: count }, (_, index) => ({
agent,
task: `task ${index + 1}`,
cwd: "/tmp",
step: mode === "chain" ? index + 1 : undefined,
})),
};
}
export function result(task: { agent: AgentConfig; task: string; cwd: string; step?: number }, output = "done"): RunResult {
return {
agent: task.agent.name,
agentSource: task.agent.source,
task: task.task,
cwd: task.cwd,
step: task.step,
exitCode: 0,
messages: [],
output,
stderr: "",
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
};
}
interface PendingRun {
task: PreparedInvocation["tasks"][number];
options: RunOptions;
resolve?: (result: RunResult) => void;
settled?: boolean;
}
export class FakeRunner implements TaskRunner {
readonly calls: PendingRun[] = [];
readonly aborted: string[] = [];
private readonly resolveOnAbort: boolean;
constructor(resolveOnAbort = true) {
this.resolveOnAbort = resolveOnAbort;
}
async run(task: PreparedInvocation["tasks"][number], _defaults: PreparedInvocation["dispatchDefaults"], options: RunOptions): Promise<RunResult> {
const pending: PendingRun = { task, options };
this.calls.push(pending);
return new Promise<RunResult>((resolve) => {
options.signal.addEventListener("abort", () => {
this.aborted.push(task.task);
if (!this.resolveOnAbort) return;
pending.settled = true;
resolve({
...result(task),
exitCode: null,
stopReason: "aborted",
errorMessage: "aborted",
terminationSignal: "SIGTERM",
});
}, { once: true });
pending.resolve = resolve;
});
}
complete(task: string, output = "done", overrides: Partial<RunResult> = {}): void {
const pending = this.calls.find((call) => call.task.task === task && !call.settled);
if (!pending?.resolve) throw new Error(`No pending run for ${task}`);
pending.settled = true;
pending.resolve({ ...result(pending.task, output), ...overrides });
}
}
+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatJob, formatJobList } from "../src/job-format.ts";
import { extractJobSnapshots, persistedJob, SUBAGENT_JOB_ENTRY } from "../src/persistence.ts";
import { emptyUsage, type JobSnapshot } from "../src/types.ts";
const job: JobSnapshot = {
id: "job_0001",
mode: "single",
agentScope: "user",
projectAgentsDir: null,
projectAgentsDirs: [],
status: "failed",
plannedTaskCount: 1,
usage: emptyUsage(),
createdAt: 10,
startedAt: 20,
finishedAt: 30,
results: [{
agent: "scout",
agentSource: "user",
task: "inspect",
cwd: "/tmp",
status: "failed",
exitCode: 1,
output: "partial",
outputTruncated: false,
outputBytesOmitted: 0,
stderr: "bad stderr",
stderrTruncated: false,
usage: emptyUsage(),
errorMessage: "boom",
}],
};
test("job formatting exposes terminal status, diagnostics, and bounded output", () => {
const text = formatJob(job);
assert.match(text, /job_0001/);
assert.match(text, /failed/);
assert.match(text, /boom/);
assert.match(text, /partial/);
assert.match(formatJobList([job]), /1 failed/);
assert.match(formatJob({ ...job, status: "running", finishedAt: undefined, timedOut: true }), /timed out/i);
});
test("persistence wraps snapshots and ignores foreign or malformed entries", () => {
const entry = { type: "custom", customType: SUBAGENT_JOB_ENTRY, data: persistedJob("session-a", job) };
const restored = extractJobSnapshots([
entry,
{ type: "custom", customType: SUBAGENT_JOB_ENTRY, data: { version: 1, job: { id: "broken" } } },
{ type: "custom", customType: "other", data: persistedJob("session-a", job) },
{ type: "message" },
]);
assert.deepEqual(restored, [job]);
});
+278
View File
@@ -0,0 +1,278 @@
import assert from "node:assert/strict";
import test from "node:test";
import { SubagentManager } from "../src/manager.ts";
import { FakeRunner, invocation } from "./helpers.ts";
test("async single returns an ID before completion and later exposes its result", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner);
const job = manager.startAsync(invocation());
assert.match(job.id, /^job_/);
assert.equal(job.status, "running");
assert.equal(runner.calls.length, 1);
runner.complete("task 1", "finished");
const terminal = await manager.wait(job.id, 1);
assert.equal(terminal.status, "succeeded");
assert.equal(terminal.results.length, 1);
assert.equal(terminal.results[0].output, "finished");
assert.equal(terminal.results[0].status, "succeeded");
});
test("parallel preserves partial results and does not finish while another task can run", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner, { maxWorkers: 1 });
const job = manager.startAsync(invocation("parallel"));
assert.equal(runner.calls.length, 1);
runner.complete("task 1", "bad", { exitCode: 1, errorMessage: "boom" });
await new Promise((resolve) => setImmediate(resolve));
assert.equal(manager.get(job.id).status, "running");
assert.equal(runner.calls.length, 2);
runner.complete("task 2", "good");
const terminal = await manager.wait(job.id, 1);
assert.equal(terminal.status, "failed");
assert.deepEqual(terminal.results.map((result) => result.status), ["failed", "succeeded"]);
assert.equal(terminal.results[0].errorMessage, "boom");
assert.equal(terminal.results[1].output, "good");
});
test("chain substitutes the previous output and starts only the next step", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner);
const request = invocation("chain");
request.tasks[1].task = "review {previous}";
const job = manager.startAsync(request);
assert.equal(runner.calls.length, 1);
assert.equal(manager.get(job.id).results.length, 1);
runner.complete("task 1", "first output");
await new Promise((resolve) => setImmediate(resolve));
assert.equal(runner.calls.length, 2);
assert.equal(runner.calls[1].task.task, "review first output");
runner.complete("review first output", "second output");
const terminal = await manager.wait(job.id, 1);
assert.equal(terminal.status, "succeeded");
assert.deepEqual(terminal.results.map((result) => result.step), [1, 2]);
});
test("cancel drains queued tasks, aborts running tasks, and is idempotent", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner, { maxWorkers: 1 });
const job = manager.startAsync(invocation("parallel"));
const cancelling = manager.cancel(job.id);
assert.equal(cancelling.status, "cancelling");
assert.deepEqual(cancelling.results.map((result) => result.status), ["running", "cancelled"]);
assert.deepEqual(runner.aborted, ["task 1"]);
const terminal = await manager.wait(job.id, 1);
assert.equal(terminal.status, "cancelled");
assert.deepEqual(terminal.results.map((result) => result.status), ["cancelled", "cancelled"]);
assert.equal(runner.calls.length, 1);
assert.equal(manager.cancel(job.id).status, "cancelled");
});
test("synchronous and async work share the global worker limit", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner, { maxWorkers: 1 });
const background = manager.startAsync(invocation());
let syncSettled = false;
const sync = manager.runSync(invocation()).then((outcome) => {
syncSettled = true;
return outcome;
});
assert.equal(runner.calls.length, 1);
assert.equal(syncSettled, false);
runner.complete("task 1", "async done");
await new Promise((resolve) => setImmediate(resolve));
assert.equal((await manager.wait(background.id, 1)).status, "succeeded");
assert.equal(runner.calls.length, 2);
runner.complete("task 1", "sync done");
const outcome = await sync;
assert.equal(outcome.status, "succeeded");
assert.equal(outcome.results[0].output, "sync done");
});
test("wait timeout and caller abort do not cancel the job", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner);
const job = manager.startAsync(invocation());
const timedOut = await manager.wait(job.id, 0.01);
assert.equal(timedOut.status, "running");
assert.equal(timedOut.timedOut, true);
assert.equal(manager.get(job.id).status, "running");
const controller = new AbortController();
const waiting = manager.wait(job.id, 1, controller.signal);
controller.abort();
await assert.rejects(waiting, /Wait aborted/);
assert.equal(manager.get(job.id).status, "running");
assert.equal(runner.aborted.length, 0);
runner.complete("task 1");
assert.equal((await manager.wait(job.id, 1)).status, "succeeded");
});
test("shutdown interrupts work, drains the queue, awaits cleanup, and rejects admission", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner, { maxWorkers: 1 });
const job = manager.startAsync(invocation("parallel"));
let shutdownResolved = false;
const shutdown = manager.shutdown().then(() => {
shutdownResolved = true;
});
const interrupted = manager.get(job.id);
assert.equal(interrupted.status, "interrupted");
assert.deepEqual(interrupted.results.map((result) => result.status), ["interrupted", "interrupted"]);
assert.deepEqual(runner.aborted, ["task 1"]);
assert.equal(runner.calls.length, 1);
await shutdown;
assert.equal(shutdownResolved, true);
assert.throws(() => manager.startAsync(invocation()), /shutting down/);
assert.equal(manager.shutdown instanceof Function, true);
await manager.shutdown();
});
test("sync abort kills work, rejects the call, and releases its worker", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner, { maxWorkers: 1 });
const controller = new AbortController();
const updates: string[] = [];
const sync = manager.runSync(invocation(), {
signal: controller.signal,
onUpdate: (outcome) => updates.push(outcome.status),
});
controller.abort();
await assert.rejects(sync, /aborted/i);
assert.deepEqual(runner.aborted, ["task 1"]);
assert.ok(updates.includes("running"));
const next = manager.startAsync(invocation());
assert.equal(next.status, "running");
runner.complete("task 1");
assert.equal((await manager.wait(next.id, 1)).status, "succeeded");
});
test("async snapshots cap output without mutating the full runner result", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner);
const job = manager.startAsync(invocation());
const output = "🙂ab".repeat(20000);
runner.complete("task 1", output);
const terminal = await manager.wait(job.id, 1);
const snapshot = terminal.results[0];
assert.equal(snapshot.outputTruncated, true);
assert.ok(Buffer.byteLength(snapshot.output, "utf8") <= 50 * 1024);
assert.equal(output.startsWith(snapshot.output), true);
assert.equal(snapshot.output.includes("\uFFFD"), false);
assert.ok(snapshot.outputBytesOmitted > 0);
});
test("active admission is capped and terminal history evicts oldest jobs only", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner, { maxActiveJobs: 1, historyLimit: 1 });
const first = manager.startAsync(invocation());
assert.throws(() => manager.startAsync(invocation()), /Too many active async jobs/);
runner.complete("task 1", "first");
assert.equal((await manager.wait(first.id, 1)).status, "succeeded");
const second = manager.startAsync(invocation());
assert.equal(manager.get(first.id).status, "succeeded");
runner.complete("task 1", "second");
assert.equal((await manager.wait(second.id, 1)).status, "succeeded");
assert.throws(() => manager.get(first.id), /Unknown or evicted/);
assert.equal(manager.get(second.id).results[0].output, "second");
});
test("restore keeps terminal history, interrupts unfinished snapshots, and deduplicates IDs", () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner);
const source = new SubagentManager(new FakeRunner());
const running = source.startAsync(invocation());
manager.restore([running, running]);
const restored = manager.get(running.id);
assert.equal(restored.status, "interrupted");
assert.equal(restored.results[0].status, "interrupted");
assert.equal(manager.list().length, 1);
assert.equal(runner.calls.length, 0);
const next = manager.startAsync(invocation());
assert.notEqual(next.id, running.id);
});
test("chain stops on the first failure without manufacturing later results", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner);
const job = manager.startAsync(invocation("chain"));
runner.complete("task 1", "bad", { exitCode: 1, errorMessage: "failed step" });
const terminal = await manager.wait(job.id, 1);
assert.equal(terminal.status, "failed");
assert.equal(terminal.results.length, 1);
assert.equal(runner.calls.length, 1);
});
test("cancellation wins over a later successful process exit", async () => {
const runner = new FakeRunner(false);
const manager = new SubagentManager(runner);
const job = manager.startAsync(invocation());
manager.cancel(job.id);
runner.complete("task 1", "too late", { exitCode: 0, stopReason: "stop" });
const terminal = await manager.wait(job.id, 1);
assert.equal(terminal.status, "cancelled");
assert.equal(terminal.results[0].status, "cancelled");
});
test("cancelled chain never starts a successor when the current step reports late success", async () => {
const runner = new FakeRunner(false);
const manager = new SubagentManager(runner);
const job = manager.startAsync(invocation("chain"));
manager.cancel(job.id);
runner.complete("task 1", "late success", { exitCode: 0, stopReason: "stop" });
const terminal = await manager.wait(job.id, 0.1);
assert.equal(terminal.status, "cancelled");
assert.equal(runner.calls.length, 1);
assert.equal(terminal.results.length, 1);
});
test("branch replacement removes terminal history without replacing active jobs", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner);
const finished = manager.startAsync(invocation());
runner.complete("task 1", "old branch");
await manager.wait(finished.id, 1);
const active = manager.startAsync(invocation());
manager.replaceHistory([]);
assert.throws(() => manager.get(finished.id), /Unknown or evicted/);
assert.equal(manager.get(active.id).status, "running");
runner.complete("task 1", "active");
assert.equal((await manager.wait(active.id, 1)).status, "succeeded");
});
test("observer failures cannot strand jobs or workers", async () => {
const runner = new FakeRunner();
const manager = new SubagentManager(runner, { onJobChange: () => { throw new Error("observer"); } });
const job = manager.startAsync(invocation());
runner.complete("task 1");
assert.equal((await manager.wait(job.id, 1)).status, "succeeded");
const sync = manager.runSync(invocation(), { onUpdate: () => { throw new Error("observer"); } });
await new Promise((resolve) => setImmediate(resolve));
runner.complete("task 1", "sync");
assert.equal((await sync).status, "succeeded");
});
+20
View File
@@ -0,0 +1,20 @@
import assert from "node:assert/strict";
import test from "node:test";
import fc from "fast-check";
import { truncateUtf8Head, truncateUtf8Tail } from "../src/output.ts";
test("UTF-8 truncation preserves exact prefixes/suffixes and valid boundaries", () => {
fc.assert(fc.property(fc.string({ unit: "grapheme" }), fc.integer({ min: 0, max: 128 }), (input, limit) => {
const head = truncateUtf8Head(input, limit);
assert.equal(input.startsWith(head.text), true);
assert.ok(Buffer.byteLength(head.text, "utf8") <= limit);
assert.equal(head.bytesOmitted, Buffer.byteLength(input, "utf8") - Buffer.byteLength(head.text, "utf8"));
assert.equal(head.truncated, head.bytesOmitted > 0);
const tail = truncateUtf8Tail(input, limit);
assert.equal(input.endsWith(tail.text), true);
assert.ok(Buffer.byteLength(tail.text, "utf8") <= limit);
assert.equal(tail.bytesOmitted, Buffer.byteLength(input, "utf8") - Buffer.byteLength(tail.text, "utf8"));
assert.equal(tail.truncated, tail.bytesOmitted > 0);
}), { numRuns: 500 });
});
+647
View File
@@ -0,0 +1,647 @@
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import test, { after } from "node:test";
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
import { Value } from "typebox/value";
import {
InvalidInvocationError,
ProjectAgentDeclinedError,
prepareInvocation,
resolveAgentScope,
type PrepareContext,
} from "../src/prepare.ts";
import {
ChainItem,
type AgentScopeValue,
type SubagentJobsParamsType,
type SubagentParamsType,
SubagentJobsParams,
SubagentParams,
TaskItem,
} from "../src/schemas.ts";
interface Confirmation {
title: string;
message: string;
}
interface FakeContext extends PrepareContext {
confirmations: Confirmation[];
}
const tempRoots: string[] = [];
after(() => {
for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
});
function makeTempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-prepare-"));
tempRoots.push(root);
return root;
}
function writeAgent(projectDir: string, name: string, description: string, systemPrompt = `You are ${description}.`): string {
const agentsDir = path.join(projectDir, ".pi", "agents");
fs.mkdirSync(agentsDir, { recursive: true });
const filePath = path.join(agentsDir, `${name}.md`);
fs.writeFileSync(filePath, `---\nname: ${name}\ndescription: ${description}\n---\n${systemPrompt}\n`, "utf-8");
return filePath;
}
function makeProject(root: string, label: string, agents: Record<string, string> = { reviewer: `${label} reviewer` }): string {
const projectDir = path.join(root, label);
fs.mkdirSync(projectDir, { recursive: true });
for (const [name, description] of Object.entries(agents)) {
writeAgent(projectDir, name, description);
}
return projectDir;
}
function projectAgentsDir(projectDir: string): string {
return path.join(projectDir, ".pi", "agents");
}
function makeContext(options: {
cwd: string;
trusted?: boolean;
hasUI?: boolean;
confirmResult?: boolean | boolean[];
model?: { provider: string; id: string };
thinkingLevel?: ThinkingLevel;
}): FakeContext {
const confirmations: Confirmation[] = [];
const answers = Array.isArray(options.confirmResult) ? [...options.confirmResult] : undefined;
const fallback = typeof options.confirmResult === "boolean" ? options.confirmResult : true;
return {
cwd: options.cwd,
model: options.model ?? { provider: "test-provider", id: "test-model" },
thinkingLevel: options.thinkingLevel ?? "medium",
hasUI: options.hasUI ?? true,
isProjectTrusted: () => options.trusted ?? false,
ui: {
async confirm(title: string, message: string): Promise<boolean> {
confirmations.push({ title, message });
return answers && answers.length > 0 ? answers.shift()! : fallback;
},
},
confirmations,
};
}
/** Project-scoped request with confirmation off unless a test opts in. */
function projectParams(overrides: Partial<SubagentParamsType> = {}): SubagentParamsType {
return { agentScope: "project", confirmProjectAgents: false, ...overrides };
}
test("single mode resolves the project agent, cwd, and dispatch defaults", async () => {
const root = makeTempRoot();
const project = makeProject(root, "project-a");
const ctx = makeContext({ cwd: root, thinkingLevel: "high" });
const prepared = await prepareInvocation(
projectParams({ agent: "reviewer", task: "review it", cwd: "project-a" }),
ctx,
);
assert.equal(prepared.mode, "single");
assert.equal(prepared.agentScope, "project");
assert.equal(prepared.tasks.length, 1);
const [task] = prepared.tasks;
assert.equal(task.agent.name, "reviewer");
assert.equal(task.agent.source, "project");
assert.equal(task.agent.description, "project-a reviewer");
assert.equal(task.agent.filePath, path.join(projectAgentsDir(project), "reviewer.md"));
assert.equal(task.task, "review it");
assert.equal(task.cwd, path.resolve(root, "project-a"));
assert.equal(task.step, undefined);
assert.equal(prepared.projectAgentsDir, projectAgentsDir(project));
assert.deepEqual(prepared.projectAgentsDirs, [projectAgentsDir(project)]);
assert.deepEqual(prepared.dispatchDefaults, {
model: "test-provider/test-model",
thinkingLevel: "high",
});
assert.equal(ctx.confirmations.length, 0);
});
test("task cwd defaults to ctx.cwd and relative cwds resolve against it", async () => {
const root = makeTempRoot();
const project = makeProject(root, "project-a");
const workspace = path.join(root, "workspace");
fs.mkdirSync(workspace);
const defaultCwd = await prepareInvocation(
projectParams({ agent: "reviewer", task: "default" }),
makeContext({ cwd: project }),
);
assert.equal(defaultCwd.tasks[0].cwd, project);
const relativeCwd = await prepareInvocation(
projectParams({ agent: "reviewer", task: "relative", cwd: path.relative(workspace, project) }),
makeContext({ cwd: workspace }),
);
assert.equal(relativeCwd.tasks[0].cwd, project);
assert.equal(relativeCwd.tasks[0].agent.filePath, path.join(projectAgentsDir(project), "reviewer.md"));
});
test("parallel preserves task order and resolves same-named agents from each task's cwd", async () => {
const root = makeTempRoot();
const projectA = makeProject(root, "project-a", { reviewer: "Reviewer A" });
const projectB = makeProject(root, "project-b", { reviewer: "Reviewer B" });
const ctx = makeContext({ cwd: root });
const prepared = await prepareInvocation(
projectParams({
tasks: [
{ agent: "reviewer", task: "first", cwd: "project-a" },
{ agent: "reviewer", task: "second", cwd: "project-b" },
],
}),
ctx,
);
assert.equal(prepared.mode, "parallel");
assert.deepEqual(
prepared.tasks.map((task) => task.task),
["first", "second"],
);
assert.deepEqual(
prepared.tasks.map((task) => task.cwd),
[path.resolve(root, "project-a"), path.resolve(root, "project-b")],
);
assert.deepEqual(
prepared.tasks.map((task) => task.agent.description),
["Reviewer A", "Reviewer B"],
);
assert.equal(prepared.tasks[0].agent.filePath, path.join(projectAgentsDir(projectA), "reviewer.md"));
assert.equal(prepared.tasks[1].agent.filePath, path.join(projectAgentsDir(projectB), "reviewer.md"));
assert.notEqual(prepared.tasks[0].agent.filePath, prepared.tasks[1].agent.filePath);
assert.deepEqual(
prepared.tasks.map((task) => task.step),
[undefined, undefined],
);
assert.deepEqual(prepared.projectAgentsDirs, [projectAgentsDir(projectA), projectAgentsDir(projectB)]);
assert.equal(prepared.projectAgentsDir, projectAgentsDir(projectA));
assert.equal(ctx.confirmations.length, 0);
});
test("parallel accepts exactly eight tasks", async () => {
const root = makeTempRoot();
makeProject(root, "project-a");
const tasks = Array.from({ length: 8 }, (_, index) => ({
agent: "reviewer",
task: `task ${index + 1}`,
cwd: "project-a",
}));
const prepared = await prepareInvocation(projectParams({ tasks }), makeContext({ cwd: root }));
assert.equal(prepared.mode, "parallel");
assert.equal(prepared.tasks.length, 8);
assert.deepEqual(
prepared.tasks.map((task) => task.task),
tasks.map((task) => task.task),
);
});
test("chain numbers steps from 1 and preserves {previous} for the manager", async () => {
const root = makeTempRoot();
const project = makeProject(root, "project-a");
const nested = path.join(project, "work");
fs.mkdirSync(nested);
const ctx = makeContext({ cwd: root });
const prepared = await prepareInvocation(
projectParams({
chain: [
{ agent: "reviewer", task: "draft", cwd: "project-a" },
{ agent: "reviewer", task: "revise {previous}", cwd: "project-a/work" },
],
}),
ctx,
);
assert.equal(prepared.mode, "chain");
assert.deepEqual(
prepared.tasks.map((task) => task.step),
[1, 2],
);
assert.deepEqual(
prepared.tasks.map((task) => task.task),
["draft", "revise {previous}"],
);
assert.deepEqual(
prepared.tasks.map((task) => task.cwd),
[project, nested],
);
assert.deepEqual(prepared.projectAgentsDirs, [projectAgentsDir(project)]);
assert.equal(ctx.confirmations.length, 0);
});
test("rejects missing, partial, and ambiguous modes", async () => {
const root = makeTempRoot();
const ctx = makeContext({ cwd: root });
await assert.rejects(prepareInvocation({}, ctx), (error: unknown) => {
assert.ok(error instanceof InvalidInvocationError);
assert.match(error.message, /exactly one mode/);
return true;
});
await assert.rejects(
prepareInvocation({ agent: "reviewer" }, ctx),
(error: unknown) => error instanceof InvalidInvocationError && /nonempty "agent" and "task"/.test(error.message),
);
await assert.rejects(
prepareInvocation({ agent: "", task: "work" }, ctx),
(error: unknown) => error instanceof InvalidInvocationError && /nonempty "agent" and "task"/.test(error.message),
);
await assert.rejects(
prepareInvocation({ agent: "reviewer", task: "work", tasks: [{ agent: "reviewer", task: "other" }] }, ctx),
(error: unknown) => error instanceof InvalidInvocationError && /exactly one mode/.test(error.message),
);
await assert.rejects(
prepareInvocation(
{ tasks: [{ agent: "reviewer", task: "one" }], chain: [{ agent: "reviewer", task: "two" }] },
ctx,
),
(error: unknown) => error instanceof InvalidInvocationError && /exactly one mode/.test(error.message),
);
await assert.rejects(
prepareInvocation({ agent: "reviewer", task: "work", chain: [{ agent: "reviewer", task: "two" }] }, ctx),
(error: unknown) => error instanceof InvalidInvocationError && /exactly one mode/.test(error.message),
);
assert.equal(ctx.confirmations.length, 0);
});
test("rejects empty task and chain arrays", async () => {
const ctx = makeContext({ cwd: makeTempRoot() });
await assert.rejects(
prepareInvocation({ tasks: [] }, ctx),
(error: unknown) => error instanceof InvalidInvocationError && /nonempty "tasks"/.test(error.message),
);
await assert.rejects(
prepareInvocation({ chain: [] }, ctx),
(error: unknown) => error instanceof InvalidInvocationError && /nonempty "chain"/.test(error.message),
);
assert.equal(ctx.confirmations.length, 0);
});
test("rejects more than eight parallel tasks before resolving agents", async () => {
const ctx = makeContext({ cwd: makeTempRoot() });
const tasks = Array.from({ length: 9 }, (_, index) => ({ agent: "missing", task: `task ${index + 1}` }));
await assert.rejects(
prepareInvocation({ tasks }, ctx),
(error: unknown) => error instanceof InvalidInvocationError && /Too many parallel tasks \(9\)\. Max is 8\./.test(error.message),
);
assert.equal(ctx.confirmations.length, 0);
});
test("rejects unknown agents and lists the agents available at that cwd", async () => {
const root = makeTempRoot();
makeProject(root, "project-a");
const ctx = makeContext({ cwd: root });
await assert.rejects(
prepareInvocation(
projectParams({ agent: "ghost", task: "work", cwd: "project-a", confirmProjectAgents: true }),
ctx,
),
(error: unknown) => {
assert.ok(error instanceof InvalidInvocationError);
assert.match(error.message, /Unknown agent: "ghost"/);
assert.match(error.message, /"reviewer"/);
return true;
},
);
assert.equal(ctx.confirmations.length, 0);
});
test("rejects missing and non-directory cwds", async () => {
const root = makeTempRoot();
const file = path.join(root, "not-a-directory.txt");
fs.writeFileSync(file, "file", "utf-8");
const ctx = makeContext({ cwd: root });
await assert.rejects(
prepareInvocation(projectParams({ agent: "reviewer", task: "work", cwd: "does-not-exist" }), ctx),
(error: unknown) => error instanceof InvalidInvocationError && /does not exist/.test(error.message),
);
await assert.rejects(
prepareInvocation(projectParams({ agent: "reviewer", task: "work", cwd: "not-a-directory.txt" }), ctx),
(error: unknown) => error instanceof InvalidInvocationError && /not a directory/.test(error.message),
);
assert.equal(ctx.confirmations.length, 0);
});
test("a later invalid task prevents every confirmation prompt", async () => {
const root = makeTempRoot();
makeProject(root, "project-a");
makeProject(root, "project-b");
const ctx = makeContext({ cwd: root, confirmResult: true });
await assert.rejects(
prepareInvocation(
projectParams({
confirmProjectAgents: true,
tasks: [
{ agent: "reviewer", task: "valid", cwd: "project-a" },
{ agent: "ghost", task: "invalid", cwd: "project-b" },
],
}),
ctx,
),
(error: unknown) => error instanceof InvalidInvocationError && /Unknown agent/.test(error.message),
);
assert.equal(ctx.confirmations.length, 0);
await assert.rejects(
prepareInvocation(
projectParams({
confirmProjectAgents: true,
tasks: [
{ agent: "reviewer", task: "valid", cwd: "project-a" },
{ agent: "reviewer", task: "invalid cwd", cwd: "missing" },
],
}),
ctx,
),
(error: unknown) => error instanceof InvalidInvocationError && /does not exist/.test(error.message),
);
assert.equal(ctx.confirmations.length, 0);
});
test("confirms every distinct project source once, naming the directory and agents", async () => {
const root = makeTempRoot();
const projectA = makeProject(root, "project-a", { reviewer: "Reviewer A", planner: "Planner A" });
const projectB = makeProject(root, "project-b", { reviewer: "Reviewer B" });
const ctx = makeContext({ cwd: root, confirmResult: true });
const prepared = await prepareInvocation(
projectParams({
confirmProjectAgents: true,
tasks: [
{ agent: "reviewer", task: "one", cwd: "project-a" },
{ agent: "planner", task: "two", cwd: "project-a" },
{ agent: "reviewer", task: "three", cwd: "project-b" },
{ agent: "reviewer", task: "four", cwd: "project-a" },
],
}),
ctx,
);
const dirA = projectAgentsDir(projectA);
const dirB = projectAgentsDir(projectB);
assert.equal(ctx.confirmations.length, 2);
assert.ok(ctx.confirmations[0].message.includes(dirA));
assert.ok(ctx.confirmations[0].message.includes("reviewer"));
assert.ok(ctx.confirmations[0].message.includes("planner"));
assert.match(ctx.confirmations[0].message, /repo-controlled/);
assert.ok(ctx.confirmations[1].message.includes(dirB));
assert.ok(ctx.confirmations[1].message.includes("reviewer"));
assert.ok(!ctx.confirmations[1].message.includes(dirA));
assert.match(ctx.confirmations[1].message, /repo-controlled/);
assert.deepEqual(prepared.projectAgentsDirs, [dirA, dirB]);
assert.equal(prepared.projectAgentsDir, dirA);
});
test("project confirmation defaults to enabled", async () => {
const root = makeTempRoot();
makeProject(root, "project-a");
const ctx = makeContext({ cwd: root, confirmResult: true });
const prepared = await prepareInvocation(
{ agentScope: "project", agent: "reviewer", task: "work", cwd: "project-a" },
ctx,
);
assert.equal(prepared.tasks.length, 1);
assert.equal(ctx.confirmations.length, 1);
assert.match(ctx.confirmations[0].message, /repo-controlled/);
});
test("refusal throws ProjectAgentDeclinedError naming the source and agents", async () => {
const root = makeTempRoot();
const project = makeProject(root, "project-a");
const ctx = makeContext({ cwd: root, confirmResult: false });
await assert.rejects(
prepareInvocation(
projectParams({ agent: "reviewer", task: "work", cwd: "project-a", confirmProjectAgents: true }),
ctx,
),
(error: unknown) => {
assert.ok(error instanceof ProjectAgentDeclinedError);
assert.equal(error.name, "ProjectAgentDeclinedError");
assert.equal(error.directory, projectAgentsDir(project));
assert.deepEqual(error.agents, ["reviewer"]);
return true;
},
);
assert.equal(ctx.confirmations.length, 1);
});
test("refusal on a later source aborts the whole invocation", async () => {
const root = makeTempRoot();
makeProject(root, "project-a");
const projectB = makeProject(root, "project-b");
const ctx = makeContext({ cwd: root, confirmResult: [true, false] });
await assert.rejects(
prepareInvocation(
projectParams({
confirmProjectAgents: true,
tasks: [
{ agent: "reviewer", task: "one", cwd: "project-a" },
{ agent: "reviewer", task: "two", cwd: "project-b" },
],
}),
ctx,
),
(error: unknown) => {
assert.ok(error instanceof ProjectAgentDeclinedError);
assert.equal(error.directory, projectAgentsDir(projectB));
return true;
},
);
assert.equal(ctx.confirmations.length, 2);
});
test("trusted projects, disabled confirmation, and missing UI bypass prompts", async () => {
const root = makeTempRoot();
const project = makeProject(root, "project-a");
const trustedCtx = makeContext({ cwd: project, trusted: true });
await prepareInvocation(
projectParams({ agent: "reviewer", task: "work", cwd: ".", confirmProjectAgents: true }),
trustedCtx,
);
assert.equal(trustedCtx.confirmations.length, 0);
const disabledCtx = makeContext({ cwd: root });
await prepareInvocation(projectParams({ agent: "reviewer", task: "work", cwd: "project-a" }), disabledCtx);
assert.equal(disabledCtx.confirmations.length, 0);
const noUiCtx = makeContext({ cwd: root, hasUI: false });
await prepareInvocation(
projectParams({ agent: "reviewer", task: "work", cwd: "project-a", confirmProjectAgents: true }),
noUiCtx,
);
assert.equal(noUiCtx.confirmations.length, 0);
});
test("trusted session confirms a different project selected through task cwd", async () => {
const root = makeTempRoot();
const local = makeProject(root, "local");
const foreign = makeProject(root, "foreign");
const ctx = makeContext({ cwd: local, trusted: true });
await prepareInvocation(projectParams({
confirmProjectAgents: true,
tasks: [
{ agent: "reviewer", task: "local", cwd: "." },
{ agent: "reviewer", task: "foreign", cwd: foreign },
],
}), ctx);
assert.equal(ctx.confirmations.length, 1);
assert.match(ctx.confirmations[0].message, new RegExp(projectAgentsDir(foreign)));
assert.equal(ctx.confirmations[0].message.includes(projectAgentsDir(local)), false);
});
test("dispatch defaults are undefined when the session has no model or thinking level", async () => {
const root = makeTempRoot();
makeProject(root, "project-a");
const ctx = { ...makeContext({ cwd: root }), model: undefined, thinkingLevel: undefined };
const prepared = await prepareInvocation(
projectParams({ agent: "reviewer", task: "work", cwd: "project-a" }),
ctx,
);
assert.deepEqual(prepared.dispatchDefaults, { model: undefined, thinkingLevel: undefined });
});
test("agent scope defaults to user", () => {
assert.equal(resolveAgentScope(undefined), "user");
assert.equal(resolveAgentScope("user"), "user");
assert.equal(resolveAgentScope("project"), "project");
assert.equal(resolveAgentScope("both"), "both");
assert.equal(resolveAgentScope("team"), "user");
});
test("request schemas accept each mode and reject malformed requests", () => {
assert.equal(Value.Check(SubagentParams, { agent: "scout", task: "work" }), true);
assert.equal(
Value.Check(SubagentParams, {
tasks: [
{ agent: "scout", task: "one" },
{ agent: "scout", task: "two", cwd: "/tmp" },
],
}),
true,
);
assert.equal(Value.Check(SubagentParams, { chain: [{ agent: "scout", task: "one {previous}" }] }), true);
for (const agentScope of ["user", "project", "both"] as const) {
assert.equal(
Value.Check(SubagentParams, { agent: "scout", task: "work", agentScope, confirmProjectAgents: false }),
true,
);
}
assert.equal(Value.Check(SubagentParams, { agent: "scout", task: "work", agentScope: "team" }), false);
assert.equal(Value.Check(SubagentParams, { tasks: [{ agent: "scout" }] }), false);
assert.equal(Value.Check(SubagentParams, { chain: [{ task: "no agent" }] }), false);
assert.equal(Value.Check(SubagentParams, { tasks: "not an array" }), false);
assert.equal(Value.Check(SubagentParams, { agent: "scout", task: "work", confirmProjectAgents: "yes" }), false);
assert.equal(Value.Check(TaskItem, { agent: "scout", task: "work" }), true);
assert.equal(Value.Check(TaskItem, { agent: "scout", task: "work", cwd: "/tmp" }), true);
assert.equal(Value.Check(TaskItem, { agent: "scout" }), false);
assert.equal(Value.Check(ChainItem, { agent: "scout", task: "work {previous}" }), true);
assert.equal(Value.Check(ChainItem, { task: "work" }), false);
});
test("agentScope keeps its literal union type and rejects non-scopes", () => {
const scope: AgentScopeValue = "project";
assert.equal(scope, "project");
const params: SubagentParamsType = { agentScope: "both" };
assert.equal(params.agentScope, "both");
// @ts-expect-error agentScope must be one of the literal scope values
const invalidScope: AgentScopeValue = "team";
assert.equal(invalidScope, "team");
// @ts-expect-error agentScope must be one of the literal scope values
const invalidParams: SubagentParamsType = { agentScope: "team" };
assert.equal(invalidParams.agentScope, "team");
});
test("management union accepts each valid action", () => {
const valid: SubagentJobsParamsType[] = [
{ action: "list" },
{ action: "list", activeOnly: true },
{ action: "list", activeOnly: false },
{ action: "get", jobId: "job_1" },
{ action: "wait", jobId: "job_1" },
{ action: "wait", jobId: "job_1", timeoutSeconds: 0.5 },
{ action: "wait", jobId: "job_1", timeoutSeconds: 1 },
{ action: "wait", jobId: "job_1", timeoutSeconds: 300 },
{ action: "cancel", jobId: "job_1" },
];
for (const params of valid) {
assert.equal(Value.Check(SubagentJobsParams, params), true, JSON.stringify(params));
}
});
test("management union rejects missing job ids, bad timeouts, and unknown actions", () => {
const invalid: unknown[] = [
{},
{ action: "get" },
{ action: "wait" },
{ action: "cancel" },
{ action: "get", jobId: 42 },
{ action: "wait", jobId: "job_1", timeoutSeconds: 0 },
{ action: "wait", jobId: "job_1", timeoutSeconds: -1 },
{ action: "wait", jobId: "job_1", timeoutSeconds: 301 },
{ action: "wait", jobId: "job_1", timeoutSeconds: "10" },
{ action: "explode", jobId: "job_1" },
{ action: "list", activeOnly: "yes" },
];
for (const params of invalid) {
assert.equal(Value.Check(SubagentJobsParams, params), false, JSON.stringify(params));
}
});
test("management union narrows on its action discriminant", () => {
function describe(params: SubagentJobsParamsType): string {
switch (params.action) {
case "list":
return params.activeOnly ? "active" : "all";
case "get":
return params.jobId;
case "wait":
return `${params.jobId}:${params.timeoutSeconds ?? "none"}`;
case "cancel":
return `cancel ${params.jobId}`;
}
}
assert.equal(describe({ action: "list", activeOnly: true }), "active");
assert.equal(describe({ action: "list" }), "all");
assert.equal(describe({ action: "get", jobId: "job_1" }), "job_1");
assert.equal(describe({ action: "wait", jobId: "job_1" }), "job_1:none");
assert.equal(describe({ action: "wait", jobId: "job_1", timeoutSeconds: 5 }), "job_1:5");
assert.equal(describe({ action: "cancel", jobId: "job_1" }), "cancel job_1");
});
+172
View File
@@ -0,0 +1,172 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { SubagentDetails, RunResult } from "../src/types.ts";
import {
PER_TASK_OUTPUT_CAP,
formatParallelSummary,
isFailedResult,
isRunningResult,
isSuccessfulResult,
renderSubagentCall,
renderSubagentResult,
truncateParallelOutput,
type SubagentRenderTheme,
} from "../src/render.ts";
const theme: SubagentRenderTheme = {
fg: (_color, text) => text,
bold: (text) => text,
};
function runResult(overrides: Partial<RunResult> = {}): RunResult {
return {
agent: "scout",
agentSource: "user",
task: "inspect the code",
cwd: "/tmp",
exitCode: 0,
messages: [],
output: "done",
stderr: "",
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
...overrides,
};
}
function details(results: RunResult[], overrides: Partial<SubagentDetails> = {}): SubagentDetails {
return {
mode: "parallel",
status: "running",
agentScope: "user",
projectAgentsDir: null,
projectAgentsDirs: [],
results,
...overrides,
};
}
function renderedText(component: { render(width: number): readonly string[] }, width = 200): string {
return component.render(width).join("\n");
}
test("queued and running tasks are neither failed nor successful", () => {
for (const status of ["queued", "running"] as const) {
const result = runResult({ status, exitCode: null, stopReason: "error", terminationSignal: "SIGTERM" });
assert.equal(isRunningResult(result), true, status);
assert.equal(isFailedResult(result), false, status);
assert.equal(isSuccessfulResult(result), false, status);
}
});
test("terminal failures come from status, exit code, stop reason, or a termination signal", () => {
for (const status of ["failed", "cancelled", "interrupted"] as const) {
const result = runResult({ status, exitCode: null });
assert.equal(isFailedResult(result), true, status);
assert.equal(isRunningResult(result), false, status);
assert.equal(isSuccessfulResult(result), false, status);
}
assert.equal(isFailedResult(runResult({ status: undefined, exitCode: 1 })), true);
assert.equal(isFailedResult(runResult({ status: undefined, exitCode: null })), true);
assert.equal(isFailedResult(runResult({ stopReason: "error" })), true);
assert.equal(isFailedResult(runResult({ stopReason: "aborted" })), true);
assert.equal(isFailedResult(runResult({ terminationSignal: "SIGTERM" })), true);
assert.equal(isFailedResult(runResult({ status: "succeeded" })), false);
assert.equal(isSuccessfulResult(runResult({ status: "succeeded" })), true);
});
test("parallel summary counts only settled successful tasks and labels running tasks", () => {
const summary = formatParallelSummary([
runResult({ agent: "one", status: "running", exitCode: null, output: "partial" }),
runResult({ agent: "two", status: "queued", exitCode: null, output: "" }),
runResult({ agent: "three", status: "succeeded", output: "finished" }),
runResult({ agent: "four", status: "failed", exitCode: 1, errorMessage: "boom" }),
]);
assert.match(summary, /^Parallel: 1\/4 succeeded/m);
assert.match(summary, /### \[one\] running\n\npartial/);
assert.match(summary, /### \[two\] running\n\n\(no output\)/);
assert.match(summary, /### \[three\] completed\n\nfinished/);
assert.match(summary, /### \[four\] failed\n\nboom/);
});
test("parallel summary truncates at the byte cap without splitting UTF-8", () => {
const original = "😀".repeat(PER_TASK_OUTPUT_CAP);
const truncated = truncateParallelOutput(original);
const [prefix, note] = truncated.split("\n\n[Output truncated: ");
assert.ok(Buffer.byteLength(prefix, "utf8") <= PER_TASK_OUTPUT_CAP);
assert.equal(prefix.includes("\uFFFD"), false);
assert.equal(original.startsWith(prefix), true);
const omitted = Buffer.byteLength(original, "utf8") - Buffer.byteLength(prefix, "utf8");
assert.equal(note, `${omitted} bytes omitted. Full output preserved in tool details.]`);
const small = "short output";
assert.equal(truncateParallelOutput(small), small);
});
test("parallel rendering shows running tasks without counting them as failures", () => {
const result = {
content: [{ type: "text" as const, text: "Parallel: 1/2 succeeded" }],
details: details(
[
runResult({ agent: "running-agent", status: "running", exitCode: null, output: "working" }),
runResult({ agent: "finished-agent", status: "succeeded", output: "finished" }),
],
{ status: "running" },
),
};
const text = renderedText(renderSubagentResult(result, { expanded: false }, theme));
assert.match(text, /1\/2 done, 1 running/);
assert.match(text, /running-agent/);
assert.match(text, /working/);
assert.match(text, /finished-agent/);
assert.doesNotMatch(text, /failed/);
assert.doesNotMatch(text, /✗/);
});
test("expanded parallel rendering uses RunResult.output for final text", () => {
const result = {
content: [{ type: "text" as const, text: "ignored" }],
details: details(
[
runResult({
status: "succeeded",
task: "write the answer",
output: "final assistant output",
}),
],
{ status: "succeeded" },
),
};
const text = renderedText(renderSubagentResult(result, { expanded: true }, theme), 120);
assert.match(text, /write the answer/);
assert.match(text, /final assistant output/);
});
test("call previews preserve mode, scope, and task summaries", () => {
const chain = renderedText(
renderSubagentCall(
{
agentScope: "project",
chain: [
{ agent: "one", task: "first task" },
{ agent: "two", task: "second {previous} task" },
],
},
theme,
),
);
assert.match(chain, /chain \(2 steps\)/);
assert.match(chain, /\[project\]/);
assert.match(chain, /one/);
assert.match(chain, /second\s+task/);
const single = renderedText(renderSubagentCall({ agent: "scout", task: "inspect this" }, theme));
assert.match(single, /subagent/);
assert.match(single, /scout/);
assert.match(single, /inspect this/);
});
+375
View File
@@ -0,0 +1,375 @@
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import type { AgentConfig } from "../src/agents.ts";
import { ProcessRunner, type ProcessRunnerOptions } from "../src/runner.ts";
import type { DispatchDefaults, PreparedTask, RunOptions, RunResult } from "../src/types.ts";
const fixturePath = fileURLToPath(new URL("./fixtures/fake-pi.mjs", import.meta.url));
const stderrLimit = 64 * 1024;
const baseAgent: AgentConfig = {
name: "scout",
description: "Test agent",
systemPrompt: "Test prompt",
source: "user",
filePath: "/tmp/scout.md",
};
function makeAgent(overrides: Partial<AgentConfig> = {}): AgentConfig {
return { ...baseAgent, ...overrides };
}
function makeTask(overrides: Partial<PreparedTask> = {}): PreparedTask {
return {
agent: makeAgent(),
task: "do the thing",
cwd: process.cwd(),
...overrides,
};
}
function makeRunner(env: NodeJS.ProcessEnv = {}, options: ProcessRunnerOptions = {}): ProcessRunner {
return new ProcessRunner({
invocation: (args) => ({ command: process.execPath, args: [fixturePath, ...args] }),
killGraceMs: 150,
env: { ...process.env, ...env },
...options,
});
}
function runOptions(overrides: Partial<RunOptions> = {}): RunOptions {
return { signal: new AbortController().signal, ...overrides };
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function waitFor<T>(condition: () => T | null | undefined | false, timeoutMs = 5000): Promise<T> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const value = condition();
if (value) return value;
await delay(10);
}
throw new Error("Timed out waiting for condition");
}
function processIsAlive(pid: number): boolean {
try {
process.kill(pid, 0);
} catch {
return false;
}
if (process.platform === "linux") {
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
const closeParen = stat.lastIndexOf(")");
if (stat.slice(closeParen + 2, closeParen + 3) === "Z") return false;
} catch {
// Fall through to the kill(0) result.
}
}
return true;
}
test("collects message_end JSONL, ignores tool_result_end, aggregates usage and returns final output", async (t) => {
const runner = makeRunner({ FAKE_PI_MODE: "success" });
const updates: RunResult[] = [];
const result = await runner.run(makeTask(), {}, runOptions({ onUpdate: (partial) => updates.push(partial) }));
assert.equal(result.exitCode, 0);
assert.equal(result.terminationSignal, undefined);
assert.equal(result.output, "final answer");
assert.equal(result.model, "fake-model");
assert.equal(result.stopReason, "stop");
assert.equal(result.stderr, "");
assert.equal(result.stderrTruncated, false);
assert.deepEqual(
result.messages.map((message) => message.role),
["assistant", "toolResult", "assistant"],
);
const toolResult = result.messages[1];
assert.equal(toolResult.role, "toolResult");
if (toolResult.role === "toolResult") {
assert.deepEqual(toolResult.content, [{ type: "text", text: "tool output" }]);
}
assert.equal(JSON.stringify(result.messages).includes("STALE"), false);
assert.deepEqual(result.usage, {
input: 30,
output: 12,
cacheRead: 5,
cacheWrite: 3,
cost: 1,
contextTokens: 30,
turns: 2,
});
assert.ok(updates.length > 0);
assert.equal(
updates.some((partial) => partial.messages.some((message) => message.role === "toolResult")),
true,
);
t.diagnostic(`onUpdate calls: ${updates.length}`);
});
test("preserves a nonzero exit and assistant error diagnostics", async () => {
const runner = makeRunner({ FAKE_PI_MODE: "failure" });
const result = await runner.run(makeTask(), {}, runOptions());
assert.equal(result.exitCode, 7);
assert.equal(result.output, "");
assert.equal(result.stderr, "diagnostic\n");
assert.equal(result.stopReason, "error");
assert.equal(result.errorMessage, "model exploded");
assert.equal(result.terminationSignal, undefined);
});
test("reports spawn failures instead of throwing or synthesising success", async () => {
let promptPath: string | undefined;
const missing = path.join(os.tmpdir(), `pi-subagent-missing-${process.pid}-${Date.now()}`);
const runner = new ProcessRunner({
invocation: (args) => {
const promptIndex = args.indexOf("--append-system-prompt");
if (promptIndex >= 0) promptPath = args[promptIndex + 1];
return { command: missing, args };
},
killGraceMs: 100,
env: process.env,
});
const result = await runner.run(makeTask(), {}, runOptions());
assert.notEqual(result.exitCode, 0);
assert.match(result.errorMessage ?? "", /ENOENT|not found|not recognized/i);
assert.equal(result.output, "");
assert.equal(result.stderr, "");
assert.equal(result.terminationSignal, undefined);
assert.ok(promptPath);
assert.equal(fs.existsSync(promptPath), false);
assert.equal(fs.existsSync(path.dirname(promptPath)), false);
});
test("bounds stderr to a valid UTF-8 64 KiB tail", async () => {
const runner = makeRunner({ FAKE_PI_MODE: "stderr" });
const result = await runner.run(makeTask(), {}, runOptions());
assert.equal(result.exitCode, 0);
assert.equal(result.stderrTruncated, true);
assert.ok(Buffer.byteLength(result.stderr, "utf8") <= stderrLimit);
assert.equal(result.stderr.endsWith("STDERR-END"), true);
assert.equal(result.stderr.includes("STDERR-START"), false);
assert.equal(result.stderr.includes("\uFFFD"), false);
assert.equal(Buffer.from(result.stderr, "utf8").toString("utf8"), result.stderr);
});
test("child arguments exclude subagent tools and do not inherit thinking with an explicit model", async () => {
let captured: string[] = [];
let promptPath: string | undefined;
let promptContent: string | undefined;
const runner = makeRunner(
{ FAKE_PI_MODE: "success" },
{
invocation: (args) => {
captured = args;
const promptIndex = args.indexOf("--append-system-prompt");
if (promptIndex >= 0) {
promptPath = args[promptIndex + 1];
promptContent = fs.readFileSync(promptPath, "utf8");
}
return { command: process.execPath, args: [fixturePath, ...args] };
},
},
);
const agent = makeAgent({
model: "agent-model",
tools: ["read", "bash"],
systemPrompt: "Prompt body",
});
const defaults: DispatchDefaults = { model: "dispatch-model", thinkingLevel: "high" };
const result = await runner.run(makeTask({ agent, task: "do the thing" }), defaults, runOptions());
assert.equal(result.exitCode, 0);
assert.deepEqual(captured.slice(0, 6), [
"--mode",
"json",
"-p",
"--no-session",
"--exclude-tools",
"subagent*",
]);
assert.equal(captured[captured.indexOf("--model") + 1], "agent-model");
assert.equal(captured.includes("--thinking"), false);
assert.equal(captured[captured.indexOf("--tools") + 1], "read,bash");
const promptFile = promptPath;
assert.ok(promptFile);
assert.equal(promptContent, "Prompt body");
assert.equal(captured[captured.indexOf("--append-system-prompt") + 1], promptFile);
assert.equal(captured.at(-1), "Task: do the thing");
assert.equal(fs.existsSync(promptFile), false);
assert.equal(fs.existsSync(path.dirname(promptFile)), false);
});
test("child arguments inherit the dispatch model and thinking only without an explicit model", async () => {
let captured: string[] = [];
const runner = makeRunner(
{ FAKE_PI_MODE: "success" },
{
invocation: (args) => {
captured = args;
return { command: process.execPath, args: [fixturePath, ...args] };
},
},
);
const agent = makeAgent({ model: undefined, tools: undefined, systemPrompt: " " });
const defaults: DispatchDefaults = { model: "dispatch-model", thinkingLevel: "high" };
const result = await runner.run(makeTask({ agent }), defaults, runOptions());
assert.equal(result.exitCode, 0);
assert.deepEqual(captured.slice(0, 6), [
"--mode",
"json",
"-p",
"--no-session",
"--exclude-tools",
"subagent*",
]);
assert.equal(captured[captured.indexOf("--model") + 1], "dispatch-model");
assert.equal(captured[captured.indexOf("--thinking") + 1], "high");
assert.equal(captured.includes("--tools"), false);
assert.equal(captured.includes("--append-system-prompt"), false);
assert.equal(captured.at(-1), "Task: do the thing");
});
test("child arguments omit optional model and thinking flags when nothing is configured", async () => {
let captured: string[] = [];
const runner = makeRunner(
{ FAKE_PI_MODE: "success" },
{
invocation: (args) => {
captured = args;
return { command: process.execPath, args: [fixturePath, ...args] };
},
},
);
const result = await runner.run(makeTask({ agent: makeAgent({ model: undefined }) }), {}, runOptions());
assert.equal(result.exitCode, 0);
assert.equal(captured.includes("--model"), false);
assert.equal(captured.includes("--thinking"), false);
assert.equal(captured.includes("--exclude-tools"), true);
assert.equal(captured[captured.indexOf("--exclude-tools") + 1], "subagent*");
assert.equal(captured.at(-1), "Task: do the thing");
});
test(
"abort reports the terminating signal instead of turning it into exit code 0",
{ skip: process.platform === "win32", timeout: 15000 },
async () => {
const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-runner-term-"));
const readyFile = path.join(dir, "ready");
try {
const controller = new AbortController();
const runner = makeRunner(
{ FAKE_PI_MODE: "wait", FAKE_PI_READY_FILE: readyFile },
{ killGraceMs: 500 },
);
const pending = runner.run(makeTask(), {}, { signal: controller.signal });
await waitFor(() => fs.existsSync(readyFile));
controller.abort();
const result = await pending;
assert.equal(result.exitCode, null);
assert.equal(result.terminationSignal, "SIGTERM");
assert.equal(result.stopReason, "aborted");
assert.match(result.errorMessage ?? "", /aborted/i);
assert.equal(result.output, "");
} finally {
await fs.promises.rm(dir, { recursive: true, force: true });
}
},
);
test(
"abort escalates SIGTERM to SIGKILL after the grace period and kills the process tree",
{ skip: process.platform === "win32", timeout: 15000 },
async () => {
const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-runner-tree-"));
const readyFile = path.join(dir, "ready");
const parentSignalFile = path.join(dir, "parent-signals");
const childReadyFile = path.join(dir, "child-ready");
const childSignalFile = path.join(dir, "child-signals");
const childPidFile = path.join(dir, "child-pid");
const pids: number[] = [];
try {
const controller = new AbortController();
const killGraceMs = 250;
const runner = makeRunner(
{
FAKE_PI_MODE: "tree-term",
FAKE_PI_READY_FILE: readyFile,
FAKE_PI_PARENT_SIGNAL_FILE: parentSignalFile,
FAKE_PI_CHILD_READY_FILE: childReadyFile,
FAKE_PI_CHILD_SIGNAL_FILE: childSignalFile,
FAKE_PI_CHILD_PID_FILE: childPidFile,
},
{ killGraceMs },
);
const pending = runner.run(makeTask(), {}, { signal: controller.signal });
const ready = await waitFor(() => {
try {
const parsed = JSON.parse(fs.readFileSync(readyFile, "utf8")) as {
parentPid: number;
childPid: number;
};
return parsed.parentPid && parsed.childPid ? parsed : null;
} catch {
return null;
}
});
pids.push(ready.parentPid, ready.childPid);
const abortedAt = Date.now();
controller.abort();
const result = await pending;
const elapsed = Date.now() - abortedAt;
assert.equal(result.exitCode, null);
assert.equal(result.terminationSignal, "SIGKILL");
assert.equal(result.stopReason, "aborted");
assert.ok(
elapsed >= killGraceMs * 0.7,
`expected SIGKILL after the grace period, got completion after ${elapsed}ms`,
);
assert.match(fs.readFileSync(parentSignalFile, "utf8"), /SIGTERM/);
assert.match(fs.readFileSync(childSignalFile, "utf8"), /SIGTERM/);
assert.equal(fs.readFileSync(childPidFile, "utf8"), String(ready.childPid));
await waitFor(() => pids.every((pid) => !processIsAlive(pid)));
} finally {
for (const pid of pids) {
try {
process.kill(pid, "SIGKILL");
} catch {
// Already gone.
}
}
await fs.promises.rm(dir, { recursive: true, force: true });
}
},
);
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"types": ["node"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"allowImportingTsExtensions": true
},
"include": ["src/*.ts", "test/**/*.ts"]
}