xonecas.io
687
Oc

orc-code / commit 51d4305

feat: minimal one-shot CLI with claude plugin

- Claude plugin: arg builder + stream-json parser yielding AgentEvents
- SQLite DB in ~/.config/orc-code/ tracking agents and sessions
- CLI entrypoint: orc <prompt> / orc -r <session-id> <prompt>
- Raw text display of streamed events (text, tool_use, tool_result, usage, done)

xonecas2026-03-26 51d4305108b9d2428dc0b4781516323715a00fc8 parent fdf2270

7 files changed

knip.json+1−5
@@ -1,8 +1,4 @@
11 {
22 "$schema": "https://unpkg.com/knip@6/schema.json",
3- "workspaces": {
4- "packages/orc-core": {
5- "ignoreDependencies": ["@orc-code/types", "@orc-code/plugin-claude"]
6- }
7- }
3+ "workspaces": {}
84 }
packages/orc-core/src/agents.ts+16−0
@@ -0,0 +1,16 @@
1+import claude from "@orc-code/plugin-claude";
2+import type { AgentPlugin } from "@orc-code/types";
3+import { upsertAgent } from "./db.js";
4+
5+const builtinPlugins: AgentPlugin[] = [claude];
6+
7+export async function discoverAgents(): Promise<AgentPlugin[]> {
8+ const available: AgentPlugin[] = [];
9+ for (const plugin of builtinPlugins) {
10+ if (await plugin.isAvailable()) {
11+ upsertAgent(plugin.name, plugin.command);
12+ available.push(plugin);
13+ }
14+ }
15+ return available;
16+}
packages/orc-core/src/cli.ts+72−2
@@ -1,4 +1,74 @@
11 #!/usr/bin/env bun
22
3-// orc-code CLI entrypoint — TODO: implement
4-console.log("orc v0.0.1");
3+import { randomUUID } from "node:crypto";
4+import { discoverAgents } from "./agents.js";
5+import { saveSession, updateSessionAgentId } from "./db.js";
6+import { printBanner, printEvent } from "./display.js";
7+
8+function parseArgs(argv: string[]): {
9+ resume?: string;
10+ prompt?: string;
11+} {
12+ const args = argv.slice(2);
13+ let resume: string | undefined;
14+ let prompt: string | undefined;
15+
16+ for (let i = 0; i < args.length; i++) {
17+ const arg = args[i];
18+ if ((arg === "-r" || arg === "--resume") && i + 1 < args.length) {
19+ resume = args[++i];
20+ } else if (!prompt && !arg.startsWith("-")) {
21+ prompt = arg;
22+ }
23+ }
24+
25+ return { resume, prompt };
26+}
27+
28+async function main(): Promise<void> {
29+ const { resume, prompt } = parseArgs(process.argv);
30+
31+ if (!prompt) {
32+ console.error("Usage: orc <prompt>");
33+ console.error(" orc -r <session-id> <prompt>");
34+ process.exit(1);
35+ }
36+
37+ const agents = await discoverAgents();
38+ if (agents.length === 0) {
39+ console.error("No agent CLIs found in $PATH. Install claude or codex.");
40+ process.exit(1);
41+ }
42+
43+ const agent = agents[0];
44+ printBanner(agent.name);
45+
46+ const orcSessionId = randomUUID();
47+ const title = prompt.slice(0, 50);
48+
49+ saveSession(orcSessionId, null, agent.name, title);
50+
51+ const ap = resume ? agent.resumeSession(resume, prompt) : agent.createSession(prompt);
52+
53+ console.log(` ${agent.name} ⟶ ${resume ? `resuming ${resume}` : "new session"}`);
54+ console.log();
55+
56+ for await (const event of ap.events) {
57+ printEvent(event);
58+ }
59+
60+ const result = await ap.result;
61+ if (result.sessionId) {
62+ updateSessionAgentId(orcSessionId, result.sessionId);
63+ }
64+
65+ console.log();
66+ console.log(`orc session: ${orcSessionId}`);
67+ if (result.sessionId) {
68+ console.log(`agent session: ${result.sessionId}`);
69+ }
70+
71+ process.exit(result.exitCode);
72+}
73+
74+main();
packages/orc-core/src/db.ts+71−0
@@ -0,0 +1,71 @@
1+import { existsSync, mkdirSync } from "node:fs";
2+import { join } from "node:path";
3+import { Database } from "bun:sqlite";
4+
5+function getConfigDir(): string {
6+ const xdg = process.env.XDG_CONFIG_HOME;
7+ const base = xdg ?? join(process.env.HOME ?? "~", ".config");
8+ const dir = join(base, "orc-code");
9+ if (!existsSync(dir)) {
10+ mkdirSync(dir, { recursive: true });
11+ }
12+ return dir;
13+}
14+
15+let _db: Database | null = null;
16+
17+function getDb(): Database {
18+ if (_db) return _db;
19+
20+ const dbPath = join(getConfigDir(), "orc.db");
21+ _db = new Database(dbPath);
22+ _db.run("PRAGMA journal_mode=WAL");
23+
24+ _db.run(`
25+ CREATE TABLE IF NOT EXISTS agents (
26+ name TEXT PRIMARY KEY,
27+ command TEXT NOT NULL,
28+ enabled INTEGER NOT NULL DEFAULT 1
29+ )
30+ `);
31+
32+ _db.run(`
33+ CREATE TABLE IF NOT EXISTS sessions (
34+ orc_session_id TEXT PRIMARY KEY,
35+ agent_session_id TEXT,
36+ agent_name TEXT NOT NULL,
37+ title TEXT NOT NULL,
38+ parent_orc_session_id TEXT,
39+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
40+ )
41+ `);
42+
43+ return _db;
44+}
45+
46+export function upsertAgent(name: string, command: string): void {
47+ getDb().run(
48+ "INSERT INTO agents (name, command) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET command = excluded.command",
49+ [name, command],
50+ );
51+}
52+
53+export function saveSession(
54+ orcSessionId: string,
55+ agentSessionId: string | null,
56+ agentName: string,
57+ title: string,
58+ parentOrcSessionId?: string,
59+): void {
60+ getDb().run(
61+ "INSERT INTO sessions (orc_session_id, agent_session_id, agent_name, title, parent_orc_session_id) VALUES (?, ?, ?, ?, ?)",
62+ [orcSessionId, agentSessionId, agentName, title, parentOrcSessionId ?? null],
63+ );
64+}
65+
66+export function updateSessionAgentId(orcSessionId: string, agentSessionId: string): void {
67+ getDb().run("UPDATE sessions SET agent_session_id = ? WHERE orc_session_id = ?", [
68+ agentSessionId,
69+ orcSessionId,
70+ ]);
71+}
packages/orc-core/src/display.ts+46−0
@@ -0,0 +1,46 @@
1+import type { AgentEvent } from "@orc-code/types";
2+
3+export function printBanner(agentName: string): void {
4+ console.log(`orc (${agentName})`);
5+ console.log("─".repeat(45));
6+ console.log();
7+}
8+
9+export function printEvent(event: AgentEvent): void {
10+ switch (event.type) {
11+ case "text":
12+ console.log(` ● text ${event.content}`);
13+ break;
14+ case "tool_use":
15+ console.log(` ● tool_use ${event.tool}`);
16+ break;
17+ case "tool_result":
18+ if (event.error) {
19+ console.log(` ● tool_result (error) ${event.output.slice(0, 120)}`);
20+ } else {
21+ const size = event.output.length;
22+ console.log(` ● tool_result (${formatSize(size)})`);
23+ }
24+ break;
25+ case "usage": {
26+ const t = event.tokens;
27+ const parts: string[] = [];
28+ if (t.inputTokens) parts.push(`in:${t.inputTokens}`);
29+ if (t.outputTokens) parts.push(`out:${t.outputTokens}`);
30+ if (t.cacheReadTokens) parts.push(`cache_read:${t.cacheReadTokens}`);
31+ console.log(` ● usage ${parts.join(" ")}`);
32+ break;
33+ }
34+ case "error":
35+ console.error(` ✖ error ${event.message}`);
36+ break;
37+ case "done":
38+ console.log(` ✔ done session ${event.sessionId}`);
39+ break;
40+ }
41+}
42+
43+function formatSize(bytes: number): string {
44+ if (bytes < 1024) return `${bytes}b`;
45+ return `${(bytes / 1024).toFixed(1)}kb`;
46+}
packages/plugin-claude/src/index.ts+75−7
@@ -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
packages/plugin-claude/src/parser.ts+115−0
@@ -0,0 +1,115 @@
1+import type { AgentEvent } from "@orc-code/types";
2+
3+interface ClaudeContentBlock {
4+ type: string;
5+ text?: string;
6+ name?: string;
7+ input?: unknown;
8+ thinking?: string;
9+}
10+
11+interface ClaudeToolResultContent {
12+ type: string;
13+ tool_use_id?: string;
14+ content?: string;
15+ is_error?: boolean;
16+}
17+
18+interface ClaudeLine {
19+ type: string;
20+ subtype?: string;
21+ session_id?: string;
22+ message?: {
23+ content?: (ClaudeContentBlock | ClaudeToolResultContent)[];
24+ };
25+ is_error?: boolean;
26+ result?: string;
27+ total_cost_usd?: number;
28+ usage?: {
29+ input_tokens?: number;
30+ output_tokens?: number;
31+ cache_read_input_tokens?: number;
32+ cache_creation_input_tokens?: number;
33+ };
34+}
35+
36+export function parseLine(raw: string): AgentEvent[] {
37+ const trimmed = raw.trim();
38+ if (trimmed === "") return [];
39+
40+ let line: ClaudeLine;
41+ try {
42+ line = JSON.parse(trimmed);
43+ } catch {
44+ return [];
45+ }
46+
47+ const events: AgentEvent[] = [];
48+
49+ switch (line.type) {
50+ case "system":
51+ // init event — no user-facing output
52+ break;
53+
54+ case "assistant": {
55+ const blocks = line.message?.content ?? [];
56+ for (const block of blocks) {
57+ if (block.type === "text" && "text" in block && block.text) {
58+ events.push({ type: "text", content: block.text });
59+ } else if (block.type === "tool_use" && "name" in block) {
60+ events.push({
61+ type: "tool_use",
62+ tool: (block as ClaudeContentBlock).name ?? "unknown",
63+ args: (block as ClaudeContentBlock).input,
64+ });
65+ }
66+ // skip thinking blocks
67+ }
68+ break;
69+ }
70+
71+ case "user": {
72+ const blocks = line.message?.content ?? [];
73+ for (const block of blocks) {
74+ if (block.type === "tool_result") {
75+ const tr = block as ClaudeToolResultContent;
76+ events.push({
77+ type: "tool_result",
78+ output: tr.content ?? "",
79+ error: tr.is_error,
80+ });
81+ }
82+ }
83+ break;
84+ }
85+
86+ case "result": {
87+ if (line.usage) {
88+ events.push({
89+ type: "usage",
90+ tokens: {
91+ inputTokens: line.usage.input_tokens,
92+ outputTokens: line.usage.output_tokens,
93+ cacheReadTokens: line.usage.cache_read_input_tokens,
94+ cacheWriteTokens: line.usage.cache_creation_input_tokens,
95+ },
96+ });
97+ }
98+ if (line.is_error) {
99+ events.push({
100+ type: "error",
101+ message: line.result ?? "Unknown error",
102+ });
103+ }
104+ events.push({
105+ type: "done",
106+ sessionId: line.session_id ?? "",
107+ });
108+ break;
109+ }
110+
111+ // rate_limit_event etc — ignored
112+ }
113+
114+ return events;
115+}