@@ -1,13 +1,81 @@
1-import type { AgentPlugin, AgentProcess, AgentSessionOpts } from "@orc-code/types";
1+import type {
2+ AgentEvent,
3+ AgentPlugin,
4+ AgentProcess,
5+ AgentResult,
6+ AgentSessionOpts,
7+} from "@orc-code/types";
8+import { parseLine } from "./parser.js";
9+
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+ }
54+ }
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+ };
66+}
267
368 const plugin: AgentPlugin = {
469 name: "claude",
570 command: "claude",
6- opts: ["--output-format", "stream-json", "--dangerously-skip-permissions"],
71+ opts: ["-p", "--output-format", "stream-json", "--verbose", "--dangerously-skip-permissions"],
772
873 async isAvailable(): Promise<boolean> {
974 try {
10- const proc = Bun.spawn(["which", "claude"], { stdout: "ignore", stderr: "ignore" });
75+ const proc = Bun.spawn(["which", "claude"], {
76+ stdout: "ignore",
77+ stderr: "ignore",
78+ });
1179 const code = await proc.exited;
1280 return code === 0;
1381 } catch {
@@ -15,12 +83,12 @@ const plugin: AgentPlugin = {
1583 }
1684 },
1785
18- createSession(_prompt: string, _opts?: AgentSessionOpts): AgentProcess {
19- throw new Error("TODO: implement createSession");
86+ createSession(prompt: string, opts?: AgentSessionOpts): AgentProcess {
87+ return spawnAgent([...this.opts, prompt], opts?.cwd);
2088 },
2189
22- resumeSession(_sessionId: string, _prompt: string, _opts?: AgentSessionOpts): AgentProcess {
23- throw new Error("TODO: implement resumeSession");
90+ resumeSession(sessionId: string, prompt: string, opts?: AgentSessionOpts): AgentProcess {
91+ return spawnAgent([...this.opts, "--resume", sessionId, prompt], opts?.cwd);
2492 },
2593 };
2694