A thin wrapper that invokes the desplega:researching skill with autonomy controls.
When Invoked
Parse autonomy mode from arguments:
Check for --autonomy=autopilot|critical|verbose flag
If document frontmatter has autonomy: field, use that as default
Otherwise, ask the user via AskUserQuestion:
code
How much should I check in with you during this research?
- Autopilot: Work independently, only present final results
- Critical questions (Recommended): Ask only when blocked or for major decisions
- Verbose: Check in frequently, validate approach at each step
ALWAYS invoke the desplega:researching skill:
Pass the research query (everything after the flag)
Pass the autonomy mode determined above
Let the skill handle all research logic
If no query provided:
Respond with: "I'm ready to research the codebase. Please provide your research question or area of interest."
Example Usage
code
/research how does the authentication system work
/research --autonomy=autopilot document all API endpoints
/research --autonomy=verbose analyze the database schema
Taras, starting the research in autopilot mode. I'll invoke the researching skill now.
Assistant
Let me start by fetching the GitHub issue and reading the key harness-related files directly, then spawn parallel research tasks.
Assistant
Good, I have the full issue context including the bot's research. Now let me spawn parallel research tasks to understand the current pi harness implementation and assess Codex feasibility.
Assistant
Launched 4 parallel research agents — analyzing the harness abstraction, finding implementation patterns, locating related files, and researching the Codex App Server API. I'll synthesize findings once they all complete.
Assistant
Got the file map. Waiting for the remaining 3 agents to complete with the code analysis, pattern details, and Codex API research.
User
Summary
The provider system currently has two adapters: claude (default) and pi (pi-mono). There is no src/harness/ or src/runtime/ directory -- all provider abstraction lives in src/providers/ (6 files). The runner at src/commands/runner.ts is the main consumer that spawns provider sessions. No codex-specific implementation exists yet; codex appears only in branding text and research notes exploring future provider targets.
<total_tokens>22170</total_tokens><tool_uses>25</tool_uses><duration_ms>78295</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-11-feat-codex-support/tasks/a97be3f9f00546bb7.output
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/docs-site/content/docs/reference/environment-variables.mdx - Env var reference (documents HARNESS_PROVIDER)
User
7. Existing Research/Thoughts on Provider Architecture
These are the most relevant thoughts files for understanding the provider abstraction:
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/thoughts/taras/plans/2026-03-08-pi-mono-provider-implementation.md - Plan for the pi-mono provider (the most recent provider added)
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/thoughts/taras/research/2026-03-05-pi-mono-provider-research.md - Research for adding the pi-mono provider
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/thoughts/taras/research/2026-03-08-pi-mono-deep-dive.md - Deep dive into pi-mono architecture (includes codex/provider comparison tables)
User
6. Codex Mentions
There is no dedicated codex provider implementation or codex-specific code yet. "Codex" appears only in:
Research notes mentioning codex as a future target:
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/thoughts/taras/research/2026-03-05-pi-mono-provider-research.md - Mentions Codex/OpenAI auth flow in provider comparison table
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/thoughts/taras/research/2026-03-08-pi-mono-deep-dive.md - Lists Codex as future harness, mentions OpenAI/Codex env vars
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/thoughts/research/2026-02-28-x402-payments-research.md - Passing mention in payments research
No existing thoughts/ research or plans specifically about codex support.
User
5. HARNESS_PROVIDER Usage Across the Codebase (17 files)
The env var HARNESS_PROVIDER is referenced in these files:
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/types.ts - Provider/adapter type definitions (HarnessProvider, ProviderAdapter)
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/index.ts - Provider registry/factory (selects adapter based on HARNESS_PROVIDER)
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/claude-adapter.ts - Claude Code adapter implementation
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/scripts/e2e-docker-provider.ts - E2E test for providers in Docker
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/scripts/e2e-provider-test.ts - E2E provider test script
Type Definitions:
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/types.ts - Shared types (likely includes provider-related types)
Note: There is NO src/harness/ or src/runtime/ directory. All provider logic lives in src/providers/.
User
File Locations for Harness Providers, Runner/Worker, Docker, Hooks, and Codex Support
All paths are rooted at /Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support.
Assistant
Got detailed pattern analysis. The provider abstraction is well-established with ProviderAdapter/ProviderSession interfaces. Still waiting for the codebase analyzer and Codex API research agents.
Also includes ProviderEvent type narrowing tests and CostData shape tests.
User
Pattern 7: Docker Entrypoint Harness Selection
Found in: /Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/docker-entrypoint.sh:1-19
bash
HARNESS_PROVIDER="${HARNESS_PROVIDER:-claude}"
if [ "$HARNESS_PROVIDER" = "pi" ]; then
if [ -z "$ANTHROPIC_API_KEY" ] && [ -z "$OPENROUTER_API_KEY" ] && [ ! -f "$HOME/.pi/agent/auth.json" ]; then
echo "Error: ANTHROPIC_API_KEY, OPENROUTER_API_KEY, or ~/.pi/agent/auth.json required for pi provider"
exit 1
fi
else
if [ -z "$CLAUDE_CODE_OAUTH_TOKEN" ]; then
echo "Error: CLAUDE_CODE_OAUTH_TOKEN environment variable is required"
exit 1
fi
fi
The entrypoint validates provider-specific auth, then at line 540 starts the same binary regardless of provider:
bash
exec /usr/local/bin/agent-swarm "$ROLE" "$@"
The binary internally uses HARNESS_PROVIDER via createProviderAdapter().
Dockerfile.worker (/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/Dockerfile.worker): Both CLIs are installed in the same image:
Line 77: Claude CLI installed via curl -fsSL https://claude.ai/install.sh | bash
Line 80-83: pi-mono installed via sudo npm install -g @mariozechner/pi-coding-agent
Line 141-142: Pi-mono skills copied to /home/worker/.pi/agent/skills/
Line 165: ENV HARNESS_PROVIDER=claude (default)
User
Pattern 6: Hooks Configuration per Harness
Claude hooks -- file-based, configured in .claude/settings.local.json
From /Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/commands/setup.tsx:56-76:
The hook handler itself is /Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/hooks/hook.ts. It reads stdin JSON (HookMessage), reads .mcp.json to find the server URL, and handles each hook_event_name via a switch statement. It runs as a separate process invoked by the Claude CLI on each hook event.
The McpHttpClient (/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/pi-mono-mcp-client.ts) performs full MCP handshake (initialize + initialized notification) and tool discovery over Streamable HTTP.
json.type === "result" yields cost/token data from json.total_cost_usd, json.usage, json.duration_ms, json.num_turns
Task file pattern (lines 17-39): Writes a JSON file to /tmp/agent-swarm-task-{pid}.json containing {taskId, agentId, startedAt}. This file is read by the Claude hook process via the TASK_FILE env var.
Stale session retry (lines 269-318): If the process fails with "session not found" and --resume was used, it strips --resume and retries with a fresh session automatically.
Key aspects:
Spawns an external CLI process (claude)
Parses stream-json stdout for events
Hooks are external (Claude's hook system reads TASK_FILE env var)
MCP tools are discovered by Claude via .mcp.json on disk
Resume uses --resume <sessionId> CLI flag
User
Pattern 2: Factory / Provider Selection
Found in: /Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/index.ts
typescript
export function createProviderAdapter(provider: string): ProviderAdapter {
switch (provider) {
case "claude":
return new ClaudeAdapter();
case "pi":
return new PiMonoAdapter();
default:
throw new Error(`Unknown HARNESS_PROVIDER: "${provider}". Supported: claude, pi`);
}
}
Called in the runner at /Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/commands/runner.ts:1428:
Events are normalized via a discriminated union (ProviderEvent) with types: session_init, message, tool_start, tool_end, result, error, raw_log, raw_stderr, custom.
Excellent — three out of four agents done. The picture is very clear: the provider abstraction (ProviderAdapter/ProviderSession) is clean and well-established. Just waiting on the Codex App Server API research.
User
Analysis: Harness/Provider Abstraction
Overview
The codebase implements a provider abstraction layer in src/providers/ that allows the runner to execute agent sessions against different CLI harnesses (Claude Code or pi-mono) through a unified interface. The runner (src/commands/runner.ts) selects the provider at startup via HARNESS_PROVIDER env var and interacts exclusively through the ProviderAdapter / ProviderSession / ProviderResult contracts. Hooks are handled completely differently per provider: Claude uses an external process invoked by Claude Code's hook system, while pi-mono uses an in-process extension API.
Entry Points
src/providers/index.ts:15 -- createProviderAdapter(provider) factory function
src/commands/runner.ts:1428 -- adapter instantiation at runner startup
All 4 research agents complete. Let me now synthesize everything into the research document.
Assistant
Research document written. Here's the synthesis, Taras:
Feasibility: Native Codex Support
Verdict: Highly feasible, ~1-2 weeks effort (down from the bot's original 5-6 week estimate).
The key insight: the original issue #100 assessment was written before the provider abstraction existed. Now that ProviderAdapter/ProviderSession is proven with two adapters (Claude + pi-mono), adding Codex is essentially implementing a third adapter following the pi-mono pattern.
Why it's reasonable now
Runner is provider-agnostic — runner.ts:1428 just calls createProviderAdapter(). Zero runner changes needed.
App Server sandbox bypass bug (#14068) — may not fully bypass for tool child processes
Approval RPC gap (#14192) — needs approval_policy = "never" workaround
MCP streamable HTTP reliability — may need SSE fallback
Open question from you
On Mar 5 you commented on #100: "#139 probably will cover this introducing pi adapter, so native codex might not be needed". Is native Codex still desired, or is pi-mono with OpenRouter sufficient?
Research doc: thoughts/taras/research/2026-03-11-codex-native-support-feasibility.md
Want me to proceed to create a plan, run a review on this research, or are we done for now?
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-11-feat-codex-support/tasks/a613257e563ae8290.output
User
Key Findings Summary
1. JSON-RPC Protocol: "JSON-RPC lite" -- same request/response/notification structure as JSON-RPC 2.0 but the "jsonrpc":"2.0" field is omitted. Framed as JSONL over stdio. Handshake starts with initialize -> initialized before any other method.
2. Spawning: codex app-server as a long-lived child process. Default: stdio. Experimental: --listen ws://127.0.0.1:4500. The TypeScript SDK (@openai/codex-sdk) wraps this -- spawns the CLI binary and exchanges JSONL over stdin/stdout.
4. Turn management: turn/start (begin generation with user input), turn/steer (inject input mid-turn without starting new), turn/interrupt (cancel in-flight turn, status becomes "interrupted").
5. Event streaming: Item lifecycle is always item/started -> zero or more item/*/delta -> item/completed. Turn lifecycle: turn/started -> turn/completed. Thread events: thread/started, thread/archived, thread/unarchived, thread/closed, thread/status/changed. Clients can opt out of specific notifications via initialize.params.capabilities.optOutNotificationMethods.
6. MCP integration: Configured in config.toml under [mcp_servers.<name>]. Supports stdio (subprocess) and StreamableHttp transports. Tool names prefixed mcp__<server_name>__<tool>. Has enabled_tools/disabled_tools allow/deny lists. Approval via tool/requestUserInput with Accept/Decline/Cancel options.
7. Authentication: Three modes -- apiKey (supply OPENAI_API_KEY), chatgpt (managed OAuth), chatgptAuthTokens (external tokens from host app). For Docker/headless: printenv OPENAI_API_KEY | codex login --with-api-key, or codex login --device-auth, or copy ~/.codex/auth.json. Can force API-only with .
User
i think having codex native is nice, in case people is used to it, and also its harness provide different vibe in terms of usage you know?
Assistant
Makes sense — each harness has its own strengths and model ecosystem. Codex with o3/gpt-5.3 gives operators a genuinely different option, not just a proxy through OpenRouter.
The research is solid. Want me to create a plan for the implementation? I can base it on the pi-mono plan as a template (thoughts/taras/plans/2026-03-08-pi-mono-provider-implementation.md).
User
did you research how the codex server work? i.e. to valiate a solid research with key findigs + links?
Assistant
Got it — you want a focused deep-dive on the Codex-specific implementation details that matter for building the adapter. Let me research the concrete specifics: config file paths, skills/instructions system (AGENTS.md equivalent), MCP config format, hook equivalents, approval handling, and the actual JSON-RPC payloads.
Assistant
Launched two focused research agents in parallel:
Codex adapter specifics — config paths, AGENTS.md equivalent, MCP config format, approval system, JSON-RPC payloads, auth protocol, process lifecycle, installation
Codex TypeScript SDK — @openai/codex-sdk as a potential integration layer instead of raw JSON-RPC (may simplify the adapter significantly)
I'll update the research doc with the concrete findings once both complete.
Assistant
Good finding from the SDK research — the @openai/codex-sdk is missing turn/interrupt (abort) and turn/steer, which are critical for our adapter. Raw App Server JSON-RPC is the right path. Still waiting on the config/protocol specifics agent.
User
Summary
The @openai/codex-sdk (latest: v0.112.0, 88 dependents on npm) is a TypeScript library that wraps the bundled codex Rust binary and communicates via JSONL over stdin/stdout. It provides a higher-level abstraction over the App Server JSON-RPC protocol with a Thread/Turn model. However, for an adapter that needs fine-grained control (like our ProviderSession interface), the raw App Server JSON-RPC approach from the existing feasibility research is the better path.
1. Package Details
npm: @openai/codex-sdk v0.112.0 (published March 11, 2026)
Requires: Node.js 18+
Install: npm install @openai/codex-sdk
88 dependents on npm
2. How It Spawns the App Server
The SDK wraps the bundled codex binary from @openai/codex. It spawns the CLI process using Node's child_process.spawn() with stdio configured as ["pipe", "pipe", "inherit"] and exchanges JSONL events over stdin/stdout. The process lifecycle is managed automatically -- you do not manually start/stop the app-server.
Instructions: AGENTS.md (not CLAUDE.md) + developer_instructions in thread/start params for programmatic system prompt injection
MCP config: config.toml with bearer_token_env_var for auth, type = "http" transport, tool names prefixed mcp__<server>__<tool>
Approvals: approval_policy = "never" + sandbox_mode = "danger-full-access" for autonomous agents, plus fallback requestApproval auto-accept handler
JSON-RPC protocol: Full payloads for initialize, auth, thread/start, turn/start, item notifications, turn/completed (includes token usage but no cost field)
Process lifecycle: SIGTERM = graceful since PR #13594, one process can multiplex threads
11 critical gotchas (JSON-RPC lite omits "jsonrpc":"2.0", TOML kebab-case vs API camelCase, 64-char tool name limit, etc.)
SDK evaluation — @openai/codex-sdk rejected: missing turn/interrupt and turn/steer, Node.js dependency, less control. Raw App Server JSON-RPC is the right path.
Ready to move to planning whenever you are.
User
desplega:review
/desplega:review
the research pls
User
Review Document
A thin wrapper that invokes the desplega:reviewing skill with autonomy controls.
When Invoked
Parse flags from arguments:
Check for --autonomy=autopilot|critical|verbose flag
Check for --output=append|separate flag (sets output mode preference, skipping the preference question)
Otherwise, default to Critical autonomy
ALWAYS invoke the desplega:reviewing skill:
Pass the document path
Pass the autonomy mode determined above
Pass the output mode if specified
Let the skill handle all review logic
If no path provided:
Respond with: "I need a document to review. Please provide the path to the research, plan, or brainstorm document you'd like me to review."
Good — appending errata + file-review after. Let me read both documents fully and spawn a codebase verification agent in parallel.
Assistant
Both documents read. I can already identify several issues while the verification agent runs. Let me compile my findings.
Structural analysis — both documents have proper frontmatter and sections. The feasibility doc follows the research template well. The deep reference is more of an implementation guide (no Research Question section, which is appropriate for its purpose).
Content issues identified so far:
Feasibility Doc
Critical:
Open Question #4 ("Strategic priority") is stale — Taras already confirmed native Codex is desired in this session
Important:
Section 8 Docker template uses sandbox = "danger-full-access" but the correct config field is sandbox_mode (as documented in the deep reference)
Section 4 mapping table says "extract cost from turn result" but deep reference clarifies there's NO cost field, only token counts — factual inconsistency
Section 6 MCP config shows headers = { ... } with env var interpolation syntax that doesn't match Codex's actual config format (bearer_token_env_var + env_http_headers)
Proposed adapter architecture (line 272) shows auth AFTER thread/start, but deep reference says auth happens BEFORE thread/start
Related Research references 2026-03-11-codex-sdk-deep-dive.md which was never written to disk
Deep Reference Doc
Important:
Docker entrypoint template (Section 11) is missing X-Agent-ID header — only has bearer_token_env_var for auth but swarm agents need the agent ID header too. Should use env_http_headers = { "X-Agent-ID" = "AGENT_ID" }
Section 1 mentions project_doc_fallback_filenames supports ["AGENTS.md", "CLAUDE.md"] — if we configure this, the AGENTS.md symlink may be unnecessary. Worth calling out.
No fallback strategy documented — if App Server has issues, codex exec --json could serve as simpler fallback
Let me wait for the codebase verification results before appending the errata.
Assistant
All verification done — 9/10 claims correct, 1 off by one line. Let me now fix minor issues and append errata.
Assistant
Now append errata to both documents.
Assistant
Errata appended to both docs. Now launching file-review for inline feedback.
Assistant
The review is complete, Taras. Here's the summary:
Review Findings
Codebase verification: 9/10 line references exactly correct, 1 off by one line (auto-fixed).
Feasibility Doc — 1 Critical, 5 Important
Severity
Finding
Critical
Open Question #4 is stale — you already confirmed Codex support is desired
Important
sandbox should be sandbox_mode in Docker template
Important
"extract cost from turn result" is wrong — only token counts, no USD field
Important
MCP config format uses wrong syntax for env var headers
Important
Auth ordering: should be BEFORE thread/start, not after
project_doc_fallback_filenames may eliminate AGENTS.md symlink need
Important
No codex exec --json fallback documented
Important
Missing github_issue in frontmatter
I've launched file-review on the feasibility doc — let me know when you're done reviewing and I'll process your comments. I can also open the deep reference doc for review after.
User
Summary: 9 out of 10 claims are exactly correct. 1 is off by one line (ProviderSession at line 50, not 49). The research doc references src/types.ts for claims 1-3; the actual file path is src/providers/types.ts -- worth correcting if the research doc uses the shorter path.
<total_tokens>46308</total_tokens><tool_uses>14</tool_uses><duration_ms>55803</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-11-feat-codex-support/tasks/ab5424b29dec6db4d.output
User
10. spawnProviderProcess at runner.ts:1098
Claim: function exists and calls adapter.createSession().
Result: ✅ Correct -- async function spawnProviderProcess( at runner.ts:1098. It takes adapter as its first parameter (line 1099) and calls adapter.createSession(config) at line 1143.
User
9. Pi-mono extension hook mapping at pi-mono-extension.ts:380 maps all 6 hook events
Claim: createSwarmHooksExtension at line 380 maps 6 hook events.
Result: ✅ Correct -- Function exported at line 380. The 6 hooks mapped are:
session_start (line 383)
tool_call (line 405)
tool_result (line 478)
context (line 561)
input (line 586)
session_shutdown (line 602)
User
8. Pi-mono MCP client
Claim: McpHttpClient is used for tool discovery.
Result: ✅ Correct -- pi-mono-mcp-client.ts defines McpHttpClient (line 20). In PiMonoAdapter.createSession (pi-mono-adapter.ts:377), it instantiates new McpHttpClient(...), calls mcpClient.initialize() then mcpClient.listTools() to discover tools, which are converted via mcpToolsToDefinitions.
Result: ✅ Correct -- The createAgentsMdSymlink function at pi-mono-adapter.ts:110-123 calls symlinkSync("CLAUDE.md", agentsMd) at line 116, creating AGENTS.md pointing to CLAUDE.md. Called during createSession at line 371.
User
6. ClaudeAdapter subprocess spawn
Claim: uses Bun.spawn() and buildCommand() builds the claude CLI command.
Result: ✅ Correct -- Bun.spawn(cmd, ...) at claude-adapter.ts:63. buildCommand() is a private method at line 76 that constructs the claude CLI array (starts with "claude", adds --model, --verbose, --output-format stream-json, etc.). The cmd variable assigned from this.buildCommand() at line 57 is passed directly to Bun.spawn.
User
5. Runner at runner.ts:1428
Claim: createProviderAdapter(process.env.HARNESS_PROVIDER || "claude") exists at line 1428.
4. Factory at index.ts:15-24
Claim: switch statement with "claude" and "pi" cases.
Result: ✅ Correct -- /Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/index.ts:15-24. Function createProviderAdapter at line 15, switch on provider with cases "claude" (line 17, returns new ClaudeAdapter()) and "pi" (line 19, returns new PiMonoAdapter()), default throws. Exact line range matches.
User
3. ProviderEvent at types.ts:18
Claim: event types are session_init, message, tool_start, tool_end, result, error, raw_log, raw_stderr, custom at line 18.
Result: ✅ Correct -- Lines 18-27. All 9 event types listed are present and accurate.
User
2. ProviderSession interface at types.ts:49
Claim: has sessionId, onEvent(listener), waitForCompletion(), abort() at line 49.
Result: ⚠️ Slightly off -- The interface is at line 50, not 49. Line 49 is the doc comment /** A running provider session. */. All four members are present (lines 51-54). Also, sessionId is readonly and typed string | undefined, not just string.
User
1. ProviderAdapter interface at types.ts:70
Claim: has name, createSession(config), canResume(sessionId) at line 70.
Result: ✅ Correct -- /Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/types.ts:70-74. The interface is at exactly line 70 with all three members. Note the file is src/providers/types.ts, not the root src/types.ts.
Assistant
Looks like file-review closed without inline comments. The automated review covered the key issues — the errata sections are in both docs with actionable items.
Assistant
Got it — 4 comments from Taras. Let me process them all:
Add event mapping section — how Codex events map to UI consumption (batching, etc.)
Research Codex subscription auth — not just API key
Fix all Important errata items
Resolve Open Question #4
Let me research the two new topics while fixing the errata in parallel.
Assistant
While those research, let me fix the errata items I can address now.
Assistant
Now fix the adapter architecture auth ordering and resolve Open Question #4.
Assistant
Now clean up the review comment markers.
Assistant
Now update the remaining Important errata items to mark them resolved.
Assistant
Good — 5 of 6 errata items fixed inline. The fallback strategy item is deferred to the plan. Now waiting for the two research agents (event mapping + subscription auth) to complete so I can add the new sections Taras requested.
Assistant
Great — the event mapping research revealed the critical insight: raw_log events must emit Claude-compatible JSON so the UI parser renders them correctly. Pi-mono already does this normalization. Waiting on subscription auth research.
Assistant
Both agents complete. Let me add the two new sections to the feasibility doc.
Assistant
Now expand the auth section with subscription options.
Assistant
Both sections added. Here's a summary of everything that was done, Taras:
Changes Applied
Errata fixes (5/6 resolved):
sandbox → sandbox_mode in Docker template
Cost claim corrected (token usage, not USD cost)
MCP config format fixed (bearer_token_env_var + env_http_headers)
Auth ordering fixed (auth before thread/start)
Open Question #4 resolved (native Codex confirmed)
Fallback strategy deferred to implementation plan
New sections added:
Section 6: Event Mapping for UI Consumption — Codex item notifications must be normalized to Claude-compatible JSON for the dashboard. Includes exact mapping table (Codex item type → content block format). Runner's LogBuffer handles batching; adapter just emits raw_log events.
Section 7: Authentication expanded with 3 strategies — API key (MVP), pre-seeded auth.json (subscription benefits), and chatgptAuthTokens via App Server (ideal for managed fleets). Includes the critical race condition warning for shared tokens (#10332).
Review comment markers cleaned up from the document.
Ready to create a plan whenever you want (/create-plan).
The #10332 race condition is especially relevant for agent-swarm: If multiple Codex workers share the same auth.json, concurrent refresh attempts will fail because refresh tokens are single-use. Each worker needs its own auth.json or use the chatgptAuthTokens app-server mode with centralized token management.
Sources: All linked GitHub issues above.
User
9. Enterprise/Team Accounts
SSO/SAML: Enterprise workspaces use SAML SSO, shared between ChatGPT and API Platform
MFA: MFA requirements from enterprise policy carry over to Codex auth
Device code may be disabled: Workspace admins must explicitly enable device code auth -- without it, headless login is impossible for subscription auth (Issue #9253)
forced_chatgpt_workspace_id: Admins can lock Codex to a specific workspace ID
Managed config distribution: Enterprise admins deploy config.toml via MDM or similar
Key insight: If you want fast mode and subscription rate limits in Docker, you must use ChatGPT subscription auth -- there is no way to get these benefits via API key.
chatgptAuthTokens (external): Host app supplies idToken and accessToken directly
For chatgptAuthTokens:
Host app sends tokens via account/login/start with type: "chatgptAuthTokens"
Codex stores tokens in memory (not persisted to disk)
When tokens expire, app-server sends account/chatgptAuthTokens/refresh request to the host
Host must respond with fresh idToken and accessToken JWTs
Codex retries the original request after successful refresh
For agent-swarm: This is the most promising path for managed Docker deployments. The swarm API could act as the "host app", manage a pool of ChatGPT OAuth tokens, and supply them to Codex workers via the app-server protocol.
Can it be volume-mounted into Docker? Yes -- this is the officially documented approach for headless environments:
Complete codex login on a machine with a browser
Copy ~/.codex/auth.json to the container's ~/.codex/auth.json
Use docker cp or volume mount
Critical rule from CI/CD docs: Seed auth.json only if missing. Never overwrite on every run -- you'd discard refreshed tokens that Codex wrote during the previous run.
codex login opens browser to ChatGPT OAuth endpoint
Uses PKCE (Proof Key for Code Exchange) for security
Runs a local HTTP server on port 1455 for the callback
After browser sign-in, callback returns access token to CLI
Tokens are persisted to ~/.codex/auth.json (or OS keyring)
For Docker: The localhost:1455 callback is the blocker. You cannot complete this flow inside a container without port forwarding or pre-seeded credentials.
Codex supports two auth modes: ChatGPT OAuth (subscription-based) and API key. When signed in with ChatGPT, Codex uses your subscription's included credits and rate limits. Features like fast mode are only available with ChatGPT sign-in -- API key auth uses standard API pricing instead.
Plus ($20/mo): 30-150 local tasks/5hrs with weekly limits, Codex agent access
Pro ($200/mo): Unlimited GPT-5.1, largest context windows, Codex agents, early access
All ChatGPT plans get 2x Codex rate limits vs API key
Credits system allows purchasing additional usage after hitting included limits
Taras, here is the complete research on Codex subscription-based authentication for headless/Docker environments. The research file should be saved to:
The core tension: Subscription-based auth (ChatGPT Plus/Pro) gives access to fast mode and higher rate limits, but was designed for interactive browser flows. Using it in Docker requires workarounds. API key auth is officially recommended for CI/CD but loses subscription benefits (fast mode, credits, 2x rate limits).
User
did we consider session follow ups?
Assistant
Good question — session resume across tasks. Let me check what we've documented so far and what the runner actually does for resume.
Assistant
Launched a research agent to trace the full resume lifecycle. We covered thread/resume in the mapping table and canResume in the interface, but we didn't dig into how the runner actually chains sessions across tasks (when it picks up claudeSessionId from a previous task, iteration flow, etc.). I'll add a proper section once the agent returns.
Assistant
Important finding — resume is currently Claude-specific via --resume in additionalArgs. The Codex adapter needs special handling. Let me add this section.
Assistant
Good catch, Taras. Here's what the session resume analysis revealed:
The resume mechanism is currently Claude-specific — it passes --resume <id> via additionalArgs, which only the Claude adapter consumes. Pi-mono ignores it entirely, and Codex would need thread/resume instead.
Key findings:
ProviderSessionConfig.resumeSessionId exists but is dead — no adapter reads it
canResume() is dead code — runner never calls it
Resume triggers from two paths: paused tasks and parent→child inheritance
For Codex: adapter must parse additionalArgs for --resume OR (better) the runner should be refactored to use resumeSessionId properly
I also added notes on thread persistence requirements for Docker (volume mount ~/.codex/sessions/ if resume across container restarts is needed).
The section renumbering cascaded — Docker Worker Changes is now Section 9. Ready for plan creation whenever you are.
User
Analysis: Session Resume Lifecycle
Overview
Session resume allows an agent to continue a previous Claude Code (or pi-mono) conversation when picking up a paused/interrupted task or when a child task inherits its parent's context. The provider's session ID is persisted to the database via the API, and on resume the runner fetches it back and passes it as a --resume <sessionId> CLI argument to the Claude process. The ProviderSessionConfig.resumeSessionId field exists in the type definition but is not actively used to drive behavior -- the actual resume mechanism is additionalArgs containing --resume.
Entry Points
src/commands/runner.ts:1423 -- runAgent(), the main entry point for both lead and worker agents
src/providers/types.ts:30-47 -- ProviderSessionConfig type defining resumeSessionId field
When a provider session starts, it emits a session_init event containing the session ID.
Claude adapter (src/providers/claude-adapter.ts:209-211): Parses stream-json stdout for a JSON line with type: "system", subtype: "init", and extracts session_id. Stores it in this._sessionId and emits { type: "session_init", sessionId }.
Pi-mono adapter (src/providers/pi-mono-adapter.ts:154): Gets sessionId directly from agentSession.sessionId at construction time and emits session_init immediately.
2. Session ID Persistence (event -> API -> DB)
In both spawnProviderProcess (src/commands/runner.ts:1151-1156) and runProviderIteration (src/commands/runner.ts:1306-1310), the runner listens for the session_init event and fires a non-blocking call to saveProviderSessionId().
saveProviderSessionId() (src/commands/runner.ts:604-617) sends PUT /api/tasks/:id/claude-session with .
createProviderAdapter(provider) accepts two values:
"claude" returns ClaudeAdapter
"pi" returns PiMonoAdapter
Any other value throws with Unknown HARNESS_PROVIDER.
3. Claude Adapter (src/providers/claude-adapter.ts)
Session creation (ClaudeAdapter.createSession, line 329): Writes a task file to /tmp/agent-swarm-task-{pid}.json (line 27-31) containing taskId, agentId, startedAt. Then spawns a ClaudeSession.
Process spawning (ClaudeSession constructor, line 50-74): Calls Bun.spawn() with the command built by buildCommand() (line 76-101). The command is:
The spawned process env includes TASK_FILE pointing to the task file (line 67-68).
Stream processing (processStreams, line 113-202): Reads stdout line-by-line, parses JSON. Extracts session_id from type:"system", subtype:"init" messages (line 209-212). Extracts cost data from type:"result" messages (line 215-245). Tracks errors via SessionErrorTracker from stderr (line 163).
Stale session retry (waitForCompletion, line 266-318): If the process failed with "session not found" error and --resume was in the args, it strips --resume and retries with a fresh ClaudeSession.
canResume (line 344): Always returns true for Claude.
Session creation (PiMonoAdapter.createSession, line 363-419) performs seven steps:
AGENTS.md symlink (line 371): Creates AGENTS.md -> CLAUDE.md symlink since pi-mono reads AGENTS.md while the project has CLAUDE.md.
MCP tool discovery (lines 374-387): Creates an McpHttpClient, performs the MCP handshake against the swarm API endpoint, calls listTools(), then wraps each tool as a pi-mono ToolDefinition via mcpToolsToDefinitions() (line 43-64). Each tool's execute() calls mcpClient.callTool().
Model resolution (line 390): resolveModel() (line 67-107) maps shortnames (opus, sonnet, haiku) to [provider, model-id] pairs, handles provider/model-id format, and falls back to trying common providers.
Swarm hooks extension (lines 393-399): Creates via createSwarmHooksExtension() from pi-mono-extension.ts.
Resource loader (lines 402-405): DefaultResourceLoader with appendSystemPrompt and the extension factory.
Returns PiMonoSession wrapping the native AgentSession.
PiMonoSession (line 137-357): Subscribes to pi-mono's AgentSessionEvent stream and normalizes events. handleAgentEvent() (line 181-254) maps:
message_end to raw_log with Claude-compatible JSON format
tool_execution_start to raw_log with tool_use content
tool_execution_end to raw_log with tool_result content
auto_retry_start to raw_stderr
runSession() (line 257-299): Calls agentSession.prompt(), waits for idle via waitForIdle() (polls isStreaming or subscribes for agent_end event), builds cost data from getSessionStats(), cleans up the symlink, and disposes the session.
canResume (line 421-432): Attempts to check pi-mono's SessionManager for the session ID.
A lightweight client that performs the MCP Streamable HTTP handshake (initialize + initialized notification at lines 72-93), discovers tools (listTools, line 96-106), and forwards tool calls (callTool, line 109-119). Handles both JSON and SSE response formats (line 56-68). This exists because pi-mono does not natively consume MCP servers the way Claude Code does via .mcp.json.
How Hooks Work Per Provider
Claude: External Process Hook (src/hooks/hook.ts)
Claude Code invokes /usr/local/bin/agent-swarm hook as an external process for each hook event. This is configured in Dockerfile.worker at line 109-116 in the settings.json hooks config, covering: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop.
The hook reads JSON from stdin (line 217), reads MCP config from .mcp.json (line 206-213), fetches agent info from the API (line 264-283), then dispatches based on hook_event_name (line 685). Tool names in Claude hooks are capitalized (Write, Edit, Bash -- line 837, 878, 907).
The Claude hook additionally manages ~/.claude/CLAUDE.md backup/restore (lines 159-195) and syncs claudeMd content to the server (line 332-355), which is Claude-specific behavior.
createSwarmHooksExtension() (line 380) returns an ExtensionFactory that registers event handlers on the pi-mono extension API (pi.on(...)). The mapping is:
Claude Hook Event
Pi-Mono Extension Event
Line
SessionStart
session_start
383
PreToolUse
tool_call
405
PostToolUse
tool_result
478
PreCompact
context
561
UserPromptSubmit
input
586
Stop
session_shutdown
602
The pi-mono extension uses lowercase tool names (write, edit, bash -- lines 459, 496, 520) versus Claude's capitalized names. The extension can return { block: true, reason } to block tool calls (line 411-417), while the Claude hook outputs { decision: "block", reason } to stdout (line 518-524).
Both implementations share the same behavioral logic: task cancellation checks, tool loop detection, polling limit checks, shared disk write prevention, heartbeat pings, identity file sync, memory auto-indexing, goal reminders at compaction, and session summarization at shutdown.
Runner Structure (src/commands/runner.ts)
The runner is fully provider-agnostic. At line 1428, runAgent() creates the adapter:
spawnProviderProcess() (line 1098-1265): Non-blocking spawn for concurrent task execution. Builds a ProviderSessionConfig, calls adapter.createSession(config), subscribes to events for log streaming and session ID capture, returns a RunningTask with a completion promise.
runProviderIteration() (line 1268-1314): Blocking single-iteration execution for AI-loop mode. Same config construction, but awaits session.waitForCompletion() directly.
Both functions resolve env from the API via fetchResolvedEnv() (line 1124, 1283) to pick up MODEL_OVERRIDE from swarm config.
Docker Worker Setup Per Provider (Dockerfile.worker, docker-entrypoint.sh)
Dockerfile.worker:
Both CLIs are installed: Claude CLI at line 77, pi-mono at line 83.
Claude-specific setup: settings.json with hooks config (lines 103-117), Claude plugins (lines 88-96).
Pi-mono-specific setup: plugin/pi-skills/ copied to ~/.pi/agent/skills/ (line 142), PI_PACKAGE_DIR env set (line 85).
Default: HARNESS_PROVIDER=claude (line 165).
docker-entrypoint.sh:
Lines 5-19: Validates auth credentials based on HARNESS_PROVIDER. For "pi": requires ANTHROPIC_API_KEY, OPENROUTER_API_KEY, or ~/.pi/agent/auth.json. For Claude (default): requires CLAUDE_CODE_OAUTH_TOKEN.
Line 540: Runs exec /usr/local/bin/agent-swarm "$ROLE" "$@" -- the compiled binary that invokes runAgent() which then uses the provider abstraction.
Data Flow
Docker container starts, docker-entrypoint.sh validates auth per HARNESS_PROVIDER (line 5-19)
Entrypoint execs agent-swarm worker (line 540)
runAgent() in runner.ts:1423 creates the adapter (line 1428)
Worker poll loop gets a task, calls spawnProviderProcess() (line 1098)
Adapter's createSession() is called (line 1143):
Claude: spawns claude CLI process, streams JSON stdout
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/Dockerfile.worker -- Installs both CLIs, configures both skill/command sets
<total_tokens>72401</total_tokens><tool_uses>24</tool_uses><duration_ms>120065</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-11-feat-codex-support/tasks/afb7a9270097f6db1.output
forced_login_method = "api"
8. Type generation: codex app-server generate-ts --out DIR and codex app-server generate-json-schema --out DIR. Pass --experimental to include experimental methods. Output is version-pinned to the binary.
9. Known issues: (a) --dangerously-bypass-approvals-and-sandbox doesn't actually bypass sandbox for tool child processes (issue #14068), (b) 503 errors when app-server tries upstream wss://chatgpt.com endpoint while codex exec works (issue #14056), (c) no RPC to trigger manual compaction when auto-compact fails (issue #9142), (d) approval response RPC gap in strict protocol-only mode (issue #14192), (e) Windows crash on certain builds (issue #12962).
10. Approval modes: approval_policy in config.toml: "untrusted" (default, only safe read-only auto-run), "on-request" (model decides), "never" (no prompts). CLI flags: --full-auto (shortcut for --sandbox workspace-write --ask-for-approval on-request), --dangerously-bypass-approvals-and-sandbox (alias --yolo). Sandbox modes: read-only, workspace-write, danger-full-access.
Integration relevance for agent-swarm: The existing ProviderAdapter interface (createSession, canResume, events like session_init, message, tool_start, tool_end, result, error) maps well to the app-server protocol. A Codex adapter would spawn codex app-server, perform the initialize handshake, use thread/start + turn/start to execute tasks, map item events to ProviderEvent, and use turn/interrupt for cancellation. API key auth (OPENAI_API_KEY env var) is the cleanest path for Docker workers.
"Shipped earlier, smaller surface area" per OpenAI
"First-class integration method maintained moving forward" per OpenAI
Verdict for Agent-Swarm Adapter
The raw App Server JSON-RPC approach is better for our use case. Here's why:
Missing critical methods: The SDK does not expose turn/interrupt (abort) or turn/steer (mid-task guidance) -- both mapped to our ProviderSession interface in the feasibility research. Issues #5494 and #12329 are open requesting these.
Node.js dependency: The SDK requires Node.js 18+. Our workers run on Bun. While Bun has high Node.js compat, it's an unnecessary compatibility risk when the App Server protocol works with any runtime.
OpenAI's own guidance: "Codex App Server will be the first-class integration method maintained moving forward. By default, clients should use Codex App Server to integrate with Codex."
Less control: The SDK abstracts away process lifecycle, which is convenient for simple use cases but means we lose control over when to restart, how to handle crashes, and how to manage long-lived server processes.
Event mapping: The SDK's 7 event types are a strict subset of what the App Server provides. The raw JSONL stream gives us item/*/delta for streaming, thread/compact/start for context preservation hooks, etc.
The SDK would be appropriate for a quick prototype or CI script, but for a production adapter that needs abort, steering, fine-grained event monitoring, and hook-equivalent behavior, the App Server JSON-RPC is the right choice.
Known SDK Issues
No abort/cancel: Issue #5494 -- no way to cancel an active thread.run() call
No turn/steer: Issue #12329 -- SDK doesn't expose the app-server's turn/steer for injecting mid-turn messages
No fork/backtrack: Issue #4972 -- conversation fork/backtrack not exposed
Auth issues: Issue #7144 -- SDK auth not working in some configurations
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-11-feat-codex-support/tasks/adb5220daff39f99a.output
{ claudeSessionId }
The HTTP handler (src/http/tasks.ts:95-118) calls updateTaskClaudeSessionId() in src/be/db.ts:907-917, which runs:
sql
UPDATE agent_tasks SET claudeSessionId = ?, lastUpdatedAt = ? WHERE id = ? RETURNING *
The claudeSessionId column is defined on agent_tasks in src/be/migrations/001_initial.sql:98.
3. Session ID Retrieval (DB -> runner)
fetchProviderSessionId() (src/commands/runner.ts:620-635) fetches GET /api/tasks/:id and extracts claudeSessionId from the response.
4. Resume Decision in the Runner
There are two distinct resume paths in the runner-level polling loop:
Path A -- Resuming paused tasks (src/commands/runner.ts:1819-1832):
When the runner finds paused tasks via getPausedTasksFromAPI(), it attempts resume with this priority:
If the task itself has task.claudeSessionId (line 1821), use that: ["--resume", task.claudeSessionId]
Else if the task has task.parentTaskId (line 1826), fetch the parent's session ID via fetchProviderSessionId() and use that
Otherwise, start fresh (no --resume arg)
Path B -- New child tasks with parentTaskId (src/commands/runner.ts:2048-2065):
When the polling loop picks up a new trigger with a parentTaskId, it fetches the parent's session ID and adds ["--resume", parentSessionId] to effectiveAdditionalArgs.
Both paths pass --resume through additionalArgs, NOT through config.resumeSessionId.
5. How --resume Reaches the Claude Process
spawnProviderProcess() (src/commands/runner.ts:1098-1264) builds a ProviderSessionConfig and passes additionalArgs into it (line 1138). The Claude adapter's buildCommand() (src/providers/claude-adapter.ts:76-101) appends config.additionalArgs to the claude CLI invocation at line 92-94:
typescript
if (this.config.additionalArgs?.length) {
cmd.push(...this.config.additionalArgs);
}
This produces a command like: claude --model opus --verbose ... -p "prompt" --resume abc123.
6. Stale Session Retry
ClaudeSession.waitForCompletion() (src/providers/claude-adapter.ts:266-319) has automatic stale-session retry logic. If the process exits non-zero and the error tracker detects a "session not found" error (line 271), AND the config included --resume (line 272), it:
Strips --resume and its value from additionalArgs (lines 278-282)
Sets resumeSessionId: undefined on the retry config (line 292)
Creates a new ClaudeSession with fresh args and re-runs
7. AI-Loop Mode (Legacy)
In AI-loop mode (src/commands/runner.ts:2222-2278), each iteration calls runProviderIteration() with opts.additionalArgs passed straight from CLI options. There is no automatic resume between iterations -- each iteration spawns a completely fresh provider session. The additionalArgs are the same on every iteration (whatever was passed at startup).
8. ProviderSessionConfig.resumeSessionId Field
The resumeSessionId field (src/providers/types.ts:40) exists on the config type but serves a passive/metadata role. It is:
Never read by ClaudeAdapter.buildCommand() to construct CLI args
Never read by PiMonoAdapter.createSession() to configure the pi-mono session
Only explicitly referenced when clearing it during stale-session retry (src/providers/claude-adapter.ts:292)
Set in tests (src/tests/claude-adapter.test.ts:57) alongside the matching additionalArgs
The actual resume mechanism is entirely through additionalArgs containing ["--resume", "<sessionId>"].
9. Pi-Mono Resume (canResume)
PiMonoAdapter.canResume() (src/providers/pi-mono-adapter.ts:421-432) checks whether a session file exists via SessionManager. However, canResume() is defined on the ProviderAdapter interface (src/providers/types.ts:73) but is never called from the runner. The runner does not gate resume on adapter capability -- it always attempts resume if a session ID is available, relying on the stale-session retry in the Claude adapter to recover from failures.
1. Provider session starts
2. Provider emits session_init event with sessionId
3. Runner catches event -> calls saveProviderSessionId()
4. PUT /api/tasks/:id/claude-session -> DB: agent_tasks.claudeSessionId = X
5. [Later] Task is paused or child task created
6. Runner fetches paused tasks (with claudeSessionId) or fetches parent sessionId
7. Runner adds ["--resume", sessionId] to additionalArgs
8. spawnProviderProcess() -> adapter.createSession(config with additionalArgs)
9. Claude adapter: buildCommand() includes --resume in CLI args
10. If session not found: retry without --resume (fresh session)
Key Files
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/commands/runner.ts -- orchestrator, resume decision logic at lines 1819-1832 (paused tasks) and 2048-2065 (child tasks)
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/claude-adapter.ts -- --resume passed via additionalArgs at line 92; stale-session retry at lines 266-319
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/pi-mono-adapter.ts -- canResume() at line 421 (never called); no resume support in createSession()
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/providers/types.ts -- ProviderSessionConfig.resumeSessionId at line 40, ProviderAdapter.canResume() at line 73
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/be/db.ts -- updateTaskClaudeSessionId() at line 907, claudeSessionId column at line 120
/Users/taras/worktrees/agent-swarm/2026-03-11-feat/codex-support/src/http/tasks.ts -- PUT /api/tasks/:id/claude-session handler at line 95
Summary for Codex Mapping
For a Codex adapter's thread/resume, the key points are:
Session ID storage: Already provider-agnostic -- stored as claudeSessionId in agent_tasks table, persisted via PUT /api/tasks/:id/claude-session. The column name says "claude" but it stores any provider's session ID.
Resume trigger: The runner decides to resume based on whether task.claudeSessionId or a parent's session ID exists. This decision happens at runner level, not adapter level.
Resume delivery mechanism: Currently Claude-specific -- resume is delivered as --resume <id> in additionalArgs, which only the Claude adapter's buildCommand() consumes. For Codex, the adapter would need to read either config.resumeSessionId or config.additionalArgs and translate it to Codex's thread/resume API.
canResume() is dead code: The interface method exists but is never called by the runner. Resume is always attempted optimistically.
Each polling iteration creates a fresh session: There is no cross-iteration session continuity in either runner mode. Resume only happens for paused-task recovery and parent-to-child context inheritance.
<total_tokens>57357</total_tokens><tool_uses>30</tool_uses><duration_ms>126421</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-11-feat-codex-support/tasks/ac3a0b95dff30d9f7.output