Launch parallel research subagents to build a grounded answer to the current question or decision.
Use fresh context, not forked context, unless I explicitly ask for forked context. Researchers and scouts should inspect sources directly instead of relying on the main conversation history.
Use a combination of researcher and scout subagents:
Use researcher for web, docs, standards, ecosystem, recent changes, benchmarks, and primary-source evidence.
Use scout for local codebase context, existing implementation patterns, repo constraints, and files that would be affected.
Give each subagent a distinct angle. Unless I specify angles, use these three:
External evidence
Use researcher to find current, authoritative sources: official docs, specs, release notes, benchmarks, issue threads, or primary explanations.
Local code context
Use scout to inspect the repository for relevant files, existing patterns, constraints, tests, and likely integration points.
Practical tradeoffs
Use researcher or scout, whichever fits the question, to compare options, risks, edge cases, maintenance cost, and what would be easiest to validate.
Adapt the angles when the question calls for it:
Library/API questions: include official docs and recent examples.
Architecture decisions: include local module boundaries, dependency direction, and migration cost.
Debugging questions: include likely failure modes, local call paths, and exact error evidence.
UI/product questions: include user flow, accessibility, design precedent, and implementation constraints.
Time-sensitive topics: include a recent-developments angle and prefer 2026/2025 sources.
Prefer two or three strong subagents over many vague ones. The parent agent should frame the question and assign angles; the child agents should research or scout, not invent broad plans.
Ask each subagent to return concise findings with evidence:
file paths and line ranges for local findings
source links for external findings
confidence level and gaps
recommended next step or decision implication
Do not ask subagents to edit files. This is a research pass only unless I explicitly ask for implementation.
After the subagents return, synthesize the answer into:
what we know
what the local codebase implies
tradeoffs and risks
gaps or assumptions
the recommended next move
If findings disagree, call out the disagreement instead of smoothing it over.
I'll start by understanding the local setup and the target repo, then launch parallel research subagents with distinct angles.
Assistant
Let me examine the existing extension pattern and pi docs briefly before launching subagents.
Assistant
Now I'll launch parallel research subagents with three distinct angles.
Assistant
The workflow timed out after 30 min — only the TUI research completed. Let me check status of the other two and re-run the missing ones.
Assistant
The workflow timed out with 2 of 3 runs incomplete. Let me check status and gather what completed.
Assistant
The foreground workflow timed out and discarded the child outputs. Let me relaunch the subagents as async background runs so they don't block, and gather the rest directly. First, let me launch the external-source researcher in the background while I scout locally and check pi TUI capabilities myself.
Assistant
The async launch needs workflowScript. Let me launch the external-source researcher as an async workflow, then continue gathering local + TUI context directly.
Assistant
Excellent — the local research-panel.ts is a perfect template (a full ctx.ui.custom component with keyboard input). Let me read the ctx.ui.custom invocation and pi TUI docs while the external researcher runs.
Assistant
There are interactive-shell.ts and bash-spawn-hook.ts examples — directly relevant. Let me read both plus the TUI docs.
Assistant
The interactive-shell.ts uses tui.stop()/tui.start() with spawnSync(stdio: "inherit") — but that's a foreground blocking pattern. Background terminals need streaming. Let me check the ssh.ts example (spawns a real shell in a custom component) and the TUI custom-component docs.
Assistant
I have strong local + TUI context now. The reference repo behavior is the missing piece — let me check the async external-source researcher.
Assistant
The researcher is struggling with the GitHub listing. Let me fetch the repo directly myself to accelerate this critical piece.
Assistant
I have the full file tree. Let me fetch the key source files directly.
Assistant
The implementation guide is the complete design. Let me fetch the actual implemented index.ts and package.json to see what shipped.
Assistant
I have the complete picture from the reference repo. Let me cancel the now-redundant async researcher and check the local README Extensions section to complete the local-context angle.
Assistant
I have all three angles. Here is the synthesized answer.
Synthesis: Adding background-terminals to sof-pi
What we know (external evidence — the reference repo)
The reference extension at davis7dotsh/my-pi-setup/extensions/background-terminals is fully specced in its own docs/implementation-guide.md (I read it end-to-end) and implemented across index.ts + src/. The design is not an interactive PTY terminal you type into — it's a fire-and-forget long-running process manager whose output you inspect. Key facts:
Backend: plain node:child_processspawn, not node-pty. stdio: ["ignore", "pipe", "pipe"] — stdin is ignored at the OS level (no input surface, ever). Shell executed via sh -c (POSIX) / cmd.exe (Windows). detached: true on POSIX so the whole process group can be killed (kill -pid → SIGTERM, escalate to SIGKILL after 2s).
bg_list{} → all tracked terminals (running + settled).
bg_kill{ids: string[]} → SIGTERM→SIGKILL whole tree, resolves after settle.
No bg_wait, no bg_send — completion is push-based, stdin is dead.
State model:Map<string, Entry> with statuses running|done|failed|killed, ids bt-1..bt-N, concurrency cap 8 running, retain 32 settled (prune oldest-settled). Output captured separately per stdout/stderr into a bounded OutputBuffer (2 MiB in-memory tail per stream) plus spill-to-disk full capture under os.tmpdir()/pi-background-terminals/<session>/.
Completion = exactly-once push: on settle, defers a copy of the snapshot, then pi.sendMessage({customType, content, display:true}, {deliverAs:"followUp", triggerTurn:true}). Flushed on and via an fast-path, guarded by a Map-keyed (drain clears) + a flag for in-flight kills. guard prevents queuing into a dying session.
Assistant
The background researcher returned with an important correction that disagrees with what I found by reading the repo directly. Let me resolve this disagreement before you act on anything.
Assistant
The disagreement is resolved — decisively in favor of my direct reading.
Correction: the background researcher was wrong
The researcher's claim that "extensions/background-terminals/ does not exist... the repo's extensions/ folder contains only 12 flat .ts files" is factually incorrect. Direct evidence from the GitHub Contents API and a raw file fetch:
https://api.github.com/repos/davis7dotsh/my-pi-setup/contents/extensions returns 12 subdirectories, including background-terminals/ as a dir.
https://api.github.com/repos/davis7dotsh/my-pi-setup/contents/extensions/background-terminals returns the full file tree I already inventoried: index.ts (15,192 bytes, HTTP 200 confirmed via HEAD), package.json, manager.test.ts, src/domain.ts, src/manager.ts, src/output.ts, src/ui/ps.ts, etc.
The index.ts I quoted earlier (factory, pi.registerTool for bg_start, the setWidget "■ N background terminal(s) running", session_shutdown disposal) is real and fetchable.
The researcher hit a tooling limit (its own note says "Tool limitation: the available fetch_content/web_search tools are Perplexity-backed..."), could not list the GitHub directory, and confabulated a different package (pi-tian-background-terminals / "overrides the built-in bash tool"). I can find no evidence for that package in this repo, and its described "override bash" mechanism contradicts the actual index.ts, which registers new tools named bg_* and never touches the built-in bash. The researcher's output was truncated mid-sentence and should be discarded.
Why I'm confident in the direct reading
I fetched the files myself with curl against the GitHub Contents API and raw.githubusercontent.com, verified HTTP 200 + byte counts, and read the actual code of index.ts, package.json, and the docs/implementation-guide.md (1,451 lines). The guide is an internal design doc for exactly this extension — it repeatedly references sibling files (extensions/subagents/..., effect-v4-extension-guide.md) that match the repo's real structure. The code and doc are mutually consistent.
I am not smoothing this over: the researcher's finding is wrong, mine is correct, and I verified mine against the primary source rather than relying on a synthesis tool that couldn't reach the source.
User
What are the trade-offs of switching to effect v4?
Assistant
I'll research Effect v4 specifically (it's a beta) and what adopting it would mean for this repo, with two fresh-context subagents in parallel.
Assistant
The workflow wrapper failed to await. Let me check the children that did complete — they may have been retained.
Assistant
Not retained. The workflow harness dropped them on failure. I already have deep local knowledge from the previous turn, so let me run the Effect v4 external research as a detached async workflow and gather the local adoption-cost facts myself in parallel (quick, deterministic).
Assistant
The Effect researcher timed out (30 min) — likely struggling with the same Perplexity-backed fetch tools that failed the previous researcher. Let me read whatever partial artifact it produced, then finish the external Effect research myself directly.
Assistant
No partial output. I'll do the Effect v4 research directly with web tools. The local adoption-cost facts I already gathered are complete (no root tsconfig, no TS in package.json, no Effect anywhere, perplexity has no per-extension package.json, tests are a shell script). Let me get the Effect v4 external facts.
Assistant
Now the TypeScript@^7 coupling question and bundle size, plus confirm the v4 docs on the v3 renames.
Assistant
I have everything needed. The key local facts: no TypeScript installed anywhere (not in node_modules, not in package.json, not in pnpm-lock.yaml), pi loads extensions via jiti (transpiles TS on the fly, no build step), the existing perplexity extension has no per-extension package.json and runs fine, and there's no tsc/check script. Now I can give grounded trade-offs.
Trade-offs of switching to Effect v4
What Effect v4 actually is (grounded)
Effect v4 is a beta rewrite of the Effect TypeScript effect system: a ground-up rewritten fiber runtime, a unified package/version model, and new APIs surfaced under effect/unstable/*. The maintainers explicitly say beta releases may still introduce breaking changes between betas and recommend v3 for production until v4 stabilizes. [Effect v4 Beta announcement; Effect blog; Office Hours Q&A]
It is coupled to a preview toolchain:
@effect/tsgo is a drop-in replacement for Microsoft's native-preview TypeScript-Go binary (tsgo) that layers the Effect Language Service on top — Effect-specific diagnostics, refactors, completions. @effect/tsgo patch replaces the stock tsgo binary with effect-tsgo. [Effect-TS/tsgo GitHub; tsgo docs]
@effect/language-service is the plugin that powers those editor features and can flag outdated v3 APIs during migration. [tsgo docs]
typescript@^7 in the reference means @typescript/native-preview (the Go-port beta, itself a preview). Effect v4's LSP support expects that native toolchain. [TS Native Preview announcement; tsgo editor setup]
The breaking-change surface (v3 → v4)
The reference guide's warnings are mostly accurate: Context.Tag → Context.Service / ServiceMap.Service; Effect.fork → Effect.forkChild, Effect.forkDaemon → Effect.forkDetach; Layer.scoped still exists; Either is not removed (the guide's warning there is overstated). [v4 Layer docs; migration docs]
Trade-offs, concretely for this repo
Dimension
Adopt Effect v4
User
Ok use subagents to implement the changes
Assistant
I'll implement this with subagents. First let me ground the work by fetching the reference source files locally (so the writer has accurate grounding, avoiding the Perplexity fetch failures the researchers hit), then launch a single writer (one writer per worktree per the orchestration guidance), followed by a fresh-context review.
Assistant
All reference files fetched. Let me read the key coordination files to craft an accurate port spec for the writer.
Assistant
Now the heavy files: the Effect-based manager (which I must port to plain TS) and the UI.
Assistant
Now the Effect-based manager — the core I need to port to plain TS — and the UI picker.
Assistant
Now the UI picker to confirm it's Effect-free (uses only the read model).
Assistant
The UI (ps.ts) is fully Effect-free — it depends only on the TerminalReadModel interface and pi-tui. So the port is concentrated in domain.ts (drop Data.TaggedError), manager.ts (the big Effect→plain-TS port), runtime.ts (delete — only bridges Effect), and index.ts (factory). The rest (output.ts, result-delivery.ts, output-view.ts, ui/ps.ts, prompt.ts) are verbatim or near-verbatim.
Let me verify the pi APIs the reference relies on are actually exported in your pinned 0.84.1, so the writer doesn't get stuck.
Assistant
Most exports confirmed. Let me verify the two critical messaging APIs (pi.sendMessage, pi.registerMessageRenderer) since the exactly-once completion depends on them.
Assistant
All APIs confirmed present in 0.84.1 (sendMessage with options at types.d.ts:867, registerMessageRenderer at :865, setWidget factory form at :97). Let me verify the sendMessage options shape (deliverAs/triggerTurn) matches the reference usage.
Assistant
sendMessage({deliverAs:"followUp", triggerTurn:true}) matches exactly. I have full API confidence. Let me check the README's skills table structure (AGENTS.md mentions keeping a skills table in sync) before launching the writer.
Assistant
README has a Skills table (lines 16-31) and Extensions section (33-58) to update. I now have complete API confidence. Launching the implementation with a single writer (fresh context, self-contained spec — avoids dragging the voluminous research cache and the earlier wrong-researcher tangent), then a fresh review.
Assistant
The implementation worker is running detached in the background. I'll arm a wake subscription so Pi notifies me when it completes, then return control to you.
Assistant
I've launched the implementation as a detached worker subagent (implement-bgterm) with a self-contained spec. Here's the plan it's executing:
What it's building — a plain-TS port of the reference background-terminals extension (zero new deps, no Effect, no node-pty), matching your perplexity/ extension's style:
Wiring + docs (same changeset, per AGENTS.md): add ./extensions/background-terminals/index.ts to package.jsonpi.extensions (the *.ts glob won't descend into subdirs), add skills/background-terminals/SKILL.md, update README skills table + Extensions section
It's also verifying each imported symbol exists against the installed 0.84.1 type defs (I pre-confirmed sendMessage/registerMessageRenderer/setWidget/formatSize/truncateTail/etc. are all present).
I'll report back when it finishes — then I'll run a fresh-context review pass and synthesize/apply any fixes. You can keep working in the meantime; Pi will wake me on completion.
Assistant
The worker reported completion but flagged one notable deviation: it changed agent_settled to agent_end. That's a real concern — agent_end fires per low-level run (and pi may auto-retry/compact/continue), while agent_settled is specifically "pi will not continue automatically." Let me read its full output and verify the deviation, then inspect the files.
Assistant
The worker completed and all files are present (8 TS files + SKILL.md, zero Effect/node-pty/as any). Now I need to verify the agent_settled → agent_end deviation the worker flagged — that's the one real correctness concern. Let me check what the installed pi version actually supports and what the worker did.
Assistant
The worker's deviation is correct and justified. The installed pi 0.84.1 type defs only expose agent_start and agent_end — there is no agent_settled event in this version (it was added in a later pi release; the docs I read earlier described it, but the actual installed API doesn't have it). agent_end is the best available hook here.
However, agent_end has a semantic gap vs agent_settled: it fires per low-level agent run, and pi may auto-retry, auto-compact-retry, or continue with queued follow-ups after it. The flushResults design is still safe because:
It's idempotent (resultDelivery.drain() clears the map), so firing extra times is harmless.
The isIdle() fast-path in onSettled is the primary delivery trigger; agent_end is the fallback for the case where the model is mid-turn when a process settles.
The consumed flag + disposed guard handle the race cases.
So the only real risk is a result delivered slightly earlier than ideal (during a retry window) — but it's still exactly-once. This is acceptable. Let me now run a fresh-context review to catch anything the worker missed, then I'll verify and fix.
Assistant
The fresh-context review passed with no blocking issues — all 12 race-safety invariants confirmed correctly ported. It found 6 non-blocking items; only N1–N3 are worth fixing (minor timer leaks: setTimeout returns in waitForClose/flushSpillStreams/sleep aren't unref'd, so they can keep the Node event loop alive briefly after pi should exit). N4–N6 are acceptable defense-in-depth. Let me apply the N1–N3 .unref() fix myself since it's small and surgical.
Assistant
Now I'll apply the .unref() fixes to the three timer sites. Each timer should be captured and .unref()'d, and cleared when the winner fires.
Assistant
Let me verify the edits landed cleanly and re-run the worker's syntax check.
Assistant
The --check output shows no errors for any file (errors would print above the arrows). Let me confirm --check actually reports failures by testing it against a deliberately broken snippet, then do a final diff summary.
Assistant
I spotted one indentation glitch from my edit (the flushSpillStreams Promise is now slightly misaligned — the inner Promise block is one tab too deep). Let me fix that for cleanliness.
Assistant
Now let me verify the README/package.json/SKILL.md changes look right and do a final full diff summary.
Assistant
All changes are in place and verified. Let me show you the final README extension subsection to confirm it reads well.
Assistant
Everything is complete and verified. Here's the final summary.
Implementation complete ✅
A plain-TypeScript background-terminals extension is implemented and wired into your pi package, with zero new dependencies.
What was built
8 new files (extensions/background-terminals/):
index.ts — factory: 4 LLM tools (bg_start/bg_status/bg_list/bg_kill), /ps command, collapsed message renderer, above-editor widget, lifecycle (manager built in session_start, disposed in session_shutdown), exactly-once completion via sendMessage({deliverAs:"followUp", triggerTurn:true})
src/manager.ts (871 lines) — the core Effect→plain-TS port: TerminalManager class with all race-safety invariants
Fresh-context reviewer (run 393292a9):No blocking issues. All 12 race-safety invariants confirmed faithfully ported — synchronous concurrency reservation, idempotent settle, consumed computed before promise resolution, killSignaled set only for live processes, closeEntryScope idempotent teardown path, spill-flush-before-settle, disposeAll safety net, etc. No leftover Effect API. All imports verified against installed pi 0.84.1 type defs.
One justified deviation: pi 0.84.1 has no agent_settled event (only agent_start/agent_end — I confirmed this in types.d.ts). The worker correctly used agent_end instead. This is safe because flushResults is idempotent ( clears the map) and the fast-path handles between-turn settles.
User
let's run a smoke test
Assistant
I'll smoke-test in layers: first verify the extension loads without import errors, then functionally exercise the TerminalManager core (spawn/kill/settle/completion) directly — that's where bugs would hide and it needs no API key. Then attempt a pi startup check.
Assistant
manager.ts only imports node builtins + local files — fully testable in isolation. Let me write a functional smoke test that exercises start/status/kill/settle, the concurrency cap, completion notification, disposeAll, and the process-tree kill.
Assistant
Found a real issue. The worker's domain.ts uses TypeScript parameter properties (constructor(readonly message: string)), which node's --experimental-strip-types can't transform (it only strips, doesn't transpile). The worker's --check validation gave a false pass. Let me check whether this would break under pi's jiti loader, and whether --check actually catches it.
Assistant
Two findings: (1) --checkdoes catch parameter properties — so the worker's "all files pass syntax validation" was inaccurate; I need to re-check all files myself. (2) pi uses jiti 2.7.0 (esbuild-based), which likely does transpile parameter properties, so it may work under pi — but I'll fix it anyway for portability and so the smoke test runs. Let me re-check all files and fix domain.ts.
Assistant
--check passes in isolation but the strip transform fails at import time — so --check is insufficient; only actual execution catches this. pi's jiti (esbuild) would transpile it fine, but I'll fix it for portability and so the smoke test can run. Let me rewrite the error classes without parameter properties.
Assistant
Actually super(message) already sets this.message, so I can simplify — no need to redeclare the field or reassign. Let me clean that up.
Assistant
Now let me check whether there are any other TS-only syntax features (beyond type stripping) elsewhere that strip-types can't handle — the only reliable way is to actually import each module. Let me run the smoke test, which transitively imports everything.
Assistant
Tests 1–5 all pass — the core semantics (spawn, capture stdout/stderr separately, settle, exit codes, the consumed flag, concurrency cap, error types) work correctly. Test 6 failed on a test bug (nested node -e quoting — the grandchild never started, so no sentinel file), not an extension bug. Let me fix test 6 using helper script files to avoid quoting hell, and also harden it.
Assistant
Tests 1–6 pass, but test 7 hangs at disposeAll() — a real bug. disposeAll is supposed to be bounded by 5s timeouts but isn't resolving. Let me investigate the implementation.
Assistant
Tests 1–6 pass. Test 7's disposeAll hangs — but the warning is "unsettled top-level await" (the event loop emptied while the await was unresolved). This points at my N1–N3 .unref() fix being too aggressive on withTimeoutVoid: the timeout is a guarantee that the promise resolves within N ms, but .unref() lets the event loop empty before the timer fires, breaking the guarantee. Let me reproduce minimally to confirm before fixing.
Assistant
Confirmed: disposeAll hangs. The cause is my .unref() fix on the timeout-race helpers — those timers ARE the resolution guarantee for bounded waits; .unref() lets the event loop empty before they fire, so Promise.race never settles. The reviewer's N1–N3 advice was theoretically tidy but practically wrong here — these aren't leaks, they're short bounded timers (0.5–5s) that fire and clean up. Reverting the .unref() calls (keeping the clearTimeout in waitForClose, which is a genuine happy-path improvement).
Assistant
I also need to remove the .unref() from waitForClose (keep the clearTimeout which is a genuine improvement).
Assistant
Now re-run the repro then the full smoke test.
Assistant
37/38 pass — the disposeAll hang is fixed. The one failure is a test bug: the flood (~575 KiB) is smaller than the 2 MiB retention cap, so truncatedBytes=0 is correct behavior (nothing evicted). I need a bigger flood to exercise the eviction path. Let me fix the test and re-run test 8.
Assistant
The nested-quoting in the flood command broke again. Let me use a helper script file like I did for test 6.
Assistant
38/38 pass. Now let me also verify the extension loads in the actual pi runtime (the real integration test — does pi discover and start it without errors?).
Assistant
No --list-tools. Let me verify the extension loads in the real pi runtime. The smoke test exercised manager.ts (no pi deps) but index.ts imports pi modules — I need pi to actually load it. Let me check what's configured and do a minimal print-mode run that loads extensions.
Assistant
OpenRouter is authed (the subagents used it). Let me do a minimal print-mode run with --no-tools (so no tool calls happen, near-zero cost) — the extension factory still loads at startup, so any import/factory error surfaces. I'll use a cheap model and capture the output.
Assistant
Pi loaded all extensions cleanly (exit 0, no load errors) — the factory ran. But --no-tools disables tools; let me verify the bg_* tools are actually registered and executable end-to-end by asking the model to call them. I'll scope to just the bg tools and use a cheap model.
Assistant
End-to-end smoke test passed. The model called bg_start (command echo hello-world, title smoke), the process spawned, captured hello-world\n (stdout 12B), exited 0, settled to done, and bg_list returned the correct snapshot line — all in the real pi runtime. This verifies extension loading, tool registration, parameter schemas, spawning, output capture, and settlement end-to-end.
Let me confirm no orphaned processes leaked from the earlier functional tests, then clean up temp files.
Assistant
Smoke test complete. Here's the final summary.
Smoke test results ✅
Layer 1 — Functional core (TerminalManager direct, 38/38 pass): A custom test script exercised every race-safety invariant by importing manager.ts directly (no pi, no API key):
Layer 2 — Real pi runtime (end-to-end):pi -p with --no-tools started cleanly (exit 0 — extension factory loaded with no import errors). Then with the bg tools enabled, the model called bg_start → bg_list and got back bt-1 [done] "smoke" (pid 40581, 0s, exit 0, ..., stdout 12B, stderr 0B) — verifying tool registration, parameter schemas, spawning, capture, and settlement in the actual pi runtime.
Two real bugs found and fixed during the test
domain.ts parameter properties (constructor(readonly message: string)) — node's strip-types can't transform them; jiti (pi's loader) can, but I fixed them to plain constructors for portability. This also exposed that the worker's --check syntax validation gave a false pass (it only parses, doesn't run the strip transform — only actual import execution catches it).
disposeAll hang — caused by my own over-aggressive .unref() fix (from the reviewer's N1–N3 advice) on the timeout-race helpers. Those timers are the bound guarantee that bounded waits resolve; .unref() let the event loop empty before they fired, so Promise.race never settled. Reverted the calls; kept the on 's happy path (a genuine improvement). This is a good lesson: the reviewer's "leak" concern was theoretically tidy but these are short bounded timers (0.5–5s) that fire and clean up — not leaks.
User
Launch parallel reviewers for an adversarial review of the current work.
Use fresh context, not forked context, unless I explicitly ask for forked context. Reviewers should inspect the repository, relevant instructions, and current diff directly from files and commands. Do not rely on the main conversation history.
Give each reviewer a distinct angle. Generate the angles dynamically from the user's intent, the plan, the implemented code, and the current diff. If I specify angles, use mine. Otherwise, choose the highest-value review angles for this specific work.
These are examples, not fixed defaults:
Correctness and regressions
Check whether the change satisfies the request, preserves existing behavior, handles edge cases, and avoids hidden runtime failures.
Tests and validation
Check whether tests or validation were added at the right layer, whether assertions are meaningful, and whether the chosen verification commands are enough.
Simplicity and maintainability
Check for unnecessary complexity, duplicate structure, single-use wrappers, brittle abstractions, confusing names, verbosity, and cleanup that is clearly worth doing.
Choose or adapt angles when the work calls for it:
TypeScript-heavy changes: include type safety, source-of-truth types, casts, and error-boundary discipline.
UI-heavy changes: include UX, accessibility, copy, and visual quality.
Security-sensitive changes: include unsafe input/output handling, auth boundaries, privacy, and data exposure.
Docs-heavy changes: include clarity, accuracy, completeness, reader flow, and non-robotic prose.
Large multi-file changes: consider a fourth reviewer for structural friction, module boundaries, and testability.
Prefer three strong reviewers over many vague reviewers.
Give every reviewer a specific task prompt naming its angle. Ask reviewers to return concise, evidence-backed findings with file/line references and suggested fixes. The response should be review feedback, not a context summary. Reviewers must not edit files unless I explicitly ask for a writer pass.
While reviewers run, do your own narrow inspection if useful. After they return, synthesize the feedback into:
fixes worth doing now
optional improvements
feedback to ignore or defer, with a short reason
Do not blindly apply every reviewer suggestion.
Autofix mode: if the invocation contains the exact word autofix, treat it as workflow control, not review scope. Remove it before deciding the review target. After synthesis, apply only fixes worth doing now, validate, and summarize. Do not apply optional improvements unless explicitly requested. If there are no fixes worth doing now, do not edit.
Assistant
I'll generate angles dynamically from the implemented work: a plain-TS port of an Effect-based process-spawning extension with a TUI overlay. The highest-value adversarial angles are race-safety correctness, process security, TS/strip-types runtime robustness (the bug class that already bit us), and maintainability/docs. Launching four fresh-context reviewers in parallel.
Assistant
The wrapper failed but all four children completed. Let me retrieve their outputs from the artifact directories.
Assistant
All four reviewer outputs are on disk. Let me read them.
Assistant
All four adversarial reviewers completed (retrieved from artifacts since the workflow wrapper failed to await, as before). Here's the synthesis.
Adversarial review synthesis
The race-safety reviewer confirmed all 12 invariants correct (again, adversarially) — but found 3 real bugs the first reviewer missed, all in resource/timer paths. The security reviewer found one real secret-persistence risk. The types reviewer found the code clean (no surviving strip-unsafe constructs) and gave a better validation command. The maintainability reviewer found only cosmetic debt.
Fixes worth doing now
R1 — Uncleared timers in withTimeoutVoid/sleep/flushSpillStreams delay shutdown (race reviewer #1, manager.ts:253-258 + :260 + :498). When the racing promise resolves first (the common case), the setTimeout still fires as a no-op later, keeping the event loop alive — concretely, disposeAll's await withTimeoutVoid(awaitCleanup, 5s) delays session shutdown by up to 5s. Fix: capture the timer and clearTimeout it on the happy path (NOT .unref() — that broke disposeAll last time; clearTimeout preserves the bound because the racing promise already resolved). I already did this for waitForClose; extend to the other three.
R2 — flushSpillStreams leaks file descriptors on timeout (race reviewer #2, manager.ts:486-507). On a hung-FS timeout, the WriteStreams are never destroy()'d and the flush promises never settle → FD leak that persists past disposeAll. Fix: on timedOut, call stream.destroy() on each.
R3 — Spill write() can throw uncaught and crash the agent (race reviewer #3, manager.ts:470). A WriteStream that hit a write error (disk-full EIO/ENOSPC) transitions to destroyed and throws on the next file.write(); there's a window before the 'error' listener sets broken=true. Since this runs inside the child's stdout/stderr'data' handler, the throw is uncaught → crashes pi. Fix: wrap file.write(chunk) in try/catch, treat throw as "broken." Crash-class on a flaky disk.
S1 — Stale spill dirs persist secrets after a hard crash (security reviewer B1, ). If pi is SIGKILLed, never fires, and dirs full of process output (build logs, env dumps, tokens) stay in forever. (The 0o600 perms mean only the user can read them, but persistence is still a real risk.)
User
Go for 1
Assistant
Applying R1–R3 and S1. Let me read the exact current code at each site first.
Assistant
Now I have exact context. Applying all four fixes in one edit call.
Assistant
My withTimeoutVoid replacement had buggy logic (two timers). Let me redo both helpers as one merged, correct edit.
Assistant
Now R3 (spill write try/catch) and R2 (destroy streams on timeout), plus S1 (stale spill dir cleanup).
Assistant
Let me re-read exact whitespace for both sites.
Assistant
Now I have exact text. Applying R3 and R2 with correct tab indentation.
Assistant
Now S1 — stale spill dir cleanup in resolveSpillDir.
Assistant
All four fixes applied. Now let me validate: the types reviewer's stricter command (actually import the module) plus re-run the functional smoke test to confirm no regressions.
Assistant
index.ts needs pi's jiti alias for typebox — can't import bare. But all four fixes are in manager.ts, which only imports node builtins + local files, so I can validate it directly via import (exercises the strip transform on my edits).
Assistant
Manager imports cleanly with all edits. Now re-run the full functional smoke test to confirm R1/R2/R3/S1 didn't regress the race semantics.
Assistant
Tests 1–8 all pass (34 checks, including the new R1 "disposeAll fast" assertion). Test 9 has a test-only bug (require in ESM). Let me fix and re-run.
Assistant
All 34 checks pass, including the two new ones validating the fixes. Let me run the end-to-end pi runtime test once more to confirm no regression in the real loader, then clean up.
Assistant
All four fixes applied and validated.
Summary
Applied the four "fix now" items from the adversarial review, all in extensions/background-terminals/src/manager.ts:
Fix
What
Validation
R1
withTimeoutVoid now clears its timer on the happy path (not .unref(), which broke disposeAll last time); sleep is .unref()'d (it's a fire-and-forget grace check, not an awaited bound).
New test 7 asserts disposeAll < 1500ms (was stalling up to 5s) ✓
R2
flushSpillStreams now stream.destroy()s each WriteStream on timeout — no FD leak on hung FS.
Manual code review + import check ✓
R3
Spill file.write(chunk) wrapped in try/catch — a destroyed WriteStream (disk-full EIO/ENOSPC) can no longer throw uncaught inside the child's 'data' handler and crash pi.
Import + smoke run ✓
S1
resolveSpillDir reaps stale session-* dirs from prior crashed sessions before creating the new one — secret-bearing spill logs no longer persist in /tmp indefinitely.
New test 9 asserts stale dir removed on startup ✓
Validation results
Functional smoke test: 34/34 pass — all original race-safety tests still green, plus two new ones (disposeAll speed, stale-dir cleanup).
End-to-end pi runtime: model called bg_start → bg_list, got bt-1 [done] "verify" (pid 46876, 0s, exit 0, ..., stdout 9B, stderr 0B) — exit 0, no loader errors.
Stricter import validation (types reviewer's recommendation): manager.ts imports cleanly via node --experimental-strip-types (exercises the strip transform, not just parse).
No orphaned processes after tests.
Not applied (per your choice [1])
Optional improvements T1/M1/M2/S2/S3 deferred. The defense-in-depth patterns (dead disposed check, unreachable settledHistory fallback) kept as-is per the maintainability reviewer's "keep" verdict.
Changes remain unstaged: modified package.json/README.md, new extensions/background-terminals/ (8 files) and skills/background-terminals/. Want me to commit now?
User
Launch parallel reviewers for an adversarial review of the current work.
Use fresh context, not forked context, unless I explicitly ask for forked context. Reviewers should inspect the repository, relevant instructions, and current diff directly from files and commands. Do not rely on the main conversation history.
Give each reviewer a distinct angle. Generate the angles dynamically from the user's intent, the plan, the implemented code, and the current diff. If I specify angles, use mine. Otherwise, choose the highest-value review angles for this specific work.
These are examples, not fixed defaults:
Correctness and regressions
Check whether the change satisfies the request, preserves existing behavior, handles edge cases, and avoids hidden runtime failures.
Tests and validation
Check whether tests or validation were added at the right layer, whether assertions are meaningful, and whether the chosen verification commands are enough.
Simplicity and maintainability
Check for unnecessary complexity, duplicate structure, single-use wrappers, brittle abstractions, confusing names, verbosity, and cleanup that is clearly worth doing.
Choose or adapt angles when the work calls for it:
TypeScript-heavy changes: include type safety, source-of-truth types, casts, and error-boundary discipline.
UI-heavy changes: include UX, accessibility, copy, and visual quality.
Security-sensitive changes: include unsafe input/output handling, auth boundaries, privacy, and data exposure.
Docs-heavy changes: include clarity, accuracy, completeness, reader flow, and non-robotic prose.
Large multi-file changes: consider a fourth reviewer for structural friction, module boundaries, and testability.
Prefer three strong reviewers over many vague reviewers.
Give every reviewer a specific task prompt naming its angle. Ask reviewers to return concise, evidence-backed findings with file/line references and suggested fixes. The response should be review feedback, not a context summary. Reviewers must not edit files unless I explicitly ask for a writer pass.
While reviewers run, do your own narrow inspection if useful. After they return, synthesize the feedback into:
fixes worth doing now
optional improvements
feedback to ignore or defer, with a short reason
Do not blindly apply every reviewer suggestion.
Autofix mode: if the invocation contains the exact word autofix, treat it as workflow control, not review scope. Remove it before deciding the review target. After synthesis, apply only fixes worth doing now, validate, and summarize. Do not apply optional improvements unless explicitly requested. If there are no fixes worth doing now, do not edit.
Assistant
The previous round already covered correctness/types/security/maintainability comprehensively (all invariants confirmed twice, 4 fixes applied). The highest-value new angles for this post-fix state are: (1) did my R1–R3/S1 fixes introduce regressions or miss edge cases, (2) is the TUI overlay (/ps + widget) actually correct against the live pi API (it's the one part never exercised by the smoke test), and (3) end-to-end behavior / docs accuracy. Launching three fresh-context reviewers.
Assistant
Same wrapper issue — children completed. Retrieving outputs from artifacts.
Assistant
All three reviewers completed. Synthesis:
Adversarial review synthesis (round 2)
Fix-regression reviewer: R1, R2, R3 all CORRECT with no regressions (re-derived from first principles). S1 flagged INCOMPLETE — the stale-dir reaping can delete a live concurrent pi session's spill dir (TOCTOU), because the comment's "any session-* dir is unambiguously stale" assumption is wrong when two pi processes run concurrently as the same user sharing os.tmpdir()/pi-background-terminals/. Impact is bounded (silent spill loss, no crash — open FDs keep writing to unlinked inodes), but it's a real correctness gap.
TUI-overlay reviewer:Sound. Every TUI API verified against installed 0.80.2 type defs — OverlayOptions, Component conformance, all 9 keybinding IDs exist, tui.terminal.rows/requestRender, widget factory arity, message renderer signature, timer cleanup idempotent, output cache invalidation correct, scroll math handles all edge cases. Two cosmetic nits (rare ESC sequences, side-effect-in-render) — non-blocking.
E2E-docs reviewer:Ship. All 10 checks pass — tool semantics, exactly-once completion (no double-delivery, no drop path), lifecycle (no /reload double-manager race), widget visibility, /ps fallback, prompt strings accuracy, SKILL.md accuracy, README character-accurate, wiring, model-visible output limits all correct.
Fixes worth doing now
S1-fix — concurrent-session TOCTOU in resolveSpillDir (fix-regression reviewer). The reaper deletes allsession-* dirs, including one a concurrent live pi session is actively writing to. Cheap, correct fix: encode the PID in the session dir name (session-<pid>-<random>) and skip dirs whose PID is still alive (process.kill(pid, 0) probe). Live sessions' dirs survive reaping; truly stale (dead-PID) dirs get cleaned.
Optional improvements (non-blocking, would accept)
R4 — flushSpillStreams happy-path timer leak (fix-regression reviewer's pre-existing note, manager.ts:521): the Promise.race timeout timer isn't cleared when flushes complete first, pinning the loop up to 1.5s per settling entry. Same class as R1. Cheap to apply the same clear-on-happy-path pattern.
E2E-docs Note 1 (re-defer loop on sendMessage failure) — bounded by session_shutdown.clear(); correct by design.
User
Go for 2 using subagents
Assistant
Applying S1 (concurrent-session fix) + R4 (flushSpillStreams timer clear) via a subagent writer, then a fresh review.
Assistant
The acceptance arg doesn't accept object form here. Let me drop acceptance (worker is a writer, not a reviewer) and launch via workflowScript.
Assistant
Arming a wake subscription so I'm notified on completion, then returning control.
Assistant
Launched the worker (apply-s1-r4) detached to apply the two fixes (S1 concurrent-session TOCTOU + R4 flushSpillStreams timer clear). It will:
Encode the PID in the session dir name (session-<pid>-<random>) and probe liveness before reaping, so live concurrent sessions aren't deleted
Clear the flushSpillStreams timeout timer on the happy path (same pattern as the R1 fix)
Run both --check and the stricter import-execute validation
I'll be woken when it completes, then I'll run a fresh review + the functional smoke test to confirm no regressions. You can keep working in the meantime.
Assistant
Worker completed, both fixes applied, verification passed. Let me verify the edits directly and run the smoke test + fresh review.
Assistant
Both fixes look correct. The S1 logic is sound: parse PID, probe process.kill(pid, 0), skip if alive (or EPERM = not ours but alive), reap only on ESRCH (dead) or unparseable/old-format. R4 wraps in try/finally with clearTimeout. Let me run validation + the smoke test (with a new concurrent-session test), then a fresh review.
Assistant
Now the functional smoke test, including a new test verifying S1 skips a live session's dir. Let me regenerate the helper + smoke files (cleaned earlier) and run.
Assistant
All 29 checks pass, including the two new S1 verification tests (dead-PID dir reaped, live-PID dir preserved). Now a fresh-context review to confirm the fixes are sound, then end-to-end pi runtime check.
Assistant
Fresh-context review verdict: SHIP — both fixes correct, complete, no regressions. Let me run the end-to-end pi runtime check once more and clean up.
Assistant
Everything is complete and verified. Here's the final summary.
S1 + R4 applied, reviewed, and validated ✅
What was applied (both in extensions/background-terminals/src/manager.ts)
S1 — concurrent-session TOCTOU fix (resolveSpillDir): Session dirs now named session-<pid>-<suffix>; the reaping loop parses the PID from each dir name and probes liveness with process.kill(pid, 0) — skips live sessions (no-throw or EPERM), reaps only dead-PID (ESRCH) or unparseable/old-format dirs. Each rmSync isolated in try/catch. This prevents deleting a live concurrent pi session's spill dir.
R4 — flushSpillStreams timer clear: Wrapped the Promise.race in try/finally, capturing the timeout timer and clearing it on the happy path (same pattern as the R1 fix). Timer stays ref'd (it's the bound guarantee). No more 1.5s event-loop pin per settling entry.
Verification
Fresh-context adversarial review: SHIP. Both fixes CORRECT, COMPLETE, no regressions. PID parsing handles all edge cases (empty, NaN, negative, old-format). Liveness probe semantics correct. R4 try/finally transparent to R2's stream.destroy(). No other code depends on the session-dir name format.
Functional smoke test: 29/29 pass, including two new S1 tests:
Test 9: stale dead-PID session dir (pid 99999999) is reaped ✓
Test 10: live concurrent session's dir (real live child PID) is NOT reaped ✓
End-to-end pi runtime: model called bg_start → bg_list, exit 0, no loader errors.
The extension is a plain-TS port (zero new deps, no Effect/node-pty) of the reference Effect-based extension, with all race-safety invariants intact, security hardening (secret spill cleanup, FD leak fixes, crash-class throw guards), and accurate docs (README + SKILL.md, AGENTS.md house rule satisfied).
Pre-existing untracked mise.toml/scripts//tests/ and modified .gitignore are not mine.
Want me to commit now?
User
Launch parallel reviewers for an adversarial review of the current work.
Use fresh context, not forked context, unless I explicitly ask for forked context. Reviewers should inspect the repository, relevant instructions, and current diff directly from files and commands. Do not rely on the main conversation history.
Give each reviewer a distinct angle. Generate the angles dynamically from the user's intent, the plan, the implemented code, and the current diff. If I specify angles, use mine. Otherwise, choose the highest-value review angles for this specific work.
These are examples, not fixed defaults:
Correctness and regressions
Check whether the change satisfies the request, preserves existing behavior, handles edge cases, and avoids hidden runtime failures.
Tests and validation
Check whether tests or validation were added at the right layer, whether assertions are meaningful, and whether the chosen verification commands are enough.
Simplicity and maintainability
Check for unnecessary complexity, duplicate structure, single-use wrappers, brittle abstractions, confusing names, verbosity, and cleanup that is clearly worth doing.
Choose or adapt angles when the work calls for it:
TypeScript-heavy changes: include type safety, source-of-truth types, casts, and error-boundary discipline.
UI-heavy changes: include UX, accessibility, copy, and visual quality.
Security-sensitive changes: include unsafe input/output handling, auth boundaries, privacy, and data exposure.
Docs-heavy changes: include clarity, accuracy, completeness, reader flow, and non-robotic prose.
Large multi-file changes: consider a fourth reviewer for structural friction, module boundaries, and testability.
Prefer three strong reviewers over many vague reviewers.
Give every reviewer a specific task prompt naming its angle. Ask reviewers to return concise, evidence-backed findings with file/line references and suggested fixes. The response should be review feedback, not a context summary. Reviewers must not edit files unless I explicitly ask for a writer pass.
While reviewers run, do your own narrow inspection if useful. After they return, synthesize the feedback into:
fixes worth doing now
optional improvements
feedback to ignore or defer, with a short reason
Do not blindly apply every reviewer suggestion.
Autofix mode: if the invocation contains the exact word autofix, treat it as workflow control, not review scope. Remove it before deciding the review target. After synthesis, apply only fixes worth doing now, validate, and summarize. Do not apply optional improvements unless explicitly requested. If there are no fixes worth doing now, do not edit.
Assistant
We've now done 3 review rounds (~8 reviewer passes) all confirming ship. A 4th round has diminishing returns, but I'll run it with angles targeting the least-exercised code: cross-file type contracts, the smaller files (prompt/output/result-delivery) that got less scrutiny, and pi integration edge cases (reload/fork/concurrent tool calls) that were never runtime-tested.
Assistant
Same wrapper issue — children completed. Retrieving outputs.
Assistant
The integration reviewer found one potential blocker: it claims agent_settledis available in pi 0.84.1 (citing CHANGELOG + docs), contradicting the worker's comment that it doesn't exist. This contradicts my earlier grep of types.d.ts (which showed only agent_start/agent_end). I must verify this carefully before applying — there's a version skew (pi CLI reports 0.84.1, installed npm package is 0.80.2).
Assistant
Critical version skew confirmed: the installed npm package is 0.80.2 (no agent_settled in its type defs or runtime JS), but the pi CLI binary is 0.84.1 (which documents agent_settled in its CHANGELOG/docs). The question is: does the 0.84.1 binary actually emit agent_settled at runtime? Let me verify the runtime code, not just docs.
Assistant
Version skew is clear: installed npm package is 0.80.2 (type defs lack agent_settled), but the pi CLI binary is 0.84.1 which documents agent_settled as added (CHANGELOG #6363). Since pi loads extensions via jiti (no type-check, so the missing type overload doesn't block), the question is purely runtime: does the 0.84.1 binary actually emit agent_settled? Let me probe it directly.
Assistant
Confirmed at runtime: pi.on("agent_settled", ...) is accepted by the 0.84.1 binary. The integration reviewer was right — agent_settled IS available (the worker's comment was based on my earlier grep of the 0.80.2 type defs, which was the wrong source). Now let me verify it actually fires on settle (not just registers) — the key question for correctness.
Assistant
Definitive confirmation: agent_settled fires exactly once at settle (same as agent_end for a single-turn print-mode run). This is the better event — it fires after auto-retries/compaction, not before. The integration reviewer's finding is valid. Let me synthesize all three reviewers.
Adversarial review synthesis (round 4)
Cross-file-contract reviewer: All contracts sound — no shape mismatches, no wrong arities, no field drift across the 8 files. TerminalReadModel has zero dead methods. All KillResult/StartOptions fields align. Type-only vs value imports all correct. Minor: manager.status()/manager.list() are dead code (tools use the read model); a few symbols are exported but never imported externally (harmless, likely for test access).
Small-files reviewer:No bugs found across output.ts, result-delivery.ts, prompt.ts, output-view.ts. The OutputBuffer byte arithmetic is sound (retainedBytes can never exceed the cap after any push path). Cache invalidation, kill-report branches, \r handling, and output-line caching all correct. Three low-severity notes (all non-issues in practice): cachedText initialized to "" not undefined, spill callback not wrapped (but the actual callback catches internally), CSI split across \n (malformed input only).
Pi-integration reviewer: One valid blocker — the extension uses agent_end but agent_settled IS available in the pi 0.84.1 runtime (I confirmed via runtime probe: it registers AND fires). agent_settled is semantically correct (fires after auto-retries/compaction, not before). The worker's comment claiming it doesn't exist was based on my earlier grep of the 0.80.2 type defs (the installed npm package), but the 0.84.1 binary (which actually runs the extension) has it. All other integration surfaces (reload, fork, concurrent tool calls, abort signal, message renderer, non-TUI modes, shutdown, factory) confirmed correct.
Fixes worth doing now
I1 — Switch agent_end → agent_settled (index.ts). I runtime-verified: pi.on("agent_settled", ...) registers and fires in 0.84.1. This is the semantically correct event (fires after retries/compaction settle, not between runs). Keep agent_end as a fallback too — flushResults is idempotent ( clears), so registering both is safe and provides a safety net if a future pi version changes behavior. Update the now-incorrect comment.
User
1
Assistant
Applying I1 — switch to agent_settled, keep agent_end as a fallback (both safe since flushResults is idempotent), and fix the now-incorrect comment.
Assistant
Now validate: syntax check, import-execute, and an end-to-end pi run that exercises agent_settled firing with a bg terminal completing during a turn.
Assistant
Now the end-to-end pi test — verify agent_settled fires and a bg terminal completion is delivered. I'll start a process that completes during the turn and check the completion message arrives via the settled hook.
Assistant
Both end-to-end tests pass perfectly:
Immediate completion:bg_start + bg_list — process settled done (exit 0, stdout "completion-delivered" 21B). The model even reported the completion, confirming delivery works.
Delayed completion (the key agent_settled test): Started sleep 1; echo settled-after-turn, model finished its turn, then the process settled ~1s later. The completion message ("The background task bt-1 ('delayed') completed successfully with output: settled-after-turn") was delivered — this is exactly the agent_settled → flushResults → sendMessage(followUp, triggerTurn) path working end-to-end. The follow-up woke the model and the completion was reported.
This is the scenario that would have been at risk with only agent_end (delivered between turns/retries). With agent_settled, it fires cleanly after settle.
Assistant
I1 applied and validated ✅
What changed
In extensions/background-terminals/index.ts (one edit):
Switched the primary flush hook from agent_end → agent_settled (the semantically correct event — fires once after auto-retries/compaction fully settle).
Kept agent_end as a belt-and-suspenders fallback (safe because flushResults is idempotent — drain() clears the map, so a double-fire is a harmless no-op).
Fixed the now-incorrect comment (the worker's claim that agent_settled doesn't exist was based on the 0.80.2 npm type defs, but the 0.84.1 binary — which actually runs extensions — has it; I runtime-verified both registration and firing).
Validation
Syntax + import-execute: both pass.
End-to-end pi runtime, immediate completion:bg_start + bg_list → process settled done, exit 0, stdout "completion-delivered" (21B). ✓
End-to-end pi runtime, delayed completion (the key agent_settled test): Started sleep 1; echo settled-after-turn, model finished its turn, process settled ~1s later, and the completion message was delivered via the agent_settled → flushResults → sendMessage(followUp, triggerTurn) path — the model was woken and reported "The background task bt-1 ('delayed') completed successfully with output: settled-after-turn." This is exactly the scenario that would have been at risk with only agent_end. ✓
No orphaned processes.
Cumulative review state (4 rounds, ~9 reviewer passes)
Round 4 (3 reviewers): cross-file contracts sound; small files clean; pi-integration found I1 → now fixed and verified end-to-end.
The extension is a plain-TS port (zero new deps) of the reference Effect-based extension, with all race-safety invariants intact across 4 adversarial review rounds, security hardening, and now the semantically-correct completion delivery hook validated end-to-end in the real pi runtime.
Pre-existing untracked mise.toml/scripts//tests/ and modified .gitignore are not mine.
Want me to commit now?
User
Yes, commit and push
Assistant
I'll commit only my work — staging the specific files (extension dir, skill, package.json, README) and leaving the pre-existing .gitignore, mise.toml, scripts/, tests/ alone.
Assistant
Clean — .gitignore remains unstaged (still shows M in working tree but not staged). Committing now.
Assistant
The heredoc got mangled by shell quoting. Let me write the message to a file and commit with -F.
Assistant
Committed cleanly (11 files, 2530 insertions, 1 deletion — the package.json change). Pre-existing .gitignore/mise.toml/scripts//tests/ left untouched. Now pushing.
The pre-existing .gitignore modification, mise.toml, scripts/, and tests/ were left unstaged and unpushed (not part of this work).
Final state
The background-terminals extension is live in your pi package — a plain-TypeScript port (zero new deps) of the reference Effect-based extension, validated across 4 adversarial review rounds and end-to-end smoke tests. After your next pi reload, the bg_start/bg_status/bg_list/bg_kill tools and /ps overlay will be available, with the above-editor widget appearing while terminals run and exactly-once completion delivery via agent_settled.
Working tree is clean except for the pre-existing changes that were there before this session.
User
Actually, how does this background terminal compare to the "!" way to run terminal commands in Pi
Assistant
Good question — they look similar but serve very different needs. Quick factual comparison:
! (and !!) user bash
bg_start / background terminals
Who runs it
The user (you type !npm test)
The agent/model (via a tool call)
Blocking
Blocks the TUI until the command finishes (or, for !i, suspends the TUI to hand the terminal to an interactive command like vim/htop)
Fire-and-forget — returns immediately, you keep working
Stdin
Full stdin (interactive — vim, htop, git rebase -i work)
No stdin (immediate EOF; interactive commands die/hang)
Output
Streamed live to your terminal as it runs
Captured to bounded buffers + on-disk spill; you peek via bg_status, /ps, or a one-shot completion message when it exits
Lifetime
Tied to that one command invocation
Session-scoped — runs across turns; killed on /reload, /new, /resume, /fork, quit
Inspection
What scrolled by is gone (or in your scrollback)
/ps overlay: dashboard → read-only detail with stdout/stderr toggle, scroll, live tail; widget above editor while ≥1 runs
Killing
Ctrl+C in the TUI
bg_kill (whole process tree, SIGTERM→SIGKILL) or x in /ps
Use case
You, the human, want to run something now and see it
The agent needs a long-running process (dev server, watcher, build) running in the background while it keeps doing other work for you
When to use which
! is for you — run a quick command, or an interactive one (!i vim file.txt, !htop), watch it live, then it's done. The agent isn't involved.
is for the — it needs a dev server up while it edits code, a watcher running while it iterates, or a build churning in the background. The agent gets notified when it exits and can peek at output, all without blocking its turn.
Commit:6fecdc6 on main, pushed to origin (github.com:BbrSofiane/sof-pi.git)
What shipped: A plain-TypeScript background-terminals pi extension (zero new deps — no Effect, no node-pty), ported from the reference Effect-based extension.
Session-scoped: killed on shutdown/reload via bounded disposeAll; stale crash-session spill dirs reaped on startup (PID-liveness probe protects live concurrent sessions)
Not included (pre-existing, left alone):.gitignore modification, mise.toml, scripts/, tests/ — these were in the working tree before this session and remain unstaged.
To activate
Reload pi (/reload) — the extension is auto-discovered via the package.jsonpi.extensions entry. Then the bg_* tools and /ps command are available.
Open (none blocking)
The TUI overlay and widget haven't been driven interactively (only verified via static review + API conformance). A quick manual /ps run with a live terminal would be the final confirmation.
Widget above the editor (default ctx.ui.setWidget placement) shown only while ≥1 running: ■ N background terminal(s) running • /ps to view. Cleared on last settle and on session_shutdown.
/ps command → full-screen overlay ({overlay:true}) two-stage: list (select/x kill/enter open) → read-only detail (metadata header, t toggles stdout/stderr, scroll keys, live-tail pinned to bottom). Output sanitized with sanitizeText (ANSI strip) at render time, never at capture; 50ms render debounce.
Lifecycle: runtime built lazily, disposed on session_shutdown (covers /new,/resume,/fork,/reload,quit) → disposeAll → bounded 5s tree-kill per entry. Processes do not survive any session transition; spill dir removed on shutdown. No cross-session persistence.
Dependencies:effect@^4.0.0-beta.99 (core async layer), typescript@^7, @effect/tsgo. Tests via node --test --experimental-strip-types. No node-pty.
Discovery requires an explicit glob entry.package.jsonpi.extensions is ["./extensions/*.ts", "./extensions/perplexity/index.ts"]. The *.ts glob does not descend into subdirectories, so ./extensions/background-terminals/index.ts will not be auto-discovered — you must add it to the pi.extensions array, exactly like perplexity was. (package.json:13-18)
Local style is plain TS, no Effect.extensions/perplexity/ (index.ts, perplexity.ts, research-panel.ts) uses typebox Type.Object + StringEnum, ctx.ui.custom<>() for full-screen components, ctx.ui.notify/setStatus/setWidget/setEditorText, and a hand-written ResearchPanel class implementing Component, Focusable from @earendil-works/pi-tui. No Effect anywhere in the repo; pnpm-lock.yaml has no effect/node-pty. Peer deps are only @earendil-works/pi-coding-agent|pi-ai|pi-tui. (package.json, extensions/perplexity/index.ts:1-60,447-492, extensions/perplexity/research-panel.ts:1-40)
A ready local template exists:research-panel.ts is a full bordered, scrollable, keyboard-handling ctx.ui.custom overlay with cached rendering, matchesKey, wrapTextWithAnsi, truncateToWidth, visibleWidth, an Input, and tui.requestRender() debouncing. The /ps detail view in the reference is structurally the same shape — you can lift rendering helpers directly from here.
README must be updated in the same changeset (AGENTS.md house rule): add a ### Background Terminals (extensions/background-terminals/) block under ## Extensions (README.md:33-57), and add a skill row if you also ship skills/background-terminals/SKILL.md.
pi TUI capabilities confirm the approach:ctx.ui.setWidget(key, factory) defaults to above the editor (tui.md Pattern 5) — matches the reference widget. ctx.ui.custom supports {overlay:true} for the /ps picker. Lifecycle warning in docs is explicit: do not spawn background resources in the factory — defer to session_start/tool handlers, clean up in session_shutdown (docs/extensions.md "Long-lived resources and shutdown").
Tradeoffs and risks
Effect vs plain TS — the big decision. The reference leans heavily on Effect v4 (ManagedRuntime, Context.Service, Layer, Deferred, FiberSet, Scope, Effect.addFinalizer). Your repo has zero Effect usage and would pull in effect@^4.0.0-beta.99 + @effect/tsgo + TS7 just for this one extension. The async core the guide buys with Effect (concurrency reservation, idempotent settle, bounded teardown, deferred delivery) is all reproducible in plain TS with a Map, AbortController, setTimeout escalation, and a Set of listeners — the same idiom perplexity/research-panel.ts already uses. Recommendation: port to plain TS matching local style, do not adopt Effect. This keeps the dep surface at zero and stays consistent with the other extensions. The guide itself notes the Node stream plumbing is "plain TS callbacks" — only the coordination layer is Effect, and that layer is small.
"Background terminal" is a misnomer vs. a real terminal. Because stdin is ignored, this is a process output inspector, not something you can npm install interactively into. If you genuinely want interactive shells (vim, repls), you'd need node-pty + tui.stop()/tui.start() with stdio:"inherit" (see examples/extensions/interactive-shell.ts) — a fundamentally different design that blocks the TUI while active. The reference deliberately chose non-interactive. Confirm which you want; I read your "same functionality as this repo" literally → non-interactive fire-and-forget.
Memory/bound discipline is the real risk. Unbounded stdout (a yes firehose) leaks memory and blows context. The reference's OutputBuffer (2 MiB tail + disk spill + truncatedBytes accounting + truncateTail on every model-visible path) is not optional — it's load-bearing. A naive port that buffers everything will fail under load.
Exactly-once completion is subtle. Settle races (kill vs exit vs error), late output after exit, and queueing into a dying session all need the consumed flag, deferred-copy (not live snapshot), disposed guard, and deliverAs:"followUp"+triggerTurn. Skimping here → double messages or dropped results.
ANSI must be stripped at render, not capture. Raw process output desyncs the TUI renderer. sanitizeText at render time only.
Gaps / assumptions
I did not fetch src/manager.ts/output.ts/ui/ps.ts source — only the guide + index.ts. The guide is detailed enough to implement from, but the exact OutputBuffer head-drop/spill code and reconcileSelection should be pulled from those files when implementing.
Assumes pi pi.sendMessage({customType, ...}, {deliverAs, triggerTurn}), pi.registerMessageRenderer, and ctx.ui.custom({overlay, overlayOptions}) are available in your pinned version (0.84.1). Confirmed from docs/extensions.md + docs/tui.md; registerMessageRenderer is referenced by the guide — verify it's exported in 0.84.1 before relying on the collapsed completion renderer.
Assumes you want the non-interactive semantics (no stdin). If you want true interactive PTY terminals, this is a different project (node-pty + tui.stop/start).
Recommended next move
Create extensions/background-terminals/ as a plain-TS port (no Effect): index.ts + src/{manager.ts,output.ts,prompt.ts,result-delivery.ts,ui/ps.ts,ui/output-view.ts}. Mirror perplexity/'s file layout and import style (typeboxType.Object, StringEnum from @earendil-works/pi-ai, Component/Focusable/Markdown/Text/matchesKey/wrapTextWithAnsi from @earendil-works/pi-tui).
Add ./extensions/background-terminals/index.ts to package.jsonpi.extensions (it won't auto-discover otherwise).
Keep the 4 tools (bg_start/bg_status/bg_list/bg_kill), stdin-ignored spawn, detached process-group kill tree, bounded OutputBuffer (2 MiB tail) with disk spill, truncateTail on all model output, the above-editor widget, /ps two-stage overlay, and the exactly-once sendMessage followUp+triggerTurn completion. Drop Effect for plain Map+AbortController+setTimeout coordination.
Add skills/background-terminals/SKILL.md (copy the reference's) and update README.md Extensions + skills table in the same commit (AGENTS.md rule).
If you'd like, I can fetch src/manager.ts and src/output.ts next to capture the exact buffer/kill logic before implementing, or go straight to a plain-TS implementation. Which would you prefer?
What this means for your decision
My earlier synthesis stands — with one note: the reference extension is built on Effect v4 (effect@^4.0.0-beta.99), and that is a genuine fork in the road for your port. To recap the recommendation:
Discovery: add ./extensions/background-terminals/index.ts to package.json's pi.extensions array (the *.ts glob doesn't descend into subdirs).
Core: 4 tools (bg_start/bg_status/bg_list/bg_kill), stdin-ignored spawn, detached process-group kill tree (SIGTERM→SIGKILL), bounded OutputBuffer (2 MiB tail) + disk spill, truncateTail on all model-visible output, above-editor widget, /ps two-stage overlay, exactly-once sendMessage completion.
The real choice: port the Effect-based coordination layer to plain TS (matching your perplexity/ extension, zero new deps) or adopt effect@^4 + @effect/tsgo + TS7 to mirror the reference 1:1. My recommendation remains plain TS — your repo has no Effect anywhere and the async core is small enough to reproduce with Map + AbortController + setTimeout.
Want me to (a) fetch src/manager.ts + src/output.ts to capture the exact buffer/kill logic before implementing, or (b) go straight to a plain-TS implementation? And do you want the non-interactive (stdin-ignored) semantics of the reference, or true interactive PTY terminals — those are different designs.
Stay plain TS
New deps
effect@^4.0.0-beta.99 + @effect/tsgo + typescript@^7 (native-preview). The repo currently has zero of these — no TS in package.json, pnpm-lock.yaml, or node_modules.
v4 is beta; breaking changes between betas are expected; maintainers say use v3 for production. You'd be pinning a moving target.
None — your code, your control.
Toolchain coupling
@effect/tsgo patch swaps a binary on disk; @effect/language-service TS plugin; TS7 native-preview is itself a beta.
Not needed. Crucially: none of this is runtime-required. pi loads extensions via jiti (transpiles TS on the fly, no compile step). tsgo/language-service are editor/type-check niceties only — you could ship Effect without them and it still runs. But then you lose the diagnostics that make Effect ergonomic, and you'd want a tsc --noEmit check step that the repo currently lacks.
Repo alignment
Introduces a per-extension package.json (the reference's pattern), a prepare script, a check script, and TS7 — none of which exist here. perplexity/ has no per-extension package.json and runs fine. You'd be inventing a new sub-build-system for one extension.
Effect ships a runtime, fiber scheduler, Layer/Service/Deferred/FiberSet/Scope. The reference's own guide says the Node stream plumbing is "plain TS callbacks" — Effect is used only for the coordination layer (concurrency reservation, idempotent settle, bounded teardown, deferred delivery). That layer is ~200 lines and reproducible with Map + AbortController + setTimeout + Set<listener>.
Direct, no scheduler.
Idiom fit
Effect earns its keep on complex async flows, deep dependency graphs, typed errors, retry/recovery, DI. For a single backend (one spawn) with a Map of state, practitioners' own guidance is that it's overkill: "do not use Effect when the project is small and simple… mostly CRUD/Promises… you pay more in learning curve and boilerplate." Multiple practitioners scope Effect to complex parts only.
Matches the actual shape of the problem.
What you gain
Structured concurrency (Scope finalizers → guaranteed teardown), typed errors (Data.TaggedError), Deferred for exactly-once settlement, FiberSet for fire-and-forget cleanup — these are real and the reference leverages them for race-safety.
You must hand-implement the race-safety (idempotent settle, kill vs exit precedence, consumed flag, disposed guard, bounded teardown). This is genuinely subtle, but the reference guide documents every race precisely — it's tractable.
Maintenance
Effect API churn during beta means re-checking APIs; v4 docs are still settling.
Stable, boring TS; only you maintain it.
The honest assessment
For this specific use case — a background process manager that is one spawn + a Map + AbortController + setTimeout + a listener set — Effect v4 is disproportionate:
The async core is small. The reference's own design doc concedes the stream plumbing is plain callbacks; Effect only wraps the coordination layer. That layer (~concurrency cap, idempotent settle, deferred delivery, bounded teardown) is reproducible in plain TS without a runtime.
The beta + preview-toolchain coupling is real cost for no project-wide benefit. You'd introduce effect@beta, @effect/tsgo, and TS7 (native-preview) into a repo that currently has no TypeScript compiler at all and loads everything via jiti. That's a new sub-build-system for one extension, on a moving target, against a house style (perplexity) that is deliberately dep-light.
tsgo/language-service are optional at runtime (jiti doesn't need them), but they're what make Effect ergonomic to write. Without them you lose the main reason to adopt Effect, while still paying the runtime/API cost.
Where Effect would actually pay off: if this repo were already an Effect shop (multiple extensions sharing a Layer/Service graph, typed error flows across extensions), or if the background-terminal logic grew to multiple heterogeneous backends needing a normalized event queue (the reference explicitly contrasts this with its sibling subagents extension, which does need Effect because three backends normalize into one event stream). Neither is true here.
Recommendation
Port to plain TS. Keep the reference's semantics (bounded OutputBuffer + spill, idempotent settle, consumed flag, disposed guard, exactly-once sendMessage, detached process-group kill, truncateTail on all model output, the above-editor widget, /ps two-stage overlay) but implement the coordination with Map + AbortController + setTimeout + Set<listener>, matching extensions/perplexity/'s style. Zero new deps, no beta toolchain, consistent with the rest of the package.
If you later want the race-safety guarantees Effect buys "for free," the upgrade path is well-documented — but start plain.
One caveat I'll flag rather than smooth over: the subtle part isn't the language choice, it's the race semantics (kill vs exit vs error precedence, late output after exit, settle-during-teardown, queueing into a dying session). Whichever path you take, port those handlers faithfully from the reference's manager.ts/output.ts — I'd fetch those two files before implementing either way. Want me to pull them?
drain()
isIdle()
My post-review fix: Applied the reviewer's N1–N3 recommendation — .unref()'d the setTimeout timers in waitForClose, sleep, withTimeoutVoid, and flushSpillStreams so they can't keep the Node event loop alive past teardown. (N4–N6 were acceptable defense-in-depth, left as-is.)
Syntax validation: All 8 .ts files pass node --experimental-strip-types --check (sanity-confirmed that the checker does report errors).
What's not done (left for you)
No commit — all changes are unstaged (git status shows modified package.json/README.md + untracked extensions/background-terminals/ and skills/background-terminals/). Note there's a pre-existing untracked mise.toml/scripts//tests/ and a modified .gitignore from before this session — those aren't mine.
Not runtime-tested in pi — there's no test harness in this repo and no tsc. I'd recommend a quick manual smoke test: reload pi, ask the model to bg_start a dev server, open /ps, kill via x, and confirm the widget disappears + completion message arrives once.
The earlier wrong-researcher artifact at .pi/subagents/artifacts/c9218737_researcher_0_output.md (claiming the extension "doesn't exist" / is some npm package) is still on disk — you can delete it; it was thoroughly debunked.
Want me to commit these changes, or run a smoke test first?
.unref()
clearTimeout
waitForClose
What's verified working
Extension loading, tool registration, all 4 tools, parameter schemas, spawn with stdin-ignored, separate stdout/stderr capture, UTF-8 decoding, bounded OutputBuffer with head eviction, concurrency cap with synchronous reservation, idempotent settle, consumed flag, killSignaled semantics, process-tree kill (group signal), disposeAll safety net, spill-dir cleanup, and agent_end (this pi version's substitute for the unavailable agent_settled).
Not yet tested live
The /ps overlay and above-editor widget (TUI-only — can't drive the interactive TUI from here; would need a manual run)
The completion follow-up message rendering in an interactive session
Changeset (unstaged)
extensions/background-terminals/ (8 new TS files, plain-TS port, zero new deps)
Pre-existing untracked mise.toml/scripts//tests/ and modified .gitignore are not mine.
Want me to commit these changes now?
Without autofix mode, ask before applying fixes unless I already told you to address review feedback. When you ask, end with a compact numbered menu so I can respond with a number. Use wording suited to the findings, but include these choices when applicable:
text
Reply with [1], [2], or further instructions:
[1] Apply only the fixes worth doing now.
[2] Apply the fixes worth doing now plus optional improvements.
Additional review target or focus from the slash command invocation:
If the invocation provides a URL, issue link, file path, plan path, or freeform focus, treat it as the primary review scope. Read or fetch that target before assigning reviewer angles, and pass the target explicitly into each reviewer task.
manager.ts:405-416
session_shutdown
session-XXXXX/
/tmp
Fix: on resolveSpillDir's first call, scan base/session-* and rmSync stale dirs before creating the new one.
Optional improvements (non-blocking, would accept)
T1 — Adopt the types reviewer's stricter validation command (node --experimental-strip-types -e "await import('./extensions/background-terminals/index.ts')") — actually executes the module, catches the bug class --check missed. (Note: the reviewer also flagged that the installed @earendil-works/pi-coding-agent is 0.80.2, while the pi CLI reports 0.84.1 — a version skew, but all APIs were verified against the actual installed 0.80.2 types and match.)
M1 — Remove the ~5 scattered "Replaces Effect X" comment tags in manager.ts (reference APIs that no longer exist; keep the file-level port note).
M2 — Remove the dead manager.status() / manager.list() methods (handlers use view.get/view.list directly) or route through them.
S2 — Add child.exitCode/signalCode guard in terminateChild before killTree to narrow the PID-reuse window (cheap, theoretical).
S3 — chmodSync(spillPath, 0o600) after createWriteStream to match the directory hardening (defensive consistency).
Feedback to ignore / defer (with reason)
Orphan processes on SIGKILL/power loss (security N3) — inherent to user-space Node process management; no TS fix without native bindings. Defer (document later if desired).
/tmp symlink race, setsid-escape, env-leakage, TOCTOU cwd (security N4/N5/N6/N7) — require attacker preconditions on a single-user machine, are inherent to the tool's purpose, or fail safely. Ignore.
No correctness regressions in the race invariants (confirmed by two independent reviews now). The four "fix now" items are real resource/security hardening — cheap, low-risk, and R3/S1 address a crash and secret-persistence respectively.
Reply with [1], [2], or further instructions:
[1] Apply only the fixes worth doing now (R1–R3, S1).
[2] Apply the fixes worth doing now plus optional improvements (R1–R3, S1, T1, M1, M2, S2, S3).
Without autofix mode, ask before applying fixes unless I already told you to address review feedback. When you ask, end with a compact numbered menu so I can respond with a number. Use wording suited to the findings, but include these choices when applicable:
text
Reply with [1], [2], or further instructions:
[1] Apply only the fixes worth doing now.
[2] Apply the fixes worth doing now plus optional improvements.
Additional review target or focus from the slash command invocation:
If the invocation provides a URL, issue link, file path, plan path, or freeform focus, treat it as the primary review scope. Read or fetch that target before assigning reviewer angles, and pass the target explicitly into each reviewer task.
R1–R3 confirmed sound. S1 has a real (low-severity, no-crash) concurrency gap worth fixing now since it's cheap and the fix is clean. R4 is a nice-to-have in the same vein as R1.
Reply with [1], [2], or further instructions:
[1] Apply only the fixes worth doing now (S1 concurrent-session fix).
[2] Apply the fixes worth doing now plus optional improvements (S1 + R4 timer-clear).
Without autofix mode, ask before applying fixes unless I already told you to address review feedback. When you ask, end with a compact numbered menu so I can respond with a number. Use wording suited to the findings, but include these choices when applicable:
text
Reply with [1], [2], or further instructions:
[1] Apply only the fixes worth doing now.
[2] Apply the fixes worth doing now plus optional improvements.
Additional review target or focus from the slash command invocation:
If the invocation provides a URL, issue link, file path, plan path, or freeform focus, treat it as the primary review scope. Read or fetch that target before assigning reviewer angles, and pass the target explicitly into each reviewer task.
drain
Optional improvements
Remove dead manager.status()/manager.list() methods (cross-file reviewer).
Fix cachedText init to undefined in output.ts (small-files reviewer, cosmetic).
FollowUp+compaction interaction (integration reviewer's speculative concern) — deliverAs:"followUp" is a documented core pi feature designed to be safe through compaction.
Bottom line
One real fix (I1), validated by runtime probe. The other two reviewers found nothing actionable — the extension is clean across contracts, small files, and pi integration.
Reply with [1], [2], or further instructions:
[1] Apply only the fixes worth doing now (I1: switch to agent_settled + keep agent_end fallback).
[2] Apply the fixes worth doing now plus optional improvements (I1 + dead method removal + cachedText init + export cleanup).
bg_start
agent
Where they overlap and don't
They only overlap in the trivial "run a short command and see output" case — and there ! (or just the agent's regular bash tool) is better. bg_start earns its keep for long-running commands where blocking would stall the whole session: starting a dev server and then asking the agent to add a feature while it runs, running a watch build while iterating on tests, tailing a log stream.
The key design difference, which the reference calls out explicitly: background terminals have no stdin at the OS level — that's the contract that makes fire-and-forget safe (no hung interactive prompt, no stuck process waiting for input you'll never send). !/!i is the opposite: full interactive terminal access, which is why it must block/suspend the TUI.
One more nuance: there's a pi example extension (interactive-shell.ts) that's the conceptual bridge — it intercepts user ! commands and, for known-interactive ones (vim, htop, git rebase -i), suspends the TUI and runs them with stdio: "inherit" for full terminal access. That's still blocking + user-driven, not agent-driven background execution. Your new bg_start is the only one of the three that's agent-driven and non-blocking.