From 4e750e4f1a8f7029c900f9433d5618c1c3e9b2df Mon Sep 17 00:00:00 2001 From: Savin Angel-Mario Date: Mon, 16 Nov 2026 23:32:24 +0200 Subject: [PATCH 1/8] Add Codex subagents on a Custom subagents settings page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude Code could only hand tasks to Claude subagents. With Codex turned on in Settings → Custom subagents, each listed model becomes an agent type (`Claudiu:codex-gpt-6-1-sol`, or `Claudiu:codex` on Codex's default model) that runs the task in OpenAI Codex. The mod answers each turn of such an agent itself, so Claude never runs for it. It starts `claudiu --acp`, a hidden helper mode that speaks the Agent Client Protocol to `npx codex-acp@2.6.0`, streams Codex's messages and steps as thinking lines, and hands back Codex's last message with SubagentHandback. Codex runs read-only unless Allow edits is on. Refs #110 --- README.md | 6 +- mod/hooks/register.js | 124 +++++++++- mod/hooks/subagents.test.ts | 109 +++++++++ src/app/headless.rs | 44 ++++ src/app/mod.rs | 18 +- src/app/modal.rs | 13 +- src/app/sessions.rs | 6 + src/app/settings.rs | 13 +- src/claude/acp.rs | 447 ++++++++++++++++++++++++++++++++++++ src/claude/mod.rs | 2 + src/claude/subagents.rs | 135 +++++++++++ src/main.rs | 4 + src/panels/settings_view.rs | 35 ++- src/store.rs | 3 + web/src/pages/index.astro | 2 +- 15 files changed, 947 insertions(+), 14 deletions(-) create mode 100644 mod/hooks/subagents.test.ts create mode 100644 src/claude/acp.rs create mode 100644 src/claude/subagents.rs diff --git a/README.md b/README.md index 4db98b4..9983f9f 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,15 @@ Each session is your own `claude` process in a real pseudo-terminal, so Claude C Around the terminal, Claudiu adds an editor mode (Ctrl+Shift+E) with files, tabs, search, Git change marks and language-server diagnostics, definitions and completion. It also adds usage and context meters, a GitHub pane for issues and pull requests through your `gh` login (Claude attaches the ones it works on to the right sidebar, from this project or another repository), defaults for the model, effort and permission mode of new sessions, and extra Claude accounts that share one configuration: settings, `CLAUDE.md`, keybindings, MCP servers, folder trust and the options `/config` saves, with your main `~/.claude` too. An account with a running session takes a changed `/config` option once its sessions have ended. You name a session yourself, from its right-click menu, by regenerating its title, or with `/rename` in Claude Code, which Claudiu's sidebar follows. When a reply needs a table, chart or diagram, Claude draws it as a card inside the terminal, under the tool call, and the card scrolls with the transcript. Cards can hold buttons that send a message for you, collapsible sections, tabs and charts, and they come back when you reopen a session. A session can move between git worktrees the way it switches branches, so several agents work on separate branches at once: the worktree button in the top bar switches the shown session into another worktree, or into a new one that Claudiu makes on a branch you name, and its conversation continues there (a session that has no conversation yet starts over in the new folder). Claude can switch the session itself with the `switch_worktree` tool, after you approve it and once its turn ends. In the menu, the hover x removes a worktree, the branch button's x deletes a local branch after telling you which commits would be lost, and ending the last session in a worktree offers to remove it. Claudiu keeps the worktrees it makes in its own data folder, outside your repositories, so they never show up in `git status`; Settings has a Worktrees page that lists them to show in the file manager or remove. Settings lists the rest. +Settings → Custom subagents can add Codex subagents, which hand a task to OpenAI Codex instead of Claude. Claude uses one only when you ask for Codex or GPT. Each model you list becomes an agent type such as `Claudiu:codex-gpt-6-1-sol`, and an empty list gives one type, `Claudiu:codex`, on Codex's default model. They need Node.js (`npx`) and a `codex login`, and the first run downloads [codex-acp](https://github.com/agentclientprotocol/codex-acp) from npm. Codex runs read-only unless you turn on Allow edits. With edits allowed, Codex changes files and runs commands in the subagent's folder without Claude Code's permission rules or hooks. A follow-up message to a finished Codex subagent starts a new Codex session without the earlier context. + Ctrl+Shift (Cmd+Shift on macOS) plus a letter drives the app. Everything else reaches Claude Code. Editor mode finds `rust-analyzer`, `tsc --lsp` and `gleam` on your PATH and installs nothing. To reduce background rendering, an inactive window updates streaming terminal output at most four times a second, with a final update when output stops. Returning to the window restores the normal frame rate. Busy sidebar icons stop animating while the window is inactive, the sidebar is hidden, or editor mode hides it. When a session finishes or asks a question while the window is in the background, Claudiu sends a system notification. ## What it touches -Claudiu never deletes a transcript. It writes to Claude Code's own data only to change the settings you switch in Claudiu, as `/config` does, to sync shared files between accounts, and to append one line to a transcript when a session that `claude --worktree` put in a worktree moves to another folder, so Claude Code knows it has left that worktree. Nothing is uploaded and terminal contents are never logged. The only network use is GitHub: the update check (off with `"settings": { "update_url": "" }` in `state.json`) and the GitHub pane. State lives in `%LOCALAPPDATA%\m4rocks\Claudiu\data` on Windows, `~/Library/Application Support/Claudiu` on macOS and `~/.local/share/claudiu` on Linux, and crashes go to `crash.log` there. +Claudiu never deletes a transcript. It writes to Claude Code's own data only to change the settings you switch in Claudiu, as `/config` does, to sync shared files between accounts, and to append one line to a transcript when a session that `claude --worktree` put in a worktree moves to another folder, so Claude Code knows it has left that worktree. Claudiu uploads nothing itself, and terminal contents are never logged. Its only network use is GitHub: the update check (off with `"settings": { "update_url": "" }` in `state.json`) and the GitHub pane. Codex subagents, once you turn them on, download codex-acp from npm and send their tasks to OpenAI through Codex. State lives in `%LOCALAPPDATA%\m4rocks\Claudiu\data` on Windows, `~/Library/Application Support/Claudiu` on macOS and `~/.local/share/claudiu` on Linux, and crashes go to `crash.log` there. ## Known gaps @@ -44,7 +46,7 @@ just ci # what CI checks, plus the mod and the web build The repository has three parts: - `src/` is the app, including the MCP server that each session connects to. -- `mod/` is the Claude Code plugin each session loads, which writes the usage snapshots. +- `mod/` is the Claude Code plugin each session loads, which writes the usage snapshots and answers for Codex subagents. - `web/` is the Astro site. `CLAUDE.md` has the conventions for contributing. Releases use [Velopack](https://velopack.io) and GitHub Releases: bump `version` in `Cargo.toml`, then `git tag vX.Y.Z && git push --tags`. `scripts\package.ps1` builds a local installer. The Linux release is an AppImage. diff --git a/mod/hooks/register.js b/mod/hooks/register.js index 41409b8..5fda7a2 100644 --- a/mod/hooks/register.js +++ b/mod/hooks/register.js @@ -18,6 +18,8 @@ // paints the live card over them. Claudiu's measured height comes back in `CLAUDIU_VISUAL_PREFIX.rows`. // - One-shot completions: runs requests from `CLAUDIU_ASK_FILE` (commit messages, session titles) with // `$.model.complete`, on this session's own client, so Claudiu needs no `claude -p`. +// - Custom subagents: registers the Codex agent types `CLAUDIU_SUBAGENTS` lists. Claude never runs for those agents: +// each turn is answered here with what Codex reports through `CLAUDIU_EXE --acp`, handed back with SubagentHandback. // ---- Constants ---------------------------------------------------------------------------------------------------- @@ -33,6 +35,9 @@ const PROMPT_MAX = 20000 // characters of a message Claudiu asks the session to const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] const ASK_MODELS = ['haiku', 'sonnet', 'opus'] const VISUAL_TOOL = 'mcp__claudiu__show_visual' +// Claude Code names a plugin's agent types `:`; this plugin is `Claudiu`. +const AGENT_PREFIX = 'Claudiu:' +const HANDBACK_TOOL = 'SubagentHandback' // The /config row for background compaction ("Precompute compaction"). Claude Code lists it only while a server-side // flag enables the feature; without the row the setting does nothing, so Claudiu offers the switch only with it. const PRECOMPUTE_ROW = 'precomputeCompactionEnabled' @@ -49,6 +54,8 @@ let askPoll // watches CLAUDIU_ASK_FILE let askSeen = null // id of the last request looked at let asking = false // a completion is running; a poll that finds another request waits for it const cardRows = new Map() // show_visual call id -> rows reserved for its card +const codexTypes = new Map() // `Claudiu:` -> { model, edits } of each Codex agent type registered +const codexRuns = new Map() // agent id -> { type, prompt, turnId, report } of each Codex subagent started const published = new Set() // call ids whose card file this process wrote from the transcript let rowsPoll // watches the heights Claudiu measures let visualChain = Promise.resolve() // visual writes in order, without holding up the stream @@ -337,6 +344,117 @@ async function watchSessionName($) { }) } +// ---- Custom subagents --------------------------------------------------------------------------------------------- + +// Registers the Codex agent types Claudiu listed, already checked (`claude/subagents.rs`). A missing or broken list +// registers none. +async function registerSubagents($) { + codexTypes.clear() + const listed = await $.env.get('CLAUDIU_SUBAGENTS') + if (!listed || !(await $.env.get('CLAUDIU_EXE'))) return + let codex + try { + codex = JSON.parse(listed).codex + } catch { + return + } + for (const { name, model } of codex?.types ?? []) { + const description = model + ? `Runs the task in OpenAI Codex on ${model}. Use only when the user asks for Codex, GPT or ${model}.` + : 'Runs the task in OpenAI Codex on its default model. Use only when the user asks for Codex or GPT.' + // Claude never runs for this agent (codexStep answers its turns), so its prompt, model and tools are never used. + await $.agent.register({ name, description, prompt: 'Codex answers for this agent.', model: 'haiku', tools: [] }) + .then(() => codexTypes.set(AGENT_PREFIX + name, { model: model ?? null, edits: codex.edits === true })) + .catch(() => {}) + } +} + +// Notes the task of each Codex subagent as it starts; its turns are answered by codexStep. +async function onAgentSpawn($, e, next) { + const r = await next(e) + if (r.agentId && codexTypes.has(e.subagentType)) { + codexRuns.set(r.agentId, { type: e.subagentType, prompt: e.prompt, turnId: null, report: null }) + } + return r +} + +// The Codex run of a subagent, or undefined for any other agent. A reload of this module forgets the runs it noted, +// so an agent of a Codex type not noted is taken up from the agent list, with its newest message as the task. +async function codexRun($, agentId) { + if (codexRuns.has(agentId) || codexTypes.size === 0) return codexRuns.get(agentId) + const agent = (await $.agent.list().catch(() => [])).find(a => a.id === agentId) + if (!agent || !codexTypes.has(agent.type)) return undefined + const run = { type: agent.type, prompt: null, turnId: null, report: null } + codexRuns.set(agentId, run) + return run +} + +// The task for this turn: the Agent call's prompt on the first turn, the newest message to the agent after that +// (a message sent to a finished subagent starts a turn of its own). +async function codexTask($, run, agentId) { + if (run.turnId === null && run.prompt !== null) return run.prompt + const messages = await $.session.messages({ agentId }).catch(() => []) + const last = Array.isArray(messages) ? messages.filter(m => m.role === 'user' && m.text?.trim()).at(-1) : undefined + return last?.text ?? run.prompt ?? '' +} + +// Answers one step of a Codex subagent: runs the task in Codex, streams what Codex writes as thinking (shown, not +// saved), and hands back Codex's report. Codex runs once per turn; a later step of the same turn (a refused hand-back) +// hands back the same report again. +async function* codexStep($, e, next, run) { + if (run.turnId !== e.turnId || run.report === null) { + const prompt = await codexTask($, run, e.agentId) + run.turnId = e.turnId + const { model, edits } = codexTypes.get(run.type) + yield { kind: 'thinking', index: 0, text: `Codex on ${model ?? "Codex's default model"}, ${edits ? 'edits allowed' : 'read-only'}\n\n` } + run.report = null + for await (const event of codexEvents($, { model, edits, cwd: await $.session.cwd(), prompt }, next.signal)) { + if (event.kind === 'text') yield { kind: 'thinking', index: 0, text: event.text } + else if (event.kind === 'step') yield { kind: 'thinking', index: 0, text: `\n▸ ${event.text}\n` } + else if (event.kind === 'report') run.report = event.text + else if (event.kind === 'failed') run.report = 'Codex failed: ' + event.reason + } + if (next.signal?.aborted) return + run.report ??= 'Codex failed: the helper stopped without an answer.' + } + const input = { message: run.report } + yield { kind: 'tool', index: 1, id: `toolu_codex_${e.turnId}_${e.index}`, name: HANDBACK_TOOL } + yield { kind: 'input', index: 1, json: JSON.stringify(input) } + yield { kind: 'stop', stopReason: 'tool_use', usage: null } + return { turnId: e.turnId, index: e.index, answer: '', toolUses: [{ name: HANDBACK_TOOL, input }], stopReason: 'tool_use', usage: null } +} + +// The helper's events, one per line of its output. Stops early, ending the helper and Codex, when the turn is +// interrupted. +async function* codexEvents($, request, signal) { + const exe = await $.env.get('CLAUDIU_EXE') + let pending = '' + try { + for await (const chunk of $.process.spawn({ argv: [exe, '--acp'], input: JSON.stringify(request) })) { + if (signal?.aborted) return + if (chunk.stream !== 'stdout') continue + pending += chunk.text + const lines = pending.split('\n') + pending = lines.pop() + for (const line of lines) { + const event = parseEvent(line) + if (event) yield event + } + } + } catch (err) { + yield { kind: 'failed', reason: 'the helper could not run (' + String(err?.message ?? err).slice(0, 200) + ')' } + } +} + +function parseEvent(line) { + try { + const event = JSON.parse(line) + return typeof event?.kind === 'string' ? event : null + } catch { + return null + } +} + // ---- Hook handlers ------------------------------------------------------------------------------------------------ async function onMeasure($, e, next) { @@ -438,8 +556,10 @@ async function onShowVisual($, e) { } // Applies the saved model and effort to this turn's steps, and streams a show_visual call to its card while the model -// writes it. Sub-agent steps are left alone. +// writes it. A Codex subagent's steps are answered by codexStep; other subagents' steps are left alone. async function* onTurnStep($, e, next) { + const run = e.agentId ? await codexRun($, e.agentId) : undefined + if (run) return yield* codexStep($, e, next, run) const step = !e.agentId && (want.model || want.effort) ? { ...e, model: want.model ?? e.model, effort: want.effort ?? e.effort } : e @@ -514,6 +634,7 @@ async function onSessionStart($, e, next) { rowsPoll?.cancel() rowsPoll = $.clock.every(200, () => readCardRows($)) await watchSessionName($) + await registerSubagents($) return r } @@ -527,5 +648,6 @@ export function register(on) { on('ui.render', { component: 'ToolUse' }, onVisualRow) on('ui.render', { component: 'ToolGroup' }, onVisualGroup) on('turn.step', onTurnStep) + on('agent.spawn', onAgentSpawn) on('session.start', onSessionStart) } diff --git a/mod/hooks/subagents.test.ts b/mod/hooks/subagents.test.ts new file mode 100644 index 0000000..5247951 --- /dev/null +++ b/mod/hooks/subagents.test.ts @@ -0,0 +1,109 @@ +import { expect, mock, test } from 'claude-code/testing' + +const SUBAGENTS = JSON.stringify({ codex: { edits: false, types: [{ name: 'codex-gpt-5-5', model: 'gpt-5.5' }] } }) + +// What the engine answers beneath the mod for a session with Codex on. `helper` is what `claudiu --acp` writes; +// `requests` collects what the mod sent it. +function engine(on: any, helper: string[], requests: unknown[], subagents = SUBAGENTS) { + mock.env(on, { CLAUDIU_SUBAGENTS: subagents, CLAUDIU_EXE: '/apps/claudiu' }) + mock.clock(on) + on('fs.read', () => ({ value: '' })) + on('fs.write', () => ({ value: undefined })) + on('session.id', () => ({ value: 's1' })) + on('session.model', () => ({ value: 'claude-haiku-5-5' })) + on('session.cwd', () => ({ value: '/work/sub' })) + on('config.list', () => ({ value: [] })) + on('settings.read', () => ({ value: {} })) + on('session.start', (_$: any, e: any) => ({ cwd: e.cwd })) + const registered: any[] = [] + on('agent.register', (_$: any, e: any) => { + registered.push(e) + return { value: undefined } + }) + on('agent.spawn', () => ({ model: 'haiku', agentId: 'a1' })) + on('process.spawn', async function* (_$: any, e: any) { + requests.push({ argv: e.argv, input: JSON.parse(e.input) }) + // Pieces cut mid-line, as a pipe delivers them. + const out = helper.join('\n') + '\n' + yield { stream: 'stdout', text: out.slice(0, 7) } + yield { stream: 'stdout', text: out.slice(7) } + return { value: { code: 0, signal: null } } + }) + // Claude, for any agent the mod leaves alone. + on('turn.step', async function* (_$: any, e: any) { + yield { kind: 'text', index: 0, text: 'Claude answered' } + return { turnId: e.turnId, index: e.index, answer: 'Claude answered', toolUses: [], stopReason: 'end_turn', usage: null } + }) + return registered +} + +async function step($: any, turnId: string, index: number, agentId?: string) { + const chunks: any[] = [] + const stream = $.turn.step({ turnId, index, model: 'haiku', messageCount: 1, agentId }) + for await (const c of stream) chunks.push(c) + return chunks +} + +test('a Codex subagent runs the task in Codex and hands back its last message', async ($, on) => { + const requests: any[] = [] + const registered = engine(on, [ + JSON.stringify({ kind: 'text', text: 'Looking.' }), + JSON.stringify({ kind: 'step', text: 'Read src/a.rs' }), + JSON.stringify({ kind: 'report', text: 'The bug is on line 12.' }), + ], requests) + + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + expect(registered.map(r => r.name)).toEqual(['codex-gpt-5-5']) + expect(registered[0].description).toBe('Runs the task in OpenAI Codex on gpt-5.5. Use only when the user asks for Codex, GPT or gpt-5.5.') + + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + + expect(requests).toEqual([{ argv: ['/apps/claudiu', '--acp'], input: { model: 'gpt-5.5', edits: false, cwd: '/work/sub', prompt: 'Find the bug' } }]) + const thinking = chunks.filter(c => c.kind === 'thinking').map(c => c.text).join('') + expect(thinking).toBe('Codex on gpt-5.5, read-only\n\nLooking.\n▸ Read src/a.rs\n') + expect(chunks.some(c => c.kind === 'text')).toBe(false) // nothing of Codex's is saved but the report + const tool = chunks.find(c => c.kind === 'tool') + expect(tool.name).toBe('SubagentHandback') + const input = chunks.filter(c => c.kind === 'input').map(c => c.json).join('') + expect(JSON.parse(input)).toEqual({ message: 'The bug is on line 12.' }) + + // A second step of the same turn (a refused hand-back) hands back the same report without running Codex again. + const again = await step($, 't1', 1, 'a1') + expect(requests.length).toBe(1) + expect(JSON.parse(again.filter(c => c.kind === 'input').map(c => c.json).join(''))).toEqual({ message: 'The bug is on line 12.' }) +}) + +test('a failure is handed back as the report', async ($, on) => { + engine(on, [JSON.stringify({ kind: 'failed', reason: "Codex isn't signed in. Run `codex login`, then try again." })], []) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + const input = JSON.parse(chunks.filter(c => c.kind === 'input').map(c => c.json).join('')) + expect(input.message).toBe("Codex failed: Codex isn't signed in. Run `codex login`, then try again.") +}) + +test('a helper that ends without an answer is a failure too', async ($, on) => { + engine(on, ['not json'], []) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + const input = JSON.parse(chunks.filter(c => c.kind === 'input').map(c => c.json).join('')) + expect(input.message).toBe('Codex failed: the helper stopped without an answer.') +}) + +test('other subagents still run on Claude', async ($, on) => { + const requests: unknown[] = [] + engine(on, [], requests) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'general-purpose', prompt: 'Look around' }) + const chunks = await step($, 't1', 0, 'a1') + expect(chunks.map(c => c.kind)).toEqual(['text']) + expect(requests).toEqual([]) +}) + +test('no Codex types are registered while Codex is off', async ($, on) => { + const registered = engine(on, [], [], '') // an empty list reads as none, like a missing one + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + expect(registered).toEqual([]) +}) diff --git a/src/app/headless.rs b/src/app/headless.rs index ae32e30..e64b920 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -2283,3 +2283,47 @@ fn the_projects_page_moves_renames_and_removes_projects() { assert_eq!(names(&h), ["beta", "alpha two"], "Undo puts it back in its place"); assert_eq!(h.ws().store.session(&session).unwrap().project_id.as_ref(), Some(&beta), "with its session"); } + +/// Settings → Custom subagents: the models field shows once Codex is on, Save keeps what was typed, and a new session +/// gets only the checked agent types. +#[test] +fn custom_subagents_reach_new_sessions() { + let mut h = Harness::new(|_| vec![]); + h.step(|ws| { + ws.act(Act::OpenSettings); + ws.set_settings_page(SettingsPage::CustomSubagents); + }); + h.settle(); + assert!(!h.drawn("modal-field-5"), "the models field waits for the Codex switch"); + h.click("settings-codex"); + h.settle(); + assert!(h.drawn("modal-field-5"), "the models field shows once Codex is on: {:?}", h.keys()); + h.click("modal-field-5"); + for c in "gpt-5.5, gpt 5".chars() { + h.press(rune::Key::Text(c.to_string()), |_| {}); + } + h.click("settings-codex-edits"); + h.step(|ws| ws.submit_modal()); + assert_eq!(h.ws().toast.as_ref().map(|t| t.text.as_str()), Some("Settings saved. Custom subagents apply to new and resumed sessions.")); + let saved = h.ws().store.data.settings.custom_subagents.clone(); + assert_eq!( + saved, + crate::claude::subagents::CustomSubagents { codex: true, codex_models: vec!["gpt-5.5".into(), "gpt 5".into()], codex_edits: true } + ); + + // A stand-in `claude` that prints what the mod would read. + let printer = h.work.join(if cfg!(windows) { "printer.cmd" } else { "printer" }); + let script = if cfg!(windows) { "@echo off\r\necho %CLAUDIU_SUBAGENTS%\r\nping -n 60 127.0.0.1 >nul\r\n" } else { "#!/bin/sh\necho \"$CLAUDIU_SUBAGENTS\"\nsleep 60\n" }; + std::fs::write(&printer, script).unwrap(); + #[cfg(unix)] + std::fs::set_permissions(&printer, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); + let cwd = h.work.clone(); + h.step(|ws| { + ws.claude_exe = Some(printer); + ws.new_claude(cwd); + }); + let id = h.ws().active.clone().expect("a session is shown"); + h.wait("the agent types to reach the session", |ws| { + ws.live_view(&id).is_some_and(|v| v.tail_text(2000).contains(r#"{"codex":{"edits":true,"types":[{"name":"codex-gpt-5-5","model":"gpt-5.5"}]}}"#)) + }); +} diff --git a/src/app/mod.rs b/src/app/mod.rs index 8b673de..3bf39d6 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -301,10 +301,21 @@ pub enum Modal { hints: [String; 4], /// The project being renamed on the Projects page, and the name typed so far. renaming: Option<(Id, TextEdit)>, + /// The Custom subagents page. + subagents: SubagentsForm, }, } -/// A field of the open modal, by its place: the dialog's only field is 0; Settings' are shell, claude, model, skills. +/// The Custom subagents page of the Settings dialog, as edited so far. +pub struct SubagentsForm { + pub codex: bool, + /// Codex models, separated by commas. + pub models: TextEdit, + pub edits: bool, +} + +/// A field of the open modal, by its place: the dialog's only field is 0; Settings' are shell, claude, model, skills, +/// the project being renamed and the Codex models. pub fn modal_field(modal: &mut Option, n: usize) -> Option<&mut TextEdit> { match (modal.as_mut()?, n) { (Modal::Rename { input, .. } | Modal::NewBranch { input, .. } | Modal::NewWorktree { input, .. } | Modal::Advisor { input, .. } | Modal::GoToLine { input, .. } | Modal::FileName { input, .. }, 0) => Some(input), @@ -313,6 +324,7 @@ pub fn modal_field(modal: &mut Option, n: usize) -> Option<&mut TextEdit> (Modal::Settings { model, .. }, 2) => Some(model), (Modal::Settings { skills_field, .. }, 3) => Some(skills_field), (Modal::Settings { renaming: Some((_, name)), .. }, 4) => Some(name), + (Modal::Settings { subagents, .. }, 5) => Some(&mut subagents.models), _ => None, } } @@ -750,7 +762,9 @@ impl Workspace { let hints = [platform::default_shell(None).0, claude_hint, "Claude Code default".into(), "none, e.g. dataviz, claude-api".into()]; self.blur = true; self.set_settings_page(self.settings_page); - self.modal = Some(Modal::Settings { shell, claude, model, effort: defaults.effort, permission: defaults.permission_mode, updates, chrome, scale: crate::panels::scale::percent(), trimmed: self.store.data.settings.trimmed_tools.clone(), claudiu_off: self.store.data.settings.claudiu_tools_off.clone(), skills_field, costly: claude::costly::scan(), hints, renaming: None }); + let custom = &self.store.data.settings.custom_subagents; + let subagents = SubagentsForm { codex: custom.codex, models: modal::field(&custom.codex_models.join(", "), false), edits: custom.codex_edits }; + self.modal = Some(Modal::Settings { shell, claude, model, effort: defaults.effort, permission: defaults.permission_mode, updates, chrome, scale: crate::panels::scale::percent(), trimmed: self.store.data.settings.trimmed_tools.clone(), claudiu_off: self.store.data.settings.claudiu_tools_off.clone(), skills_field, costly: claude::costly::scan(), hints, renaming: None, subagents }); self.modal_serial += 1; } Act::PickEffort(choice) => { diff --git a/src/app/modal.rs b/src/app/modal.rs index d4010af..9e9951c 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -94,7 +94,7 @@ impl Workspace { } } } - Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming }) => { + Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming, subagents }) => { let clean = |s: &str| s.trim().trim_matches('"').to_string(); let (shell_t, claude_t) = (clean(&shell.text), clean(&claude.text)); let model_name = claude::defaults::parse_model(&model.text); @@ -109,7 +109,7 @@ impl Workspace { let bad_limits = limits.as_ref().err().map(|why| (SettingsPage::ClaudeTools, 3, why.clone())); if let Some((page, field, msg)) = paths.or(bad_model).or(bad_limits) { self.settings_page = page; - self.modal = Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming }); + self.modal = Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming, subagents }); if let Some(f) = modal_field(&mut self.modal, field) { f.focused = true; } @@ -150,16 +150,25 @@ impl Workspace { } } } + let custom_subagents = claude::subagents::CustomSubagents { + codex: subagents.codex, + codex_models: claude::subagents::parse_models(&subagents.models.text), + codex_edits: subagents.edits, + }; let tools_changed = s.trimmed_tools != trimmed || s.limits != limits || s.claudiu_tools_off != claudiu_off; + let subagents_changed = s.custom_subagents != custom_subagents; s.trimmed_tools = trimmed; s.limits = limits; s.claudiu_tools_off = claudiu_off; + s.custom_subagents = custom_subagents; crate::panels::scale::set(scale); self.shell = platform::default_shell(s.shell.as_deref()); self.claude_exe = claude::discover(s.claude_path.as_deref()); self.store.mark_dirty(); if let Some(e) = trim_error { self.toast(format!("Settings saved, but Claude Code's settings.json could not be changed ({e}), so the tool trims stay as they were."), true); + } else if subagents_changed && !tools_changed { + self.toast("Settings saved. Custom subagents apply to new and resumed sessions.", false); } else if tools_changed { self.toast("Settings saved. Tool changes apply to new sessions; resumed sessions keep the old instructions until their next compaction.", false); } else { diff --git a/src/app/sessions.rs b/src/app/sessions.rs index 9f90523..e3b1c76 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -36,6 +36,12 @@ impl Workspace { spec.env.push((usage::CTL_ENV.into(), usage::ctl_file(record_id).to_string_lossy().into_owned())); spec.env.push((crate::visual::VISUAL_ENV.into(), crate::visual::prefix(record_id).to_string_lossy().into_owned())); spec.env.push((crate::claude::ask::ASK_ENV.into(), crate::claude::ask::request_file(record_id).to_string_lossy().into_owned())); + if let Some(subagents) = settings.custom_subagents.env() + && let Ok(exe) = std::env::current_exe() + { + spec.env.push((crate::claude::subagents::ENV.into(), subagents)); + spec.env.push((crate::claude::subagents::EXE_ENV.into(), exe.to_string_lossy().into_owned())); + } } if chrome { spec.args.push("--chrome".into()); diff --git a/src/app/settings.rs b/src/app/settings.rs index 2507437..79440fc 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -12,12 +12,13 @@ pub enum SettingsPage { Projects, ClaudeTools, ClaudiuTools, + CustomSubagents, Worktrees, About, } impl SettingsPage { - pub const ALL: [SettingsPage; 7] = [Self::General, Self::Sessions, Self::Projects, Self::ClaudeTools, Self::ClaudiuTools, Self::Worktrees, Self::About]; + pub const ALL: [SettingsPage; 8] = [Self::General, Self::Sessions, Self::Projects, Self::ClaudeTools, Self::ClaudiuTools, Self::CustomSubagents, Self::Worktrees, Self::About]; pub fn label(self) -> &'static str { match self { @@ -26,6 +27,7 @@ impl SettingsPage { Self::Projects => "Projects", Self::ClaudeTools => "Claude Code tools", Self::ClaudiuTools => "Claudiu tools", + Self::CustomSubagents => "Custom subagents", Self::Worktrees => "Worktrees", Self::About => "About", } @@ -52,10 +54,12 @@ impl Workspace { SettingsPage::General => &[0, 1], SettingsPage::Sessions => &[2], SettingsPage::ClaudeTools => &[3], + // The models field shows only while Codex is on. + SettingsPage::CustomSubagents if matches!(&self.modal, Some(Modal::Settings { subagents, .. }) if subagents.codex) => &[5], SettingsPage::Projects if modal_field(&mut self.modal, 4).is_some() => &[4], _ => &[], }; - let focused = (0..5).find(|n| modal_field(&mut self.modal, *n).is_some_and(|f| f.focused)); + let focused = (0..6).find(|n| modal_field(&mut self.modal, *n).is_some_and(|f| f.focused)); let on_list = focused.is_none(); let plain = !ks.modifiers.control && !ks.modifiers.alt && !ks.modifiers.platform; match ks.key.as_str() { @@ -66,7 +70,7 @@ impl Workspace { let here = focused.and_then(|f| fields.iter().position(|x| *x == f)).map_or(0, |i| i + 1); let stops = fields.len() + 1; let there = if ks.modifiers.shift { (here + stops - 1) % stops } else { (here + 1) % stops }; - for n in 0..5 { + for n in 0..6 { if let Some(f) = modal_field(&mut self.modal, n) { f.focused = there.checked_sub(1).map(|i| fields[i]) == Some(n); } @@ -88,7 +92,8 @@ mod tests { #[test] fn next_and_prev_walk_the_list_and_stop_at_the_ends() { assert_eq!(General.next(), Sessions); - assert_eq!(ClaudiuTools.next(), Worktrees); + assert_eq!(ClaudiuTools.next(), CustomSubagents); + assert_eq!(CustomSubagents.next(), Worktrees); assert_eq!(Worktrees.next(), About); assert_eq!(About.next(), About); assert_eq!(About.prev(), Worktrees); diff --git a/src/claude/acp.rs b/src/claude/acp.rs new file mode 100644 index 0000000..5600de9 --- /dev/null +++ b/src/claude/acp.rs @@ -0,0 +1,447 @@ +//! Runs one task in Codex for a custom subagent (`claude/subagents.rs`), through the Agent Client Protocol: +//! `claudiu --acp`. +//! +//! The mod starts this once per subagent turn and writes the task to stdin as JSON (`Request`). A mod can write a +//! child's stdin only once, and ACP is a conversation in both directions, so the conversation happens here. Progress +//! goes to stdout as JSON lines (`Event`), ending with the report or the reason it failed. +//! +//! Codex runs through `npx codex-acp`, which uses the user's own `codex login`. Its stdin is a pipe from this +//! process, so when the mod stops this helper (the user interrupted the subagent), the pipe closes and codex-acp +//! exits with it. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +pub const FLAG: &str = "--acp"; +/// Pinned so an upstream change reaches users only with a Claudiu release. +const CODEX_ACP: &str = "@agentclientprotocol/codex-acp@2.6.0"; +/// ACP's error code for "authentication required". +const AUTH_REQUIRED: i64 = -32000; +/// Lines of codex-acp's stderr kept for a failure's reason. +const STDERR_LINES: usize = 5; + +/// What the mod asks for. +#[derive(Debug, Deserialize)] +pub struct Request { + /// Codex's model; none for Codex's own default. + pub model: Option, + /// Whether Codex may edit files and run commands (`workspace-write`) or only read (`read-only`). + pub edits: bool, + /// The folder Codex works in. + pub cwd: PathBuf, + /// The task, as Claude wrote it. + pub prompt: String, +} + +/// One line of stdout. +#[derive(Debug, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Event { + /// A piece of a message Codex is writing. + Text { text: String }, + /// A tool call Codex started: a command, a read, an edit. + Step { text: String }, + /// The last message Codex wrote: the subagent's report. + Report { text: String }, + Failed { reason: String }, +} + +pub fn run() -> i32 { + let mut out = std::io::stdout().lock(); + let mut emit = |event: Event| { + if let Ok(line) = serde_json::to_string(&event) { + let _ = writeln!(out, "{line}"); + let _ = out.flush(); + } + }; + let mut input = String::new(); + let request = std::io::stdin().read_to_string(&mut input).map_err(|e| e.to_string()).and_then(|_| serde_json::from_str::(&input).map_err(|e| e.to_string())); + let request = match request { + Ok(r) => r, + Err(e) => { + emit(Event::Failed { reason: format!("the task could not be read ({e})") }); + return 1; + } + }; + let finished = run_codex(&request, &mut emit); + emit(match finished { + Ok(text) => Event::Report { text }, + Err(reason) => Event::Failed { reason }, + }); + 0 +} + +fn run_codex(request: &Request, emit: &mut impl FnMut(Event)) -> Result { + let npx = which::which("npx").map_err(|_| "npx was not found on PATH. Codex subagents need Node.js.".to_string())?; + let mut command = Command::new(npx); + command + .args(["-y", CODEX_ACP]) + .current_dir(&request.cwd) + .env("INITIAL_AGENT_MODE", if request.edits { "workspace-write" } else { "read-only" }) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if let Some(model) = &request.model { + command.env("CODEX_CONFIG", json!({ "model": model }).to_string()); + } + let mut child = command.spawn().map_err(|e| format!("codex-acp could not start ({e})"))?; + let (Some(to_agent), Some(from_agent), Some(stderr)) = (child.stdin.take(), child.stdout.take(), child.stderr.take()) else { + let _ = child.kill(); + return Err("codex-acp could not start (no pipes)".into()); + }; + // The last lines of stderr explain an exit; read on a thread so a full stderr pipe can't stall codex-acp. + let errors = std::thread::spawn(move || { + let mut last: Vec = vec![]; + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + if !line.trim().is_empty() { + last.push(line); + if last.len() > STDERR_LINES { + last.remove(0); + } + } + } + last.join("\n") + }); + + let result = converse(BufReader::new(from_agent), to_agent, request, emit); + // Closing its stdin (dropped with `to_agent`) ends codex-acp; kill it in case it lingers. + let _ = child.kill(); + let _ = child.wait(); + let stderr = errors.join().unwrap_or_default(); + result.map_err(|reason| if reason == EXITED && !stderr.is_empty() { format!("{EXITED}: {stderr}") } else { reason }) +} + +const EXITED: &str = "codex-acp exited before Codex answered"; + +/// The ACP conversation for one task: start, open a session in the task's folder, send the task, and follow the +/// session's updates until Codex answers. Returns the last message Codex wrote. +fn converse(from_agent: impl BufRead, mut to_agent: impl Write, request: &Request, emit: &mut impl FnMut(Event)) -> Result { + let mut lines = from_agent.lines(); + let send = |to_agent: &mut dyn Write, message: Value| -> Result<(), String> { + writeln!(to_agent, "{message}").and_then(|_| to_agent.flush()).map_err(|_| EXITED.to_string()) + }; + // Waits for the answer to request `id`, handling what Codex sends meanwhile. + let mut messages = Messages::default(); + // What read-only refused first: codex-acp offers only "cancel" for some commands, which ends Codex's turn. + let mut refused: Option = None; + let mut answer = |to_agent: &mut dyn Write, id: i64, messages: &mut Messages, emit: &mut dyn FnMut(Event)| -> Result { + for line in lines.by_ref() { + let line = line.map_err(|_| EXITED.to_string())?; + let Ok(msg) = serde_json::from_str::(&line) else { continue }; + if msg.get("method").is_none() && msg["id"].as_i64() == Some(id) { + return match msg.get("error") { + Some(error) => Err(error_reason(error)), + None => Ok(msg["result"].clone()), + }; + } + match msg["method"].as_str() { + Some("session/update") => messages.update(&msg["params"]["update"], emit), + Some("session/request_permission") => { + let outcome = permission(&msg["params"]["options"], request.edits); + if !request.edits && refused.is_none() { + refused = Some(msg["params"]["toolCall"]["title"].as_str().unwrap_or("an action").to_string()); + } + send(to_agent, json!({ "jsonrpc": "2.0", "id": msg["id"], "result": { "outcome": outcome } }))?; + } + // A request this client doesn't serve: it offered no file or terminal access. + Some(_) if msg.get("id").is_some() => { + send(to_agent, json!({ "jsonrpc": "2.0", "id": msg["id"], "error": { "code": -32601, "message": "method not found" } }))?; + } + _ => {} + } + } + Err(EXITED.to_string()) + }; + + send(&mut to_agent, json!({ "jsonrpc": "2.0", "id": 0, "method": "initialize", "params": { + "protocolVersion": 1, + "clientCapabilities": { "fs": { "readTextFile": false, "writeTextFile": false }, "terminal": false }, + "clientInfo": { "name": "claudiu", "version": env!("CARGO_PKG_VERSION") }, + }}))?; + answer(&mut to_agent, 0, &mut messages, emit)?; + + send(&mut to_agent, json!({ "jsonrpc": "2.0", "id": 1, "method": "session/new", "params": { "cwd": request.cwd, "mcpServers": [] } }))?; + let session = answer(&mut to_agent, 1, &mut messages, emit)?; + let session_id = session["sessionId"].as_str().ok_or("codex-acp opened no session")?.to_string(); + + send(&mut to_agent, json!({ "jsonrpc": "2.0", "id": 2, "method": "session/prompt", "params": { + "sessionId": session_id, + "prompt": [{ "type": "text", "text": request.prompt }], + }}))?; + let done = answer(&mut to_agent, 2, &mut messages, emit)?; + let stop = done["stopReason"].as_str().unwrap_or("end_turn"); + match (stop, messages.last()) { + ("end_turn", Some(text)) => Ok(text), + ("end_turn", None) => Err("Codex finished without writing a report".into()), + ("cancelled", _) => Err(match refused { + Some(action) => format!("Codex stopped when read-only mode refused `{action}`. Turn on Allow edits in Settings → Custom subagents to let it."), + None => "Codex's turn was cancelled".into(), + }), + ("refusal", _) => Err("Codex refused the task".into()), + // Out of tokens or turns: what Codex wrote last is still the best report there is. + (_, Some(text)) => Ok(text), + (other, None) => Err(format!("Codex stopped ({other}) without writing a report")), + } +} + +/// The messages Codex wrote in this run, as their pieces arrive. A message ends where a tool call starts or another +/// message begins. +#[derive(Default)] +struct Messages { + current: String, + current_id: Option, + last: Option, +} + +impl Messages { + fn update(&mut self, update: &Value, emit: &mut dyn FnMut(Event)) { + match update["sessionUpdate"].as_str() { + Some("agent_message_chunk") => { + let Some(text) = update["content"]["text"].as_str() else { return }; + let id = update["messageId"].as_str().map(String::from); + if id.is_some() && id != self.current_id { + self.close(); + self.current_id = id; + } + self.current.push_str(text); + emit(Event::Text { text: text.to_string() }); + } + Some("tool_call") => { + self.close(); + let title = update["title"].as_str().unwrap_or("a tool"); + emit(Event::Step { text: title.to_string() }); + } + _ => {} + } + } + + /// Ends the message being written; a blank one doesn't replace the last. + fn close(&mut self) { + let text = std::mem::take(&mut self.current); + if !text.trim().is_empty() { + self.last = Some(text); + } + self.current_id = None; + } + + fn last(&mut self) -> Option { + self.close(); + self.last.clone() + } +} + +/// The answer to a permission request: an allowing option when edits are on, a refusing one when they are off. +/// codex-acp offers two refusals of the same kind: `decline` lets Codex carry on without the action, `cancel` ends its +/// turn, so `decline` comes first. Without a fitting option the request is answered as cancelled, which refuses it too. +fn permission(options: &Value, edits: bool) -> Value { + let options: Vec<&Value> = options.as_array().into_iter().flatten().collect(); + let of_kind = |kinds: &[&str]| options.iter().copied().find(|o| o["kind"].as_str().is_some_and(|k| kinds.contains(&k))); + let chosen = if edits { + of_kind(&["allow_once", "allow_always"]) + } else { + options.iter().copied().find(|o| o["optionId"] == "decline").or_else(|| of_kind(&["reject_once", "reject_always"])) + }; + match chosen.and_then(|o| o["optionId"].as_str()) { + Some(id) => json!({ "outcome": "selected", "optionId": id }), + None => json!({ "outcome": "cancelled" }), + } +} + +fn error_reason(error: &Value) -> String { + if error["code"].as_i64() == Some(AUTH_REQUIRED) { + return "Codex isn't signed in. Run `codex login`, then try again.".into(); + } + match error["message"].as_str() { + Some(message) => format!("codex-acp: {message}"), + None => format!("codex-acp: {error}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(edits: bool) -> Request { + Request { model: Some("gpt-5.5".into()), edits, cwd: PathBuf::from("/work"), prompt: "Find the bug".into() } + } + + fn update(update: Value) -> Value { + json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "sessionId": "s1", "update": update } }) + } + + fn chunk(id: &str, text: &str) -> Value { + update(json!({ "sessionUpdate": "agent_message_chunk", "messageId": id, "content": { "type": "text", "text": text } })) + } + + fn reply(id: i64, result: Value) -> Value { + json!({ "jsonrpc": "2.0", "id": id, "result": result }) + } + + /// Runs the conversation against what a fake agent says, in order. Returns the result, what was sent to the agent, + /// and the events. + fn talk(agent_says: &[Value], edits: bool) -> (Result, Vec, Vec) { + let script: String = agent_says.iter().map(|m| format!("{m}\n")).collect(); + let mut sent = Vec::new(); + let mut events = vec![]; + let result = converse(script.as_bytes(), &mut sent, &request(edits), &mut |e| events.push(e)); + let sent = String::from_utf8(sent).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + (result, sent, events) + } + + fn opening() -> Vec { + vec![reply(0, json!({ "protocolVersion": 1 })), reply(1, json!({ "sessionId": "s1" }))] + } + + #[test] + fn the_report_is_the_last_message_and_every_piece_streams() { + let mut says = opening(); + says.extend([ + chunk("m1", "Looking at "), + chunk("m1", "the parser."), + update(json!({ "sessionUpdate": "tool_call", "toolCallId": "c1", "title": "Read src/parse.rs", "kind": "read", "status": "pending" })), + chunk("m2", "The bug is on line 12."), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + let (result, sent, events) = talk(&says, false); + assert_eq!(result, Ok("The bug is on line 12.".into())); + assert_eq!( + events, + vec![ + Event::Text { text: "Looking at ".into() }, + Event::Text { text: "the parser.".into() }, + Event::Step { text: "Read src/parse.rs".into() }, + Event::Text { text: "The bug is on line 12.".into() }, + ] + ); + assert_eq!(sent.iter().map(|m| m["method"].as_str().unwrap()).collect::>(), ["initialize", "session/new", "session/prompt"]); + assert_eq!(sent[1]["params"]["cwd"], "/work"); + assert_eq!(sent[2]["params"]["sessionId"], "s1"); + assert_eq!(sent[2]["params"]["prompt"][0]["text"], "Find the bug"); + assert_eq!(sent[0]["params"]["clientCapabilities"]["terminal"], false); + } + + #[test] + fn messages_without_ids_split_at_tool_calls() { + let mut says = opening(); + says.extend([ + update(json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "First." } })), + update(json!({ "sessionUpdate": "tool_call", "toolCallId": "c1", "title": "Ran ls" })), + update(json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": "Second." } })), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + assert_eq!(talk(&says, false).0, Ok("Second.".into())); + } + + fn asks_permission() -> Vec { + let mut says = opening(); + says.extend([ + json!({ "jsonrpc": "2.0", "id": 7, "method": "session/request_permission", "params": { "sessionId": "s1", "toolCall": { "toolCallId": "c1" }, "options": [ + { "optionId": "yes", "name": "Allow once", "kind": "allow_once" }, + { "optionId": "no", "name": "Reject", "kind": "reject_once" }, + ]}}), + chunk("m1", "Done."), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + says + } + + #[test] + fn a_turn_ended_by_a_refusal_says_what_was_refused() { + let mut says = opening(); + says.extend([ + json!({ "jsonrpc": "2.0", "id": 0, "method": "session/request_permission", "params": { "sessionId": "s1", + "toolCall": { "toolCallId": "c1", "title": "printf hi > made.txt" }, + "options": [{ "optionId": "allow_once", "kind": "allow_once" }, { "optionId": "cancel", "kind": "reject_once" }] } }), + reply(2, json!({ "stopReason": "cancelled" })), + ]); + let (result, sent, _) = talk(&says, false); + assert_eq!( + result, + Err("Codex stopped when read-only mode refused `printf hi > made.txt`. Turn on Allow edits in Settings → Custom subagents to let it.".into()) + ); + assert_eq!(sent.last().unwrap()["result"]["outcome"]["optionId"], "cancel"); + } + + #[test] + fn read_only_refuses_permission_requests() { + let (_, sent, _) = talk(&asks_permission(), false); + let answer = sent.iter().find(|m| m["id"] == 7).unwrap(); + assert_eq!(answer["result"]["outcome"], json!({ "outcome": "selected", "optionId": "no" })); + } + + #[test] + fn with_edits_on_permission_requests_are_allowed() { + let (_, sent, _) = talk(&asks_permission(), true); + let answer = sent.iter().find(|m| m["id"] == 7).unwrap(); + assert_eq!(answer["result"]["outcome"], json!({ "outcome": "selected", "optionId": "yes" })); + } + + #[test] + fn read_only_declines_rather_than_ending_codex_turn() { + let options = json!([ + { "optionId": "allow_once", "kind": "allow_once" }, + { "optionId": "cancel", "kind": "reject_once" }, + { "optionId": "decline", "kind": "reject_once" }, + ]); + assert_eq!(permission(&options, false), json!({ "outcome": "selected", "optionId": "decline" })); + } + + #[test] + fn a_permission_request_with_no_refusing_option_is_cancelled() { + let options = json!([{ "optionId": "yes", "kind": "allow_once" }]); + assert_eq!(permission(&options, false), json!({ "outcome": "cancelled" })); + } + + #[test] + fn file_and_terminal_requests_are_refused() { + let mut says = opening(); + says.extend([ + json!({ "jsonrpc": "2.0", "id": 9, "method": "fs/write_text_file", "params": { "sessionId": "s1", "path": "/etc/x", "content": "" } }), + chunk("m1", "Done."), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + let (result, sent, _) = talk(&says, true); + assert_eq!(result, Ok("Done.".into())); + assert_eq!(sent.iter().find(|m| m["id"] == 9).unwrap()["error"]["code"], -32601); + } + + #[test] + fn signed_out_says_to_run_codex_login() { + let says = vec![ + reply(0, json!({ "protocolVersion": 1 })), + json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": "Authentication required" } }), + ]; + assert_eq!(talk(&says, false).0, Err("Codex isn't signed in. Run `codex login`, then try again.".into())); + } + + #[test] + fn an_agent_that_exits_midway_fails() { + let mut says = opening(); + says.push(chunk("m1", "Starting")); + assert_eq!(talk(&says, false).0, Err(EXITED.into())); + } + + #[test] + fn a_turn_without_a_message_fails() { + let mut says = opening(); + says.push(reply(2, json!({ "stopReason": "end_turn" }))); + assert_eq!(talk(&says, false).0, Err("Codex finished without writing a report".into())); + } + + #[test] + fn running_out_of_tokens_still_reports_the_last_message() { + let mut says = opening(); + says.extend([chunk("m1", "Partial findings."), reply(2, json!({ "stopReason": "max_tokens" }))]); + assert_eq!(talk(&says, false).0, Ok("Partial findings.".into())); + } + + #[test] + fn events_are_json_lines_the_mod_reads() { + assert_eq!(serde_json::to_value(Event::Step { text: "Ran ls".into() }).unwrap(), json!({ "kind": "step", "text": "Ran ls" })); + assert_eq!(serde_json::to_value(Event::Failed { reason: "x".into() }).unwrap(), json!({ "kind": "failed", "reason": "x" })); + } +} diff --git a/src/claude/mod.rs b/src/claude/mod.rs index 839090b..2856d9e 100644 --- a/src/claude/mod.rs +++ b/src/claude/mod.rs @@ -9,6 +9,7 @@ //! per-session config) and `plugin` (the mod Claudiu ships). pub mod accounts; +pub mod acp; pub mod ask; pub mod bridge; pub mod config_sync; @@ -16,6 +17,7 @@ pub mod costly; pub mod defaults; pub mod mcp; pub mod plugin; +pub mod subagents; pub mod trim; pub mod usage; diff --git a/src/claude/subagents.rs b/src/claude/subagents.rs new file mode 100644 index 0000000..db148a1 --- /dev/null +++ b/src/claude/subagents.rs @@ -0,0 +1,135 @@ +//! Custom subagents: agent types that run a task in another coding agent instead of Claude (Settings → Custom +//! subagents). Codex is the only one so far. +//! +//! Claudiu checks the settings here, once, and hands the result to the mod in `CLAUDIU_SUBAGENTS`. The mod registers +//! one agent type per entry and answers that agent's turns through the `claudiu --acp` helper (`claude/acp.rs`). + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// The settings the mod reads, as JSON. Absent when no custom subagent is on. +pub const ENV: &str = "CLAUDIU_SUBAGENTS"; +/// The path of this executable, which the mod runs as ` --acp`. +pub const EXE_ENV: &str = "CLAUDIU_EXE"; + +/// Claude Code takes up to 64 characters in an agent type's name. +const TYPE_NAME_MAX: usize = 64; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CustomSubagents { + #[serde(default)] + pub codex: bool, + /// The model names as typed, trimmed and without blanks, including any the check skips, so the page can still + /// show them. Empty means one type on Codex's own default model. + #[serde(default)] + pub codex_models: Vec, + /// Codex may edit files and run commands outside its read-only sandbox. + #[serde(default)] + pub codex_edits: bool, +} + +/// One Codex agent type: Claude Code's name for it (after `Claudiu:`) and the model Codex runs, `None` for Codex's +/// default. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CodexType { + pub name: String, + pub model: Option, +} + +/// The model field split into names: on commas, each trimmed, blanks dropped. +pub fn parse_models(field: &str) -> Vec { + field.split(',').map(str::trim).filter(|n| !n.is_empty()).map(String::from).collect() +} + +/// The agent types the model names give, and the names that give none: a name with characters other than letters, +/// digits, `.`, `_` and `-`, one too long for a type name, or one whose type name an earlier name already took. +/// Agent type names can't hold a dot, so dots become dashes (`gpt-5.5` → `codex-gpt-5-5`). +pub fn codex_types(models: &[String]) -> (Vec, Vec) { + if models.is_empty() { + return (vec![CodexType { name: "codex".into(), model: None }], vec![]); + } + let mut types: Vec = vec![]; + let mut skipped = vec![]; + for model in models { + let allowed = model.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')); + let name = format!("codex-{}", model.replace('.', "-")); + if !allowed || name.len() > TYPE_NAME_MAX || types.iter().any(|t| t.name == name) { + skipped.push(model.clone()); + } else { + types.push(CodexType { name, model: Some(model.clone()) }); + } + } + (types, skipped) +} + +impl CustomSubagents { + /// What the mod reads from `CLAUDIU_SUBAGENTS`; `None` when Codex is off. + pub fn env(&self) -> Option { + if !self.codex { + return None; + } + let (types, _) = codex_types(&self.codex_models); + let types: Vec = types.iter().map(|t| json!({ "name": t.name, "model": t.model })).collect(); + Some(json!({ "codex": { "edits": self.codex_edits, "types": types } }).to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn the_field_splits_on_commas_and_drops_blanks() { + assert_eq!(parse_models(" gpt-5.5 ,, gpt-6.1-sol, "), names(&["gpt-5.5", "gpt-6.1-sol"])); + assert_eq!(parse_models(""), Vec::::new()); + } + + #[test] + fn no_models_gives_one_type_on_codex_default() { + let (types, skipped) = codex_types(&[]); + assert_eq!(types, vec![CodexType { name: "codex".into(), model: None }]); + assert!(skipped.is_empty()); + } + + #[test] + fn dots_become_dashes_and_codex_gets_the_real_name() { + let (types, skipped) = codex_types(&names(&["gpt-5.5", "gpt-6.1-sol"])); + assert_eq!( + types, + vec![ + CodexType { name: "codex-gpt-5-5".into(), model: Some("gpt-5.5".into()) }, + CodexType { name: "codex-gpt-6-1-sol".into(), model: Some("gpt-6.1-sol".into()) }, + ] + ); + assert!(skipped.is_empty()); + } + + #[test] + fn bad_names_and_repeats_are_skipped() { + let long = "g".repeat(59); // "codex-" plus 59 is 65 characters + let (types, skipped) = codex_types(&names(&["gpt 5", "gpt-5.5", "gpt-5-5", "o3", &long])); + assert_eq!(types.iter().map(|t| t.name.as_str()).collect::>(), ["codex-gpt-5-5", "codex-o3"]); + assert_eq!(skipped, names(&["gpt 5", "gpt-5-5", &long])); + } + + #[test] + fn the_mod_gets_nothing_while_codex_is_off() { + let off = CustomSubagents { codex: false, codex_models: names(&["gpt-5.5"]), codex_edits: true }; + assert_eq!(off.env(), None); + } + + #[test] + fn the_mod_gets_the_checked_types_and_the_edit_switch() { + let on = CustomSubagents { codex: true, codex_models: names(&["gpt-5.5", "bad name"]), codex_edits: false }; + let env: Value = serde_json::from_str(&on.env().unwrap()).unwrap(); + assert_eq!(env, json!({ "codex": { "edits": false, "types": [{ "name": "codex-gpt-5-5", "model": "gpt-5.5" }] } })); + + let default = CustomSubagents { codex: true, codex_models: vec![], codex_edits: true }; + let env: Value = serde_json::from_str(&default.env().unwrap()).unwrap(); + assert_eq!(env, json!({ "codex": { "edits": true, "types": [{ "name": "codex", "model": null }] } })); + } +} diff --git a/src/main.rs b/src/main.rs index 6dd23f0..ccd15c1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -71,6 +71,10 @@ fn main() { if std::env::args().nth(1).as_deref() == Some(claude::mcp::FLAG) { std::process::exit(claude::mcp::run()); } + // Hidden helper mode: runs one task in Codex for a custom subagent (see claude/acp.rs). + if std::env::args().nth(1).as_deref() == Some(claude::acp::FLAG) { + std::process::exit(claude::acp::run()); + } install_crash_log(); #[cfg(windows)] priority::restore_own_priority(); diff --git a/src/panels/settings_view.rs b/src/panels/settings_view.rs index ff679e5..82cce31 100644 --- a/src/panels/settings_view.rs +++ b/src/panels/settings_view.rs @@ -3,7 +3,7 @@ use rune::tok::motion; use rune::{Color, Cursor, El, ScrollSpec, Tx, col, el, row}; -use crate::app::{Act, MenuAnchor, MenuItem, Modal, SettingsPage, Workspace}; +use crate::app::{Act, MenuAnchor, MenuItem, Modal, SettingsPage, SubagentsForm, Workspace}; use crate::claude::defaults::{Effort, PermissionMode}; use crate::claude::mcp::Feature; use crate::claude::trim::Trim; @@ -65,6 +65,36 @@ fn settings_toggle(key: &str, title: &str, on: bool, field: fn(&mut Modal) -> Op }) } +/// The Custom subagents page: Codex's switch, its models and whether it may edit. +fn subagents_page(form: &SubagentsForm) -> El { + let mut page = col() + .gap(8.0) + .child(faint("Agent types that run a task in another coding agent instead of Claude. Claude uses one only when you ask for it. Applies to new and resumed sessions. Running sessions keep theirs.")) + .child(section_label("CODEX".to_string()).mt(4.0)) + .child(faint("Runs the task in OpenAI Codex through codex-acp. Needs Node (npx) and a `codex login`; the first run downloads codex-acp from npm.")) + .child(settings_toggle("settings-codex", "Codex subagents", form.codex, |m| match m { + Modal::Settings { subagents, .. } => Some(&mut subagents.codex), + _ => None, + })); + if !form.codex { + return page; + } + page = page.child(field(5, "MODELS, SEPARATED BY COMMAS", &form.models, "none: Codex's default model, e.g. gpt-5.5, gpt-6.1-sol")); + let (_, skipped) = crate::claude::subagents::codex_types(&crate::claude::subagents::parse_models(&form.models.text)); + if !skipped.is_empty() { + page = page.child(faint(format!("Skipped: {} (only letters, digits, . _ -; each name once).", skipped.join(", ")))); + } + page.child(settings_toggle("settings-codex-edits", "Allow edits", form.edits, |m| match m { + Modal::Settings { subagents, .. } => Some(&mut subagents.edits), + _ => None, + })) + .child(faint(if form.edits { + "Codex may edit files and run commands in the subagent's folder. Its edits skip Claude Code's permission rules and hooks." + } else { + "Codex runs read-only: it can read and search, but not change files." + })) +} + /// A row that opens a menu of `options` under itself; the first entry, "Claude Code default", clears the choice. fn picker_row(key: &'static str, title: &str, current: Option, options: &'static [T], name: fn(T) -> &'static str, pick: fn(Option) -> Act) -> El { const DEFAULT: &str = "Claude Code default"; @@ -115,7 +145,7 @@ fn scale_step(key: &'static str, sign: &'static str, by: i32) -> El { impl Workspace { pub(crate) fn settings_body(&self) -> El { - let Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming }) = &self.modal else { + let Some(Modal::Settings { shell, claude, model, effort, permission, updates, chrome, scale, trimmed, claudiu_off, skills_field, costly, hints, renaming, subagents }) = &self.modal else { return el(); }; let page = self.settings_page; @@ -197,6 +227,7 @@ impl Workspace { } list } + SettingsPage::CustomSubagents => subagents_page(subagents), SettingsPage::Projects => self.projects_page(renaming.as_ref()), SettingsPage::Worktrees => self.worktrees_page(), SettingsPage::About => col().child(faint(format!( diff --git a/src/store.rs b/src/store.rs index cf8797a..660ff09 100644 --- a/src/store.rs +++ b/src/store.rs @@ -308,6 +308,9 @@ pub struct Settings { /// Output caps and turned-off skills for Claude Code (`claude/trim.rs`); empty leaves Claude Code's own behavior. #[serde(default)] pub limits: crate::claude::trim::Limits, + /// Agent types that run a task in another coding agent (Settings → Custom subagents); all off by default. + #[serde(default)] + pub custom_subagents: crate::claude::subagents::CustomSubagents, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] diff --git a/web/src/pages/index.astro b/web/src/pages/index.astro index 920c23d..8703ef4 100644 --- a/web/src/pages/index.astro +++ b/web/src/pages/index.astro @@ -214,7 +214,7 @@ const calls = [
ClaudiuSpecifications
-

Specifications.

Claudiu owns the workspace. Claude Code owns the agent.

Built withRust and Rune, not a web wrapper
Terminalone real PTY per session; typed into only for the editor's @path#L reference
Anthropic APInever called by Claudiu
Claude Code datatranscripts never deleted; settings change only when you flip a switch
NetworkGitHub only
Uploadsnone
After a restartrunning sessions come back
Download Windows, macOS and Linux
+

Specifications.

Claudiu owns the workspace. Claude Code owns the agent.

Built withRust and Rune, not a web wrapper
Terminalone real PTY per session; typed into only for the editor's @path#L reference
Anthropic APInever called by Claudiu
Claude Code datatranscripts never deleted; settings change only when you flip a switch
NetworkGitHub only, plus npm and OpenAI once you turn on Codex subagents
Uploadsnone
After a restartrunning sessions come back
Download Windows, macOS and Linux