Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(agents): run Codex through its app-server, handing it the browser tools as its own — in the model's list from the first request, its replies streamed and its window counted per request — with every MCP server of the user's switched off, and exec as the fallback when a Codex refuses it

Shahriar83c263652101
diff --git a/src/daemon/agent/config.ts b/src/daemon/agent/config.ts
index 242990c..7bdeb7d 100644
--- a/src/daemon/agent/config.ts
+++ b/src/daemon/agent/config.ts
@@ -11,6 +11,8 @@ export interface AgentSettings {
bin: string;
model?: string;
effort?: string;
+ /** How a runner that can reach its CLI two ways should; Codex takes `exec` to keep off its app-server. */
+ transport?: string;
}
export interface AgentConfig {
@@ -88,7 +90,7 @@ const DEFAULT_APPROVALS = ['page.submitForm'];
interface StoredConfig extends Record<string, unknown> {
agent?: unknown;
- agents?: Record<string, { bin?: unknown; model?: unknown; effort?: unknown } | undefined>;
+ agents?: Record<string, { bin?: unknown; model?: unknown; effort?: unknown; transport?: unknown } | undefined>;
requireApproval?: unknown;
guardrails?: unknown;
/** Pre-0.2 layout: one Claude Code runner, configured at the top level. */
@@ -128,6 +130,7 @@ function settingsFor(stored: StoredConfig, kind: AgentKind): AgentSettings {
bin: text(scoped.bin) ?? text(legacy.bin) ?? AGENTS[kind].bin,
model: modelOf(kind, scoped.model) ?? modelOf(kind, legacy.model) ?? DEFAULT_MODEL[kind],
effort: text(scoped.effort) ?? text(legacy.effort),
+ transport: text(scoped.transport),
};
}
diff --git a/src/daemon/agent/runner.ts b/src/daemon/agent/runner.ts
index 7cd8905..8fb7284 100644
--- a/src/daemon/agent/runner.ts
+++ b/src/daemon/agent/runner.ts
@@ -1,5 +1,9 @@
import { join } from 'node:path';
import type { RunEvent } from '@/lib/actions/protocol';
+import { fenceTag, policyFrom } from '../guardrails';
+import { readLockfile } from '../lockfile';
+import { RemoteBridge } from '../remote-bridge';
+import { toolHost, type ToolHost } from '../tool-host';
import type { AgentConfig } from './config';
import { runJson, runStream, type JsonOptions } from './runners/drive';
import { mcpServerFor, runnerFor } from './runners';
@@ -24,25 +28,50 @@ export interface RunRequest {
emit: (event: RunEvent) => void;
}
-export function runInstruction(request: RunRequest): Promise<RunOutcome> {
+export async function runInstruction(request: RunRequest): Promise<RunOutcome> {
const { runner, settings } = runnerFor(request.config);
- return runStream(
- runner,
- {
- runId: request.runId,
- conversation: request.conversation,
- instruction: request.instruction,
- systemPrompt: request.systemPrompt,
- research: request.research === true,
- settings,
- sessionId: request.sessionId,
- workspace: runner.workspace('run'),
- mcp: mcpServerFor(request.runId),
- mcpTools: request.mcpTools,
- },
- request.signal,
- request.emit,
- );
+ const tools = inProcessTools(request.runId, request.config);
+ try {
+ return await runStream(
+ runner,
+ {
+ runId: request.runId,
+ conversation: request.conversation,
+ instruction: request.instruction,
+ systemPrompt: request.systemPrompt,
+ research: request.research === true,
+ settings,
+ sessionId: request.sessionId,
+ workspace: runner.workspace('run'),
+ mcp: mcpServerFor(request.runId),
+ mcpTools: request.mcpTools,
+ tools: tools.open,
+ },
+ request.signal,
+ request.emit,
+ );
+ } finally {
+ tools.close();
+ }
+}
+
+/**
+ * The run's tools served here, for a CLI that takes them other than over MCP. They go through the
+ * daemon's own control socket under the run's id — the door its MCP server would use — so a call is
+ * gated, shown and answered exactly as one made over MCP. Opened on first use, closed with the run.
+ */
+function inProcessTools(runId: string, config: AgentConfig): { open: () => Promise<ToolHost>; close: () => void } {
+ let bridge: Promise<RemoteBridge> | undefined;
+ let host: Promise<ToolHost> | undefined;
+ const connect = () => {
+ const lock = readLockfile();
+ if (!lock) return Promise.reject(new RunError('AGENT_FAILED', 'The daemon has no lockfile to reach its own tools through.'));
+ return RemoteBridge.connect(lock.port, lock.token, runId);
+ };
+ return {
+ open: () => (host ??= (bridge = connect()).then((connected) => toolHost(connected, { agentRun: true, policy: policyFrom(config.guardrails), tag: fenceTag() }))),
+ close: () => void bridge?.then((connected) => connected.close()).catch(() => {}),
+ };
}
/** One-shot, no browser: summarize a file, name a conversation, read back a recording. */
diff --git a/src/daemon/agent/runners/codex-app-server.test.ts b/src/daemon/agent/runners/codex-app-server.test.ts
new file mode 100644
index 0000000..c9e8edc
--- /dev/null
+++ b/src/daemon/agent/runners/codex-app-server.test.ts
@@ -0,0 +1,247 @@
+import { describe, expect, test, vi } from 'vitest';
+import type { ToolHost } from '../../tool-host';
+import { codexRunner } from './codex';
+import { streamContext, transcript } from './fixtures/support';
+import { CONVERSATION_REFUSED, type Conversation, type StreamSink } from './types';
+
+const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
+const schema = { type: 'object' as const, properties: {} };
+
+const host = () => {
+ const tools: ToolHost = {
+ list: vi.fn(async () => ({
+ tools: [
+ { name: 'page_echo', description: 'Echo', inputSchema: schema },
+ { name: 'page_shot', description: 'Shot', inputSchema: schema },
+ ],
+ withheld: [{ name: 'page_runCode', description: 'Run page code', inputSchema: schema }],
+ })),
+ call: vi.fn(async (name: string) =>
+ name === 'page_shot'
+ ? { content: [{ type: 'image' as const, data: PNG, mimeType: 'image/png' }, { type: 'text' as const, text: 'the shot' }] }
+ : { content: [{ type: 'text' as const, text: 'echoed' }] },
+ ),
+ };
+ return tools;
+};
+
+/** A conversation fed lines by hand: what it wrote to Codex, and what it told the run. */
+function hold({ bin = 'codex', sessionId = null as string | null, transport = undefined as string | undefined } = {}) {
+ const tools = host();
+ const conversation = codexRunner.converse?.(
+ streamContext({ bin, transport }, { sessionId, systemPrompt: 'You are Browsentic.', tools: async () => tools }),
+ ) as Conversation;
+ const written: Record<string, unknown>[] = [];
+ const calls: unknown[][] = [];
+ const record =
+ (signal: keyof StreamSink) =>
+ (...args: unknown[]) =>
+ void calls.push([signal, ...args]);
+ const sink: StreamSink = {
+ text: record('text'),
+ tool: record('tool'),
+ toolResult: record('toolResult'),
+ session: record('session'),
+ usage: record('usage'),
+ done: record('done'),
+ fail: record('fail'),
+ };
+ const io = { write: (message: unknown) => void written.push(message as Record<string, unknown>) };
+ conversation?.open(io);
+ const feed = async (...lines: (string | object)[]) => {
+ for (const line of lines) {
+ conversation.read(typeof line === 'string' ? line : JSON.stringify(line), sink, io);
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ };
+ return { conversation, tools, written, calls, feed };
+}
+
+const recorded = transcript('codex', '0.155.1-app-server-turn.jsonl');
+const response = (id: number) => recorded.find((line) => JSON.parse(line).id === id && !JSON.parse(line).method)!;
+const sent = (written: Record<string, unknown>[], method: string) => written.find((message) => message.method === method);
+
+describe('the handshake', () => {
+ test("starts a thread with the browser tools as its own, the withheld ones out of sight, and every server of the user's switched off", async () => {
+ const { written, feed } = hold({ bin: 'codex-handshake' });
+ expect(written[0]).toMatchObject({ id: 1, method: 'initialize', params: { capabilities: { experimentalApi: true } } });
+ await feed(response(1), response(2));
+ const start = sent(written, 'thread/start')?.params as Record<string, unknown> & { config: object; dynamicTools: object[] };
+ expect({
+ initialized: written.some((message) => message.method === 'initialized'),
+ sandbox: start.sandbox,
+ approvals: start.approvalPolicy,
+ prompt: String(start.developerInstructions).startsWith('You are Browsentic.') && String(start.developerInstructions).includes('# Your browser tools in Codex'),
+ config: start.config,
+ tools: start.dynamicTools,
+ }).toEqual({
+ initialized: true,
+ sandbox: 'read-only',
+ approvals: 'never',
+ prompt: true,
+ config: { 'mcp_servers.decoy.enabled': false },
+ tools: [
+ { type: 'function', name: 'page_echo', description: 'Echo', inputSchema: schema, deferLoading: false },
+ { type: 'function', name: 'page_shot', description: 'Shot', inputSchema: schema, deferLoading: false },
+ {
+ type: 'namespace',
+ name: 'browsentic',
+ description: 'Browsentic tools that answer only once the user has switched them on for a message.',
+ tools: [{ type: 'function', name: 'page_runCode', description: 'Run page code', inputSchema: schema, deferLoading: true }],
+ },
+ ],
+ });
+ });
+
+ test('once the thread is named, the turn starts with the instruction', async () => {
+ const { written, calls, feed } = hold({ bin: 'codex-named' });
+ await feed(response(1), response(2), response(3));
+ expect([calls[0], sent(written, 'turn/start')?.params]).toEqual([
+ ['session', '01a0e2bc-4675-7451-bab0-c6b9d7740962'],
+ { threadId: '01a0e2bc-4675-7451-bab0-c6b9d7740962', input: [{ type: 'text', text: 'what does this page cost', text_elements: [] }] },
+ ]);
+ });
+
+ test('a resumed thread is resumed rather than started, and is sent no tools, which it kept from its start', async () => {
+ const { written, tools, feed } = hold({ bin: 'codex-resume', sessionId: 'thread-1' });
+ await feed(response(1), response(2));
+ expect([sent(written, 'thread/resume')?.params, sent(written, 'thread/start'), vi.mocked(tools.list).mock.calls.length]).toEqual([
+ expect.objectContaining({ threadId: 'thread-1', sandbox: 'read-only', approvalPolicy: 'never', config: { 'mcp_servers.decoy.enabled': false } }),
+ undefined,
+ 0,
+ ]);
+ });
+});
+
+describe('a recorded turn', () => {
+ test("answers each tool call through the run's own tools, streams the reply, and counts each request's tokens", async () => {
+ const { written, tools, calls, feed } = hold({ bin: 'codex-turn' });
+ await feed(...recorded);
+ const answers = written.filter((message) => 'result' in message && !('method' in message));
+ expect({
+ called: vi.mocked(tools.call).mock.calls.map(([name]) => name),
+ answers: answers.map((message) => [message.id, message.result]),
+ said: calls.filter(([signal]) => signal === 'text').map(([, delta]) => delta).join(''),
+ usage: calls.filter(([signal]) => signal === 'usage').map(([, usage]) => usage),
+ end: calls.at(-1),
+ }).toEqual({
+ called: ['page_echo', 'page_shot'],
+ answers: [
+ [0, { contentItems: [{ type: 'inputText', text: 'echoed' }], success: true }],
+ [1, { contentItems: [{ type: 'inputImage', imageUrl: `data:image/png;base64,${PNG}` }, { type: 'inputText', text: 'the shot' }], success: true }],
+ ],
+ said: 'It costs\ntwelve dollars.',
+ usage: [
+ { contextTokens: 110, outputTokens: 10 },
+ { contextTokens: 110, outputTokens: 20 },
+ { contextTokens: 3030, outputTokens: 50 },
+ ],
+ end: ['done', 'end_turn'],
+ });
+ });
+
+ test('a message that came whole, without deltas, is said once when it completes', async () => {
+ const { calls, feed } = hold({ bin: 'codex-whole' });
+ await feed(response(1), response(2), response(3));
+ const thread = '01a0e2bc-4675-7451-bab0-c6b9d7740962';
+ await feed(
+ { method: 'item/agentMessage/delta', params: { threadId: thread, itemId: 'm1', delta: 'It costs' } },
+ { method: 'item/completed', params: { threadId: thread, item: { type: 'agentMessage', id: 'm1', text: 'It costs $12.' } } },
+ { method: 'item/completed', params: { threadId: thread, item: { type: 'agentMessage', id: 'm2', text: 'Done.' } } },
+ );
+ expect(calls.filter(([signal]) => signal === 'text')).toEqual([
+ ['text', 'It costs'],
+ ['text', ' $12.'],
+ ['text', 'Done.'],
+ ]);
+ });
+
+ test("a sub-agent's thread says nothing to the panel, though its tool calls are still answered", async () => {
+ const { calls, tools, feed } = hold({ bin: 'codex-sub-agent' });
+ await feed(response(1), response(2), response(3));
+ await feed(
+ { method: 'item/agentMessage/delta', params: { threadId: 'child', itemId: 'm1', delta: 'thinking aloud' } },
+ { id: 9, method: 'item/tool/call', params: { threadId: 'child', tool: 'page_echo', arguments: {} } },
+ );
+ expect([calls.filter(([signal]) => signal === 'text'), vi.mocked(tools.call).mock.calls.length]).toEqual([[], 1]);
+ });
+
+ test('a web search opens a row when it starts and closes it when it ends', async () => {
+ const { calls, feed } = hold({ bin: 'codex-search' });
+ await feed(response(1), response(2), response(3));
+ const thread = '01a0e2bc-4675-7451-bab0-c6b9d7740962';
+ await feed(
+ { method: 'item/started', params: { threadId: thread, item: { type: 'webSearch', id: 'ws1' } } },
+ { method: 'item/completed', params: { threadId: thread, item: { type: 'webSearch', id: 'ws1' } } },
+ );
+ expect(calls.slice(1)).toEqual([
+ ['tool', 'ws1', 'web_search'],
+ ['toolResult', 'ws1', true],
+ ]);
+ });
+
+ test('anything else it asks of the client is declined, so it never waits on nobody', async () => {
+ const { written, feed } = hold({ bin: 'codex-ask' });
+ await feed({ id: 7, method: 'item/commandExecution/requestApproval', params: {} });
+ expect(written.at(-1)).toEqual({
+ jsonrpc: '2.0',
+ id: 7,
+ error: { code: -32601, message: 'Browsentic does not answer item/commandExecution/requestApproval' },
+ });
+ });
+
+ test('a failed turn fails with what Codex said', async () => {
+ const { calls, feed } = hold({ bin: 'codex-failed' });
+ await feed(response(1), response(2), response(3), {
+ method: 'turn/completed',
+ params: { threadId: '01a0e2bc-4675-7451-bab0-c6b9d7740962', turn: { status: 'failed', error: { message: 'You hit your usage limit.' } } },
+ });
+ expect(calls.at(-1)).toEqual(['fail', 'AGENT_FAILED', 'You hit your usage limit.']);
+ });
+});
+
+describe('what stops a run', () => {
+ const stopped = (what: string) =>
+ `Codex ${what} in a run Browsentic keeps to the browser, so the run was stopped. Update Codex and Browsentic; if it persists, please report it.`;
+
+ test('an MCP server starting, even before the thread is named', async () => {
+ const { calls, feed } = hold({ bin: 'codex-mcp' });
+ await feed(response(1), { method: 'mcpServer/startupStatus/updated', params: { threadId: 'any', name: 'decoy', status: 'starting' } });
+ expect(calls).toEqual([['fail', 'AGENT_UNSAFE', stopped('started an MCP server')]]);
+ });
+
+ test('a shell command or a changed file', async () => {
+ const shell = hold({ bin: 'codex-shell' });
+ const patch = hold({ bin: 'codex-patch' });
+ await shell.feed({ method: 'item/started', params: { item: { type: 'commandExecution', id: 'c1' } } });
+ await patch.feed({ method: 'item/completed', params: { item: { type: 'fileChange', id: 'f1' } } });
+ expect([shell.calls, patch.calls]).toEqual([
+ [['fail', 'AGENT_UNSAFE', stopped('ran a shell command')]],
+ [['fail', 'AGENT_UNSAFE', stopped('changed a file')]],
+ ]);
+ });
+});
+
+describe('a conversation Codex will not hold', () => {
+ test("an app-server that will not start a session hands the turn back, and this Codex's later turns skip it", async () => {
+ const { calls, feed } = hold({ bin: 'codex-old' });
+ await feed({ id: 1, error: { code: -32600, message: 'unknown capability experimentalApi' } });
+ expect([calls, hold({ bin: 'codex-old' }).conversation, hold({ bin: 'codex-other' }).conversation !== null]).toEqual([
+ [['fail', CONVERSATION_REFUSED, 'its app-server would not start a session: unknown capability experimentalApi']],
+ null,
+ true,
+ ]);
+ });
+
+ test('a thread start refused as unknown hands the turn back; refused for any other reason, the turn fails', async () => {
+ const unknown = hold({ bin: 'codex-unknown-param' });
+ const other = hold({ bin: 'codex-signed-out' });
+ await unknown.feed(response(1), response(2), { id: 3, error: { code: -32602, message: 'unknown field dynamicTools' } });
+ await other.feed(response(1), response(2), { id: 3, error: { code: -32000, message: 'Not signed in.' } });
+ expect([unknown.calls.at(-1)?.[1], other.calls.at(-1)]).toEqual([CONVERSATION_REFUSED, ['fail', 'AGENT_FAILED', 'Not signed in.']]);
+ });
+
+ test('transport "exec" in config.json keeps Codex on exec', () => {
+ expect(hold({ bin: 'codex-configured', transport: 'exec' }).conversation).toBeNull();
+ });
+});
diff --git a/src/daemon/agent/runners/codex-app-server.ts b/src/daemon/agent/runners/codex-app-server.ts
new file mode 100644
index 0000000..4322e68
--- /dev/null
+++ b/src/daemon/agent/runners/codex-app-server.ts
@@ -0,0 +1,265 @@
+import type { ListedTool, ToolReply } from '../../tool-host';
+import type { AgentSettings } from '../config';
+import { CONVERSATION_REFUSED, type Conversation, type ConversationIO, type Plan, type StreamContext, type StreamSink } from './types';
+
+/** JSON-RPC's own codes for a method or parameters the server does not know: an older app-server, not a failed turn. */
+const UNKNOWN = [-32601, -32602];
+
+const ASK = { initialize: 1, config: 2, thread: 3, turn: 4 } as const;
+
+/** Codex's word for each of its own actions that a run has switched off. */
+const OFF_LIMITS: Record<string, string> = {
+ commandExecution: 'ran a shell command',
+ fileChange: 'changed a file',
+ mcpToolCall: 'called an MCP server',
+};
+
+interface Message {
+ id?: number | string;
+ method?: string;
+ params?: Record<string, unknown> & { threadId?: string };
+ result?: Record<string, unknown>;
+ error?: { code?: number; message?: string };
+}
+
+interface Item {
+ id?: string;
+ type?: string;
+ text?: string;
+}
+
+interface Usage {
+ inputTokens?: number;
+ outputTokens?: number;
+}
+
+export interface AppServerTurn {
+ plan: Plan;
+ settings: AgentSettings;
+ effort?: string;
+ developerInstructions: string;
+ /** Called once the app-server has turned the conversation down, so later turns go straight to the plain plan. */
+ declined: (reason: string) => void;
+ explain: (message: string | undefined) => string | undefined;
+ stoppedFor: (what: string) => string;
+}
+
+/**
+ * One turn with Codex's app-server. The browser tools go to it as its own tools — listed in the
+ * model's first request, not deferred behind a search — and each call comes back here to be made
+ * through the run's gate. Its words arrive as they are written, and its token counts are the
+ * request's own rather than a sum. No MCP server starts: the run registers none, every one the user
+ * configured is switched off for the thread, and one that starts anyway stops the run.
+ */
+export function appServerTurn(context: StreamContext, turn: AppServerTurn): Conversation {
+ let thread: string | undefined;
+ let holding = false;
+ let generated = 0;
+ const said = new Map<string, string>();
+ const searches = new Set<string>();
+
+ const refuse = (sink: StreamSink, reason: string) => {
+ turn.declined(reason);
+ sink.fail(CONVERSATION_REFUSED, reason);
+ };
+
+ const threadParams = (disabled: string[]) => ({
+ cwd: turn.plan.cwd,
+ sandbox: 'read-only',
+ approvalPolicy: 'never',
+ developerInstructions: turn.developerInstructions,
+ ...(turn.settings.model ? { model: turn.settings.model } : {}),
+ config: {
+ ...Object.fromEntries(disabled.map((name) => [`mcp_servers.${name}.enabled`, false])),
+ ...(turn.effort ? { model_reasoning_effort: turn.effort } : {}),
+ },
+ });
+
+ const startThread = (io: ConversationIO, sink: StreamSink, disabled: string[]) => {
+ if (context.sessionId) {
+ io.write({ jsonrpc: '2.0', id: ASK.thread, method: 'thread/resume', params: { threadId: context.sessionId, ...threadParams(disabled) } });
+ return;
+ }
+ // A tool list is fixed when the thread begins, so what is withheld now is listed out of sight, for later turns.
+ context
+ .tools()
+ .then((host) => host.list())
+ .then(({ tools, withheld }) =>
+ io.write({
+ jsonrpc: '2.0',
+ id: ASK.thread,
+ method: 'thread/start',
+ params: {
+ ...threadParams(disabled),
+ dynamicTools: [...tools.map((tool) => dynamicTool(tool, false)), ...(withheld.length ? [outOfSight(withheld)] : [])],
+ },
+ }),
+ )
+ .catch((error: unknown) => sink.fail('AGENT_FAILED', `Browsentic could not list its browser tools for Codex: ${String(error)}`));
+ };
+
+ const answerToolCall = (io: ConversationIO, sink: StreamSink, id: Message['id'], params: Message['params']) => {
+ const tool = String(params?.tool ?? '');
+ const args = (params?.arguments ?? {}) as Record<string, unknown>;
+ context
+ .tools()
+ .then((host) => host.call(tool, args))
+ .then((reply) => io.write({ jsonrpc: '2.0', id, result: toolResult(reply) }))
+ .catch((error: unknown) => {
+ io.write({ jsonrpc: '2.0', id, result: { contentItems: [{ type: 'inputText', text: `TOOL_FAILED: ${String(error)}` }], success: false } });
+ if (!holding) sink.fail('AGENT_FAILED', String(error));
+ });
+ };
+
+ const onResponse = (message: Message, io: ConversationIO, sink: StreamSink) => {
+ const failed = message.error;
+ switch (message.id) {
+ case ASK.initialize:
+ if (failed) return refuse(sink, `its app-server would not start a session: ${failed.message}`);
+ io.write({ jsonrpc: '2.0', method: 'initialized' });
+ return io.write({ jsonrpc: '2.0', id: ASK.config, method: 'config/read', params: {} });
+
+ case ASK.config: {
+ if (failed) return refuse(sink, `its app-server would not show its config: ${failed.message}`);
+ const config = message.result?.config as { mcp_servers?: Record<string, unknown> } | undefined;
+ return startThread(io, sink, Object.keys(config?.mcp_servers ?? {}));
+ }
+
+ case ASK.thread: {
+ if (failed) {
+ const reason = `its app-server would not ${context.sessionId ? 'resume' : 'start'} the thread: ${failed.message}`;
+ return UNKNOWN.includes(failed.code ?? 0) ? refuse(sink, reason) : sink.fail('AGENT_FAILED', turn.explain(failed.message) ?? reason);
+ }
+ thread = (message.result?.thread as { id?: string } | undefined)?.id;
+ if (!thread) return sink.fail('AGENT_FAILED', 'Codex started a thread without naming it.');
+ holding = true;
+ sink.session(thread);
+ return io.write({
+ jsonrpc: '2.0',
+ id: ASK.turn,
+ method: 'turn/start',
+ params: { threadId: thread, input: [{ type: 'text', text: context.instruction, text_elements: [] }] },
+ });
+ }
+
+ case ASK.turn:
+ if (failed) return sink.fail('AGENT_FAILED', turn.explain(failed.message) ?? 'Codex would not start the turn.');
+ return;
+ }
+ };
+
+ const onItem = (item: Item | undefined, finished: boolean, sink: StreamSink) => {
+ const kind = item?.type;
+ if (!kind) return;
+ if (OFF_LIMITS[kind]) return sink.fail('AGENT_UNSAFE', turn.stoppedFor(OFF_LIMITS[kind]));
+ if (kind === 'webSearch' && item.id) {
+ if (!searches.has(item.id)) {
+ searches.add(item.id);
+ sink.tool(item.id, 'web_search');
+ }
+ if (finished) sink.toolResult(item.id, true);
+ return;
+ }
+ // A message that came whole, without deltas, is said here; one that streamed says only what is left.
+ if (kind === 'agentMessage' && finished && item.id && item.text) {
+ const before = said.get(item.id) ?? '';
+ if (item.text.startsWith(before) && item.text.length > before.length) sink.text(item.text.slice(before.length));
+ said.set(item.id, item.text);
+ }
+ };
+
+ const onNotification = (message: Message, sink: StreamSink) => {
+ const params = message.params ?? {};
+ // Any thread's, and even before the thread is named: a server announces itself while the thread starts.
+ if (message.method === 'mcpServer/startupStatus/updated') return sink.fail('AGENT_UNSAFE', turn.stoppedFor('started an MCP server'));
+ // Only the run's own thread speaks to the panel; a sub-agent's thread works through the same tools.
+ if (thread && params.threadId && params.threadId !== thread) return;
+
+ switch (message.method) {
+ case 'item/agentMessage/delta': {
+ const id = String(params.itemId ?? '');
+ const delta = String(params.delta ?? '');
+ said.set(id, (said.get(id) ?? '') + delta);
+ return sink.text(delta);
+ }
+ case 'item/started':
+ return onItem(params.item as Item | undefined, false, sink);
+ case 'item/completed':
+ return onItem(params.item as Item | undefined, true, sink);
+ case 'thread/tokenUsage/updated': {
+ const last = (params.tokenUsage as { last?: Usage } | undefined)?.last;
+ if (!last) return;
+ generated += last.outputTokens ?? 0;
+ return sink.usage({ contextTokens: (last.inputTokens ?? 0) + (last.outputTokens ?? 0), outputTokens: generated });
+ }
+ case 'error': {
+ const error = params.error as { message?: string } | undefined;
+ if (params.willRetry) return;
+ return sink.fail('AGENT_FAILED', turn.explain(error?.message) ?? 'Codex reported an error');
+ }
+ case 'turn/completed': {
+ const done = params.turn as { status?: string; error?: { message?: string } | null } | undefined;
+ if (done?.status === 'completed') return sink.done('end_turn');
+ if (done?.status === 'failed') return sink.fail('AGENT_FAILED', turn.explain(done.error?.message) ?? 'Codex could not finish the turn');
+ return sink.fail('AGENT_FAILED', `Codex ended the turn ${done?.status ?? 'without saying how'}.`);
+ }
+ }
+ };
+
+ return {
+ plan: turn.plan,
+ get holding() {
+ return holding;
+ },
+ declined: turn.declined,
+ open(io) {
+ io.write({
+ jsonrpc: '2.0',
+ id: ASK.initialize,
+ method: 'initialize',
+ params: { clientInfo: { name: 'browsentic', title: 'Browsentic', version: '1' }, capabilities: { experimentalApi: true, requestAttestation: false } },
+ });
+ },
+ read(line, sink, io) {
+ let message: Message;
+ try {
+ message = JSON.parse(line) as Message;
+ } catch {
+ return;
+ }
+ if (message.method === 'item/tool/call' && message.id !== undefined) return answerToolCall(io, sink, message.id, message.params);
+ // Anything else it asks of the client — an approval, a question for the user — has no one to answer it.
+ if (message.method && message.id !== undefined) {
+ return io.write({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: `Browsentic does not answer ${message.method}` } });
+ }
+ if (message.method) return onNotification(message, sink);
+ return onResponse(message, io, sink);
+ },
+ };
+}
+
+const dynamicTool = (tool: ListedTool, deferLoading: boolean) => ({
+ type: 'function',
+ name: tool.name,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ deferLoading,
+});
+
+/** Codex keeps a deferred tool only inside a namespace, where the model finds it by searching. */
+const outOfSight = (tools: ListedTool[]) => ({
+ type: 'namespace',
+ name: 'browsentic',
+ description: 'Browsentic tools that answer only once the user has switched them on for a message.',
+ tools: tools.map((tool) => dynamicTool(tool, true)),
+});
+
+/** A browser tool's result as Codex takes one: text as text, a picture as a data URL it shows the model. */
+function toolResult(reply: ToolReply) {
+ return {
+ contentItems: reply.content.map((block) =>
+ block.type === 'image' ? { type: 'inputImage', imageUrl: `data:${block.mimeType};base64,${block.data}` } : { type: 'inputText', text: block.text },
+ ),
+ success: reply.isError !== true,
+ };
+}
diff --git a/src/daemon/agent/runners/codex.ts b/src/daemon/agent/runners/codex.ts
index 0166a40..7df317a 100644
--- a/src/daemon/agent/runners/codex.ts
+++ b/src/daemon/agent/runners/codex.ts
@@ -3,11 +3,13 @@ import { readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { stateDir } from '../../lockfile';
+import { log } from '../../log';
import { isModelId } from '@/lib/agents/catalog';
import type { AgentSettings } from '../config';
import { MCP_SERVER_NAME } from './claude';
import { browserToolsDidNotStart, effortOf, MCP_CALL_TIMEOUT_MS, parseJsonLine } from './util';
-import type { JsonContext, Plan, Runner, StreamContext, StreamReader, StreamSink } from './types';
+import { appServerTurn } from './codex-app-server';
+import type { Conversation, JsonContext, Plan, Runner, StreamContext, StreamReader, StreamSink } from './types';
/**
* Codex has no per-run tool allowlist; the read-only sandbox is what keeps a run inside the browser.
@@ -24,6 +26,12 @@ const SANDBOX = ['-c', 'sandbox_mode="read-only"', '-c', 'approval_policy="never
*/
const WITHOUT_USER_CONFIG = '--ignore-user-config';
+/** The same, for the app-server, which takes no `exec` flag. */
+const SANDBOX_CONFIG = ['-c', 'sandbox_mode="read-only"', '-c', 'approval_policy="never"'];
+
+/** A Codex whose app-server turned a conversation down, so later turns go straight to `exec`. */
+const noConversation = new Set<string>();
+
/**
* The shell and the image viewer read the machine, and a run has the page for that. A code-mode
* model keeps its `exec` and reaches the browser tools from inside it, and the sub-agents it can
@@ -81,6 +89,11 @@ const RESULT_TOKENS = 25_000;
/** Codex gives a server ten seconds to start, which a cold start of the browser tools' own process can pass. */
const STARTUP_SECONDS = 30;
+/** What every Codex run is told, however its tools reach it. */
+const keepToThePage = (research: boolean) => `The page the user means is the one open in their browser. Read it with these tools. Never answer from memory${research ? '' : ', from a web search,'} or by fetching the page from the shell${research ? ', and keep a web search to background the page cannot give you' : ''}. Do the job yourself rather than spawning sub-agents: what they say never reaches the user.
+
+When you reach the tools through \`exec\`, start every script that reads the page with the line \`// @exec: {"max_output_tokens": ${RESULT_TOKENS}}\`, or its output is cut at 10,000 tokens. Even then a tool result over ${RESULT_TOKENS} tokens comes back cut, so ask for less at a time — \`page_getPageInfo\` with a small \`maxPerKind\`, \`page_extractText\` with the cursor it hands back — rather than one large read whose middle goes missing.`;
+
/**
* Codex keeps an MCP server's tools out of the model's tool list: they are deferred behind
* `tool_search`, and a code-mode model reaches them only from inside `exec`. A run that does not
@@ -90,9 +103,17 @@ const reachingTheBrowser = (research: boolean) => `# Reaching the browser from C
Your browsentic tools are not in your tool list yet, because Codex defers them. Before you plan anything, call \`tool_search\` for what this job needs — query "browsentic page", limit 20 — and search again for a tool you have not loaded. If the only way you can call a tool is \`exec\`, the same tools are there as \`tools.mcp__browsentic__<name>({ ... })\`: find them by filtering \`ALL_TOOLS\`, and pass a screenshot on with \`image(result.content[0])\`, because \`text()\` alone drops the picture.
-The page the user means is the one open in their browser. Read it with these tools. Never answer from memory${research ? '' : ', from a web search,'} or by fetching the page from the shell${research ? ', and keep a web search to background the page cannot give you' : ''}. Do the job yourself rather than spawning sub-agents: what they say never reaches the user.
+${keepToThePage(research)}`;
-When you reach the tools through \`exec\`, start every script that reads the page with the line \`// @exec: {"max_output_tokens": ${RESULT_TOKENS}}\`, or its output is cut at 10,000 tokens. Even then a tool result over ${RESULT_TOKENS} tokens comes back cut, so ask for less at a time — \`page_getPageInfo\` with a small \`maxPerKind\`, \`page_extractText\` with the cursor it hands back — rather than one large read whose middle goes missing.`;
+/**
+ * Held through the app-server, the browser tools are the model's own. A code-mode model calls them
+ * inside `exec`, where a result comes back as one string, a picture's data URL on its first line.
+ */
+const holdingTheBrowser = (research: boolean) => `# Your browser tools in Codex
+
+Your browsentic tools — \`page_getPageInfo\`, \`page_clickElement\` and the rest — are in your tool list. If the only way you can call a tool is \`exec\`, they are there as \`tools.page_getPageInfo({ ... })\` and the like; a result that holds a picture comes back as text whose first line is a \`data:image/\` URL, and passing that line to \`image()\` is how you see it.
+
+${keepToThePage(research)}`;
interface Item {
id?: string;
@@ -163,6 +184,40 @@ export const codexRunner: Runner = {
parse: listedModels,
},
+ /**
+ * Codex's app-server, unless the config says `exec` or this Codex already turned it down. It takes
+ * the browser tools as its own, streams its words, and counts tokens per request; `exec` is the
+ * fallback, and a thread either one began, the other resumes.
+ */
+ converse(context: StreamContext): Conversation | null {
+ const { settings, research } = context;
+ if (settings.transport === 'exec' || noConversation.has(settings.bin)) return null;
+ return appServerTurn(context, {
+ plan: {
+ cwd: this.workspace('run'),
+ args: [
+ 'app-server',
+ ...SANDBOX_CONFIG,
+ ...NO_SHELL,
+ ...NO_IMAGE_VIEWER,
+ ...QUIETED,
+ ...searching(research),
+ '-c',
+ `tool_output_token_limit=${RESULT_TOKENS}`,
+ ],
+ },
+ settings,
+ effort: effortOf(settings, this.efforts),
+ developerInstructions: `${context.systemPrompt.trim()}\n\n${holdingTheBrowser(research)}`,
+ declined: (reason) => {
+ noConversation.add(settings.bin);
+ log(`codex at ${settings.bin} holds no conversation from now on: ${reason}`);
+ },
+ explain,
+ stoppedFor,
+ });
+ },
+
stream(context: StreamContext): Plan {
const { mcp, research } = context;
const settings = withUserDefaults(context.settings);
diff --git a/src/daemon/agent/runners/drive.test.ts b/src/daemon/agent/runners/drive.test.ts
index 9df6d58..634391d 100644
--- a/src/daemon/agent/runners/drive.test.ts
+++ b/src/daemon/agent/runners/drive.test.ts
@@ -1,5 +1,5 @@
import { once } from 'node:events';
-import { existsSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs';
+import { existsSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Readable } from 'node:stream';
import { afterEach, describe, expect, test, vi } from 'vitest';
@@ -8,6 +8,7 @@ import { AGENTS } from '@/lib/agents/catalog';
import { logPath, stateDir } from '../../lockfile';
import { configPath } from '../config';
import { antigravityRunner } from './antigravity';
+import { codexRunner } from './codex';
import { launch, runJson, runStream } from './drive';
import { jsonContext, streamContext } from './fixtures/support';
import { RunError, type Plan, type Runner, type StreamReader, type StreamSink } from './types';
@@ -34,12 +35,16 @@ const printing = (...lines: unknown[]) =>
const node = { bin: process.execPath };
+/** Browser tools with nothing in them, for a runner that asks for its own. */
+const noTools = async () => ({ list: async () => ({ tools: [], withheld: [] }), call: async () => ({ content: [] }) });
+
const run = async (
runner: Runner,
{ runId = 'drive-run', conversation = 'conversation-1', signal = new AbortController().signal, bin = node.bin } = {},
) => {
const events: RunEvent[] = [];
- const outcome = await runStream(runner, streamContext({ bin }, { runId, conversation }), signal, (event) => events.push(event));
+ const context = streamContext({ bin }, { runId, conversation, tools: noTools });
+ const outcome = await runStream(runner, context, signal, (event) => events.push(event));
return { outcome, events, said: events.flatMap((event) => (event.kind === 'text' ? [event.delta] : [])).join('') };
};
@@ -175,6 +180,68 @@ describe('a streamed run', () => {
});
});
+/**
+ * A Node script in place of `codex`, so Codex's real plans are vetted and spawned as they would be.
+ * It notes each subcommand it was started with, then plays the part `behaviour` gives it.
+ */
+function codexStandIn(name: string, behaviour: string): { bin: string; started: () => string[] } {
+ const bin = join(stateDir, `${name}.js`);
+ const log = join(stateDir, `${name}.log`);
+ rmSync(log, { force: true });
+ writeFileSync(
+ bin,
+ `#!${process.execPath}\nconst fs = require('node:fs');\nfs.appendFileSync(${JSON.stringify(log)}, process.argv[2] + '\\n');\n${behaviour}\n`,
+ { mode: 0o755 },
+ );
+ return { bin, started: () => (existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n') : []) };
+}
+
+/** Enough of the app-server to hold one turn: each request answered, then a reply and the end of the turn. */
+const APP_SERVER = `
+if (process.argv[2] !== 'app-server') process.exit(9);
+const reply = (id, result) => console.log(JSON.stringify({ jsonrpc: '2.0', id, result }));
+const note = (method, params) => console.log(JSON.stringify({ jsonrpc: '2.0', method, params }));
+require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {
+ const { id, method } = JSON.parse(line);
+ if (method === 'initialize') reply(id, {});
+ if (method === 'config/read') reply(id, { config: {} });
+ if (method === 'thread/start') reply(id, { thread: { id: 'thread-held' } });
+ if (method === 'turn/start') {
+ reply(id, { turn: { id: 'turn-1' } });
+ note('item/agentMessage/delta', { threadId: 'thread-held', itemId: 'm1', delta: 'Held over stdin.' });
+ note('turn/completed', { threadId: 'thread-held', turn: { status: 'completed' } });
+ }
+});
+process.stdin.on('end', () => process.exit(0));
+`;
+
+const EXEC = `
+if (process.argv[2] !== 'exec') { console.error("error: unrecognized subcommand 'app-server'"); process.exit(2); }
+console.log(JSON.stringify({ type: 'thread.started', thread_id: 'thread-exec' }));
+console.log(JSON.stringify({ type: 'item.completed', item: { id: 'm1', type: 'agent_message', text: 'Through exec.' } }));
+console.log(JSON.stringify({ type: 'turn.completed' }));
+`;
+
+describe('a turn held as a conversation', () => {
+ test('is spoken to over stdin, and the CLI goes when its stdin is closed', async () => {
+ const codex = codexStandIn('codex-held', APP_SERVER);
+ const { outcome, said } = await run(codexRunner, { bin: codex.bin });
+ expect([outcome, said, codex.started()]).toEqual([{ stopReason: 'end_turn', sessionId: 'thread-held' }, 'Held over stdin.', ['app-server']]);
+ });
+
+ test('a Codex with no app-server runs the same turn through exec, and its later turns go straight there', async () => {
+ const codex = codexStandIn('codex-no-app-server', EXEC);
+ const first = await run(codexRunner, { bin: codex.bin });
+ const second = await run(codexRunner, { bin: codex.bin });
+ expect([first.outcome, first.said, second.said, codex.started()]).toEqual([
+ { stopReason: 'end_turn', sessionId: 'thread-exec' },
+ 'Through exec.',
+ 'Through exec.',
+ ['app-server', 'exec', 'exec'],
+ ]);
+ });
+});
+
describe('what reaches the process', () => {
const unsafe = (real: Plan): Plan => ({ ...real, cwd: join(stateDir, 'agents', 'unsafe-run'), files: real.files?.filter((file) => file.path !== 'AGENTS.md') });
const marker = join(stateDir, 'unsafe-ran');
diff --git a/src/daemon/agent/runners/drive.ts b/src/daemon/agent/runners/drive.ts
index df222f6..078e68d 100644
--- a/src/daemon/agent/runners/drive.ts
+++ b/src/daemon/agent/runners/drive.ts
@@ -10,7 +10,10 @@ import { configPath, type AgentSettings } from '../config';
import { stateDir } from '../../lockfile';
import { log } from '../../log';
import {
+ CONVERSATION_REFUSED,
RunError,
+ type Conversation,
+ type ConversationIO,
type JsonContext,
type Plan,
type RunOutcome,
@@ -25,6 +28,9 @@ const STRIPPED = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'BROWSENTIC_AGENT_RUN'
type Child = ChildProcessByStdio<Writable | null, Readable, Readable>;
+/** What a plan is spawned with: stdin stays closed unless the CLI is held in a conversation over it. */
+type Stdin = 'ignore' | 'pipe';
+
/**
* Vet, then spawn. Every run reaches the CLI through here, so this is where a plan that
* has lost its containment is stopped — before the process exists, not after it has
@@ -36,6 +42,7 @@ export function launch(
settings: AgentSettings,
plan: Plan,
signal: AbortSignal,
+ stdin: Stdin = 'ignore',
): { child: Child; release: () => void; stop: () => void } {
const problems = vetPlan(kind, mode, plan, stateDir);
if (problems.length) {
@@ -64,7 +71,7 @@ export function launch(
const child = spawn(settings.bin, plan.args, {
cwd: plan.cwd,
env,
- stdio: ['ignore', 'pipe', 'pipe'],
+ stdio: [stdin, 'pipe', 'pipe'],
}) as Child;
const kill = () => {
@@ -98,26 +105,67 @@ function spawnError(runner: Runner, settings: AgentSettings, error: NodeJS.Errno
return error.code === 'ENOENT' ? notInstalled(runner, settings) : new RunError('AGENT_FAILED', error.message);
}
-export function runStream(
+/**
+ * A turn, through the conversation the runner offers when it has one. A conversation the CLI will
+ * not hold — an older build, a handshake it refuses — is dropped before anything reached the user,
+ * and the same turn goes through the runner's plain stream instead.
+ */
+export async function runStream(
runner: Runner,
context: StreamContext,
signal: AbortSignal,
emit: (event: RunEvent) => void,
): Promise<RunOutcome> {
- const plan = runner.stream(context);
+ const conversation = runner.converse?.(context);
+ if (conversation) {
+ try {
+ return await drive(runner, context, conversation.plan, signal, emit, conversation);
+ } catch (error) {
+ if (!(error instanceof RunError) || error.code !== CONVERSATION_REFUSED) throw error;
+ log(`${runner.kind} would not hold a conversation (${error.message}); running this turn from its plan instead`);
+ }
+ }
+ return drive(runner, context, runner.stream(context), signal, emit);
+}
+
+function drive(
+ runner: Runner,
+ context: StreamContext,
+ plan: Plan,
+ signal: AbortSignal,
+ emit: (event: RunEvent) => void,
+ conversation?: Conversation,
+): Promise<RunOutcome> {
const label = AGENTS[runner.kind].label;
+ const mode = conversation ? 'conversation' : 'run';
return new Promise<RunOutcome>((resolve, reject) => {
- const { child, release, stop } = launch(runner.kind, 'run', context.settings, plan, signal);
+ const { child, release, stop } = launch(runner.kind, mode, context.settings, plan, signal, conversation ? 'pipe' : 'ignore');
let sessionId: string | null = null;
let settled = false;
let stderrTail = '';
+ const io: ConversationIO = {
+ write: (message) => {
+ if (child.stdin?.writable) child.stdin.write(`${JSON.stringify(message)}\n`);
+ },
+ };
+
+ // A conversation ends when its stdin does; the CLI is asked to go, and stopped if it lingers.
+ const hangUp = () => {
+ if (!child.stdin) return;
+ child.stdin.end();
+ const lingering = setTimeout(stop, KILL_GRACE_MS);
+ lingering.unref();
+ child.once('close', () => clearTimeout(lingering));
+ };
+
const settle = (outcome: () => void) => {
if (settled) return;
settled = true;
outcome();
+ hangUp();
};
// What the agent says reaches the user and the transcript, so it goes through the
@@ -153,12 +201,13 @@ export function runStream(
stderrTail = (stderrTail + chunk.toString()).slice(-2_000);
});
- const read = runner.reader();
+ const reader = runner.reader();
+ const read = (line: string) => (conversation ? conversation.read(line, sink, io) : reader(line, sink));
const lines = createInterface({ input: child.stdout });
lines.on('line', (line) => {
if (!line.trim()) return;
try {
- read(line, sink);
+ read(line);
} catch (error) {
log(`${runner.kind} runner could not read a stream line: ${String(error)}`);
}
@@ -172,6 +221,11 @@ export function runStream(
release();
if (settled) return;
if (signal.aborted) return settle(() => reject(new RunError('CANCELLED', 'Run cancelled.')));
+ if (conversation && !conversation.holding) {
+ const reason = `it exited with code ${exitCode}${tail(stderrTail)}`;
+ conversation.declined(reason);
+ return settle(() => reject(new RunError(CONVERSATION_REFUSED, reason)));
+ }
if (runner.endsOnExit && exitCode === 0) return sink.done('end_turn');
const hint = runner.hint?.(stderrTail);
settle(() =>
@@ -183,6 +237,8 @@ export function runStream(
),
);
});
+
+ conversation?.open(io);
});
}
diff --git a/src/daemon/agent/runners/fixtures/codex/0.155.1-app-server-turn.jsonl b/src/daemon/agent/runners/fixtures/codex/0.155.1-app-server-turn.jsonl
new file mode 100644
index 0000000..147a49e
--- /dev/null
+++ b/src/daemon/agent/runners/fixtures/codex/0.155.1-app-server-turn.jsonl
@@ -0,0 +1,33 @@
+# Recorded from codex 0.155.1's app-server with a local stand-in for the model: what it printed for one turn with the user's one MCP server switched off — two browser tool calls, the second answered with a picture, a streamed reply and a token count per request. The machine's name, installation id and paths are replaced.
+{"id":1,"result":{"userAgent":"browsentic/0.155.1 (Mac OS 26.6.2; arm64) unknown (browsentic; 0)","codexHome":"/Users/you/.browsentic/homes/rec","platformFamily":"unix","platformOs":"macos"}}
+{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"your-mac","installationId":"00000000-0000-0000-0000-000000000000","environmentId":null},"emittedAtMs":1790510384754}
+{"id":2,"result":{"config":{"model":null,"review_model":null,"model_context_window":null,"model_auto_compact_token_limit":null,"model_auto_compact_token_limit_scope":null,"model_provider":"mock","approval_policy":null,"approvals_reviewer":null,"sandbox_mode":null,"sandbox_workspace_write":null,"forced_chatgpt_workspace_id":null,"forced_login_method":null,"web_search":null,"tools":null,"instructions":null,"developer_instructions":null,"compact_prompt":null,"model_reasoning_effort":null,"model_reasoning_summary":null,"model_verbosity":null,"service_tier":null,"analytics":null,"apps":null,"browser_use":null,"computer_use":null,"desktop":null,"disable_paste_burst":null,"suppress_unstable_features_warning":null,"mcp_oauth_callback_url":null,"ghost_snapshot":null,"include_apps_instructions":true,"mcp_oauth_callback_port":null,"show_raw_agent_reasoning":null,"hooks":null,"otel":null,"mcp_optional_startup_grace_ms":null,"goals":null,"mcp_servers":{"decoy":{"command":"node","args":["/Users/you/.browsentic/h/stub-mcp.js"],"environment_id":"local","enabled":true,"tool_timeout_sec":null}},"include_collaboration_mode_instructions":true,"js_repl_node_module_dirs":null,"skills":null,"js_repl_node_path":null,"file_opener":"vscode","oss_provider":null,"windows":null,"include_permissions_instructions":true,"history":{"persistence":"save-all","max_bytes":null},"orchestrator":null,"hide_agent_reasoning":false,"experimental_thread_store_endpoint":null,"check_for_update_on_startup":null,"shell_environment_policy":{"inherit":null,"ignore_default_excludes":null,"exclude":null,"set":null,"include_only":null,"filters":null,"experimental_use_profile":null},"experimental_realtime_ws_backend_prompt":null,"profiles":{},"cli_auth_credentials_store":"file","notify":null,"plugins":{},"permissions":null,"allow_symlinked_codex_home":null,"notice":null,"realtime":null,"background_terminal_max_timeout":300000,"tool_suggest":null,"responses_api_metadata":null,"experimental_realtime_start_instructions":null,"default_permissions":null,"feedback":null,"openai_base_url":null,"experimental_realtime_ws_startup_context":null,"experimental_realtime_ws_model":null,"tool_output_token_limit":null,"include_environment_context":true,"sqlite_home":null,"tui":null,"marketplaces":{},"project_doc_max_bytes":32768,"personality":null,"experimental_realtime_ws_base_url":null,"profile":null,"experimental_thread_store":null,"model_instructions_file":null,"projects":null,"agents":null,"experimental_compact_prompt_file":null,"allow_login_shell":true,"auto_review":null,"features":{"api_key_model_discovery":false,"auth_elicitation":true,"background_paginated_rollout_migration":false,"codex_apps_mcp_2026_07_28":false,"mcp_2026_07_28":false,"memories":false,"mentions_v2":true,"remote_control":false,"remote_plugin":true,"tool_suggest":true,"windows_sandbox_service":false},"log_dir":null,"plan_mode_reasoning_effort":null,"chatgpt_base_url":"https://chatgpt.com/backend-api/","experimental_use_unified_exec_tool":null,"experimental_realtime_webrtc_call_base_url":null,"audio":null,"thread_unload_delay_secs":null,"model_catalog_json":null,"apps_mcp_product_sku":null,"model_providers":{"mock":{"name":"mock","base_url":"http://127.0.0.1:18901/v1","env_key":null,"env_key_instructions":null,"experimental_bearer_token":null,"auth":null,"aws":null,"wire_api":"responses","query_params":null,"http_headers":null,"env_http_headers":null,"request_max_retries":null,"stream_max_retries":null,"stream_idle_timeout_ms":null,"websocket_connect_timeout_ms":null,"requires_openai_auth":false,"supports_websockets":false,"supports_standalone_web_search":false}},"memories":null,"project_root_markers":[".git"],"mcp_oauth_credentials_store":"auto","project_doc_fallback_filenames":[]},"origins":{"model_providers.mock.wire_api":{"name":{"type":"sessionFlags"},"version":"sha256:c8d94a07ab5733f38149f9eebef976ded2cb0c1bb466121044760a0dbca1400d"},"mcp_servers.decoy.args.0":{"name":{"type":"user","file":"/Users/you/.browsentic/homes/rec/config.toml","profile":null},"version":"sha256:8824174b1a77d0af8a680338e868b11111aada16c4a8387965ba324e21e8d3f4"},"mcp_servers.decoy.command":{"name":{"type":"user","file":"/Users/you/.browsentic/homes/rec/config.toml","profile":null},"version":"sha256:8824174b1a77d0af8a680338e868b11111aada16c4a8387965ba324e21e8d3f4"},"model_providers.mock.base_url":{"name":{"type":"sessionFlags"},"version":"sha256:c8d94a07ab5733f38149f9eebef976ded2cb0c1bb466121044760a0dbca1400d"},"model_providers.mock.name":{"name":{"type":"sessionFlags"},"version":"sha256:c8d94a07ab5733f38149f9eebef976ded2cb0c1bb466121044760a0dbca1400d"},"model_provider":{"name":{"type":"sessionFlags"},"version":"sha256:c8d94a07ab5733f38149f9eebef976ded2cb0c1bb466121044760a0dbca1400d"}}}}
+{"id":3,"result":{"thread":{"id":"01a0e2bc-4675-7451-bab0-c6b9d7740962","environments":[{"environmentId":"local","cwd":"/Users/you/.browsentic/cwd","runtimeWorkspaceRoots":["/Users/you/.browsentic/cwd"]}],"extra":null,"sessionId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"mock","model":"gpt-5.5","reasoningEffort":null,"createdAt":1790510384,"updatedAt":1790510384,"recencyAt":1790510384,"status":{"type":"idle"},"path":"/Users/you/.browsentic/homes/rec/sessions/2026/09/27/rollout-2026-09-27T13-59-44-01a0e2bc-4675-7451-bab0-c6b9d7740962.jsonl","cwd":"/Users/you/.browsentic/cwd","cliVersion":"0.155.1","originator":"browsentic","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-5.5","modelProvider":"mock","serviceTier":null,"cwd":"/Users/you/.browsentic/cwd","runtimeWorkspaceRoots":["/Users/you/.browsentic/cwd"],"instructionSources":[],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"readOnly","networkAccess":false},"activePermissionProfile":null,"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}
+{"method":"thread/started","params":{"thread":{"id":"01a0e2bc-4675-7451-bab0-c6b9d7740962","environments":[{"environmentId":"local","cwd":"/Users/you/.browsentic/cwd","runtimeWorkspaceRoots":["/Users/you/.browsentic/cwd"]}],"extra":null,"sessionId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"mock","model":"gpt-5.5","reasoningEffort":null,"createdAt":1790510384,"updatedAt":1790510384,"recencyAt":1790510384,"status":{"type":"idle"},"path":"/Users/you/.browsentic/homes/rec/sessions/2026/09/27/rollout-2026-09-27T13-59-44-01a0e2bc-4675-7451-bab0-c6b9d7740962.jsonl","cwd":"/Users/you/.browsentic/cwd","cliVersion":"0.155.1","originator":"browsentic","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790510384764}
+{"id":4,"result":{"turn":{"id":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}
+{"method":"thread/status/changed","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790510384770}
+{"method":"turn/started","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turn":{"id":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790510384,"completedAt":null,"durationMs":null}},"emittedAtMs":1790510384770}
+{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0e2bc-4687-7840-9152-0e8d32cb8701","clientId":null,"content":[{"type":"text","text":"read the page","text_elements":[]}]},"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","startedAtMs":1790510384775},"emittedAtMs":1790510384775}
+{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0e2bc-4687-7840-9152-0e8d32cb8701","clientId":null,"content":[{"type":"text","text":"read the page","text_elements":[]}]},"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","completedAtMs":1790510384775},"emittedAtMs":1790510384776}
+{"method":"item/started","params":{"item":{"type":"dynamicToolCall","id":"call-1","namespace":null,"tool":"page_echo","arguments":{},"status":"inProgress","contentItems":null,"success":null,"durationMs":null},"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","startedAtMs":1790510384781},"emittedAtMs":1790510384782}
+{"method":"item/tool/call","id":0,"params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","callId":"call-1","namespace":null,"tool":"page_echo","arguments":{}}}
+{"method":"item/completed","params":{"item":{"type":"dynamicToolCall","id":"call-1","namespace":null,"tool":"page_echo","arguments":{},"status":"completed","contentItems":[{"type":"inputText","text":"MARKER=DEV_ONE"}],"success":true,"durationMs":0},"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","completedAtMs":1790510384782},"emittedAtMs":1790510384782}
+{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","tokenUsage":{"total":{"totalTokens":110,"inputTokens":100,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":10,"reasoningOutputTokens":0},"last":{"totalTokens":110,"inputTokens":100,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":10,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790510384783}
+{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":null,"secondary":null,"credits":null,"individualLimit":null,"spendControlReached":null,"planType":null,"rateLimitReachedType":null}},"emittedAtMs":1790510384783}
+{"method":"item/started","params":{"item":{"type":"dynamicToolCall","id":"call-2","namespace":null,"tool":"page_shot","arguments":{},"status":"inProgress","contentItems":null,"success":null,"durationMs":null},"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","startedAtMs":1790510384790},"emittedAtMs":1790510384790}
+{"method":"item/tool/call","id":1,"params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","callId":"call-2","namespace":null,"tool":"page_shot","arguments":{}}}
+{"method":"item/completed","params":{"item":{"type":"dynamicToolCall","id":"call-2","namespace":null,"tool":"page_shot","arguments":{},"status":"completed","contentItems":[{"type":"inputImage","imageUrl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="},{"type":"inputText","text":"SHOT_NOTE"}],"success":true,"durationMs":0},"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","completedAtMs":1790510384790},"emittedAtMs":1790510384790}
+{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","tokenUsage":{"total":{"totalTokens":220,"inputTokens":200,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":20,"reasoningOutputTokens":0},"last":{"totalTokens":110,"inputTokens":100,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":10,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790510384791}
+{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":null,"secondary":null,"credits":null,"individualLimit":null,"spendControlReached":null,"planType":null,"rateLimitReachedType":null}},"emittedAtMs":1790510384791}
+{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg-3","text":"","phase":null,"memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","startedAtMs":1790510384793},"emittedAtMs":1790510384793}
+{"method":"item/agentMessage/delta","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","itemId":"msg-3","delta":"It c"},"emittedAtMs":1790510384793}
+{"method":"item/agentMessage/delta","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","itemId":"msg-3","delta":"osts"},"emittedAtMs":1790510384793}
+{"method":"item/agentMessage/delta","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","itemId":"msg-3","delta":"\ntwe"},"emittedAtMs":1790510384793}
+{"method":"item/agentMessage/delta","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","itemId":"msg-3","delta":"lve "},"emittedAtMs":1790510384793}
+{"method":"item/agentMessage/delta","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","itemId":"msg-3","delta":"doll"},"emittedAtMs":1790510384793}
+{"method":"item/agentMessage/delta","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","itemId":"msg-3","delta":"ars."},"emittedAtMs":1790510384793}
+{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg-3","text":"It costs\ntwelve dollars.","phase":null,"memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","completedAtMs":1790510384793},"emittedAtMs":1790510384793}
+{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turnId":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","tokenUsage":{"total":{"totalTokens":3250,"inputTokens":3200,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":50,"reasoningOutputTokens":0},"last":{"totalTokens":3030,"inputTokens":3000,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":30,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790510384794}
+{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":null,"secondary":null,"credits":null,"individualLimit":null,"spendControlReached":null,"planType":null,"rateLimitReachedType":null}},"emittedAtMs":1790510384794}
+{"method":"thread/status/changed","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","status":{"type":"idle"}},"emittedAtMs":1790510384795}
+{"method":"turn/completed","params":{"threadId":"01a0e2bc-4675-7451-bab0-c6b9d7740962","turn":{"id":"01a0e2bc-467c-7ec3-9aa7-a369c5667475","items":[{"type":"agentMessage","id":"msg-3","text":"It costs\ntwelve dollars.","phase":null,"memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790510384,"completedAt":1790510384,"durationMs":29}},"emittedAtMs":1790510384795}
diff --git a/src/daemon/agent/runners/fixtures/support.ts b/src/daemon/agent/runners/fixtures/support.ts
index c4bca2b..50721bd 100644
--- a/src/daemon/agent/runners/fixtures/support.ts
+++ b/src/daemon/agent/runners/fixtures/support.ts
@@ -67,6 +67,7 @@ export const streamContext = (settings: AgentSettings, overrides: Partial<Stream
workspace: stateDir,
mcp,
mcpTools: ['page_getPageInfo', 'page_clickElement', 'browsentic_status'],
+ tools: () => Promise.reject(new Error('no browser tools in a runner test')),
...overrides,
});
diff --git a/src/daemon/agent/runners/types.ts b/src/daemon/agent/runners/types.ts
index 109b469..8d3402b 100644
--- a/src/daemon/agent/runners/types.ts
+++ b/src/daemon/agent/runners/types.ts
@@ -2,6 +2,7 @@ import type { TokenUsage } from '@/lib/actions/protocol';
import type { AgentKind, AgentProblem } from '@/lib/agents/catalog';
import type { FileKind } from '@/lib/files/report';
import type { AgentSettings } from '../config';
+import type { ToolHost } from '../../tool-host';
/** `run` drives the browser and resumes conversations; `task` is a one-shot with no browser. */
export type RunMode = 'run' | 'task';
@@ -39,6 +40,8 @@ export interface StreamContext {
mcp: McpServer;
/** Every tool that server will offer, for a CLI that grants MCP tools one name at a time. */
mcpTools: string[];
+ /** The run's browser tools served in this process, for a CLI that takes tools other than over MCP. */
+ tools: () => Promise<ToolHost>;
}
export interface JsonContext {
@@ -66,6 +69,27 @@ export interface StreamSink {
export type StreamReader = (line: string, sink: StreamSink) => void;
+export interface ConversationIO {
+ write(message: unknown): void;
+}
+
+/**
+ * A CLI spoken to over stdin for the length of a turn rather than handed it on argv: it is sent
+ * `open`'s messages as it starts, and each line it prints may be answered.
+ */
+export interface Conversation {
+ plan: Plan;
+ open(io: ConversationIO): void;
+ read(line: string, sink: StreamSink, io: ConversationIO): void;
+ /** Whether it got as far as holding a session. One that ends before is refused, not failed. */
+ readonly holding: boolean;
+ /** It was refused — told so, or it ended before holding a session — so later turns need not ask again. */
+ declined(reason: string): void;
+}
+
+/** A conversation the CLI would not hold; the turn is run through `stream()` instead. */
+export const CONVERSATION_REFUSED = 'CONVERSATION_REFUSED';
+
export interface Listing {
stdout: string;
stderr: string;
@@ -92,6 +116,8 @@ export interface Runner {
/** Absent: the picker offers the catalog's curated models. */
models?: ModelLister;
stream(context: StreamContext): Plan;
+ /** A conversation to hold for this turn instead, where the CLI offers one; null to use `stream`. */
+ converse?(context: StreamContext): Conversation | null;
/** Fresh per run — readers carry state across lines. */
reader(): StreamReader;
/** This CLI's stream has no closing event, so exiting cleanly is how it says the turn is over. */
diff --git a/src/daemon/guardrails/spawn.test.ts b/src/daemon/guardrails/spawn.test.ts
index 082220d..f2c41cc 100644
--- a/src/daemon/guardrails/spawn.test.ts
+++ b/src/daemon/guardrails/spawn.test.ts
@@ -1,27 +1,34 @@
import { describe, expect, test } from 'vitest';
import { AGENT_KINDS, AGENTS, type AgentKind } from '@/lib/agents/catalog';
import { mcpServerFor, RUNNERS } from '../agent/runners';
-import type { Plan } from '../agent/runners/types';
+import type { Plan, StreamContext } from '../agent/runners/types';
import { stateDir } from '../lockfile';
-import { CONTAINMENT, sealEnv, sealedAway, vetPlan } from './spawn';
+import { CONTAINMENT, sealEnv, sealedAway, vetPlan, type SpawnMode } from './spawn';
const settingsFor = (kind: AgentKind) => ({ bin: AGENTS[kind].bin });
-const planOf = (kind: AgentKind, mode: 'run' | 'task', { research = false, reads = false } = {}): Plan =>
- mode === 'run'
- ? RUNNERS[kind].stream({
- runId: 'run-1',
- conversation: 'conversation-1',
- instruction: 'what does this page cost',
- systemPrompt: 'You are Browsentic.',
- research,
- settings: settingsFor(kind),
- sessionId: null,
- workspace: stateDir,
- mcp: mcpServerFor('run-1'),
- mcpTools: ['page_getPageInfo', 'page_clickElement', 'browsentic_status'],
- })
- : RUNNERS[kind].json({ prompt: 'summarize this', settings: settingsFor(kind), workspace: stateDir, reads });
+const contextFor = (kind: AgentKind, research: boolean): StreamContext => ({
+ runId: 'run-1',
+ conversation: 'conversation-1',
+ instruction: 'what does this page cost',
+ systemPrompt: 'You are Browsentic.',
+ research,
+ settings: settingsFor(kind),
+ sessionId: null,
+ workspace: stateDir,
+ mcp: mcpServerFor('run-1'),
+ mcpTools: ['page_getPageInfo', 'page_clickElement', 'browsentic_status'],
+ tools: () => Promise.reject(new Error('no browser tools in a containment test')),
+});
+
+const planOf = (kind: AgentKind, mode: SpawnMode, { research = false, reads = false } = {}): Plan => {
+ if (mode === 'task') return RUNNERS[kind].json({ prompt: 'summarize this', settings: settingsFor(kind), workspace: stateDir, reads });
+ const context = contextFor(kind, research);
+ if (mode === 'run') return RUNNERS[kind].stream(context);
+ const conversation = RUNNERS[kind].converse?.(context);
+ if (!conversation) throw new Error(`${kind} holds no conversation`);
+ return conversation.plan;
+};
const without = (plan: Plan, arg: string): Plan => ({ ...plan, args: plan.args.filter((value) => value !== arg) });
const plus = (plan: Plan, ...args: string[]): Plan => ({ ...plan, args: [...plan.args, ...args] });
@@ -179,6 +186,18 @@ describe('spawn containment', () => {
expect([vetPlan('codex', 'run', reading, stateDir), vetPlan('codex', 'run', plus(codexRun, '--profile', 'work'), stateDir)].map((problems) => problems.length)).toEqual([1, 1]);
});
+ // Held over stdin, Codex takes its tools in-process; the argv is what can still be vetted.
+ test('a codex conversation is contained, and one without its switches, or from any other agent, is refused', () => {
+ const held = planOf('codex', 'conversation');
+ const shell = { ...held, args: held.args.filter((arg) => arg !== 'features.shell_tool=false') };
+ expect({
+ held: vetPlan('codex', 'conversation', held, stateDir),
+ shell: vetPlan('codex', 'conversation', shell, stateDir).length,
+ enabled: vetPlan('codex', 'conversation', plus(held, '--enable', 'shell_tool'), stateDir).length,
+ claude: vetPlan('claude', 'conversation', planOf('claude', 'run'), stateDir),
+ }).toEqual({ held: [], shell: 1, enabled: 1, claude: ['Claude Code (conversation) has no containment written for it.'] });
+ });
+
test('the codex shell or image viewer switched back on is caught, however it is spelled', () => {
expect(
[
diff --git a/src/daemon/guardrails/spawn.ts b/src/daemon/guardrails/spawn.ts
index f3556a0..e1a8acf 100644
--- a/src/daemon/guardrails/spawn.ts
+++ b/src/daemon/guardrails/spawn.ts
@@ -28,8 +28,11 @@
import { AGENTS, isModelId, type AgentKind } from '@/lib/agents/catalog';
-/** `run` drives the browser; `task` is a one-shot that must not reach it at all. */
-export type SpawnMode = 'run' | 'task';
+/**
+ * `run` drives the browser; `task` is a one-shot that must not reach it at all; `conversation` drives
+ * the browser too, through a CLI held over stdin and handed the tools in-process rather than over MCP.
+ */
+export type SpawnMode = 'run' | 'task' | 'conversation';
/** Structural view of a runner's `Plan`. Kept local so guardrails never import runners. */
export interface SpawnPlan {
@@ -100,6 +103,8 @@ interface Containment {
readonly note: string;
readonly run: Requirements;
readonly task: Requirements;
+ /** Only a runner that holds conversations has these; any other refuses to start one. */
+ readonly conversation?: Requirements;
}
/**
@@ -206,6 +211,21 @@ export const CONTAINMENT: Record<AgentKind, Containment> = {
pairs: [],
files: [],
},
+ // The app-server has no --ignore-user-config. It is handed the browser tools in-process and no MCP
+ // server of Browsentic's; each one config.toml names is switched off for the thread once Codex has
+ // said which there are, and one that starts anyway stops the run.
+ conversation: {
+ required: [
+ 'app-server',
+ 'sandbox_mode="read-only"',
+ 'approval_policy="never"',
+ 'features.multi_agent=false',
+ 'features.shell_tool=false',
+ 'features.view_image=false',
+ ],
+ pairs: [],
+ files: [],
+ },
},
antigravity: {
@@ -389,8 +409,9 @@ export const CONTAINMENT: Record<AgentKind, Containment> = {
*/
export function vetPlan(kind: AgentKind, mode: SpawnMode, plan: SpawnPlan, home: string): string[] {
const rules = CONTAINMENT[kind][mode];
- const problems: string[] = [];
const label = `${AGENTS[kind].label} (${mode})`;
+ if (!rules) return [`${label} has no containment written for it.`];
+ const problems: string[] = [];
for (const arg of rules.required) {
if (!plan.args.includes(arg)) problems.push(`${label} is spawned without ${arg}.`);
diff --git a/src/extension/components/context-card.tsx b/src/extension/components/context-card.tsx
index 1c2353e..11be40f 100644
--- a/src/extension/components/context-card.tsx
+++ b/src/extension/components/context-card.tsx
@@ -72,7 +72,7 @@ export function ContextCard({ breakdown }: { breakdown: ContextBreakdown }) {
) : breakdown.agent === 'vibe' ? (
'Mistral Vibe does not report token counts.'
) : breakdown.agent === 'codex' ? (
- 'Codex does not report how full its window is.'
+ 'Token counts appear after Codex’s first reply — or never, when it runs through exec.'
) : (
'Token counts appear after the agent’s first reply.'
)}