nanocoai/nanoclaw / .claude/skills/add-codex
add-codex
FlaggedUse Codex (OpenAI's codex app-server) as a full agent provider — planning, tool orchestration, MCP tools, server-side history, session resume — alongside or instead of Claude. ChatGPT subscription or OpenAI API key, vault-only via the selected gateway. Per-group via `ncl groups config update --provider codex`. Distinct from using OpenAI as an MCP tool (where Claude remains the planner).
payload/container/agent-runner/src/providers/codex.turns.test.ts
View on GitHubimport { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { CodexProvider, codexImageSavedNote, type CodexRuntimeDeps } from './codex.js';
import type { AppServer, JsonRpcNotification, TurnParams } from './codex-app-server.js';
import type { ProviderEvent } from './types.js';
const MEMORY_SESSION_HOOK = {
command: 'bun /app/src/memory/hook.ts',
legacyCommands: ['bun /app/src/memory-hook.ts'],
sources: ['startup', 'clear', 'compact'],
} as const;
function createCodexProvider(...args: ConstructorParameters<typeof CodexProvider>): CodexProvider {
const provider = new CodexProvider(...args);
provider.registerMemorySessionHook(MEMORY_SESSION_HOOK);
return provider;
}
describe('CodexProvider active turns', () => {
it('steers follow-ups into the active turn and yields liveness activity', async () => {
const fake = createFakeCodexRuntime();
const provider = createCodexProvider({}, fake.runtime);
const query = provider.query({ prompt: 'first prompt', cwd: '/workspace/agent' });
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
query.push('follow-up prompt');
await waitFor(() => fake.steerCalls.length === 1);
query.end();
fake.completeTurn('final answer');
await collect;
expect(fake.startCalls).toHaveLength(1);
expect(fake.startCalls[0].inputText).toBe('first prompt');
expect(fake.steerCalls).toEqual([{ threadId: 'thread-1', turnId: 'turn-1', inputText: 'follow-up prompt' }]);
expect(events.filter((event) => event.type === 'activity').length).toBeGreaterThanOrEqual(2);
expect(events.filter((event) => event.type === 'result')).toEqual([{ type: 'result', text: 'final answer' }]);
expect(fake.killed).toBe(true);
});
it('queues follow-ups for the next turn when steering is rejected', async () => {
const fake = createFakeCodexRuntime({ rejectSteer: true });
const provider = createCodexProvider({}, fake.runtime);
const query = provider.query({ prompt: 'first prompt', cwd: '/workspace/agent' });
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
query.push('queued follow-up');
await waitFor(() => fake.steerCalls.length === 1);
await sleep(0);
fake.completeTurn('first answer');
await waitFor(() => fake.startCalls.length === 2);
query.end();
fake.completeTurn('second answer');
await collect;
expect(fake.startCalls.map((call) => call.inputText)).toEqual(['first prompt', 'queued follow-up']);
expect(fake.steerCalls).toHaveLength(1);
expect(events.filter((event) => event.type === 'result')).toEqual([
{ type: 'result', text: 'first answer' },
{ type: 'result', text: 'second answer' },
]);
});
it('queues a follow-up that races turn completion into a new turn, never steering the finished turn', async () => {
const fake = createFakeCodexRuntime();
const provider = createCodexProvider({}, fake.runtime);
const query = provider.query({ prompt: 'first prompt', cwd: '/workspace/agent' });
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
// The turn completes, then a follow-up lands in the same tick — before the
// generator has drained and torn the turn down. codex's turn/steer no-ops
// on a finished turn (resolves without error), so steering here would drop
// the message silently. It must start a fresh turn instead.
fake.completeTurn('first answer');
query.push('racing follow-up');
await waitFor(() => fake.startCalls.length === 2);
query.end();
fake.completeTurn('second answer');
await collect;
expect(fake.steerCalls).toHaveLength(0);
expect(fake.startCalls.map((call) => call.inputText)).toEqual(['first prompt', 'racing follow-up']);
expect(events.filter((event) => event.type === 'result')).toEqual([
{ type: 'result', text: 'first answer' },
{ type: 'result', text: 'second answer' },
]);
});
it('interrupts the active turn and closes the stream on abort', async () => {
const fake = createFakeCodexRuntime();
const provider = createCodexProvider({}, fake.runtime);
const query = provider.query({ prompt: 'first prompt', cwd: '/workspace/agent' });
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
query.abort();
await collect;
expect(fake.interruptCalls).toEqual([{ threadId: 'thread-1', turnId: 'turn-1' }]);
expect(events.some((event) => event.type === 'result')).toBe(false);
expect(fake.killed).toBe(true);
});
it('threads the configured model and effort into the turn', async () => {
const fake = createFakeCodexRuntime();
const provider = createCodexProvider({ model: 'gpt-5.5', effort: 'high' }, fake.runtime);
const query = provider.query({ prompt: 'first prompt', cwd: '/workspace/agent' });
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
query.end();
fake.completeTurn('final answer');
await collect;
expect(fake.startCalls[0].model).toBe('gpt-5.5');
expect(fake.startCalls[0].effort).toBe('high');
expect(events.filter((event) => event.type === 'result')).toEqual([{ type: 'result', text: 'final answer' }]);
});
it('tells the agent mid-turn where a generated image is saved, so it sends the file itself', async () => {
const fake = createFakeCodexRuntime();
const provider = createCodexProvider({}, fake.runtime);
const query = provider.query({ prompt: 'make an image', cwd: '/workspace/agent' });
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
// Codex's built-in image tool reports each saved image mid-turn; one that
// failed to save has no path and gets no note. A sub-agent's turn/started
// arrives on the same connection, so the note must follow the image's own
// thread and turn, not the last turn started.
const savedPath = '/home/node/.codex/generated_images/thread-1/ig_abc.png';
fake.notify('turn/started', { threadId: 'child-thread', turn: { id: 'child-turn' } });
fake.notify('item/completed', {
threadId: 'thread-1',
turnId: 'turn-1',
item: { type: 'imageGeneration', status: 'failed' },
});
fake.notify('item/completed', {
threadId: 'thread-1',
turnId: 'turn-1',
item: { type: 'imageGeneration', status: 'completed', savedPath },
});
// A sub-agent's image is noted in the sub-agent's own turn.
const childPath = '/home/node/.codex/generated_images/child-thread/ig_def.png';
fake.notify('item/completed', {
threadId: 'child-thread',
turnId: 'child-turn',
item: { type: 'imageGeneration', status: 'completed', savedPath: childPath },
});
await waitFor(() => fake.steerCalls.length === 2);
query.end();
fake.completeTurn('Sent it.');
await collect;
expect(fake.steerCalls).toEqual([
{ threadId: 'thread-1', turnId: 'turn-1', inputText: codexImageSavedNote(savedPath) },
{ threadId: 'child-thread', turnId: 'child-turn', inputText: codexImageSavedNote(childPath) },
]);
expect(codexImageSavedNote(savedPath)).toContain(savedPath);
expect(codexImageSavedNote(savedPath)).toContain('send_file');
expect(fake.startCalls).toHaveLength(1);
expect(events.filter((event) => event.type === 'result')).toEqual([{ type: 'result', text: 'Sent it.' }]);
});
it('keeps a save-only image unsent: the note defers to the request and the provider delivers nothing', async () => {
const fake = createFakeCodexRuntime();
const provider = createCodexProvider({}, fake.runtime);
// Like an isolated task that must not notify anyone unless it asks to.
const query = provider.query({
prompt: 'Save a logo to /workspace/agent/logo.png. Do not send it to anyone.',
cwd: '/workspace/agent',
});
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
const savedPath = '/home/node/.codex/generated_images/thread-1/ig_logo.png';
fake.notify('item/completed', {
threadId: 'thread-1',
turnId: 'turn-1',
item: { type: 'imageGeneration', status: 'completed', savedPath },
});
await waitFor(() => fake.steerCalls.length === 1);
query.end();
fake.completeTurn('Saved.');
await collect;
// Exact text: any edit that makes sending unconditional must change this test.
expect(fake.steerCalls.map((call) => call.inputText)).toEqual([
`<system>Your image generation tool saved ${savedPath}. Nobody has seen it: it is not shown automatically. ` +
"Follow the original request's delivery instructions. If whoever asked expects to see the image, send it with send_file. " +
'If the request only asked to save it, said not to send it, or is a task that did not ask you to notify anyone, do not send it.</system>',
]);
// Only the agent's own send_file delivers; the provider emits no file.
expect(events.map((event) => event.type)).not.toContain('file');
expect(events.filter((event) => event.type === 'result')).toEqual([{ type: 'result', text: 'Saved.' }]);
});
it('drops an image note it cannot steer instead of starting a turn the runner never asked for', async () => {
const fake = createFakeCodexRuntime({ rejectSteer: true });
const provider = createCodexProvider({}, fake.runtime);
const query = provider.query({ prompt: 'make an image', cwd: '/workspace/agent' });
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
const savedPath = '/home/node/.codex/generated_images/thread-1/ig_abc.png';
fake.notify('item/completed', {
threadId: 'thread-1',
turnId: 'turn-1',
item: { type: 'imageGeneration', status: 'completed', savedPath },
});
await waitFor(() => fake.steerCalls.length === 1);
await sleep(0);
query.end();
fake.completeTurn('Done.');
await collect;
expect(fake.startCalls).toHaveLength(1);
expect(events.filter((event) => event.type === 'result')).toEqual([{ type: 'result', text: 'Done.' }]);
});
it('ends the turn immediately with the real cause when the app-server dies mid-turn', async () => {
const fake = createFakeCodexRuntime();
const provider = createCodexProvider({}, fake.runtime);
const query = provider.query({ prompt: 'prompt', cwd: '/workspace/agent' });
const events: ProviderEvent[] = [];
const collect = collectEvents(query.events, events);
await waitFor(() => fake.startCalls.length === 1);
// No pending request exists mid-turn (turn/start already resolved), so
// only the exitHandlers seam can end the turn — without it this parks
// on the waker until the 10-minute turn timeout.
fake.crashServer(new Error('Codex app-server exited: code=1 signal=null'));
// The generator yields the error event, then rethrows to its consumer.
await collect.catch(() => {});
const errors = events.filter((event) => event.type === 'error');
expect(errors).toHaveLength(1);
expect((errors[0] as { message: string }).message).toContain('app-server exited');
});
});
function createFakeCodexRuntime(opts: { rejectSteer?: boolean } = {}) {
const server = fakeServer();
const startCalls: TurnParams[] = [];
const steerCalls: Array<{ threadId: string; turnId: string; inputText: string }> = [];
const interruptCalls: Array<{ threadId: string; turnId: string }> = [];
let killed = false;
const notify = (method: string, params?: Record<string, unknown>): void => {
const notification: JsonRpcNotification = { method, params };
for (const handler of [...server.notificationHandlers]) handler(notification);
};
const runtime: CodexRuntimeDeps = {
writeCodexConfigToml: () => {},
spawnCodexAppServer: () => server,
attachCodexAutoApproval: () => {},
initializeCodexAppServer: async () => {},
startOrResumeCodexThread: async (_server, threadId) => threadId ?? 'thread-1',
startCodexTurn: async (_server, params) => {
startCalls.push(params);
const turnId = `turn-${startCalls.length}`;
notify('turn/started', { turn: { id: turnId } });
return turnId;
},
steerCodexTurn: async (_server, threadId, turnId, inputText) => {
steerCalls.push({ threadId, turnId, inputText });
if (opts.rejectSteer) throw new Error('steer rejected');
},
interruptCodexTurn: async (_server, threadId, turnId) => {
interruptCalls.push({ threadId, turnId });
},
killCodexAppServer: () => {
killed = true;
},
};
return {
runtime,
startCalls,
steerCalls,
interruptCalls,
get killed() {
return killed;
},
notify,
completeTurn(text: string) {
notify('turn/completed', { turn: { items: [{ type: 'agentMessage', text }] } });
},
crashServer(err: Error) {
for (const h of [...server.exitHandlers]) h(err);
},
};
}
function fakeServer(): AppServer {
return {
process: { stdin: { write: () => true }, kill: () => true },
readline: { close: () => {} },
pending: new Map(),
notificationHandlers: [],
exitHandlers: [],
serverRequestHandlers: [],
} as unknown as AppServer;
}
async function collectEvents(events: AsyncIterable<ProviderEvent>, sink: ProviderEvent[]): Promise<void> {
for await (const event of events) {
sink.push(event);
}
}
async function waitFor(condition: () => boolean, timeoutMs = 1000): Promise<void> {
const start = Date.now();
while (!condition()) {
if (Date.now() - start > timeoutMs) throw new Error('waitFor timeout');
await sleep(10);
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |