[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F2Y418AXPKW459P5ZXX3RM":3,"skill-same:01M7F2Y418AXPKW459P5ZXX3RM":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7F2Y418AXPKW459P5ZXX3RM","pi-interactive-shell",null,"Cheat sheet + workflow for launching interactive coding-agent CLIs (Claude Code, Gemini CLI, Codex CLI, Cursor CLI, and pi itself) via the interactive_shell overlay, headless dispatch, or monitor mode. Use for TUI agents and long-running processes that need supervision, fire-and-forget delegation, or event-driven background monitoring. If interactive_shell is unavailable, enable it with enable_interactive_shell first. Regular bash commands should use the bash tool instead.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F05-技能与代理开发\u002Fpi-interactive-shell\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: pi-interactive-shell\ndescription: Cheat sheet + workflow for launching interactive coding-agent CLIs (Claude Code, Gemini CLI, Codex CLI, Cursor CLI, and pi itself) via the interactive_shell overlay, headless dispatch, or monitor mode. Use for TUI agents and long-running processes that need supervision, fire-and-forget delegation, or event-driven background monitoring. If interactive_shell is unavailable, enable it with enable_interactive_shell first. Regular bash commands should use the bash tool instead.\n---\n\n# Interactive Shell (Skill)\n\n## Deferred activation\n\nWhen `interactive_shell` is unavailable, call `enable_interactive_shell` first. The tool becomes callable on the next turn and stays active until Pi reloads or the session changes; reloaded, new, resumed, and forked sessions reset it to inactive. Do not call the loader when `interactive_shell` is already available.\n\nUsers opt in with `\"defer\": true` in `interactive-shell.json`. Older Pi versions without active-tool APIs warn and keep eager loading. A CLI `--tools` allowlist must include both `enable_interactive_shell` and `interactive_shell`.\n\n## Foreground vs Background Subagents\n\nPi has two ways to delegate work to other AI coding agents:\n\n| | Foreground Subagents | Dispatch Subagents | Background Subagents |\n|---|---|---|---|\n| **Tool** | `interactive_shell` | `interactive_shell` (dispatch) | `subagent` |\n| **Visibility** | User sees overlay | User sees overlay (or headless) | Hidden from user |\n| **Agent model** | Polls for status | Notified on completion | Full output captured |\n| **Default agent** | `pi` (others if user requests) | `pi` (others if user requests) | Pi only |\n| **User control** | Can take over anytime | Can take over anytime | No intervention |\n| **Best for** | Long tasks needing supervision | Fire-and-forget delegations | Parallel tasks, structured delegation |\n\n**Foreground subagents** run in an overlay where the user watches and can intervene. Use `interactive_shell` with `mode: \"interactive\"` when the agent or user will drive the shell by session id, `mode: \"hands-free\"` to monitor while receiving periodic updates, or `mode: \"dispatch\"` to be notified on completion without polling.\n\n**Dispatch subagents** also use `interactive_shell` but with `mode: \"dispatch\"`. The agent fires the session and moves on. When the session completes, the agent is woken up via `triggerTurn` with the output in context. Add `background: true` for headless execution (no overlay).\n\n**Monitor mode** (`mode: \"monitor\"`) runs headless and event-driven. It wakes the agent on structured monitor trigger events (stream or poll-diff), so there is no polling loop.\n\n**Background subagents** run invisibly via the `subagent` tool. Pi-only, but captures full output and supports parallel execution.\n\n## When to Use Foreground Subagents\n\nUse `interactive_shell` (foreground) when:\n- The task is **long-running** and the user should see progress\n- The user might want to **intervene or guide** the agent\n- You want **hands-free monitoring** with periodic status updates\n- You need a **different agent's capabilities** (only if user specifies)\n\nUse `subagent` (background) when:\n- You need **parallel execution** of multiple tasks\n- You want **full output capture** for processing\n- The task is **quick and deterministic**\n- User doesn't need to see the work happening\n\n### Default Agent Choice\n\n**Default to `pi`** for foreground subagents unless the user explicitly requests a different agent:\n\n| User says | Agent to use |\n|-----------|--------------|\n| \"Run this in hands-free\" | `pi` |\n| \"Delegate this task\" | `pi` |\n| \"Use Claude to review this\" | `claude` |\n| \"Have Gemini analyze this\" | `gemini` |\n| \"Run aider to fix this\" | `aider` |\n\nPi is the default because it's already available, has the same capabilities, and maintains consistency. Only use Claude, Gemini, Codex, or other agents when the user specifically asks for them.\n\n## Structured Spawn and `\u002Fspawn`\n\nFor Pi, Codex, Claude, and Cursor, prefer structured `spawn` params when you want the extension's shared resolver, config defaults, native startup prompt forms, or Pi-only fork\u002Fworktree behavior. For unattended coding-agent work in a repository, use `worktree: true` or an explicitly isolated `cwd`; raw commands run in their supplied working directory and can change its Git state:\n\n```typescript\ninteractive_shell({ spawn: { agent: \"pi\" }, mode: \"interactive\" })\ninteractive_shell({ spawn: { agent: \"codex\" }, mode: \"dispatch\" })\ninteractive_shell({ spawn: { agent: \"cursor\", prompt: \"Review the diffs\" }, mode: \"dispatch\" })\ninteractive_shell({ spawn: { agent: \"claude\", prompt: \"Review the diffs\" }, mode: \"dispatch\" })\ninteractive_shell({ spawn: { agent: \"claude\", worktree: true }, mode: \"hands-free\" })\ninteractive_shell({ spawn: { mode: \"fork\" }, mode: \"interactive\" }) \u002F\u002F Pi-only\n```\n\nStructured `spawn` uses the same resolver and defaults as the user-facing `\u002Fspawn` command. Raw `command` is still the right choice for arbitrary CLIs and custom launch strings. Users can add their own agents under `spawn.commands`; those keys work in `spawn: { agent: \"...\" }` just like the built-ins, and an unknown key returns the configured agent list as an error. Cursor structured spawn defaults to `--model composer-2-fast`, which explicitly selects Composer 2 Fast.\n\nFor Codex image or design work, Codex can invoke `gpt-image-2` directly from the prompt. Natural language is usually enough, and `$imagegen` forces the image-generation tool when you need it. Attach references with `-i` for edits and iterations. See the bundled `codex-cli` skill for concrete examples.\n\nFor users in chat, `\u002Fspawn` now supports the configured default agent plus explicit overrides like `\u002Fspawn codex`, `\u002Fspawn cursor`, `\u002Fspawn claude`, `\u002Fspawn pi`, `\u002Fspawn fork`, `\u002Fspawn pi fork`, and any custom agent key from `spawn.commands`. Add `--worktree` to run in a separate git worktree.\n\nQuoted prompt text plus `--hands-free` or `--dispatch` turns `\u002Fspawn` into a monitored delegated run instead of a plain interactive overlay:\n\n```bash\n\u002Fspawn cursor \"review the diffs\" --dispatch\n\u002Fspawn claude \"review the diffs\" --dispatch\n\u002Fspawn codex \"fix the failing tests\" --hands-free\n\u002Fspawn pi fork \"continue from here\" --dispatch\n```\n\n## Foreground Subagent Modes\n\n### Interactive (default)\nThe overlay opens and returns a stable `sessionId` immediately. The user can type directly, and the agent can send input to the same shell.\n```typescript\nconst { sessionId } = interactive_shell({ command: 'pi' })\ninteractive_shell({ sessionId, input: '\u002Fhelp', submit: true })\n```\n\n### Interactive with Initial Prompt\nAgent starts working immediately, user supervises.\n```typescript\ninteractive_shell({ command: 'pi \"Review this codebase for security issues\"' })\n```\n\n### Dispatch (Fire-and-Forget) - NON-BLOCKING, NO POLLING\nAgent fires a session and moves on. Notified automatically on completion via `triggerTurn`.\n\n```typescript\n\u002F\u002F Start session - returns immediately, no polling needed\ninteractive_shell({\n  command: 'pi \"Fix all TypeScript errors in src\u002F\"',\n  mode: \"dispatch\",\n  reason: \"Fixing TS errors\"\n})\n\u002F\u002F Returns: { sessionId: \"calm-reef\", mode: \"dispatch\" }\n\u002F\u002F → Do other work. When session completes, you receive notification with output.\n```\n\nDispatch defaults `autoExitOnQuiet: true`. A quiet TUI auto-closes after the threshold and reports `completionReason: \"auto-close-quiet\"` separately from a user kill. This is not a terminal command verdict. The agent can still query the sessionId if needed, but doesn't have to.\n\nFor a provider-agnostic external gate watcher, use `mode: \"monitor\"`, set `handsFree: { autoExitOnQuiet: false }`, set a hard `timeout`, and match explicit terminal lines such as `ready`, `blocked`, and `stale-head`. The watcher command must exit only after it emits a terminal line. If raw dispatch is required, disable quiet auto-close and treat `completionReason: \"auto-close-quiet\"` as non-terminal.\n\nFor fire-and-forget delegated runs (including QA-style delegated checks), prefer dispatch as the default mode.\n\n#### Background Dispatch (Headless)\nNo overlay opens. Multiple headless dispatches can run concurrently:\n\n```typescript\ninteractive_shell({\n  command: 'pi \"Fix lint errors\"',\n  mode: \"dispatch\",\n  background: true\n})\n\u002F\u002F → No overlay. User can \u002Fattach to watch. Agent notified on completion.\n```\n\n### Monitor (Event-Driven, Headless)\nRun a background process and wake the agent on structured monitor triggers.\n\n```typescript\ninteractive_shell({\n  command: 'npm test --watch',\n  mode: \"monitor\",\n  monitor: {\n    strategy: \"stream\",\n    triggers: [\n      { id: \"failed\", literal: \"FAIL\" },\n      { id: \"error\", regex: \"\u002Ferror|warn\u002Fi\" }\n    ],\n    throttle: { dedupeExactLine: true }\n  }\n})\n\ninteractive_shell({\n  command: 'curl -sf http:\u002F\u002Flocalhost:3000\u002Fhealth',\n  mode: \"monitor\",\n  monitor: {\n    strategy: \"poll-diff\",\n    triggers: [{ id: \"changed\", regex: \"\u002F.\u002F\" }],\n    poll: { intervalMs: 5000 }\n  }\n})\n```\n\nUse monitor mode for log watchers and long-running checks where polling would be noisy or expensive.\n\n### Hands-Free (Foreground Subagent) - NON-BLOCKING\nAgent works autonomously, **returns immediately** with sessionId. You query for status\u002Foutput and kill when done.\n\n```typescript\n\u002F\u002F 1. Start session - returns immediately\ninteractive_shell({\n  command: 'pi \"Fix all TypeScript errors in src\u002F\"',\n  mode: \"hands-free\",\n  reason: \"Fixing TS errors\"\n})\n\u002F\u002F Returns: { sessionId: \"calm-reef\", status: \"running\" }\n\n\u002F\u002F 2. Check status and get new output\ninteractive_shell({ sessionId: \"calm-reef\" })\n\u002F\u002F Returns: { status: \"running\", output: \"...\", runtime: 30000 }\n\n\u002F\u002F 3. When you see task is complete, kill session\ninteractive_shell({ sessionId: \"calm-reef\", kill: true })\n\u002F\u002F Returns: { status: \"killed\", output: \"final output...\" }\n```\n\nThis is the primary pattern for **foreground subagents** - you delegate to pi (or another agent), query for progress, and decide when the task is done.\n\n## Hands-Free Workflow\n\n### Starting a Session\n```typescript\nconst result = interactive_shell({\n  command: 'codex \"Review this codebase\"',\n  mode: \"hands-free\"\n})\n\u002F\u002F result.details.sessionId = \"calm-reef\"\n\u002F\u002F result.details.status = \"running\"\n```\n\nThe user sees the overlay immediately. You get control back to continue working. If the user types to take over a monitored hands-free or dispatch session, they can press `Ctrl+G` to return control to the agent.\n\n### Querying Status\n```typescript\ninteractive_shell({ sessionId: \"calm-reef\" })\n```\n\nReturns:\n- `status`: \"running\" | \"monitoring\" | \"user-takeover\" | \"exited\" | \"killed\" | \"backgrounded\"\n- `output`: Last 20 lines of rendered terminal (clean, no TUI animation noise)\n- `runtime`: Time elapsed in ms\n\n**Rate limited:** Queries are limited to once every 60 seconds. If you query too soon, the tool will automatically wait until the limit expires before returning. The user is watching the overlay in real-time - you're just checking in periodically.\n\n### Ending a Session\n```typescript\ninteractive_shell({ sessionId: \"calm-reef\", kill: true })\n```\n\nKill when you see the task is complete in the output. Returns final status and output.\n\n### Fire-and-Forget Tasks\n\nFor single-task delegations where you don't need multi-turn interaction, enable auto-exit so the session kills itself when the agent goes quiet:\n\n```typescript\ninteractive_shell({\n  command: 'pi \"Review this codebase for security issues. Save your findings to \u002Ftmp\u002Fsecurity-review.md\"',\n  mode: \"hands-free\",\n  reason: \"Security review\",\n  handsFree: { autoExitOnQuiet: true }\n})\n\u002F\u002F Session auto-kills after ~8s of quiet (after the startup grace period)\n\u002F\u002F Read results from file:\n\u002F\u002F read(\"\u002Ftmp\u002Fsecurity-review.md\")\n```\n\n**Instruct subagent to save results to a file** since the session closes automatically.\n\n### Multi-Turn Sessions (default)\n\nFor back-and-forth interaction, leave auto-exit disabled (the default). Query status and kill manually when done:\n\n```typescript\ninteractive_shell({\n  spawn: { agent: \"cursor\" },\n  mode: \"hands-free\",\n  reason: \"Interactive refactoring\"\n})\n\n\u002F\u002F Send follow-up prompts\ninteractive_shell({ sessionId: \"calm-reef\", input: \"Now fix the tests\", submit: true })\n\n\u002F\u002F Kill when done\ninteractive_shell({ sessionId: \"calm-reef\", kill: true })\n```\n\n### Sending Input\n```typescript\ninteractive_shell({ sessionId: \"calm-reef\", input: \"\u002Fhelp\", submit: true })\ninteractive_shell({ sessionId: \"calm-reef\", inputKeys: [\"ctrl+c\"] })\ninteractive_shell({ sessionId: \"calm-reef\", inputPaste: \"multi\\nline\\ncode\" })\ninteractive_shell({ sessionId: \"calm-reef\", input: \"y\", inputKeys: [\"enter\"] })  \u002F\u002F combine text + keys\n```\n\n### Query Output\n\nStatus queries return **rendered terminal output** (what's actually on screen), not raw stream:\n- Default: 20 lines, 5KB max per query\n- No TUI animation noise (spinners, progress bars, etc.)\n- Configurable via `outputLines` (max: 200) and `outputMaxChars` (max: 50KB)\n\n```typescript\n\u002F\u002F Get more output when reviewing a session\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50 })\n\n\u002F\u002F Get even more for detailed review\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 100, outputMaxChars: 30000 })\n```\n\n### Incremental Reading\n\nUse `incremental: true` to paginate through output without re-reading:\n\n```typescript\n\u002F\u002F First call: get first 50 lines\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50, incremental: true })\n\u002F\u002F → { output: \"...\", hasMore: true }\n\n\u002F\u002F Next call: get next 50 lines (server tracks position)\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50, incremental: true })\n\u002F\u002F → { output: \"...\", hasMore: true }\n\n\u002F\u002F Keep calling until hasMore: false\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50, incremental: true })\n\u002F\u002F → { output: \"...\", hasMore: false }\n```\n\nThe server tracks your read position - just keep calling with `incremental: true` to get the next chunk.\n\n### Reviewing Output\n\nQuery sessions to see progress. Increase limits when you need more context:\n\n```typescript\n\u002F\u002F Default: last 20 lines\ninteractive_shell({ sessionId: \"calm-reef\" })\n\n\u002F\u002F Get more lines when you need more context\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50 })\n\n\u002F\u002F Get even more for detailed review\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 100, outputMaxChars: 30000 })\n```\n\n## Sending Input to Active Sessions\n\nUse the `sessionId` from updates to send input to a running hands-free session:\n\n### Basic Input\n```typescript\n\u002F\u002F Send text and submit it\ninteractive_shell({ sessionId: \"shell-1\", input: \"\u002Fhelp\", submit: true })\n\n\u002F\u002F Send text with keys\ninteractive_shell({ sessionId: \"shell-1\", input: \"\u002Fmodel\", inputKeys: [\"enter\"] })\n\n\u002F\u002F Navigate menus\ninteractive_shell({ sessionId: \"shell-1\", inputKeys: [\"down\", \"down\", \"enter\"] })\n\n\u002F\u002F Interrupt\ninteractive_shell({ sessionId: \"shell-1\", inputKeys: [\"ctrl+c\"] })\n```\n\n### Named Keys\n| Key | Description |\n|-----|-------------|\n| `up`, `down`, `left`, `right` | Arrow keys |\n| `enter`, `return` | Enter\u002FReturn |\n| `escape`, `esc` | Escape |\n| `tab`, `shift+tab` (or `btab`) | Tab \u002F Back-tab |\n| `backspace`, `bspace` | Backspace |\n| `delete`, `del`, `dc` | Delete |\n| `insert`, `ic` | Insert |\n| `home`, `end` | Home\u002FEnd |\n| `pageup`, `pgup`, `ppage` | Page Up |\n| `pagedown`, `pgdn`, `npage` | Page Down |\n| `f1`-`f12` | Function keys |\n| `kp0`-`kp9`, `kp\u002F`, `kp*`, `kp-`, `kp+`, `kp.`, `kpenter` | Keypad keys |\n| `ctrl+c`, `ctrl+d`, `ctrl+z` | Control sequences |\n| `ctrl+a` through `ctrl+z` | All control keys |\n\nNote: `ic`\u002F`dc`, `ppage`\u002F`npage`, `bspace` are tmux-style aliases for compatibility.\n\n### Modifier Combinations\nSupports `ctrl+`, `alt+`, `shift+` prefixes (or shorthand `c-`, `m-`, `s-`):\n```typescript\n\u002F\u002F Cancel\ninputKeys: [\"ctrl+c\"]\n\n\u002F\u002F Alt+Tab\ninputKeys: [\"alt+tab\"]\n\n\u002F\u002F Ctrl+Alt+Delete\ninputKeys: [\"ctrl+alt+delete\"]\n\n\u002F\u002F Shorthand syntax\ninputKeys: [\"c-c\", \"m-x\", \"s-tab\"]\n```\n\n### Hex Bytes (Advanced)\nSend raw escape sequences:\n```typescript\ninputHex: [\"0x1b\", \"0x5b\", \"0x41\"]  \u002F\u002F ESC[A (up arrow)\n```\n\n### Bracketed Paste\nPaste multiline text without triggering autocompletion\u002Fexecution:\n```typescript\ninputPaste: \"function foo() {\\n  return 42;\\n}\"\n```\n\n### Model Selection Example\n```typescript\n\u002F\u002F Step 1: Open model selector\ninteractive_shell({ sessionId: \"shell-1\", input: \"\u002Fmodel\", inputKeys: [\"enter\"] })\n\n\u002F\u002F Step 2: Filter and select (after ~500ms delay)\ninteractive_shell({ sessionId: \"shell-1\", input: \"sonnet\", inputKeys: [\"enter\"] })\n\n\u002F\u002F Or navigate with arrows:\ninteractive_shell({ sessionId: \"shell-1\", inputKeys: [\"down\", \"down\", \"down\", \"enter\"] })\n```\n\n### Context Compaction\n```typescript\ninteractive_shell({ sessionId: \"shell-1\", input: \"\u002Fcompact\", submit: true })\n```\n\nFor editor-based TUIs like pi, raw `input` only types text. It does not submit the prompt. Prefer `submit: true` or `inputKeys: [\"enter\"]` instead of relying on `\\n`.\n\n### Changing Update Settings\nAdjust timing during a session:\n```typescript\n\u002F\u002F Change max interval (fallback for on-quiet mode)\ninteractive_shell({ sessionId: \"calm-reef\", settings: { updateInterval: 120000 } })\n\n\u002F\u002F Change quiet threshold (how long to wait after output stops)\ninteractive_shell({ sessionId: \"calm-reef\", settings: { quietThreshold: 3000 } })\n\n\u002F\u002F Both at once\ninteractive_shell({ sessionId: \"calm-reef\", settings: { updateInterval: 30000, quietThreshold: 2000 } })\n```\n\n## CLI Quick Reference\n\n| Agent | Interactive | With Prompt | Headless (bash) | Dispatch |\n|-------|-------------|-------------|-----------------|----------|\n| `claude` | `claude` | `claude \"prompt\"` | `claude -p \"prompt\"` | `mode: \"dispatch\"` |\n| `gemini` | `gemini` | `gemini -i \"prompt\"` | `gemini \"prompt\"` | `mode: \"dispatch\"` |\n| `codex` | `codex` | `codex \"prompt\"` | `codex exec \"prompt\"` | `mode: \"dispatch\"` |\n| `agent` | `agent` | `agent \"prompt\"` | `agent -p \"prompt\"` | `mode: \"dispatch\"` |\n| `pi` | `pi` | `pi \"prompt\"` | `pi -p \"prompt\"` | `mode: \"dispatch\"` |\n\n**Gemini model:** `gemini -m gemini-3-flash-preview -i \"prompt\"`\n\n## Prompt Packaging Rules\n\nThe `reason` parameter is **UI-only** - it's shown in the overlay header but NOT passed to the subprocess.\n\nTo give the agent an initial prompt, embed it in the `command`:\n```typescript\n\u002F\u002F WRONG - agent starts idle, reason is just UI text\ninteractive_shell({ command: 'claude', reason: 'Review the codebase' })\n\n\u002F\u002F RIGHT - agent receives the prompt\ninteractive_shell({ command: 'claude \"Review the codebase\"', reason: 'Code review' })\n```\n\n## Handoff Options\n\n### Transfer (Ctrl+T) - Recommended\nWhen the subagent finishes, the user presses **Ctrl+T** to transfer output directly to you:\n\n```\n[Subagent finishes work in overlay]\n        ↓\n[User presses Ctrl+T]\n        ↓\n[You receive: \"Session output transferred (150 lines):\n  \n  Completing skill integration...\n  Modified files:\n  - skills.ts\n  - agents\u002Ftypes\u002F...\"]\n```\n\nThis is the cleanest workflow - the subagent's response becomes your context automatically.\n\n**Configuration:** `transferLines` (default: 200), `transferMaxChars` (default: 20KB)\n\n### Tail Preview (default)\nLast 30 lines included in tool result. Good for seeing errors\u002Ffinal status.\n\n### Snapshot to File\nWrite full transcript to `~\u002F.pi\u002Fagent\u002Fcache\u002Finteractive-shell\u002Fsnapshot-*.log`:\n```typescript\ninteractive_shell({\n  command: 'claude \"Fix bugs\"',\n  handoffSnapshot: { enabled: true, lines: 200 }\n})\n```\n\n### Artifact Handoff (for complex tasks)\nInstruct the delegated agent to write a handoff file:\n```\nWrite your findings to .pi\u002Fdelegation\u002Fclaude-handoff.md including:\n- What you did\n- Files changed\n- Any errors\n- Next steps for the main agent\n```\n\n## Safe TUI Capture\n\n**Never run TUI agents via bash** - they hang even with `--help`. Use `interactive_shell` with `timeout` instead:\n\n```typescript\ninteractive_shell({\n  command: \"pi --help\",\n  mode: \"hands-free\",\n  timeout: 5000  \u002F\u002F Auto-kill after 5 seconds\n})\n```\n\nThe process is killed after timeout and captured output is returned in the handoff preview. This is useful for:\n- Getting CLI help from TUI applications\n- Capturing output from commands that don't exit cleanly\n- Any TUI command where you need quick output without user interaction\n\nFor pi CLI documentation, you can also read directly: `\u002Fopt\u002Fhomebrew\u002Flib\u002Fnode_modules\u002F@earendil-works\u002Fpi-coding-agent\u002FREADME.md`\n\n## Background Session Management\n\n```typescript\n\u002F\u002F Background an active session (close overlay, keep running)\ninteractive_shell({ sessionId: \"calm-reef\", background: true })\n\n\u002F\u002F List all background sessions\ninteractive_shell({ listBackground: true })\n\n\u002F\u002F Reattach to a background session\ninteractive_shell({ attach: \"calm-reef\" })                    \u002F\u002F interactive (blocking)\ninteractive_shell({ attach: \"calm-reef\", mode: \"hands-free\" })  \u002F\u002F hands-free (poll)\ninteractive_shell({ attach: \"calm-reef\", mode: \"dispatch\" })    \u002F\u002F dispatch (notified)\n\n\u002F\u002F Dismiss background sessions (kill running, remove exited)\ninteractive_shell({ dismissBackground: true })               \u002F\u002F all\ninteractive_shell({ dismissBackground: \"calm-reef\" })        \u002F\u002F specific\n\n\u002F\u002F Start an event-driven monitor session (headless)\ninteractive_shell({\n  command: 'npm test --watch',\n  mode: \"monitor\",\n  monitor: { strategy: \"stream\", triggers: [{ id: \"failed\", literal: \"FAIL\" }] }\n})\n```\n\n## Local Testing Hygiene\n\nWhen using `interactive_shell` for one-off local testing, do **not** leave sessions running in the background unless the user explicitly wants them kept alive. A stack of background sessions in the widget usually means the agent used backgrounding as an escape hatch and never cleaned up.\n\nBest practice:\n- Prefer `kill: true` or normal process exit for finite test runs.\n- Only background a session if you expect to come back to it soon or the user asked to keep it.\n- Before ending the task, sweep background sessions created for testing.\n- Keep background sessions only for intentional long-lived work like dev servers, watchers, or manual validation the user is actively using.\n\nTypical cleanup flow:\n\n```typescript\n\u002F\u002F Inspect what is still running\ninteractive_shell({ listBackground: true })\n\n\u002F\u002F Dismiss a specific leftover test session\ninteractive_shell({ dismissBackground: \"keen-cove\" })\n\n\u002F\u002F Or, if the background sessions were just temporary test artifacts from this task,\n\u002F\u002F dismiss all of them in one sweep\ninteractive_shell({ dismissBackground: true })\n```\n\nTo kill all backgrounded interactive shell sessions and their processes in one sweep, use `interactive_shell({ dismissBackground: true })`.\n\nDecision rule:\n- **One-off test \u002F repro \u002F validation run** → kill or dismiss it when done.\n- **Dev server \u002F watch mode \u002F ongoing manual check** → background only if the user wants it preserved.\n\nIf the user backgrounds a session manually with `Ctrl+B`, the agent should still clean it up later unless the user clearly wants it kept.\n\n## Quick Reference\n\n**Dispatch subagent (fire-and-forget, default to pi):**\n```typescript\ninteractive_shell({\n  command: 'pi \"Implement the feature described in SPEC.md\"',\n  mode: \"dispatch\",\n  reason: \"Implementing feature\"\n})\n\u002F\u002F Returns immediately. You'll be notified when done.\n```\n\n**Background dispatch (headless, no overlay):**\n```typescript\ninteractive_shell({\n  command: 'pi \"Fix lint errors\"',\n  mode: \"dispatch\",\n  background: true,\n  reason: \"Fixing lint\"\n})\n```\n\n**Monitor watcher (event-driven, no polling):**\n```typescript\ninteractive_shell({\n  command: 'npm run dev',\n  mode: \"monitor\",\n  monitor: {\n    strategy: \"stream\",\n    triggers: [{ id: \"warn\", regex: \"\u002Ferror|warn\u002Fi\" }],\n    persistence: { stopAfterFirstEvent: false }\n  },\n  reason: \"Wake me on server warnings\"\n})\n```\n\n**Start foreground subagent (hands-free, default to pi):**\n```typescript\ninteractive_shell({\n  command: 'pi \"Implement the feature described in SPEC.md\"',\n  mode: \"hands-free\",\n  reason: \"Implementing feature\"\n})\n\u002F\u002F Returns sessionId in updates, e.g., \"shell-1\"\n```\n\n**Send input to active session:**\n```typescript\n\u002F\u002F Text with enter\ninteractive_shell({ sessionId: \"calm-reef\", input: \"\u002Fcompact\", submit: true })\n\n\u002F\u002F Text + named keys\ninteractive_shell({ sessionId: \"calm-reef\", input: \"\u002Fmodel\", inputKeys: [\"enter\"] })\n\n\u002F\u002F Menu navigation\ninteractive_shell({ sessionId: \"calm-reef\", inputKeys: [\"down\", \"down\", \"enter\"] })\n```\n\n**Change update frequency:**\n```typescript\ninteractive_shell({ sessionId: \"calm-reef\", settings: { updateInterval: 60000 } })\n```\n\n**Foreground subagent (user requested different agent):**\n```typescript\ninteractive_shell({\n  command: 'claude \"Review this code for security issues\"',\n  mode: \"hands-free\",\n  reason: \"Security review with Claude\"\n})\n```\n\n**Background subagent:**\n```typescript\nsubagent({ agent: \"scout\", task: \"Find all TODO comments\" })\n```\n","# Interactive Shell (Skill)\n\n## Deferred activation\n\nWhen `interactive_shell` is unavailable, call `enable_interactive_shell` first. The tool becomes callable on the next turn and stays active until Pi reloads or the session changes; reloaded, new, resumed, and forked sessions reset it to inactive. Do not call the loader when `interactive_shell` is already available.\n\nUsers opt in with `\"defer\": true` in `interactive-shell.json`. Older Pi versions without active-tool APIs warn and keep eager loading. A CLI `--tools` allowlist must include both `enable_interactive_shell` and `interactive_shell`.\n\n## Foreground vs Background Subagents\n\nPi has two ways to delegate work to other AI coding agents:\n\n| | Foreground Subagents | Dispatch Subagents | Background Subagents |\n|---|---|---|---|\n| **Tool** | `interactive_shell` | `interactive_shell` (dispatch) | `subagent` |\n| **Visibility** | User sees overlay | User sees overlay (or headless) | Hidden from user |\n| **Agent model** | Polls for status | Notified on completion | Full output captured |\n| **Default agent** | `pi` (others if user requests) | `pi` (others if user requests) | Pi only |\n| **User control** | Can take over anytime | Can take over anytime | No intervention |\n| **Best for** | Long tasks needing supervision | Fire-and-forget delegations | Parallel tasks, structured delegation |\n\n**Foreground subagents** run in an overlay where the user watches and can intervene. Use `interactive_shell` with `mode: \"interactive\"` when the agent or user will drive the shell by session id, `mode: \"hands-free\"` to monitor while receiving periodic updates, or `mode: \"dispatch\"` to be notified on completion without polling.\n\n**Dispatch subagents** also use `interactive_shell` but with `mode: \"dispatch\"`. The agent fires the session and moves on. When the session completes, the agent is woken up via `triggerTurn` with the output in context. Add `background: true` for headless execution (no overlay).\n\n**Monitor mode** (`mode: \"monitor\"`) runs headless and event-driven. It wakes the agent on structured monitor trigger events (stream or poll-diff), so there is no polling loop.\n\n**Background subagents** run invisibly via the `subagent` tool. Pi-only, but captures full output and supports parallel execution.\n\n## When to Use Foreground Subagents\n\nUse `interactive_shell` (foreground) when:\n- The task is **long-running** and the user should see progress\n- The user might want to **intervene or guide** the agent\n- You want **hands-free monitoring** with periodic status updates\n- You need a **different agent's capabilities** (only if user specifies)\n\nUse `subagent` (background) when:\n- You need **parallel execution** of multiple tasks\n- You want **full output capture** for processing\n- The task is **quick and deterministic**\n- User doesn't need to see the work happening\n\n### Default Agent Choice\n\n**Default to `pi`** for foreground subagents unless the user explicitly requests a different agent:\n\n| User says | Agent to use |\n|-----------|--------------|\n| \"Run this in hands-free\" | `pi` |\n| \"Delegate this task\" | `pi` |\n| \"Use Claude to review this\" | `claude` |\n| \"Have Gemini analyze this\" | `gemini` |\n| \"Run aider to fix this\" | `aider` |\n\nPi is the default because it's already available, has the same capabilities, and maintains consistency. Only use Claude, Gemini, Codex, or other agents when the user specifically asks for them.\n\n## Structured Spawn and `\u002Fspawn`\n\nFor Pi, Codex, Claude, and Cursor, prefer structured `spawn` params when you want the extension's shared resolver, config defaults, native startup prompt forms, or Pi-only fork\u002Fworktree behavior. For unattended coding-agent work in a repository, use `worktree: true` or an explicitly isolated `cwd`; raw commands run in their supplied working directory and can change its Git state:\n\n```typescript\ninteractive_shell({ spawn: { agent: \"pi\" }, mode: \"interactive\" })\ninteractive_shell({ spawn: { agent: \"codex\" }, mode: \"dispatch\" })\ninteractive_shell({ spawn: { agent: \"cursor\", prompt: \"Review the diffs\" }, mode: \"dispatch\" })\ninteractive_shell({ spawn: { agent: \"claude\", prompt: \"Review the diffs\" }, mode: \"dispatch\" })\ninteractive_shell({ spawn: { agent: \"claude\", worktree: true }, mode: \"hands-free\" })\ninteractive_shell({ spawn: { mode: \"fork\" }, mode: \"interactive\" }) \u002F\u002F Pi-only\n```\n\nStructured `spawn` uses the same resolver and defaults as the user-facing `\u002Fspawn` command. Raw `command` is still the right choice for arbitrary CLIs and custom launch strings. Users can add their own agents under `spawn.commands`; those keys work in `spawn: { agent: \"...\" }` just like the built-ins, and an unknown key returns the configured agent list as an error. Cursor structured spawn defaults to `--model composer-2-fast`, which explicitly selects Composer 2 Fast.\n\nFor Codex image or design work, Codex can invoke `gpt-image-2` directly from the prompt. Natural language is usually enough, and `$imagegen` forces the image-generation tool when you need it. Attach references with `-i` for edits and iterations. See the bundled `codex-cli` skill for concrete examples.\n\nFor users in chat, `\u002Fspawn` now supports the configured default agent plus explicit overrides like `\u002Fspawn codex`, `\u002Fspawn cursor`, `\u002Fspawn claude`, `\u002Fspawn pi`, `\u002Fspawn fork`, `\u002Fspawn pi fork`, and any custom agent key from `spawn.commands`. Add `--worktree` to run in a separate git worktree.\n\nQuoted prompt text plus `--hands-free` or `--dispatch` turns `\u002Fspawn` into a monitored delegated run instead of a plain interactive overlay:\n\n```bash\n\u002Fspawn cursor \"review the diffs\" --dispatch\n\u002Fspawn claude \"review the diffs\" --dispatch\n\u002Fspawn codex \"fix the failing tests\" --hands-free\n\u002Fspawn pi fork \"continue from here\" --dispatch\n```\n\n## Foreground Subagent Modes\n\n### Interactive (default)\nThe overlay opens and returns a stable `sessionId` immediately. The user can type directly, and the agent can send input to the same shell.\n```typescript\nconst { sessionId } = interactive_shell({ command: 'pi' })\ninteractive_shell({ sessionId, input: '\u002Fhelp', submit: true })\n```\n\n### Interactive with Initial Prompt\nAgent starts working immediately, user supervises.\n```typescript\ninteractive_shell({ command: 'pi \"Review this codebase for security issues\"' })\n```\n\n### Dispatch (Fire-and-Forget) - NON-BLOCKING, NO POLLING\nAgent fires a session and moves on. Notified automatically on completion via `triggerTurn`.\n\n```typescript\n\u002F\u002F Start session - returns immediately, no polling needed\ninteractive_shell({\n  command: 'pi \"Fix all TypeScript errors in src\u002F\"',\n  mode: \"dispatch\",\n  reason: \"Fixing TS errors\"\n})\n\u002F\u002F Returns: { sessionId: \"calm-reef\", mode: \"dispatch\" }\n\u002F\u002F → Do other work. When session completes, you receive notification with output.\n```\n\nDispatch defaults `autoExitOnQuiet: true`. A quiet TUI auto-closes after the threshold and reports `completionReason: \"auto-close-quiet\"` separately from a user kill. This is not a terminal command verdict. The agent can still query the sessionId if needed, but doesn't have to.\n\nFor a provider-agnostic external gate watcher, use `mode: \"monitor\"`, set `handsFree: { autoExitOnQuiet: false }`, set a hard `timeout`, and match explicit terminal lines such as `ready`, `blocked`, and `stale-head`. The watcher command must exit only after it emits a terminal line. If raw dispatch is required, disable quiet auto-close and treat `completionReason: \"auto-close-quiet\"` as non-terminal.\n\nFor fire-and-forget delegated runs (including QA-style delegated checks), prefer dispatch as the default mode.\n\n#### Background Dispatch (Headless)\nNo overlay opens. Multiple headless dispatches can run concurrently:\n\n```typescript\ninteractive_shell({\n  command: 'pi \"Fix lint errors\"',\n  mode: \"dispatch\",\n  background: true\n})\n\u002F\u002F → No overlay. User can \u002Fattach to watch. Agent notified on completion.\n```\n\n### Monitor (Event-Driven, Headless)\nRun a background process and wake the agent on structured monitor triggers.\n\n```typescript\ninteractive_shell({\n  command: 'npm test --watch',\n  mode: \"monitor\",\n  monitor: {\n    strategy: \"stream\",\n    triggers: [\n      { id: \"failed\", literal: \"FAIL\" },\n      { id: \"error\", regex: \"\u002Ferror|warn\u002Fi\" }\n    ],\n    throttle: { dedupeExactLine: true }\n  }\n})\n\ninteractive_shell({\n  command: 'curl -sf http:\u002F\u002Flocalhost:3000\u002Fhealth',\n  mode: \"monitor\",\n  monitor: {\n    strategy: \"poll-diff\",\n    triggers: [{ id: \"changed\", regex: \"\u002F.\u002F\" }],\n    poll: { intervalMs: 5000 }\n  }\n})\n```\n\nUse monitor mode for log watchers and long-running checks where polling would be noisy or expensive.\n\n### Hands-Free (Foreground Subagent) - NON-BLOCKING\nAgent works autonomously, **returns immediately** with sessionId. You query for status\u002Foutput and kill when done.\n\n```typescript\n\u002F\u002F 1. Start session - returns immediately\ninteractive_shell({\n  command: 'pi \"Fix all TypeScript errors in src\u002F\"',\n  mode: \"hands-free\",\n  reason: \"Fixing TS errors\"\n})\n\u002F\u002F Returns: { sessionId: \"calm-reef\", status: \"running\" }\n\n\u002F\u002F 2. Check status and get new output\ninteractive_shell({ sessionId: \"calm-reef\" })\n\u002F\u002F Returns: { status: \"running\", output: \"...\", runtime: 30000 }\n\n\u002F\u002F 3. When you see task is complete, kill session\ninteractive_shell({ sessionId: \"calm-reef\", kill: true })\n\u002F\u002F Returns: { status: \"killed\", output: \"final output...\" }\n```\n\nThis is the primary pattern for **foreground subagents** - you delegate to pi (or another agent), query for progress, and decide when the task is done.\n\n## Hands-Free Workflow\n\n### Starting a Session\n```typescript\nconst result = interactive_shell({\n  command: 'codex \"Review this codebase\"',\n  mode: \"hands-free\"\n})\n\u002F\u002F result.details.sessionId = \"calm-reef\"\n\u002F\u002F result.details.status = \"running\"\n```\n\nThe user sees the overlay immediately. You get control back to continue working. If the user types to take over a monitored hands-free or dispatch session, they can press `Ctrl+G` to return control to the agent.\n\n### Querying Status\n```typescript\ninteractive_shell({ sessionId: \"calm-reef\" })\n```\n\nReturns:\n- `status`: \"running\" | \"monitoring\" | \"user-takeover\" | \"exited\" | \"killed\" | \"backgrounded\"\n- `output`: Last 20 lines of rendered terminal (clean, no TUI animation noise)\n- `runtime`: Time elapsed in ms\n\n**Rate limited:** Queries are limited to once every 60 seconds. If you query too soon, the tool will automatically wait until the limit expires before returning. The user is watching the overlay in real-time - you're just checking in periodically.\n\n### Ending a Session\n```typescript\ninteractive_shell({ sessionId: \"calm-reef\", kill: true })\n```\n\nKill when you see the task is complete in the output. Returns final status and output.\n\n### Fire-and-Forget Tasks\n\nFor single-task delegations where you don't need multi-turn interaction, enable auto-exit so the session kills itself when the agent goes quiet:\n\n```typescript\ninteractive_shell({\n  command: 'pi \"Review this codebase for security issues. Save your findings to \u002Ftmp\u002Fsecurity-review.md\"',\n  mode: \"hands-free\",\n  reason: \"Security review\",\n  handsFree: { autoExitOnQuiet: true }\n})\n\u002F\u002F Session auto-kills after ~8s of quiet (after the startup grace period)\n\u002F\u002F Read results from file:\n\u002F\u002F read(\"\u002Ftmp\u002Fsecurity-review.md\")\n```\n\n**Instruct subagent to save results to a file** since the session closes automatically.\n\n### Multi-Turn Sessions (default)\n\nFor back-and-forth interaction, leave auto-exit disabled (the default). Query status and kill manually when done:\n\n```typescript\ninteractive_shell({\n  spawn: { agent: \"cursor\" },\n  mode: \"hands-free\",\n  reason: \"Interactive refactoring\"\n})\n\n\u002F\u002F Send follow-up prompts\ninteractive_shell({ sessionId: \"calm-reef\", input: \"Now fix the tests\", submit: true })\n\n\u002F\u002F Kill when done\ninteractive_shell({ sessionId: \"calm-reef\", kill: true })\n```\n\n### Sending Input\n```typescript\ninteractive_shell({ sessionId: \"calm-reef\", input: \"\u002Fhelp\", submit: true })\ninteractive_shell({ sessionId: \"calm-reef\", inputKeys: [\"ctrl+c\"] })\ninteractive_shell({ sessionId: \"calm-reef\", inputPaste: \"multi\\nline\\ncode\" })\ninteractive_shell({ sessionId: \"calm-reef\", input: \"y\", inputKeys: [\"enter\"] })  \u002F\u002F combine text + keys\n```\n\n### Query Output\n\nStatus queries return **rendered terminal output** (what's actually on screen), not raw stream:\n- Default: 20 lines, 5KB max per query\n- No TUI animation noise (spinners, progress bars, etc.)\n- Configurable via `outputLines` (max: 200) and `outputMaxChars` (max: 50KB)\n\n```typescript\n\u002F\u002F Get more output when reviewing a session\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50 })\n\n\u002F\u002F Get even more for detailed review\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 100, outputMaxChars: 30000 })\n```\n\n### Incremental Reading\n\nUse `incremental: true` to paginate through output without re-reading:\n\n```typescript\n\u002F\u002F First call: get first 50 lines\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50, incremental: true })\n\u002F\u002F → { output: \"...\", hasMore: true }\n\n\u002F\u002F Next call: get next 50 lines (server tracks position)\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50, incremental: true })\n\u002F\u002F → { output: \"...\", hasMore: true }\n\n\u002F\u002F Keep calling until hasMore: false\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50, incremental: true })\n\u002F\u002F → { output: \"...\", hasMore: false }\n```\n\nThe server tracks your read position - just keep calling with `incremental: true` to get the next chunk.\n\n### Reviewing Output\n\nQuery sessions to see progress. Increase limits when you need more context:\n\n```typescript\n\u002F\u002F Default: last 20 lines\ninteractive_shell({ sessionId: \"calm-reef\" })\n\n\u002F\u002F Get more lines when you need more context\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 50 })\n\n\u002F\u002F Get even more for detailed review\ninteractive_shell({ sessionId: \"calm-reef\", outputLines: 100, outputMaxChars: 30000 })\n```\n\n## Sending Input to Active Sessions\n\nUse the `sessionId` from updates to send input to a running hands-free session:\n\n### Basic Input\n```typescript\n\u002F\u002F Send text and submit it\ninteractive_shell({ sessionId: \"shell-1\", input: \"\u002Fhelp\", submit: true })\n\n\u002F\u002F Send text with keys\ninteractive_shell({ sessionId: \"shell-1\", input: \"\u002Fmodel\", inputKeys: [\"enter\"] })\n\n\u002F\u002F Navigate menus\ninteractive_shell({ sessionId: \"shell-1\", inputKeys: [\"down\", \"down\", \"enter\"] })\n\n\u002F\u002F Interrupt\ninteractive_shell({ sessionId: \"shell-1\", inputKeys: [\"ctrl+c\"] })\n```\n\n### Named Keys\n| Key | Description |\n|-----|-------------|\n| `up`, `down`, `left`, `right` | Arrow keys |\n| `enter`, `return` | Enter\u002FReturn |\n| `escape`, `esc` | Escape |\n| `tab`, `shift+tab` (or `btab`) | Tab \u002F Back-tab |\n| `backspace`, `bspace` | Backspace |\n| `delete`, `del`, `dc` | Delete |\n| `insert`, `ic` | Insert |\n| `home`, `end` | Home\u002FEnd |\n| `pageup`, `pgup`, `ppage` | Page Up |\n| `pagedown`, `pgdn`, `npage` | Page Down |\n| `f1`-`f12` | Function keys |\n| `kp0`-`kp9`, `kp\u002F`, `kp*`, `kp-`, `kp+`, `kp.`, `kpenter` | Keypad keys |\n| `ctrl+c`, `ctrl+d`, `ctrl+z` | Control sequences |\n| `ctrl+a` through `ctrl+z` | All control keys |\n\nNote: `ic`\u002F`dc`, `ppage`\u002F`npage`, `bspace` are tmux-style aliases for compatibility.\n\n### Modifier Combinations\nSupports `ctrl+`, `alt+`, `shift+` prefixes (or shorthand `c-`, `m-`, `s-`):\n```typescript\n\u002F\u002F Cancel\ninputKeys: [\"ctrl+c\"]\n\n\u002F\u002F Alt+Tab\ninputKeys: [\"alt+tab\"]\n\n\u002F\u002F Ctrl+Alt+Delete\ninputKeys: [\"ctrl+alt+delete\"]\n\n\u002F\u002F Shorthand syntax\ninputKeys: [\"c-c\", \"m-x\", \"s-tab\"]\n```\n\n### Hex Bytes (Advanced)\nSend raw escape sequences:\n```typescript\ninputHex: [\"0x1b\", \"0x5b\", \"0x41\"]  \u002F\u002F ESC[A (up arrow)\n```\n\n### Bracketed Paste\nPaste multiline text without triggering autocompletion\u002Fexecution:\n```typescript\ninputPaste: \"function foo() {\\n  return 42;\\n}\"\n```\n\n### Model Selection Example\n```typescript\n\u002F\u002F Step 1: Open model selector\ninteractive_shell({ sessionId: \"shell-1\", input: \"\u002Fmodel\", inputKeys: [\"enter\"] })\n\n\u002F\u002F Step 2: Filter and select (after ~500ms delay)\ninteractive_shell({ sessionId: \"shell-1\", input: \"sonnet\", inputKeys: [\"enter\"] })\n\n\u002F\u002F Or navigate with arrows:\ninteractive_shell({ sessionId: \"shell-1\", inputKeys: [\"down\", \"down\", \"down\", \"enter\"] })\n```\n\n### Context Compaction\n```typescript\ninteractive_shell({ sessionId: \"shell-1\", input: \"\u002Fcompact\", submit: true })\n```\n\nFor editor-based TUIs like pi, raw `input` only types text. It does not submit the prompt. Prefer `submit: true` or `inputKeys: [\"enter\"]` instead of relying on `\\n`.\n\n### Changing Update Settings\nAdjust timing during a session:\n```typescript\n\u002F\u002F Change max interval (fallback for on-quiet mode)\ninteractive_shell({ sessionId: \"calm-reef\", settings: { updateInterval: 120000 } })\n\n\u002F\u002F Change quiet threshold (how long to wait after output stops)\ninteractive_shell({ sessionId: \"calm-reef\", settings: { quietThreshold: 3000 } })\n\n\u002F\u002F Both at once\ninteractive_shell({ sessionId: \"calm-reef\", settings: { updateInterval: 30000, quietThreshold: 2000 } })\n```\n\n## CLI Quick Reference\n\n| Agent | Interactive | With Prompt | Headless (bash) | Dispatch |\n|-------|-------------|-------------|-----------------|----------|\n| `claude` | `claude` | `claude \"prompt\"` | `claude -p \"prompt\"` | `mode: \"dispatch\"` |\n| `gemini` | `gemini` | `gemini -i \"prompt\"` | `gemini \"prompt\"` | `mode: \"dispatch\"` |\n| `codex` | `codex` | `codex \"prompt\"` | `codex exec \"prompt\"` | `mode: \"dispatch\"` |\n| `agent` | `agent` | `agent \"prompt\"` | `agent -p \"prompt\"` | `mode: \"dispatch\"` |\n| `pi` | `pi` | `pi \"prompt\"` | `pi -p \"prompt\"` | `mode: \"dispatch\"` |\n\n**Gemini model:** `gemini -m gemini-3-flash-preview -i \"prompt\"`\n\n## Prompt Packaging Rules\n\nThe `reason` parameter is **UI-only** - it's shown in the overlay header but NOT passed to the subprocess.\n\nTo give the agent an initial prompt, embed it in the `command`:\n```typescript\n\u002F\u002F WRONG - agent starts idle, reason is just UI text\ninteractive_shell({ command: 'claude', reason: 'Review the codebase' })\n\n\u002F\u002F RIGHT - agent receives the prompt\ninteractive_shell({ command: 'claude \"Review the codebase\"', reason: 'Code review' })\n```\n\n## Handoff Options\n\n### Transfer (Ctrl+T) - Recommended\nWhen the subagent finishes, the user presses **Ctrl+T** to transfer output directly to you:\n\n```\n[Subagent finishes work in overlay]\n        ↓\n[User presses Ctrl+T]\n        ↓\n[You receive: \"Session output transferred (150 lines):\n  \n  Completing skill integration...\n  Modified files:\n  - skills.ts\n  - agents\u002Ftypes\u002F...\"]\n```\n\nThis is the cleanest workflow - the subagent's response becomes your context automatically.\n\n**Configuration:** `transferLines` (default: 200), `transferMaxChars` (default: 20KB)\n\n### Tail Preview (default)\nLast 30 lines included in tool result. Good for seeing errors\u002Ffinal status.\n\n### Snapshot to File\nWrite full transcript to `~\u002F.pi\u002Fagent\u002Fcache\u002Finteractive-shell\u002Fsnapshot-*.log`:\n```typescript\ninteractive_shell({\n  command: 'claude \"Fix bugs\"',\n  handoffSnapshot: { enabled: true, lines: 200 }\n})\n```\n\n### Artifact Handoff (for complex tasks)\nInstruct the delegated agent to write a handoff file:\n```\nWrite your findings to .pi\u002Fdelegation\u002Fclaude-handoff.md including:\n- What you did\n- Files changed\n- Any errors\n- Next steps for the main agent\n```\n\n## Safe TUI Capture\n\n**Never run TUI agents via bash** - they hang even with `--help`. Use `interactive_shell` with `timeout` instead:\n\n```typescript\ninteractive_shell({\n  command: \"pi --help\",\n  mode: \"hands-free\",\n  timeout: 5000  \u002F\u002F Auto-kill after 5 seconds\n})\n```\n\nThe process is killed after timeout and captured output is returned in the handoff preview. This is useful for:\n- Getting CLI help from TUI applications\n- Capturing output from commands that don't exit cleanly\n- Any TUI command where you need quick output without user interaction\n\nFor pi CLI documentation, you can also read directly: `\u002Fopt\u002Fhomebrew\u002Flib\u002Fnode_modules\u002F@earendil-works\u002Fpi-coding-agent\u002FREADME.md`\n\n## Background Session Management\n\n```typescript\n\u002F\u002F Background an active session (close overlay, keep running)\ninteractive_shell({ sessionId: \"calm-reef\", background: true })\n\n\u002F\u002F List all background sessions\ninteractive_shell({ listBackground: true })\n\n\u002F\u002F Reattach to a background session\ninteractive_shell({ attach: \"calm-reef\" })                    \u002F\u002F interactive (blocking)\ninteractive_shell({ attach: \"calm-reef\", mode: \"hands-free\" })  \u002F\u002F hands-free (poll)\ninteractive_shell({ attach: \"calm-reef\", mode: \"dispatch\" })    \u002F\u002F dispatch (notified)\n\n\u002F\u002F Dismiss background sessions (kill running, remove exited)\ninteractive_shell({ dismissBackground: true })               \u002F\u002F all\ninteractive_shell({ dismissBackground: \"calm-reef\" })        \u002F\u002F specific\n\n\u002F\u002F Start an event-driven monitor session (headless)\ninteractive_shell({\n  command: 'npm test --watch',\n  mode: \"monitor\",\n  monitor: { strategy: \"stream\", triggers: [{ id: \"failed\", literal: \"FAIL\" }] }\n})\n```\n\n## Local Testing Hygiene\n\nWhen using `interactive_shell` for one-off local testing, do **not** leave sessions running in the background unless the user explicitly wants them kept alive. A stack of background sessions in the widget usually means the agent used backgrounding as an escape hatch and never cleaned up.\n\nBest practice:\n- Prefer `kill: true` or normal process exit for finite test runs.\n- Only background a session if you expect to come back to it soon or the user asked to keep it.\n- Before ending the task, sweep background sessions created for testing.\n- Keep background sessions only for intentional long-lived work like dev servers, watchers, or manual validation the user is actively using.\n\nTypical cleanup flow:\n\n```typescript\n\u002F\u002F Inspect what is still running\ninteractive_shell({ listBackground: true })\n\n\u002F\u002F Dismiss a specific leftover test session\ninteractive_shell({ dismissBackground: \"keen-cove\" })\n\n\u002F\u002F Or, if the background sessions were just temporary test artifacts from this task,\n\u002F\u002F dismiss all of them in one sweep\ninteractive_shell({ dismissBackground: true })\n```\n\nTo kill all backgrounded interactive shell sessions and their processes in one sweep, use `interactive_shell({ dismissBackground: true })`.\n\nDecision rule:\n- **One-off test \u002F repro \u002F validation run** → kill or dismiss it when done.\n- **Dev server \u002F watch mode \u002F ongoing manual check** → background only if the user wants it preserved.\n\nIf the user backgrounds a session manually with `Ctrl+B`, the agent should still clean it up later unless the user clearly wants it kept.\n\n## Quick Reference\n\n**Dispatch subagent (fire-and-forget, default to pi):**\n```typescript\ninteractive_shell({\n  command: 'pi \"Implement the feature described in SPEC.md\"',\n  mode: \"dispatch\",\n  reason: \"Implementing feature\"\n})\n\u002F\u002F Returns immediately. You'll be notified when done.\n```\n\n**Background dispatch (headless, no overlay):**\n```typescript\ninteractive_shell({\n  command: 'pi \"Fix lint errors\"',\n  mode: \"dispatch\",\n  background: true,\n  reason: \"Fixing lint\"\n})\n```\n\n**Monitor watcher (event-driven, no polling):**\n```typescript\ninteractive_shell({\n  command: 'npm run dev',\n  mode: \"monitor\",\n  monitor: {\n    strategy: \"stream\",\n    triggers: [{ id: \"warn\", regex: \"\u002Ferror|warn\u002Fi\" }],\n    persistence: { stopAfterFirstEvent: false }\n  },\n  reason: \"Wake me on server warnings\"\n})\n```\n\n**Start foreground subagent (hands-free, default to pi):**\n```typescript\ninteractive_shell({\n  command: 'pi \"Implement the feature described in SPEC.md\"',\n  mode: \"hands-free\",\n  reason: \"Implementing feature\"\n})\n\u002F\u002F Returns sessionId in updates, e.g., \"shell-1\"\n```\n\n**Send input to active session:**\n```typescript\n\u002F\u002F Text with enter\ninteractive_shell({ sessionId: \"calm-reef\", input: \"\u002Fcompact\", submit: true })\n\n\u002F\u002F Text + named keys\ninteractive_shell({ sessionId: \"calm-reef\", input: \"\u002Fmodel\", inputKeys: [\"enter\"] })\n\n\u002F\u002F Menu navigation\ninteractive_shell({ sessionId: \"calm-reef\", inputKeys: [\"down\", \"down\", \"enter\"] })\n```\n\n**Change update frequency:**\n```typescript\ninteractive_shell({ sessionId: \"calm-reef\", settings: { updateInterval: 60000 } })\n```\n\n**Foreground subagent (user requested different agent):**\n```typescript\ninteractive_shell({\n  command: 'claude \"Review this code for security issues\"',\n  mode: \"hands-free\",\n  reason: \"Security review with Claude\"\n})\n```\n\n**Background subagent:**\n```typescript\nsubagent({ agent: \"scout\", task: \"Find all TODO comments\" })\n```\n",{"name":5,"description":7},"main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","05-技能与代理开发\u002Fpi-interactive-shell",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill pi-interactive-shell",{"tool":38,"command":39},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill pi-interactive-shell",{"tool":41,"command":42},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill pi-interactive-shell","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F05-技能与代理开发\u002Fpi-interactive-shell\u002FSKILL.md",true,[],[47,54,59,66,73,80],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":55,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]