@oalo-ai/cli 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -303,25 +303,68 @@ oalo build --app shop --download # a Flutter or Expo app's store files (.ipa
303
303
  after the copy starts is lost. `oalo docs migrating-from-heroku` (or
304
304
  `-railway`, `-render`, `-fly`, `-primcloud`) has each platform's steps.
305
305
  8. **Moving an app from another platform** (Heroku, Railway, Render, Fly.io,
306
- Primcloud): in the app's repo, run `oalo migrate <platform> --from-app
307
- <name>` first (the app or service's name on the old platform, the Heroku
308
- app say) and show the person the plan; it changes nothing. Only `--apply`
309
- writes the Procfile and `.oalo/app.json` and sets the variables, and it
310
- sets them only once the app exists, so the order is `--apply`, commit,
311
- `oalo deploy --new`, then the same `oalo migrate ... --apply` again. The
312
- variables go to the app's prod settings with nothing restarted or deployed,
313
- so this doesn't put it live; the preview keeps its own (`--env dev`, test
314
- keys). It never prints a value. Don't copy variables by hand with `oalo env
315
- set NAME=value`: for values it can't read (Fly secrets, Primcloud) the
316
- person puts them in a .env file and you pass `--env-file`. Then the data
317
- (rule 7), and live only when the person says so.
306
+ Primcloud; the old host stays live with zero downtime until DNS flips):
307
+ execute in this exact order inside the app's repo:
308
+ 1. **Pre-flight files:** Confirm Node apps have a committed lockfile
309
+ (`package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`) and a `Procfile`
310
+ `web:` line listening on `$PORT` (or `package.json` `start`, or a
311
+ `Dockerfile`).
312
+ 2. **Plan first (read-only):** Run `oalo migrate <platform> --from-app
313
+ <name>` and show the person the plan + warnings (sizes mapped into
314
+ `.oalo/app.json`, `Aptfile`, cron/scheduler, `> large` 4 GB dynos). It
315
+ changes nothing and never prints secret values.
316
+ 3. **Write config files:** Run `oalo migrate <platform> --from-app <name>
317
+ --apply` (writes `Procfile` / `.oalo/app.json` without overwriting an
318
+ existing `Procfile`), then `git add Procfile .oalo/app.json && git
319
+ commit`.
320
+ 4. **Create the app & preview:** Run `oalo deploy --new <slug>`. If it adds
321
+ `.oalo/credentials*` to `.gitignore`, commit `.gitignore` before the next
322
+ deploy.
323
+ 5. **Push prod variables:** Run the exact same `oalo migrate <platform>
324
+ --from-app <name> --apply` a second time (now the app exists, it sends
325
+ the prod vars safely without restarting or printing values, renaming
326
+ `DATABASE_URL` to `EXTERNAL_DATABASE_URL`). For platforms whose CLI
327
+ can't read secret values back (Fly secrets, Primcloud), have the person
328
+ put them in an uncommitted `.env` file and pass `--env-file`. Don't copy
329
+ secrets by hand with `oalo env set NAME=value`.
330
+ 6. **Move Postgres (optional, rule 7):** If moving the database into Oalo,
331
+ run `oalo db restore --from-env SOURCE_DATABASE_URL --env prod --check`,
332
+ then without `--check` once writes stop, then `oalo env unset
333
+ EXTERNAL_DATABASE_URL --env prod`.
334
+ 7. **Go live when the person says so:** Run `oalo deploy --app <slug> --env
335
+ prod` (zero-downtime health-checked swap; web/server self-healing
336
+ telemetry starts automatically with no code changes).
318
337
  9. **App Store and Google Play files** (a Flutter or Expo app): `oalo deploy`
319
338
  updates only the web preview. `oalo build --app shop --download` makes a
320
339
  store build (15 to 60 minutes, both platforms) and saves the `.ipa` and
321
- `.aab` where you run it. Oalo doesn't upload them: tell the person to
322
- deliver the `.ipa` with Transporter and upload the `.aab` in Google Play
323
- Console. Each build raises the version code, so start one only when asked.
324
- Don't build them locally with Xcode, Gradle, `flutter build` or `eas build`.
340
+ `.aab` where you run it. When Apple App Store Connect or Google Play
341
+ credentials are connected in Integrations, Oalo can also publish Expo
342
+ JS-only fixes over the air (EAS Update) and submit native builds to Apple
343
+ App Review and a 10% Google Play staged rollout from **Apps > Logs &
344
+ Errors**; otherwise deliver the `.ipa` with Transporter and upload the
345
+ `.aab` in Google Play Console. Each build raises the version code, so start
346
+ one only when asked. Don't build them locally with Xcode, Gradle,
347
+ `flutter build` or `eas build`.
348
+ 10. **Self-healing, error telemetry, and integration tests** (`oalo docs
349
+ self-healing`):
350
+ - **Hosted web & server apps** get error capture automatically (HTML gets
351
+ `/_oalo/error-beacon.js`; proxied server routes capture `5xx`, `502`,
352
+ status regressions, and JSON shape drift). In React apps, forward caught
353
+ `ErrorBoundary` errors via `window.__oaloReportError?.(error, {
354
+ component_stack: info.componentStack })`.
355
+ - **Native mobile apps (Expo / Flutter) and off-box frontends** do not go
356
+ through Oalo's HTML proxy: wire a global crash handler that POSTs to
357
+ `<OALO_ORIGIN>/_oalo/errors` (`{ app, env, platform, message, stack,
358
+ route, app_version }`). Copy the exact snippet from `oalo docs
359
+ self-healing`.
360
+ - **Write `.oalo/tests/smoke.json`** as you add API routes (`tests: [{
361
+ name, method, path, expect_status, expect_json_keys, expect_json_shape,
362
+ max_ms }]`) and verify with `oalo heal tests --app <slug>` (or `oalo
363
+ heal suggest-tests --app <slug>`).
364
+ - **Investigate and fix runtime errors** with `oalo heal list --app
365
+ <slug>`, `oalo heal inspect <error_id>`, `oalo heal run <error_id>`
366
+ (Base PR by default, or `--local` to download the error bundle and fix
367
+ locally), and `oalo heal approve|reject <heal_id>`.
325
368
 
326
369
  ## An app's environment variables
327
370
 
@@ -369,6 +412,7 @@ writing it: the endpoints, headers and shapes are there.
369
412
  | Give the live app more CPU or memory, a health check, or required variables | All in one committed file, `.oalo/app.json`: `{"sizes": {"web": "medium"}, "health": "/healthz", "env": {"required": ["STRIPE_KEY"]}}`. A live deploy is refused while a required variable isn't set for prod. There is no `infra.json`. | `live-server-apps` |
370
413
  | Show the app's own numbers to its users (a chart in the app) | `queryMetric({ table: "sessions", every: "week", days: 90, by: "coach_id" })` from `oalo typegen`, called on the app's server. | `dashboards` |
371
414
  | Work on an app made from Oalo's Flutter template on this machine | `oalo typegen --dart` (the models, and `.oalo/dart-defines.json`), then `flutter run -d chrome --dart-define-from-file=.oalo/dart-defines.json`. | `flutter-on-your-machine` |
415
+ | Wire self-healing error telemetry & `.oalo/tests/smoke.json` | Web & server capture is automatic; forward React `ErrorBoundary` via `window.__oaloReportError`, POST native Expo/Flutter crashes to `/_oalo/errors`, and add `.oalo/tests/smoke.json` checked with `oalo heal tests`. | `self-healing` |
372
416
 
373
417
  ## Selling: products and paid content
374
418
 
@@ -427,6 +471,7 @@ oalo bots # the bots, by public id (b
427
471
  oalo data vectorize products --fields title,description # make a table searchable
428
472
  oalo bots knowledge bot_ABC --add products # let the bot search it
429
473
  oalo bots tools bot_ABC --add order_status # let it call a tool
474
+ oalo bots graph bot_ABC [--build] [--search "<q>"] [--export f.json] [--import f.json] [--resync] [--reset --yes]
430
475
  oalo bots settings --explain model # what each setting does
431
476
  oalo bots settings bot_ABC set <key>=<value> --dry-run
432
477
  oalo channels # WhatsApp, Instagram, email, web chat: which bot answers
@@ -454,20 +499,68 @@ oalo channels # WhatsApp, Instagram, emai
454
499
  but the bot's data tools leave it out, and it can't be embedded. Don't
455
500
  vectorize it.
456
501
 
457
- ## Several agents on one repo
502
+ ## Local data & own models (`oalo machines` and `oalo serve`)
503
+
504
+ ```sh
505
+ oalo machines # online status, handlers, BYO model check results
506
+ oalo machines add shop-pc # register this computer (admins only)
507
+ oalo machines allow <byo-id> [--off] # admin override for unverified/failed BYO model
508
+ oalo machines revoke shop-pc --yes # disconnect a machine immediately
509
+ oalo serve add folder handbook ~/Handbook --describe "Store policies and returns"
510
+ oalo serve add command stock --input 'sku:string' --timeout 30 --describe "Stock lookup" -- python3 stock.py
511
+ oalo serve add model ollama --models qwen3:14b # share a local OpenAI-compatible model server
512
+ oalo serve test handbook '{"query": "returns"}' # test locally before serving (answers up to 1 MB)
513
+ oalo serve # connect out to the workspace (or `oalo serve install`)
514
+ ```
515
+
516
+ - Command timeouts accept `1` to `3600` seconds (interactive chat tool calls cap at 120 s on the box; workflow `remote_step` runs up to 1 hour). Output limit is **1 MB**.
517
+ - Folders index 29 text/code file types up to 2 MB each.
518
+ - Give handlers to a bot by bare handler name: `oalo bots tools <bot> --add handbook` (and built-in multi-bot handoff with `oalo bots tools <bot> --add transfer_to_bot`).
519
+ - Read `oalo docs answer-from-your-own-data` and `oalo docs run-your-bot-on-your-own-model`.
520
+
521
+ ## Workflow replay, Inbox Copilot, Usage breakdown & CRM CSV import
522
+
523
+ ```sh
524
+ # Replay a failed loop run from any step (restores earlier step outputs; optional --input edit)
525
+ oalo loops replay <run-id> --from <node-id> [--input '{"key":"val"}'] [--json]
526
+
527
+ # Month-to-date AI spend broken down by bot, workflow loop, and top conversations
528
+ oalo usage [--json]
458
529
 
