xonecas.io
687
Oc

orc-code / commit faaf7a3

feat: add codex plugin with shared spawn helpers

- Codex plugin: parser for JSONL events (thread.started, item.started/completed, turn.completed)
- Extract spawnAgentProcess + checkCommand into @orc-code/types/helpers
- Slim down both plugins to arg builder + parser only (0% code duplication)
- Add -a/--agent flag to CLI for agent selection
- Tested live: both claude and codex work end-to-end

xonecas2026-03-26 faaf7a304c65bba0ebc5b40983ac434f8322402f parent 51d4305

11 files changed

bun.lock+14−0
@@ -22,6 +22,7 @@
2222 },
2323 "dependencies": {
2424 "@orc-code/plugin-claude": "workspace:*",
25+ "@orc-code/plugin-codex": "workspace:*",
2526 "@orc-code/types": "workspace:*",
2627 },
2728 "devDependencies": {
@@ -40,6 +41,17 @@
4041 "typescript": "^5.8.2",
4142 },
4243 },
44+ "packages/plugin-codex": {
45+ "name": "@orc-code/plugin-codex",
46+ "version": "0.0.1",
47+ "dependencies": {
48+ "@orc-code/types": "workspace:*",
49+ },
50+ "devDependencies": {
51+ "@types/bun": "^1.2.0",
52+ "typescript": "^5.8.2",
53+ },
54+ },
4355 "packages/types": {
4456 "name": "@orc-code/types",
4557 "version": "0.0.1",
@@ -124,6 +136,8 @@
124136
125137 "@orc-code/plugin-claude": ["@orc-code/plugin-claude@workspace:packages/plugin-claude"],
126138
139+ "@orc-code/plugin-codex": ["@orc-code/plugin-codex@workspace:packages/plugin-codex"],
140+
127141 "@orc-code/types": ["@orc-code/types@workspace:packages/types"],
128142
129143 "@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.120.0", "", { "os": "android", "cpu": "arm" }, "sha512-WU3qtINx802wOl8RxAF1v0VvmC2O4D9M8Sv486nLeQ7iPHVmncYZrtBhB4SYyX+XZxj2PNnCcN+PW21jHgiOxg=="],
packages/orc-core/package.json+2−1
@@ -11,7 +11,8 @@
1111 },
1212 "dependencies": {
1313 "@orc-code/types": "workspace:*",
14- "@orc-code/plugin-claude": "workspace:*"
14+ "@orc-code/plugin-claude": "workspace:*",
15+ "@orc-code/plugin-codex": "workspace:*"
1516 },
1617 "devDependencies": {
1718 "@types/bun": "^1.2.0",
packages/orc-core/src/agents.ts+2−1
@@ -1,8 +1,9 @@
11 import claude from "@orc-code/plugin-claude";
2+import codex from "@orc-code/plugin-codex";
23 import type { AgentPlugin } from "@orc-code/types";
34 import { upsertAgent } from "./db.js";
45
5-const builtinPlugins: AgentPlugin[] = [claude];
6+const builtinPlugins: AgentPlugin[] = [claude, codex];
67
78 export async function discoverAgents(): Promise<AgentPlugin[]> {
89 const available: AgentPlugin[] = [];
packages/orc-core/src/cli.ts+14−4
@@ -8,29 +8,33 @@ import { printBanner, printEvent } from "./display.js";
88 function parseArgs(argv: string[]): {
99 resume?: string;
1010 prompt?: string;
11+ agent?: string;
1112 } {
1213 const args = argv.slice(2);
1314 let resume: string | undefined;
1415 let prompt: string | undefined;
16+ let agent: string | undefined;
1517
1618 for (let i = 0; i < args.length; i++) {
1719 const arg = args[i];
1820 if ((arg === "-r" || arg === "--resume") && i + 1 < args.length) {
1921 resume = args[++i];
22+ } else if ((arg === "-a" || arg === "--agent") && i + 1 < args.length) {
23+ agent = args[++i];
2024 } else if (!prompt && !arg.startsWith("-")) {
2125 prompt = arg;
2226 }
2327 }
2428
25- return { resume, prompt };
29+ return { resume, prompt, agent };
2630 }
2731
2832 async function main(): Promise<void> {
29- const { resume, prompt } = parseArgs(process.argv);
33+ const { resume, prompt, agent: agentName } = parseArgs(process.argv);
3034
3135 if (!prompt) {
3236 console.error("Usage: orc <prompt>");
33- console.error(" orc -r <session-id> <prompt>");
37+ console.error(" orc -a <agent> -r <session-id> <prompt>");
3438 process.exit(1);
3539 }
3640
@@ -40,7 +44,13 @@ async function main(): Promise<void> {
4044 process.exit(1);
4145 }
4246
43- const agent = agents[0];
47+ const agent = agentName ? agents.find((a) => a.name === agentName) : agents[0];
48+ if (!agent) {
49+ console.error(
50+ `Agent "${agentName}" not found. Available: ${agents.map((a) => a.name).join(", ")}`,
51+ );
52+ process.exit(1);
53+ }
4454 printBanner(agent.name);
4555
4656 const orcSessionId = randomUUID();
packages/plugin-claude/src/index.ts+21−76
@@ -1,68 +1,12 @@
1-import type {
2- AgentEvent,
3- AgentPlugin,
4- AgentProcess,
5- AgentResult,
6- AgentSessionOpts,
7-} from "@orc-code/types";
1+import type { AgentEvent, AgentPlugin, AgentProcess, AgentSessionOpts } from "@orc-code/types";
2+import { checkCommand, spawnAgentProcess } from "@orc-code/types";
83 import { parseLine } from "./parser.js";
94
10-function spawnAgent(args: string[], cwd?: string): AgentProcess {
11- const child = Bun.spawn(["claude", ...args], {
12- cwd: cwd ?? process.cwd(),
13- stdout: "pipe",
14- stderr: "pipe",
15- });
16-
17- let resolvedSessionId: string | null = null;
18-
19- async function* streamEvents(): AsyncIterable<AgentEvent> {
20- const reader = child.stdout.getReader();
21- const decoder = new TextDecoder();
22- let buffer = "";
23-
24- while (true) {
25- const { done, value } = await reader.read();
26- if (done) break;
27- buffer += decoder.decode(value, { stream: true });
28-
29- const lines = buffer.split("\n");
30- // keep the last incomplete line in the buffer
31- buffer = lines.pop() ?? "";
32-
33- for (const line of lines) {
34- const events = parseLine(line);
35- for (const event of events) {
36- if (event.type === "done") {
37- resolvedSessionId = event.sessionId;
38- }
39- yield event;
40- }
41- }
42- }
43-
44- // flush remaining buffer
45- if (buffer.trim()) {
46- const events = parseLine(buffer);
47- for (const event of events) {
48- if (event.type === "done") {
49- resolvedSessionId = event.sessionId;
50- }
51- yield event;
52- }
53- }
5+function extractSessionId(_raw: string, events: AgentEvent[]): string | null {
6+ for (const event of events) {
7+ if (event.type === "done") return event.sessionId;
548 }
55-
56- const result: Promise<AgentResult> = child.exited.then((exitCode) => ({
57- sessionId: resolvedSessionId,
58- exitCode,
59- }));
60-
61- return {
62- child,
63- events: streamEvents(),
64- result,
65- };
9+ return null;
6610 }
6711
6812 const plugin: AgentPlugin = {
@@ -70,25 +14,26 @@ const plugin: AgentPlugin = {
7014 command: "claude",
7115 opts: ["-p", "--output-format", "stream-json", "--verbose", "--dangerously-skip-permissions"],
7216
73- async isAvailable(): Promise<boolean> {
74- try {
75- const proc = Bun.spawn(["which", "claude"], {
76- stdout: "ignore",
77- stderr: "ignore",
78- });
79- const code = await proc.exited;
80- return code === 0;
81- } catch {
82- return false;
83- }
84- },
17+ isAvailable: () => checkCommand("claude"),
8518
8619 createSession(prompt: string, opts?: AgentSessionOpts): AgentProcess {
87- return spawnAgent([...this.opts, prompt], opts?.cwd);
20+ return spawnAgentProcess(
21+ "claude",
22+ [...this.opts, prompt],
23+ parseLine,
24+ extractSessionId,
25+ opts?.cwd,
26+ );
8827 },
8928
9029 resumeSession(sessionId: string, prompt: string, opts?: AgentSessionOpts): AgentProcess {
91- return spawnAgent([...this.opts, "--resume", sessionId, prompt], opts?.cwd);
30+ return spawnAgentProcess(
31+ "claude",
32+ [...this.opts, "--resume", sessionId, prompt],
33+ parseLine,
34+ extractSessionId,
35+ opts?.cwd,
36+ );
9237 },
9338 };
9439
packages/plugin-codex/package.json+17−0
@@ -0,0 +1,17 @@
1+{
2+ "name": "@orc-code/plugin-codex",
3+ "version": "0.0.1",
4+ "type": "module",
5+ "main": "src/index.ts",
6+ "types": "src/index.ts",
7+ "scripts": {
8+ "typecheck": "tsc --noEmit"
9+ },
10+ "dependencies": {
11+ "@orc-code/types": "workspace:*"
12+ },
13+ "devDependencies": {
14+ "@types/bun": "^1.2.0",
15+ "typescript": "^5.8.2"
16+ }
17+}
packages/plugin-codex/src/index.ts+54−0
@@ -0,0 +1,54 @@
1+import type { AgentEvent, AgentPlugin, AgentProcess, AgentSessionOpts } from "@orc-code/types";
2+import { checkCommand, spawnAgentProcess } from "@orc-code/types";
3+import { extractThreadId, parseLine } from "./parser.js";
4+
5+function extractSessionId(raw: string, _events: AgentEvent[]): string | null {
6+ return extractThreadId(raw);
7+}
8+
9+const plugin: AgentPlugin = {
10+ name: "codex",
11+ command: "codex",
12+ opts: ["exec", "--json", "--full-auto"],
13+
14+ isAvailable: () => checkCommand("codex"),
15+
16+ createSession(prompt: string, opts?: AgentSessionOpts): AgentProcess {
17+ const proc = spawnAgentProcess(
18+ "codex",
19+ [...this.opts, prompt],
20+ parseLine,
21+ extractSessionId,
22+ opts?.cwd,
23+ );
24+ return appendDoneEvent(proc);
25+ },
26+
27+ resumeSession(sessionId: string, prompt: string, opts?: AgentSessionOpts): AgentProcess {
28+ const proc = spawnAgentProcess(
29+ "codex",
30+ [...this.opts, "resume", sessionId, prompt],
31+ parseLine,
32+ extractSessionId,
33+ opts?.cwd,
34+ );
35+ return appendDoneEvent(proc);
36+ },
37+};
38+
39+/** Codex doesn't emit a done event — we synthesize one after the stream ends. */
40+function appendDoneEvent(proc: AgentProcess): AgentProcess {
41+ async function* withDone(): AsyncIterable<AgentEvent> {
42+ yield* proc.events;
43+ const { sessionId } = await proc.result;
44+ yield { type: "done", sessionId: sessionId ?? "" };
45+ }
46+
47+ return {
48+ child: proc.child,
49+ events: withDone(),
50+ result: proc.result,
51+ };
52+}
53+
54+export default plugin;
packages/plugin-codex/src/parser.ts+101−0
@@ -0,0 +1,101 @@
1+import type { AgentEvent } from "@orc-code/types";
2+
3+interface CodexItem {
4+ id?: string;
5+ type?: string;
6+ text?: string;
7+ command?: string;
8+ aggregated_output?: string;
9+ exit_code?: number | null;
10+ status?: string;
11+}
12+
13+interface CodexLine {
14+ type: string;
15+ thread_id?: string;
16+ item?: CodexItem;
17+ usage?: {
18+ input_tokens?: number;
19+ cached_input_tokens?: number;
20+ output_tokens?: number;
21+ };
22+}
23+
24+export function parseLine(raw: string): AgentEvent[] {
25+ const trimmed = raw.trim();
26+ if (trimmed === "") return [];
27+
28+ let line: CodexLine;
29+ try {
30+ line = JSON.parse(trimmed);
31+ } catch {
32+ return [];
33+ }
34+
35+ const events: AgentEvent[] = [];
36+
37+ switch (line.type) {
38+ case "item.completed": {
39+ const item = line.item;
40+ if (!item) break;
41+
42+ if (item.type === "agent_message" && item.text) {
43+ events.push({ type: "text", content: item.text });
44+ } else if (item.type === "command_execution") {
45+ events.push({
46+ type: "tool_result",
47+ output: item.aggregated_output ?? "",
48+ error: item.exit_code !== null && item.exit_code !== undefined && item.exit_code !== 0,
49+ });
50+ }
51+ break;
52+ }
53+
54+ case "item.started": {
55+ const item = line.item;
56+ if (!item) break;
57+
58+ if (item.type === "command_execution" && item.command) {
59+ events.push({
60+ type: "tool_use",
61+ tool: "command_execution",
62+ args: item.command,
63+ });
64+ }
65+ break;
66+ }
67+
68+ case "turn.completed": {
69+ if (line.usage) {
70+ events.push({
71+ type: "usage",
72+ tokens: {
73+ inputTokens: line.usage.input_tokens,
74+ outputTokens: line.usage.output_tokens,
75+ cacheReadTokens: line.usage.cached_input_tokens,
76+ },
77+ });
78+ }
79+ break;
80+ }
81+
82+ // thread.started, turn.started — no user-facing output
83+ }
84+
85+ return events;
86+}
87+
88+export function extractThreadId(raw: string): string | null {
89+ const trimmed = raw.trim();
90+ if (trimmed === "") return null;
91+
92+ try {
93+ const line = JSON.parse(trimmed) as CodexLine;
94+ if (line.type === "thread.started" && line.thread_id) {
95+ return line.thread_id;
96+ }
97+ } catch {
98+ // ignore
99+ }
100+ return null;
101+}
packages/plugin-codex/tsconfig.json+8−0
@@ -0,0 +1,8 @@
1+{
2+ "extends": "../../tsconfig.json",
3+ "compilerOptions": {
4+ "rootDir": "src",
5+ "outDir": "dist"
6+ },
7+ "include": ["src"]
8+}
packages/types/src/helpers.ts+79−0
@@ -0,0 +1,79 @@
1+import type { AgentEvent, AgentProcess, AgentResult } from "./index.js";
2+
3+export type LineParseFn = (raw: string) => AgentEvent[];
4+export type SessionIdExtractFn = (raw: string, events: AgentEvent[]) => string | null;
5+
6+/**
7+ * Spawns a CLI process and streams its stdout through a line parser,
8+ * yielding normalized AgentEvents.
9+ */
10+export function spawnAgentProcess(
11+ command: string,
12+ args: string[],
13+ parseLine: LineParseFn,
14+ extractSessionId: SessionIdExtractFn,
15+ cwd?: string,
16+): AgentProcess {
17+ const child = Bun.spawn([command, ...args], {
18+ cwd: cwd ?? process.cwd(),
19+ stdout: "pipe",
20+ stderr: "pipe",
21+ });
22+
23+ let resolvedSessionId: string | null = null;
24+
25+ function processLine(line: string) {
26+ const events = parseLine(line);
27+ const sid = extractSessionId(line, events);
28+ if (sid) resolvedSessionId = sid;
29+ return events;
30+ }
31+
32+ async function* streamEvents(): AsyncIterable<AgentEvent> {
33+ const reader = child.stdout.getReader();
34+ const decoder = new TextDecoder();
35+ let buffer = "";
36+
37+ while (true) {
38+ const { done, value } = await reader.read();
39+ if (done) break;
40+ buffer += decoder.decode(value, { stream: true });
41+
42+ const lines = buffer.split("\n");
43+ buffer = lines.pop() ?? "";
44+
45+ for (const line of lines) {
46+ yield* processLine(line);
47+ }
48+ }
49+
50+ if (buffer.trim()) {
51+ yield* processLine(buffer);
52+ }
53+ }
54+
55+ const result: Promise<AgentResult> = child.exited.then((exitCode) => ({
56+ sessionId: resolvedSessionId,
57+ exitCode,
58+ }));
59+
60+ return {
61+ child,
62+ events: streamEvents(),
63+ result,
64+ };
65+}
66+
67+/** Check if a command exists in $PATH */
68+export async function checkCommand(command: string): Promise<boolean> {
69+ try {
70+ const proc = Bun.spawn(["which", command], {
71+ stdout: "ignore",
72+ stderr: "ignore",
73+ });
74+ const code = await proc.exited;
75+ return code === 0;
76+ } catch {
77+ return false;
78+ }
79+}
packages/types/src/index.ts+3−0
@@ -53,3 +53,6 @@ export interface AgentPlugin {
5353 /** Sends a follow-up prompt to an existing session */
5454 resumeSession(sessionId: string, prompt: string, opts?: AgentSessionOpts): AgentProcess;
5555 }
56+
57+export { checkCommand, spawnAgentProcess } from "./helpers.js";
58+export type { LineParseFn, SessionIdExtractFn } from "./helpers.js";