{"id":"c69f7942-ebd2-42df-9e75-df6fc9e144ec","entityType":"agent","slug":"nicobailon-pi-foreground-chains","name":"foreground-chains","canonicalUrl":"https://www.xpersona.co/agent/nicobailon-pi-foreground-chains","canonicalPath":"/agent/nicobailon-pi-foreground-chains","generatedAt":"2026-10-09T13:52:13.290Z","source":"GITHUB_OPENCLEW","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-04-15T05:21:22.124Z","emptyReason":null},"description":"Orchestrate multi-agent workflows where users watch each step in the overlay. Uses different CLI agents (cursor, pi, codex) for specialized roles with file-based handoff and auto-continue support for agents that pause mid-task. --- name: foreground-chains description: Orchestrate multi-agent workflows where users watch each step in the overlay. Uses different CLI agents (cursor, pi, codex) for specialized roles with file-based handoff and auto-continue support for agents that pause mid-task. --- Foreground Agent Chains Run multi-step agent workflows with full user visibility. Each step runs in an overlay where the user watches and can inter","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 31 GitHub stars reported by the source. Last updated 4/15/2026.","installCommand":"git clone https://github.com/nicobailon/pi-foreground-chains.git","sourceUrl":"https://github.com/nicobailon/pi-foreground-chains","homepage":null,"primaryLinks":[{"label":"View Source","url":"https://github.com/nicobailon/pi-foreground-chains","kind":"source"}],"safetyScore":100,"overallRank":38.2,"popularityScore":38,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Orchestrate multi-agent workflows where users watch each step in the overlay. Uses different CLI agents (cursor, pi, codex) for specialized roles with file-base"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-04-15T05:21:22.124Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[{"label":"intervene","status":"self-declared"},{"label":"read","status":"self-declared"},{"label":"still","status":"self-declared"},{"label":"be","status":"self-declared"},{"label":"auto","status":"self-declared"}],"verifiedCount":0,"selfDeclaredCount":6,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"},{"key":"intervene","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"read","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"still","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"be","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"},{"key":"auto","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile capability:intervene|supported|profile capability:read|supported|profile capability:still|supported|profile capability:be|supported|profile capability:auto|supported|profile"}},"adoption":{"evidence":{"source":"GITHUB OPENCLEW","verified":false,"confidence":"medium","updatedAt":"2026-04-15T05:21:22.124Z","emptyReason":null},"stars":31,"forks":4,"downloads":null,"packageName":null,"latestVersion":null,"tractionLabel":"31 GitHub stars"},"release":{"evidence":{"source":"agent-index","verified":false,"confidence":"medium","updatedAt":"2026-04-15T03:16:24.483Z","emptyReason":null},"lastUpdatedAt":"2026-04-15T05:21:22.124Z","lastCrawledAt":"2026-04-15T03:16:24.483Z","lastIndexedAt":null,"nextCrawlAt":"2026-04-16T03:16:24.483Z","lastVerifiedAt":null,"highlights":[]},"execution":{"evidence":{"source":"GITHUB OPENCLEW","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"git clone https://github.com/nicobailon/pi-foreground-chains.git","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"GITHUB_OPENCLEW","generatedAt":"2026-10-09T13:52:13.290Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/nicobailon-pi-foreground-chains/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"GITHUB OPENCLEW","verified":false,"confidence":"high","updatedAt":"2026-04-15T05:21:22.124Z","emptyReason":null},"readme":"---\nname: foreground-chains\ndescription: Orchestrate multi-agent workflows where users watch each step in the overlay. Uses different CLI agents (cursor, pi, codex) for specialized roles with file-based handoff and auto-continue support for agents that pause mid-task.\n---\n\n# Foreground Agent Chains\n\nRun multi-step agent workflows with full user visibility. Each step runs in an overlay where the user watches and can intervene. Uses file-based handoff through a shared chain directory.\n\n## Agent Roles\n\n| Role | CLI | Model | Purpose |\n|------|-----|-------|---------|\n| **Scout** | `agent` (cursor) | (default) | Fast codebase scanning, context gathering |\n| **Planner** | `pi` | claude-sonnet-4-5 | Strategic planning, task breakdown |\n| **Worker** | `codex` | (default) | Implementation, code changes |\n| **Reviewer** | `pi` | claude-sonnet-4-5 | Validates implementation, fixes issues |\n\n*Adjust models based on availability and task complexity. Use `pi --list-models` to see available options.*\n\n## Architecture\n\n```\nScout ──► context.md ──► Planner ──► plan.md ──► Worker ──► impl.md ──► Reviewer\n  │                          │                      │                       │\n  │ gathers code +           │ head start,          │ auto-continue         │ validates +\n  │ meta-prompt              │ can read more        │ for \"Should I...\"     │ fixes issues\n  │                          │                      │                       │\n  └──────────────────────────┴──────────────────────┴───────────────────────┤\n                                                                            ▼\n                                                                      progress.md\n                                                                    (all agents append)\n                                                                            │\n                                                                            ▼\n                                                                      Main Agent\n                                                                    (reads at chain end)\n```\n\n## CLI Commands\n\n```bash\n# Scout (cursor-agent)\nagent \"prompt\"\n\n# Planner (pi)\npi --model claude-sonnet-4-5 \"prompt\"\n\n# Worker (codex)\ncodex \"prompt\"\n\n# Reviewer (pi)\npi --model claude-sonnet-4-5 \"prompt\"\n```\n\n## Chain Directory Structure\n\n```\n/tmp/pi-chain-runs/{runId}/\n├── progress.md     # Running log - ALL agents append to this\n├── context.md      # Scout → Planner handoff\n├── plan.md         # Planner → Worker handoff\n└── impl.md         # Worker → Reviewer handoff\n```\n\n**Handoff files**: Structured output passed to the next agent.\n\n**progress.md**: Running log that every agent appends to. Main agent reads this at the end for the complete chain story.\n\n## Step 1: Scout\n\nFast codebase recon that gathers relevant code so the planner gets a head start and spends less time reading files.\n\n```typescript\nconst runId = Date.now().toString(36);\nconst chainDir = `/tmp/pi-chain-runs/${runId}`;\n\n// Create chain directory\nbash({ command: `mkdir -p ${chainDir}` })\n\n// Start scout\ninteractive_shell({\n  command: `agent \"You are a scout. The user wants: ${task}\n\nYour job: Gather all relevant code into context.md so the planner gets a head start and spends less time reading files.\n\nStrategy:\n1. grep/find to locate relevant code\n2. Read key sections (not entire files)  \n3. Stuff actual code snippets into context.md\n4. Note how pieces connect\n\nSave to ${chainDir}/context.md:\n\n# Code Context\n\n## User Intent\nRestate what the user wants in your own words.\n\n## Files Retrieved\nList with exact line ranges:\n1. \\`path/to/file.ts\\` (lines 10-50) - Description\n2. \\`path/to/other.ts\\` (lines 100-150) - Description\n\n## Key Code\nThe actual code snippets from those files. Include complete types, interfaces, functions - everything the planner needs to see. This is the main payload.\n\n## Architecture\nBrief explanation of how the pieces connect. Dependencies between files.\n\n## Planning Guidance\nSynthesize the user's intent with your codebase findings:\n- What approach makes sense given the existing architecture?\n- Which files need modification and in what order?\n- What patterns should the implementation follow?\n- Risks or edge cases to address?\n\nThis is your tailored meta-prompt for the planner - connect what the user wants with how the codebase actually works.\n\nAlso CREATE ${chainDir}/progress.md:\n## Scout - Context Gathered\n- X files analyzed\n- Key findings\n- Recommended approach\"`,\n  mode: \"hands-free\",\n  reason: \"Step 1: Scout (cursor-agent)\"\n})\n```\n\n**Completion**: Poll until `status: \"exited\"`. Scout typically finishes cleanly without needing auto-continue.\n\n## Step 2: Planner\n\nCreates implementation plan. Gets a head start from context.md (scout pre-gathered the relevant code), but can still read additional files if needed.\n\n```typescript\ninteractive_shell({\n  command: `pi --model claude-sonnet-4-5 \"Read ${chainDir}/context.md first - the scout already gathered relevant code snippets and provided planning guidance.\n\nCreate a detailed implementation plan for: ${task}\n\nYou have a head start from context.md, but you can read additional files if needed.\n\nYour plan should include:\n1. Task breakdown with clear steps\n2. File modification order\n3. Testing strategy\n4. Risk areas to watch\n\nSave your plan to ${chainDir}/plan.md with numbered steps.\n\nAlso APPEND to ${chainDir}/progress.md:\n## Planner - Implementation Plan\n- (number of tasks, key decisions, risks identified)\"`,\n  mode: \"hands-free\",\n  reason: \"Step 2: Planner (pi)\"\n})\n```\n\n**Completion**: Poll until `status: \"exited\"`. Planner typically finishes cleanly.\n\n## Step 3: Worker (with Auto-Continue)\n\nImplementation step that often pauses to ask questions.\n\n### The Problem\n\nCodex frequently pauses mid-task with prompts like:\n- \"Should I also update the tests?\"\n- \"Do you want me to refactor this function?\"\n- \"Would you like me to continue with the next file?\"\n- \"Shall I proceed with the remaining tasks?\"\n\nWithout intervention, it stops and waits indefinitely.\n\n### The Solution\n\n1. **Disable auto-exit** so the session stays alive when codex pauses\n2. **Detect waiting patterns** in the output\n3. **Send \"continue\"** to keep it working\n4. **Detect true completion** via explicit signal or exit\n\n```typescript\n// Start worker with auto-exit disabled\ninteractive_shell({\n  command: `codex \"Read the implementation plan at ${chainDir}/plan.md\n\nImplement ALL tasks in the plan. Do not stop until everything is complete.\n\nAs you work, APPEND to ${chainDir}/progress.md:\n## Worker - Implementation\n- [x] Task 1 - (what you did)\n- [x] Task 2 - (what you did)\n- (update as you complete each task)\n\nWhen ALL tasks are done:\n- Save a summary to ${chainDir}/impl.md\n- Your final message must be exactly: IMPLEMENTATION COMPLETE\"`,\n  mode: \"hands-free\",\n  handsFree: { autoExitOnQuiet: false },\n  reason: \"Step 3: Worker (codex)\"\n})\n\n// Returns sessionId immediately\n```\n\n### Auto-Continue Loop\n\n```typescript\nconst sessionId = startResult.details.sessionId;\n\nwhile (true) {\n  // Query status (rate limiting handles 60s wait automatically)\n  const pollResult = interactive_shell({ sessionId, outputLines: 30 });\n  const status = pollResult.details.status;\n  \n  // Check if session exited\n  if (status === \"exited\") {\n    break;\n  }\n  \n  // User took over - don't interfere, just keep polling\n  if (status === \"user-takeover\") {\n    continue;\n  }\n  \n  const output = pollResult.details.output;\n  \n  // Check for explicit completion signal\n  if (output.includes(\"IMPLEMENTATION COMPLETE\")) {\n    interactive_shell({ sessionId, kill: true });\n    break;\n  }\n  \n  // Auto-continue if waiting for input\n  if (needsContinue(output)) {\n    interactive_shell({ sessionId, input: \"continue\\n\" });\n  }\n}\n```\n\n### Continue Detection\n\nPatterns that indicate codex is waiting:\n\n```typescript\nfunction needsContinue(output: string): boolean {\n  const lines = output.trim().split('\\n');\n  const lastLines = lines.slice(-5).join('\\n').toLowerCase();\n  \n  const patterns = [\n    /should i (also|continue|proceed)/,\n    /do you want me to/,\n    /would you like me to/,\n    /shall i (proceed|continue)/,\n    /want me to (continue|proceed)/,\n    /continue\\?$/,\n    /proceed\\?$/,\n  ];\n  \n  return patterns.some(p => p.test(lastLines));\n}\n```\n\n### Alternative: Yes-Mode\n\nSome agents support auto-approval flags:\n\n```bash\n# Codex with full auto-approval (if supported)\ncodex --full-auto \"prompt\"\n\n# Aider with yes-always\naider --yes-always \"prompt\"\n```\n\nCheck the agent's CLI options for auto-approval modes that eliminate the need for manual continues.\n\n## Step 4: Reviewer (Validate + Fix)\n\nValidates the worker's implementation and fixes any issues found.\n\n```typescript\ninteractive_shell({\n  command: `pi --model claude-sonnet-4-5 \"Review and fix the implementation:\n\n1. Read the original context: ${chainDir}/context.md (user intent + codebase analysis)\n2. Read the plan: ${chainDir}/plan.md\n3. Read the progress log: ${chainDir}/progress.md  \n4. Read the implementation summary: ${chainDir}/impl.md\n5. Examine the actual code changes\n\nValidate:\n- All planned tasks were completed\n- Code quality meets standards\n- No obvious bugs or issues\n- Tests are adequate\n\nIf you find issues, FIX THEM directly. Don't just report - make the code right.\n\nAPPEND to ${chainDir}/progress.md with your final section:\n\n## Reviewer - Validation & Fixes\n**Status: PASS** (or FAIL if critical issues remain)\n\nValidated:\n- [x] All planned tasks completed\n- [x] Code quality verified  \n- [x] Tests passing\n- [x] No security issues\n\nIssues Fixed:\n- (list any issues you found and fixed, or 'None')\n\nFiles Modified by Reviewer:\n- (list files you changed, or 'None')\n\n---\n**Chain Complete** | scout → planner → worker → reviewer\nTotal files modified: X\nNotes: (anything the main agent should know)\"`,\n  mode: \"hands-free\",\n  reason: \"Step 4: Reviewer (pi)\"\n})\n```\n\n**Completion**: Poll until `status: \"exited\"`. Reviewer validates, fixes issues, appends final status to progress.md.\n\n## Status Values\n\n| Status | Meaning | Action |\n|--------|---------|--------|\n| `running` | Agent still working | Wait, check for continue patterns |\n| `exited` | Agent finished | Move to next step |\n| `user-takeover` | User started typing | Wait for user to finish |\n| `killed` | Session terminated | Chain interrupted |\n| `backgrounded` | User moved to background | Session continues invisibly |\n\n## Complete Chain Example\n\n```typescript\nasync function runForegroundChain(task: string) {\n  const runId = Date.now().toString(36);\n  const chainDir = `/tmp/pi-chain-runs/${runId}`;\n  \n  // Setup\n  bash({ command: `mkdir -p ${chainDir}` });\n  \n  // Step 1: Scout - gather code into context.md with structured format\n  // (See Step 1 section above for full context.md format: User Intent, Files Retrieved, Key Code, Architecture, Planning Guidance)\n  let session = interactive_shell({\n    command: `agent \"Scout for: ${task}. Gather relevant code into ${chainDir}/context.md (format: User Intent, Files Retrieved, Key Code, Architecture, Planning Guidance). CREATE ${chainDir}/progress.md with ## Scout section.\"`,\n    mode: \"hands-free\",\n    reason: \"Step 1: Scout\"\n  });\n  await pollUntilExited(session.details.sessionId);\n  \n  // Step 2: Planner\n  session = interactive_shell({\n    command: `pi --model claude-sonnet-4-5 \"Read ${chainDir}/context.md. Create plan for: ${task}. Save to ${chainDir}/plan.md. APPEND ## Planner section to ${chainDir}/progress.md.\"`,\n    mode: \"hands-free\",\n    reason: \"Step 2: Planner\"\n  });\n  await pollUntilExited(session.details.sessionId);\n  \n  // Step 3: Worker (with auto-continue)\n  session = interactive_shell({\n    command: `codex \"Read ${chainDir}/plan.md. Implement ALL tasks. APPEND ## Worker section to ${chainDir}/progress.md as you complete tasks. Save summary to ${chainDir}/impl.md. End with: IMPLEMENTATION COMPLETE\"`,\n    mode: \"hands-free\",\n    handsFree: { autoExitOnQuiet: false },\n    reason: \"Step 3: Worker\"\n  });\n  await pollWithAutoContinue(session.details.sessionId, \"IMPLEMENTATION COMPLETE\");\n  \n  // Step 4: Reviewer (validate + fix)\n  session = interactive_shell({\n    command: `pi --model claude-sonnet-4-5 \"Review and fix: Read ${chainDir}/context.md (user intent), ${chainDir}/plan.md, ${chainDir}/progress.md, ${chainDir}/impl.md. Validate implementation matches intent, fix issues. APPEND ## Reviewer section with status and **Chain Complete** to ${chainDir}/progress.md.\"`,\n    mode: \"hands-free\",\n    reason: \"Step 4: Reviewer\"\n  });\n  await pollUntilExited(session.details.sessionId);\n  \n  // Read progress.md - contains complete chain history\n  const progress = read(`${chainDir}/progress.md`);\n  \n  // Parse status from reviewer section\n  const passed = progress.includes(\"Status: PASS\");\n  \n  // Output chain completion summary\n  console.log(`\n✅ Chain completed: scout → planner → worker → reviewer (4 steps)\n\n📋 Progress: ${chainDir}/progress.md\n📁 Artifacts: ${chainDir}/\n  `);\n  \n  return { chainDir, progress, passed };\n}\n\nasync function pollUntilExited(sessionId: string) {\n  while (true) {\n    const result = interactive_shell({ sessionId });\n    if (result.details.status === \"exited\") break;\n    // Rate limiting handles the wait\n  }\n}\n\nasync function pollWithAutoContinue(sessionId: string, completionSignal: string) {\n  while (true) {\n    const result = interactive_shell({ sessionId, outputLines: 30 });\n    const status = result.details.status;\n    \n    // Session ended\n    if (status === \"exited\") break;\n    \n    // User took over - don't interfere, just wait\n    if (status === \"user-takeover\") continue;\n    \n    const output = result.details.output;\n    \n    // Check for explicit completion signal\n    if (output.includes(completionSignal)) {\n      interactive_shell({ sessionId, kill: true });\n      break;\n    }\n    \n    // Auto-continue if waiting for input (only when running, not user-takeover)\n    if (needsContinue(output)) {\n      interactive_shell({ sessionId, input: \"continue\\n\" });\n    }\n  }\n}\n\n// See \"Continue Detection\" section above for needsContinue() implementation\n```\n\n## Tips\n\n**progress.md is the chain result**: After the chain completes, read `progress.md` for the complete story - every agent's section, final status, issues fixed. It's the single source of truth.\n\n**Handoff files are for agents**: context.md, plan.md, impl.md exist for structured agent-to-agent communication. The main agent reads progress.md.\n\n**File-based handoff is reliable**: Terminal output can be truncated. Always have agents write to chain_dir files.\n\n**Explicit completion signals**: Tell agents to output a specific phrase when truly done (e.g., \"IMPLEMENTATION COMPLETE\").\n\n**User takeover**: If status becomes `user-takeover`, the user started typing. Wait for them to finish - don't try to send input.\n\n**Cleanup**: Chain directories in `/tmp/` persist until OS cleanup. Remove manually when done: `rm -rf /tmp/pi-chain-runs/{runId}`\n\n**Model selection**: Adjust models based on task complexity. Use faster models for simple steps, more capable models for complex reasoning.\n\n## Customization\n\n### Different Agent Combinations\n\n```typescript\n// Research-heavy chain\nconst agents = {\n  scout: 'gemini --model gemini-2.5-pro \"...\"',      // Good at synthesis\n  planner: 'claude \"...\"',                       // Strong reasoning\n  worker: 'codex \"...\"',                         // Fast implementation\n  reviewer: 'pi --model claude-opus-4-5 \"...\"',       // Thorough review\n};\n\n// Speed-optimized chain\nconst agents = {\n  scout: 'agent \"...\"',            // Fast scanning\n  planner: 'pi --model claude-haiku-4-5 \"...\"',           // Quick planning\n  worker: 'codex \"...\"',                         // Fast implementation\n  reviewer: 'pi --model claude-haiku-4-5 \"...\"',          // Quick review\n};\n```\n\n### Adding Steps\n\nInsert additional steps as needed:\n\n```typescript\n// Add a \"tester\" step after review to verify everything works\ninteractive_shell({\n  command: `pi \"Run the test suite. Verify all tests pass. If any fail, investigate and report to ${chainDir}/test-results.md. APPEND ## Tester section with results to ${chainDir}/progress.md.\"`,\n  mode: \"hands-free\",\n  reason: \"Step 5: Tester\"\n});\n\n// Add a \"documenter\" step to update docs\ninteractive_shell({\n  command: `pi \"Read ${chainDir}/progress.md. Update README and any relevant documentation to reflect the changes. Save summary to ${chainDir}/docs-updated.md. APPEND ## Documenter section to ${chainDir}/progress.md.\"`,\n  mode: \"hands-free\",\n  reason: \"Step 5: Documenter\"\n});\n```\n\n### Parallel Scouts\n\nRun multiple scouts for different aspects. Create progress.md first to avoid race conditions:\n\n```typescript\n// Create progress.md before starting parallel scouts\nbash({ command: `echo \"# Chain Progress\" > ${chainDir}/progress.md` });\n\n// Start both scouts simultaneously - both APPEND (no race condition)\nconst scout1 = interactive_shell({\n  command: `agent \"Analyze architecture. Save to ${chainDir}/arch.md. APPEND ## Scout 1 - Architecture section to ${chainDir}/progress.md.\"`,\n  mode: \"hands-free\"\n});\nconst sessionId1 = scout1.details.sessionId;\n\nconst scout2 = interactive_shell({\n  command: `agent \"Analyze test coverage. Save to ${chainDir}/tests.md. APPEND ## Scout 2 - Test Coverage section to ${chainDir}/progress.md.\"`,\n  mode: \"hands-free\"\n});\nconst sessionId2 = scout2.details.sessionId;\n\n// Poll alternately until both complete (rate limiting applies per-query)\nlet done1 = false, done2 = false;\nwhile (!done1 || !done2) {\n  if (!done1) {\n    const r1 = interactive_shell({ sessionId: sessionId1 });\n    if (r1.details.status === \"exited\") done1 = true;\n  }\n  if (!done2) {\n    const r2 = interactive_shell({ sessionId: sessionId2 });\n    if (r2.details.status === \"exited\") done2 = true;\n  }\n}\n\n// Planner reads both files\ninteractive_shell({\n  command: `pi --model claude-sonnet-4-5 \"Read ${chainDir}/arch.md and ${chainDir}/tests.md. Create unified plan. Save to ${chainDir}/plan.md. APPEND ## Planner section to ${chainDir}/progress.md.\"`,\n  mode: \"hands-free\",\n  reason: \"Step 2: Planner\"\n});\n```\n","readmeExcerpt":"--- name: foreground-chains description: Orchestrate multi-agent workflows where users watch each step in the overlay. Uses different CLI agents (cursor, pi, codex) for specialized roles with file-based handoff and auto-continue support for agents that pause mid-task. --- Foreground Agent Chains Run multi-step agent workflows with full user visibility. Each step runs in an overlay where the user watches and can inter","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"Scout ──► context.md ──► Planner ──► plan.md ──► Worker ──► impl.md ──► Reviewer\n  │                          │                      │                       │\n  │ gathers code +           │ head start,          │ auto-continue         │ validates +\n  │ meta-prompt              │ can read more        │ for \"Should I...\"     │ fixes issues\n  │                          │                      │                       │\n  └──────────────────────────┴──────────────────────┴───────────────────────┤\n                                                                            ▼\n                                                                      progress.md\n                                                                    (all agents append)\n                                                                            │\n                                                                            ▼\n                                                                      Main Agent\n                                                                    (reads at chain end)"},{"language":"bash","snippet":"# Scout (cursor-agent)\nagent \"prompt\"\n\n# Planner (pi)\npi --model claude-sonnet-4-5 \"prompt\"\n\n# Worker (codex)\ncodex \"prompt\"\n\n# Reviewer (pi)\npi --model claude-sonnet-4-5 \"prompt\""},{"language":"text","snippet":"/tmp/pi-chain-runs/{runId}/\n├── progress.md     # Running log - ALL agents append to this\n├── context.md      # Scout → Planner handoff\n├── plan.md         # Planner → Worker handoff\n└── impl.md         # Worker → Reviewer handoff"},{"language":"typescript","snippet":"const runId = Date.now().toString(36);\nconst chainDir = `/tmp/pi-chain-runs/${runId}`;\n\n// Create chain directory\nbash({ command: `mkdir -p ${chainDir}` })\n\n// Start scout\ninteractive_shell({\n  command: `agent \"You are a scout. The user wants: ${task}\n\nYour job: Gather all relevant code into context.md so the planner gets a head start and spends less time reading files.\n\nStrategy:\n1. grep/find to locate relevant code\n2. Read key sections (not entire files)  \n3. Stuff actual code snippets into context.md\n4. Note how pieces connect\n\nSave to ${chainDir}/context.md:\n\n# Code Context\n\n## User Intent\nRestate what the user wants in your own words.\n\n## Files Retrieved\nList with exact line ranges:\n1. \\`path/to/file.ts\\` (lines 10-50) - Description\n2. \\`path/to/other.ts\\` (lines 100-150) - Description\n\n## Key Code\nThe actual code snippets from those files. Include complete types, interfaces, functions - everything the planner needs to see. This is the main payload.\n\n## Architecture\nBrief explanation of how the pieces connect. Dependencies between files.\n\n## Planning Guidance\nSynthesize the user's intent with your codebase findings:\n- What approach makes sense given the existing architecture?\n- Which files need modification and in what order?\n- What patterns should the implementation follow?\n- Risks or edge cases to address?\n\nThis is your tailored meta-prompt for the planner - connect what the user wants with how the codebase actually works.\n\nAlso CREATE ${chainDir}/progress.md:\n## Scout - Context Gathered\n- X files analyzed\n- Key findings\n- Recommended approach\"`,\n  mode: \"hands-free\",\n  reason: \"Step 1: Scout (cursor-agent)\"\n})"},{"language":"typescript","snippet":"interactive_shell({\n  command: `pi --model claude-sonnet-4-5 \"Read ${chainDir}/context.md first - the scout already gathered relevant code snippets and provided planning guidance.\n\nCreate a detailed implementation plan for: ${task}\n\nYou have a head start from context.md, but you can read additional files if needed.\n\nYour plan should include:\n1. Task breakdown with clear steps\n2. File modification order\n3. Testing strategy\n4. Risk areas to watch\n\nSave your plan to ${chainDir}/plan.md with numbered steps.\n\nAlso APPEND to ${chainDir}/progress.md:\n## Planner - Implementation Plan\n- (number of tasks, key decisions, risks identified)\"`,\n  mode: \"hands-free\",\n  reason: \"Step 2: Planner (pi)\"\n})"},{"language":"typescript","snippet":"// Start worker with auto-exit disabled\ninteractive_shell({\n  command: `codex \"Read the implementation plan at ${chainDir}/plan.md\n\nImplement ALL tasks in the plan. Do not stop until everything is complete.\n\nAs you work, APPEND to ${chainDir}/progress.md:\n## Worker - Implementation\n- [x] Task 1 - (what you did)\n- [x] Task 2 - (what you did)\n- (update as you complete each task)\n\nWhen ALL tasks are done:\n- Save a summary to ${chainDir}/impl.md\n- Your final message must be exactly: IMPLEMENTATION COMPLETE\"`,\n  mode: \"hands-free\",\n  handsFree: { autoExitOnQuiet: false },\n  reason: \"Step 3: Worker (codex)\"\n})\n\n// Returns sessionId immediately"}],"parameters":{},"dependencies":[],"permissions":[],"extractedFiles":[],"languages":["typescript"],"docsSourceLabel":"GITHUB OPENCLEW","editorialOverview":"Orchestrate multi-agent workflows where users watch each step in the overlay. Uses different CLI agents (cursor, pi, codex) for specialized roles with file-based handoff and auto-continue support for agents that pause mid-task. --- name: foreground-chains description: Orchestrate multi-agent workflows where users watch each step in the overlay. Uses different CLI agents (cursor, pi, codex) for specialized roles with file-based handoff and auto-continue support for agents that pause mid-task. --- Foreground Agent Chains Run multi-step agent workflows with full user visibility. Each step runs in an overlay where the user watches and can inter","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":404,"uniquenessScore":61,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-04-15T05:21:22.124Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-04-15T05:21:22.124Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T13:52:13.290Z","emptyReason":null},"items":[{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-10T18:48:31.762Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/github_openclew","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}