459
- When the person wants work split across several agent sessions on one repo at
460
- once, use `oalo coord`: a shared task board, a git worktree per task and a
461
- merge queue that runs the tests. It needs no Oalo workspace.
530
+ # Team Inbox: list threads, add internal whisper notes, draft Copilot replies, manage / saved replies
531
+ oalo inbox list [--limit 20] [--json]
532
+ oalo inbox note <conversation-id> "Internal team note (never sent to customer or LLM)"
533
+ oalo inbox draft <conversation-id> [--hint "offer 10% discount"] [--json]
534
+ oalo inbox replies [list | set <shortcut> "<body...>" [--title "..."] | delete <id>]
535
+
536
+ # Bulk-import contacts from CSV (deduplicates by email/phone/external_ref)
537
+ oalo crm import contacts.csv --tags vip,latam [--dry-run] [--json]
538
+ ```
539
+
540
+ Operational trigger events available in `trigger_catalog` for error workflows and alerts: `loop.failed`, `bot.cap_reached`, `guardrail.triggered`, and `conversation.transferred`. Inbound WhatsApp/Instagram voice notes are auto-transcribed via Whisper before the bot turn.
541
+
542
+ ## Several agents on one repo
462
543
 
463
- 1. **Set it up once:** `oalo coord install` (once per machine), then in the
464
- repo `oalo coord init` and `oalo coord hooks install`, and commit what they
465
- write. Each session then has the board's tools (MCP server `oalo-coord`).
466
- 2. **The person approves, never you.** The manager drafts tasks and calls
467
- `plan_submit`; the person runs `oalo coord approve plan` in their own
468
- terminal. Never run `oalo coord approve` or `reject` yourself: say what is
469
- waiting and give them the command.
470
- 3. `oalo help coord` has every command.
544
+ When the person wants to coordinate agents across a repo (no Oalo workspace
545
+ needed unless `--verify` runs `oalo qa`), pick the strategy that fits the job:
546
+
547
+ 1. **Multi-file parallel build (`oalo coord`):** `oalo coord install` (once per
548
+ machine), then `oalo coord init [--reviewer claude:sonnet]` and
549
+ `oalo coord hooks install`. The manager drafts tasks and calls `plan_submit`;
550
+ **the person approves, never you** (`oalo coord approve plan` in their own
551
+ terminal). After approval, `oalo coord up --workers 3 --harness <spec> --budget <usd>`
552
+ runs ephemeral workers in isolated worktrees with a stall watchdog and
553
+ test/critic merge queue automatically.
554
+ 2. **Explore/design before planning (`oalo swarm`):** Read-only multi-role
555
+ blackboard (`--team engineering|audit|research|feature|oalo-bot`, 16 built-in
556
+ roles, `oalo swarm roles list|add|show|rm`, and per-role `@harness` routing).
557
+ `oalo swarm promote` imports `plan.json` directly into `oalo coord` drafts.
558
+ 3. **Fresh-context verifier loop (`oalo ralph`):** `oalo ralph --goal "..." --verify "npm test"` (or `--verify "oalo qa bot_xxx --script suite.json"`), with `--plan PLAN.md`, `--max-iters`, `--max-cost`, `--commit`, `--worktree`.
559
+ 4. **Best-of-N worktree racing (`oalo race`):** `oalo race "..." --models a,b --verify "..." [--judge claude:sonnet]` (blind anonymized judge when 2+ pass) -> `oalo race pick <run-id> <slot>`.
560
+ 5. **Independent diff critic (`oalo review`):** Read-only cross-model review (`oalo review --against main --models a,b --strict`).
561
+ 6. **Composable packs (`oalo auto`):** `oalo auto list`, built-ins (`qa-grind`, `bugfix`, `audit`, `feature`), plus `.oalo/workflows/*.json`.
562
+
563
+ Run `oalo help <coord|swarm|ralph|race|review|auto>` for exact flags.
471
564
 
472
565
  ## Reading the docs
473
566
 
@@ -486,6 +579,7 @@ Over MCP: `oalo_docs` with `q` or `slug`. Good first pages:
486
579
  and `triggers-and-chaining`.
487
580
 
488
581
  For anything the commands don't cover, `oalo call --list <text>` lists the
489
- events you may call and the params each accepts (MCP: `oalo_call` with event
490
- `cli_api:events` and `{"q": "<text>"}`). Don't guess param names: a wrong
582
+ events you may call and the params each accepts (`oalo call <event> '<json>'
583
+ --timeout <ms>` for slow actions; MCP: `oalo_call` with `timeout_ms`, or event
584
+ `cli_api:events` with `{"q": "<text>"}`). Don't guess param names: a wrong
491
585
  shape is refused with the shapes the event takes.
@@ -0,0 +1,357 @@
1
+ /**
2
+ * Unified headless agent harness runner shared by all Oalo coordination
3
+ * strategies (`coord up`, `ralph`, `race`, `review`, `swarm`, `auto`).
4
+ *
5
+ * Pure Node ESM (works under both Node >= 18 and Bun with zero external deps).
6
+ *
7
+ * Supported harness specs:
8
+ * - "claude" or "claude:sonnet" / "claude:opus"
9
+ * - "opencode" or "opencode:openrouter/deepseek/deepseek-v4.1-flash"
10
+ * - "codex" or "codex:gpt-5.4"
11
+ * - "cmd:<shell command>" (receives OALO_PROMPT_FILE, OALO_PROMPT, OALO_MODEL,
12
+ * OALO_READONLY, OALO_CWD, plus caller env; great for custom CLIs & tests)
13
+ */
14
+ import { spawn, spawnSync } from "node:child_process";
15
+ import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+
19
+ /**
20
+ * Parse a harness spec like "claude:sonnet", "opencode:provider/model",
21
+ * "codex", or "cmd:node ./mock.mjs".
22
+ */
23
+ export function parseHarnessSpec(raw) {
24
+ const s = String(raw || "").trim();
25
+ if (!s) return { harness: detectDefaultHarness(), model: null, command: null, label: detectDefaultHarness() };
26
+ if (s.startsWith("cmd:")) {
27
+ const command = s.slice(4).trim();
28
+ if (!command) throw new Error("cmd: harness requires a shell command after `cmd:`");
29
+ return { harness: "cmd", model: null, command, label: s };
30
+ }
31
+ const idx = s.indexOf(":");
32
+ if (idx === -1) return { harness: s, model: null, command: null, label: s };
33
+ const harness = s.slice(0, idx).trim();
34
+ const model = s.slice(idx + 1).trim() || null;
35
+ return { harness, model, command: null, label: s };
36
+ }
37
+
38
+ /** Parse a comma-separated list of harness specs (respecting `cmd:` commands). */
39
+ export function parseHarnessList(raw) {
40
+ if (!raw) return [];
41
+ if (Array.isArray(raw)) return raw.map(parseHarnessSpec);
42
+ const s = String(raw).trim();
43
+ if (!s) return [];
44
+ // Allow `||` separator when custom `cmd:` commands themselves contain commas.
45
+ const parts = s.includes("||") ? s.split("||") : s.split(",");
46
+ return parts.map((p) => p.trim()).filter(Boolean).map(parseHarnessSpec);
47
+ }
48
+
49
+ /** Check if an executable exists on PATH. */
50
+ export function hasBinary(name) {
51
+ const r = spawnSync("sh", ["-c", `command -v ${name} >/dev/null 2>&1`], { stdio: "ignore" });
52
+ return r.status === 0;
53
+ }
54
+
55
+ /** Detect the best available local agent harness. */
56
+ export function detectDefaultHarness() {
57
+ if (process.env.OALO_AGENT_HARNESS) return process.env.OALO_AGENT_HARNESS;
58
+ for (const bin of ["claude", "opencode", "codex"]) {
59
+ if (hasBinary(bin)) return bin;
60
+ }
61
+ return "claude";
62
+ }
63
+
64
+ /**
65
+ * Extract clean text and optional USD cost from harness stdout.
66
+ * Claude `--output-format json` emits `{ result, total_cost_usd, is_error }`.
67
+ * OpenCode `--format json` emits NDJSON events.
68
+ * Custom `cmd:` harnesses may emit plain text or a final JSON line `{"text":..., "cost_usd":...}`.
69
+ */
70
+ export function parseHarnessOutput(harness, stdout) {
71
+ const trimmed = String(stdout || "").trim();
72
+ if (!trimmed) return { text: "", costUsd: 0, structured: null };
73
+
74
+ if (harness === "claude") {
75
+ try {
76
+ const obj = JSON.parse(trimmed);
77
+ const text = typeof obj.result === "string" ? obj.result : trimmed;
78
+ const costUsd = typeof obj.total_cost_usd === "number" ? obj.total_cost_usd : typeof obj.cost_usd === "number" ? obj.cost_usd : 0;
79
+ return { text, costUsd, structured: obj, isError: obj.is_error === true };
80
+ } catch {
81
+ return { text: trimmed, costUsd: 0, structured: null };
82
+ }
83
+ }
84
+
85
+ if (harness === "opencode") {
86
+ const lines = trimmed.split("\n").map((l) => l.trim()).filter(Boolean);
87
+ const chunks = [];
88
+ const errors = [];
89
+ let costUsd = 0;
90
+ let parsedAny = false;
91
+ for (const line of lines) {
92
+ try {
93
+ const ev = JSON.parse(line);
94
+ parsedAny = true;
95
+ if (ev.type === "error") {
96
+ const msg = ev.error?.data?.message || ev.error?.message || ev.message || JSON.stringify(ev.error || ev);
97
+ if (msg) errors.push(String(msg));
98
+ } else if (ev.type === "text" && ev.part?.text) chunks.push(ev.part.text);
99
+ else if (typeof ev.text === "string") chunks.push(ev.text);
100
+ else if (typeof ev.result === "string") chunks.push(ev.result);
101
+ if (typeof ev.part?.cost === "number") costUsd += ev.part.cost;
102
+ else if (typeof ev.cost_usd === "number") costUsd += ev.cost_usd;
103
+ } catch {
104
+ // Ignore non-JSON log lines when mixing text + events
105
+ }
106
+ }
107
+ if (errors.length && !chunks.length) {
108
+ return { text: errors.join("\n"), costUsd, structured: null, isError: true };
109
+ }
110
+ return {
111
+ text: parsedAny && chunks.length ? chunks.join("\n").trim() : trimmed,
112
+ costUsd,
113
+ structured: null,
114
+ isError: errors.length > 0 && !chunks.length,
115
+ };
116
+ }
117
+
118
+ // `codex` or `cmd:` — tolerate a JSON object on the full output or last line.
119
+ try {
120
+ const obj = JSON.parse(trimmed);
121
+ if (obj && typeof obj === "object" && ("text" in obj || "result" in obj || "cost_usd" in obj)) {
122
+ return {
123
+ text: typeof obj.text === "string" ? obj.text : typeof obj.result === "string" ? obj.result : trimmed,
124
+ costUsd: typeof obj.cost_usd === "number" ? obj.cost_usd : 0,
125
+ structured: obj,
126
+ };
127
+ }
128
+ } catch {
129
+ const lines = trimmed.split("\n");
130
+ const last = lines[lines.length - 1]?.trim();
131
+ if (last?.startsWith("{") && last.endsWith("}")) {
132
+ try {
133
+ const obj = JSON.parse(last);
134
+ if (obj && typeof obj === "object" && ("text" in obj || "cost_usd" in obj)) {
135
+ const rest = lines.slice(0, -1).join("\n").trim();
136
+ return {
137
+ text: typeof obj.text === "string" ? obj.text : rest || trimmed,
138
+ costUsd: typeof obj.cost_usd === "number" ? obj.cost_usd : 0,
139
+ structured: obj,
140
+ };
141
+ }
142
+ } catch {}
143
+ }
144
+ }
145
+ return { text: trimmed, costUsd: 0, structured: null };
146
+ }
147
+
148
+ /**
149
+ * Extract the first JSON object from an LLM text response (handling ```json fences).
150
+ */
151
+ export function extractJsonObject(text) {
152
+ const s = String(text || "").trim();
153
+ if (!s) return null;
154
+ try {
155
+ const parsed = JSON.parse(s);
156
+ if (parsed && typeof parsed === "object") return parsed;
157
+ } catch {}
158
+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/i);
159
+ if (fence) {
160
+ try {
161
+ const parsed = JSON.parse(fence[1].trim());
162
+ if (parsed && typeof parsed === "object") return parsed;
163
+ } catch {}
164
+ }
165
+ const first = s.indexOf("{");
166
+ const last = s.lastIndexOf("}");
167
+ if (first !== -1 && last > first) {
168
+ try {
169
+ const parsed = JSON.parse(s.slice(first, last + 1));
170
+ if (parsed && typeof parsed === "object") return parsed;
171
+ } catch {}
172
+ }
173
+ return null;
174
+ }
175
+
176
+ /**
177
+ * Build the executable + argv for a harness invocation.
178
+ */
179
+ export function buildHarnessInvocation(spec, { prompt, readonly = false, maxBudgetUsd = null }) {
180
+ const parsed = typeof spec === "string" ? parseHarnessSpec(spec) : spec;
181
+ const h = parsed.harness;
182
+ const model = parsed.model || null;
183
+
184
+ if (h === "cmd") {
185
+ return { file: "sh", args: ["-c", parsed.command], parsed };
186
+ }
187
+ if (h === "claude") {
188
+ const args = ["-p", prompt, "--output-format", "json", "--no-session-persistence"];
189
+ if (model) args.push("--model", model);
190
+ if (maxBudgetUsd != null && Number.isFinite(Number(maxBudgetUsd))) {
191
+ args.push("--max-budget-usd", String(maxBudgetUsd));
192
+ }
193
+ if (readonly) {
194
+ args.push(
195
+ "--permission-mode",
196
+ "plan",
197
+ "--allowedTools",
198
+ "Read,Glob,Grep,Bash(git log:*),Bash(git diff:*),Bash(git status:*),Bash(git show:*)",
199
+ );
200
+ } else {
201
+ args.push("--permission-mode", "bypassPermissions", "--allow-dangerously-skip-permissions");
202
+ }
203
+ return { file: "claude", args, parsed };
204
+ }
205
+ if (h === "opencode") {
206
+ const args = ["run", prompt, "--format", "json"];
207
+ if (model) args.push("-m", model);
208
+ if (!readonly) args.push("--auto");
209
+ return { file: "opencode", args, parsed };
210
+ }
211
+ if (h === "codex") {
212
+ const args = ["exec", prompt];
213
+ if (model) args.push("-m", model);
214
+ if (readonly) args.push("--sandbox", "read-only");
215
+ else args.push("--full-auto");
216
+ return { file: "codex", args, parsed };
217
+ }
218
+ throw new Error(`unknown agent harness: ${h} (use claude, opencode, codex, or cmd:<shell>)`);
219
+ }
220
+
221
+ /**
222
+ * Run a single headless agent session with timeout and structured result parsing.
223
+ */
224
+ export function runAgent({
225
+ harness,
226
+ model = null,
227
+ prompt,
228
+ cwd = process.cwd(),
229
+ readonly = false,
230
+ maxBudgetUsd = null,
231
+ timeoutMs = 15 * 60 * 1000,
232
+ env = {},
233
+ signal = null,
234
+ onOutput = null,
235
+ }) {
236
+ const baseSpec = typeof harness === "string" ? parseHarnessSpec(harness) : harness || parseHarnessSpec("");
237
+ const spec = { ...baseSpec, model: model || baseSpec.model || null };
238
+ const inv = buildHarnessInvocation(spec, { prompt, readonly, maxBudgetUsd });
239
+
240
+ const tmpDir = mkdtempSync(join(tmpdir(), "oalo-agent-"));
241
+ const promptFile = join(tmpDir, "prompt.md");
242
+ writeFileSync(promptFile, String(prompt || ""), "utf8");
243
+
244
+ const start = Date.now();
245
+ return new Promise((resolve) => {
246
+ const childEnv = {
247
+ ...process.env,
248
+ ...env,
249
+ OALO_PROMPT_FILE: promptFile,
250
+ OALO_PROMPT: String(prompt || "").slice(0, 32768),
251
+ OALO_HARNESS: spec.harness,
252
+ OALO_MODEL: spec.model || "",
253
+ OALO_READONLY: readonly ? "1" : "0",
254
+ OALO_CWD: cwd,
255
+ };
256
+ const child = spawn(inv.file, inv.args, {
257
+ cwd,
258
+ env: childEnv,
259
+ stdio: ["ignore", "pipe", "pipe"],
260
+ });
261
+
262
+ let stdout = "";
263
+ let stderr = "";
264
+ let timedOut = false;
265
+ let aborted = false;
266
+
267
+ const keepOut = (chunk) => {
268
+ const s = chunk.toString("utf8");
269
+ stdout += s;
270
+ if (stdout.length > 2 * 1024 * 1024) stdout = stdout.slice(-1024 * 1024);
271
+ if (onOutput) onOutput("stdout", s);
272
+ };
273
+ const keepErr = (chunk) => {
274
+ const s = chunk.toString("utf8");
275
+ stderr += s;
276
+ if (stderr.length > 512 * 1024) stderr = stderr.slice(-256 * 1024);
277
+ if (onOutput) onOutput("stderr", s);
278
+ };
279
+ child.stdout.on("data", keepOut);
280
+ child.stderr.on("data", keepErr);
281
+
282
+ const killChild = () => {
283
+ try {
284
+ child.kill("SIGTERM");
285
+ } catch {}
286
+ setTimeout(() => {
287
+ try {
288
+ child.kill("SIGKILL");
289
+ } catch {}
290
+ }, 3000).unref();
291
+ };
292
+
293
+ const timer = timeoutMs > 0
294
+ ? setTimeout(() => {
295
+ timedOut = true;
296
+ killChild();
297
+ }, timeoutMs)
298
+ : null;
299
+
300
+ const onAbort = () => {
301
+ aborted = true;
302
+ killChild();
303
+ };
304
+ if (signal) {
305
+ if (signal.aborted) onAbort();
306
+ else signal.addEventListener("abort", onAbort, { once: true });
307
+ }
308
+
309
+ const cleanup = () => {
310
+ if (timer) clearTimeout(timer);
311
+ if (signal) signal.removeEventListener("abort", onAbort);
312
+ try {
313
+ rmSync(tmpDir, { recursive: true, force: true });
314
+ } catch {}
315
+ };
316
+
317
+ child.on("error", (err) => {
318
+ cleanup();
319
+ resolve({
320
+ ok: false,
321
+ code: 127,
322
+ signal: null,
323
+ timedOut,
324
+ aborted,
325
+ text: "",
326
+ rawStdout: stdout,
327
+ stderr: `${stderr}\n${err.message}`.trim(),
328
+ costUsd: 0,
329
+ durationMs: Date.now() - start,
330
+ harness: spec.harness,
331
+ model: spec.model,
332
+ label: spec.label,
333
+ });
334
+ });
335
+
336
+ child.on("close", (code, sig) => {
337
+ cleanup();
338
+ const parsed = parseHarnessOutput(spec.harness, stdout);
339
+ resolve({
340
+ ok: code === 0 && !timedOut && !aborted && !parsed.isError,
341
+ code,
342
+ signal: sig,
343
+ timedOut,
344
+ aborted,
345
+ text: parsed.text,
346
+ structured: parsed.structured,
347
+ rawStdout: stdout,
348
+ stderr: stderr.trim(),
349
+ costUsd: parsed.costUsd,
350
+ durationMs: Date.now() - start,
351
+ harness: spec.harness,
352
+ model: spec.model,
353
+ label: spec.label,
354
+ });
355
+ });
356
+ });
357
+ }