master-orchestrator 0.0.0-stage → 0.1.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +174 -2
  4. package/package.json +56 -4
  5. package/src/adapters/agy.ts +285 -0
  6. package/src/adapters/claude.ts +317 -0
  7. package/src/adapters/codex.ts +162 -0
  8. package/src/adapters/common.ts +211 -0
  9. package/src/adapters/cursor.ts +242 -0
  10. package/src/adapters/dsh.ts +356 -0
  11. package/src/adapters/fake-agent.mjs +50 -0
  12. package/src/adapters/fake.ts +88 -0
  13. package/src/adapters/gemini.ts +225 -0
  14. package/src/adapters/grok.ts +328 -0
  15. package/src/adapters/muse.ts +281 -0
  16. package/src/adapters/omp.ts +119 -0
  17. package/src/adapters/opencode.ts +228 -0
  18. package/src/adapters/pi.ts +284 -0
  19. package/src/adapters/registry.ts +31 -0
  20. package/src/adapters/types.ts +201 -0
  21. package/src/config/load.ts +290 -0
  22. package/src/config/profiles.ts +64 -0
  23. package/src/config/schema.ts +158 -0
  24. package/src/config/write.ts +83 -0
  25. package/src/engine/artifacts.ts +145 -0
  26. package/src/engine/baseline.ts +132 -0
  27. package/src/engine/execute.ts +437 -0
  28. package/src/engine/git.ts +32 -0
  29. package/src/engine/hostenv.ts +54 -0
  30. package/src/engine/registry.ts +280 -0
  31. package/src/engine/runner.ts +203 -0
  32. package/src/engine/types.ts +55 -0
  33. package/src/engine/verify.ts +100 -0
  34. package/src/index.ts +602 -0
  35. package/src/prompts/envelope.ts +29 -0
  36. package/src/prompts/templates.ts +389 -0
  37. package/src/ui/configure.ts +174 -0
  38. package/src/ui/dialogs.ts +88 -0
  39. package/src/ui/doctor.ts +120 -0
  40. package/src/ui/format.ts +94 -0
  41. package/src/ui/host.ts +100 -0
  42. package/src/ui/render.ts +86 -0
  43. package/src/ui/widget.ts +70 -0
  44. package/src/workflows/budget.ts +66 -0
  45. package/src/workflows/common.ts +100 -0
  46. package/src/workflows/debate.ts +488 -0
  47. package/src/workflows/host.ts +78 -0
  48. package/src/workflows/plan-exec.ts +807 -0
  49. package/src/workflows/plan.ts +407 -0
  50. package/src/workflows/planfile.ts +380 -0
  51. package/src/workflows/planstate.ts +229 -0
  52. package/src/workflows/verdict.ts +74 -0
@@ -0,0 +1,317 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ clip,
4
+ detectByVersion,
5
+ getNumber,
6
+ getString,
7
+ isObject,
8
+ parseJsonAnswer,
9
+ parseJsonLine,
10
+ recordDenied,
11
+ recordSession,
12
+ recordText,
13
+ recordUsage,
14
+ standardFinalize,
15
+ } from "./common.ts";
16
+ import {
17
+ STATUS_PRECEDENCE,
18
+ type AdapterOutcome,
19
+ type AgentAdapter,
20
+ type AuthStatus,
21
+ type HostEnv,
22
+ type Invocation,
23
+ type NormalizedEvent,
24
+ type ParserState,
25
+ type RunRequest,
26
+ type RunStatus,
27
+ } from "./types.ts";
28
+
29
+ const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
30
+
31
+ /**
32
+ * Inline settings that turn the sandbox off. Always passed: `buildInvocation` cannot read the user's settings to
33
+ * know whether they enable it, disabling a sandbox that is already off is a no-op, and `--settings` is not restored
34
+ * on `--resume`, so every run has to restate it.
35
+ */
36
+ const SANDBOX_OFF = JSON.stringify({ sandbox: { enabled: false } });
37
+
38
+ /** `assistant.error` kinds (claude stream-json) and the status each one means. */
39
+ const ERROR_KIND_STATUS: Record<string, RunStatus> = {
40
+ authentication_failed: "auth_required",
41
+ oauth_org_not_allowed: "auth_required",
42
+ account_on_hold: "auth_required",
43
+ verification_required: "auth_required",
44
+ cloud_credential_error: "auth_required",
45
+ billing_error: "quota",
46
+ rate_limit: "quota",
47
+ overloaded: "quota",
48
+ model_not_found: "unavailable",
49
+ };
50
+
51
+ /** `result.startup_failure_reason` values that are a sign-in problem rather than a broken installation. */
52
+ const STARTUP_AUTH_REASONS = new Set(["gateway_signin_required"]);
53
+
54
+ /** bypassPermissions is refused when claude runs as root. */
55
+ const ROOT_REFUSAL = /cannot be used with root\/sudo privileges/i;
56
+
57
+ /**
58
+ * Deterministic session id for a first run: a name-based UUID (version 5 layout) over the run directory.
59
+ * `buildInvocation` must be pure, so it cannot call `randomUUID()`; the run directory is unique per run, which
60
+ * makes the id unique too (claude refuses an id that is already in use). The id is also read back from the stream
61
+ * (`system/init` and `result`), which stays authoritative.
62
+ */
63
+ export function sessionUuidFromRunDir(runDir: string): string {
64
+ const bytes = createHash("sha1").update(`master-orchestrator:${runDir}`).digest().subarray(0, 16);
65
+ bytes[6] = (bytes[6]! & 0x0f) | 0x50;
66
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
67
+ const hex = bytes.toString("hex");
68
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
69
+ }
70
+
71
+ /**
72
+ * Claude Code (`claude -p --output-format stream-json`). Events: `system/init`, `assistant`, `user`,
73
+ * `system/api_retry`, and a final `result` that alone carries the answer, the cost and `permission_denials`.
74
+ * Interrupts on SIGINT (the print loop aborts the turn and writes the result).
75
+ */
76
+ export const claudeAdapter: AgentAdapter = {
77
+ id: "claude",
78
+ displayName: "Claude Code",
79
+ binary: "claude",
80
+ testedVersions: ">=2.1.305 <2.2.0",
81
+ stability: "experimental",
82
+ liveChecked: "2.1.328 on 2026-11-25: analyze, implement, follow-up, cancellation, auth failure",
83
+ stopSignal: "SIGINT",
84
+ capabilities: {
85
+ resume: true,
86
+ structuredOutput: true,
87
+ listModels: false,
88
+ effortLevels: EFFORT_LEVELS,
89
+ reportsCost: true,
90
+ },
91
+
92
+ detect(env: HostEnv) {
93
+ return detectByVersion(env, this.testedVersions);
94
+ },
95
+
96
+ async checkAuth(env: HostEnv): Promise<AuthStatus> {
97
+ const result = await env.exec(env.bin, ["auth", "status", "--json"], { timeoutMs: 20_000 });
98
+ if (result.error) return { state: "unknown", detail: result.error };
99
+ const status = parseJsonObject(result.stdout);
100
+ if (!status || typeof status.loggedIn !== "boolean") {
101
+ return { state: "unknown", detail: clip(`${result.stdout}\n${result.stderr}`.trim() || "no output", 120) };
102
+ }
103
+ if (!status.loggedIn) return { state: "missing", detail: "not logged in (run `claude auth login`)" };
104
+ // Never echo the account e-mail; the method and provider are enough for `doctor`.
105
+ const method = [getString(status, "authMethod"), getString(status, "apiProvider")].filter(Boolean).join(", ");
106
+ return { state: "ok", detail: method ? `logged in (${method})` : "logged in" };
107
+ },
108
+
109
+ buildInvocation(req: RunRequest): Invocation {
110
+ // The prompt goes on stdin: variadic flags (`--allowedTools`, `--add-dir`, ...) in extraArgs would swallow a
111
+ // positional prompt. Flags are not restored on `--resume`, so a follow-up restates all of them. Never `--bare`:
112
+ // it skips the user's settings, hooks and credentials helpers.
113
+ const args = [
114
+ "-p",
115
+ "--output-format",
116
+ "stream-json",
117
+ "--verbose",
118
+ "--permission-mode",
119
+ "bypassPermissions",
120
+ "--permission-prompts",
121
+ "none",
122
+ "--settings",
123
+ SANDBOX_OFF,
124
+ ];
125
+ if (req.sessionId) args.push("--resume", req.sessionId);
126
+ else args.push("--session-id", sessionUuidFromRunDir(req.runDir));
127
+ if (req.model) args.push("--model", req.model);
128
+ if (req.effort) args.push("--effort", req.effort);
129
+ if (req.outputSchema) args.push("--json-schema", JSON.stringify(req.outputSchema));
130
+ args.push(...(req.extraArgs ?? []));
131
+ return { args, cwd: req.workspace, env: req.env, stdin: req.prompt, files: [] };
132
+ },
133
+
134
+ parseEvent(line: string, state: ParserState): NormalizedEvent[] {
135
+ const event = parseJsonLine(line);
136
+ if (!event) {
137
+ if (line.trim()) state.nonJsonLines++;
138
+ return [];
139
+ }
140
+ switch (getString(event, "type")) {
141
+ case "system":
142
+ return parseSystem(event, state);
143
+ case "assistant":
144
+ return parseAssistant(event, state);
145
+ case "result":
146
+ return parseResult(event, state);
147
+ default:
148
+ return [];
149
+ }
150
+ },
151
+
152
+ finalize(raw, state) {
153
+ // Only a successful `result` carries the answer; assistant text of a run that never reached one is not it.
154
+ const outcome = standardFinalize(raw, state, { finalText: state.finalText ?? "" });
155
+ if (outcome.status !== "completed") {
156
+ for (const [status, reason] of typedFailures(raw, state)) escalate(outcome, status, reason);
157
+ return outcome;
158
+ }
159
+ const structured = "structured" in state.extra ? state.extra.structured : parseJsonAnswer(outcome.finalText);
160
+ if (structured !== undefined) outcome.structuredOutput = structured;
161
+ return outcome;
162
+ },
163
+ };
164
+
165
+ function parseSystem(event: Record<string, unknown>, state: ParserState): NormalizedEvent[] {
166
+ const subtype = getString(event, "subtype");
167
+ if (subtype === "init") return recordSession(state, getString(event, "session_id"));
168
+ if (subtype === "api_retry") {
169
+ const attempt = getNumber(event, "attempt");
170
+ const max = getNumber(event, "max_retries");
171
+ const detail = getString(event, "error") ?? String(getNumber(event, "error_status") ?? "error");
172
+ const message = `API retry ${attempt ?? "?"}/${max ?? "?"}: ${detail}`;
173
+ state.warnings.push(message);
174
+ return [{ type: "warning", message: clip(message, 200) }];
175
+ }
176
+ return [];
177
+ }
178
+
179
+ function parseAssistant(event: Record<string, unknown>, state: ParserState): NormalizedEvent[] {
180
+ const content = getContent(event);
181
+ const errorKind = getString(event, "error");
182
+ if (errorKind) {
183
+ // A synthetic message that reports an API failure ("Not logged in · Please run /login", ...): an error, not an answer.
184
+ const text = content.map((block) => getString(block, "text")).filter(Boolean).join(" ");
185
+ const message = text || errorKind;
186
+ state.errors.push(message);
187
+ const apiErrors = (state.extra.apiErrors as ApiError[] | undefined) ?? [];
188
+ apiErrors.push({ kind: errorKind, message });
189
+ state.extra.apiErrors = apiErrors;
190
+ return [{ type: "warning", message: clip(`${errorKind}: ${message}`, 200) }];
191
+ }
192
+ // Subagent messages (parent_tool_use_id set) are activity, never the answer of the run.
193
+ const fromSubagent = typeof event.parent_tool_use_id === "string";
194
+ const events: NormalizedEvent[] = [];
195
+ for (const block of content) {
196
+ const blockType = getString(block, "type");
197
+ if (blockType === "text") {
198
+ const text = getString(block, "text");
199
+ if (fromSubagent) {
200
+ if (text?.trim()) events.push({ type: "activity", kind: "text", summary: clip(text) });
201
+ } else {
202
+ events.push(...recordText(state, text));
203
+ }
204
+ } else if (blockType === "tool_use") {
205
+ const name = getString(block, "name") ?? "tool";
206
+ const input = isObject(block) ? block.input : undefined;
207
+ events.push({ type: "activity", kind: "tool", summary: `${name} ${clip(summarizeInput(input), 80)}`.trim() });
208
+ } else if (blockType === "thinking") {
209
+ const text = getString(block, "thinking");
210
+ if (text?.trim()) events.push({ type: "activity", kind: "thinking", summary: clip(text) });
211
+ }
212
+ }
213
+ return events;
214
+ }
215
+
216
+ function parseResult(event: Record<string, unknown>, state: ParserState): NormalizedEvent[] {
217
+ const events: NormalizedEvent[] = [...recordSession(state, getString(event, "session_id"))];
218
+ const denials = Array.isArray(event.permission_denials) ? event.permission_denials : [];
219
+ for (const denial of denials) {
220
+ const tool = getString(denial, "tool_name") ?? "tool";
221
+ const input = isObject(denial) ? summarizeInput(denial.tool_input) : "";
222
+ events.push(recordDenied(state, input ? `${tool}: ${clip(input, 160)}` : tool));
223
+ }
224
+
225
+ const input = sumDefined([
226
+ getNumber(event, "usage", "input_tokens"),
227
+ getNumber(event, "usage", "cache_creation_input_tokens"),
228
+ getNumber(event, "usage", "cache_read_input_tokens"),
229
+ ]);
230
+ const output = getNumber(event, "usage", "output_tokens");
231
+ const cost = getNumber(event, "total_cost_usd");
232
+ // One result per process; on a resumed session the cost is cumulative, so it replaces rather than adds.
233
+ events.push(recordUsage(state, { inputTokens: input, outputTokens: output, costUsd: cost }, "replace"));
234
+ const turns = getNumber(event, "num_turns");
235
+ if (turns !== undefined) state.usage.turns = turns;
236
+
237
+ const subtype = getString(event, "subtype") ?? "unknown";
238
+ const result = getString(event, "result");
239
+ const startupFailure = getString(event, "startup_failure_reason");
240
+ if (startupFailure) state.extra.startupFailure = startupFailure;
241
+ if (subtype === "success" && event.is_error !== true) {
242
+ state.finalText = result ?? "";
243
+ state.terminal = { ok: true };
244
+ if ("structured_output" in event && event.structured_output !== undefined && event.structured_output !== null) {
245
+ state.extra.structured = event.structured_output;
246
+ }
247
+ return events;
248
+ }
249
+
250
+ const errors = Array.isArray(event.errors) ? event.errors.filter((item): item is string => typeof item === "string") : [];
251
+ if (result?.trim()) errors.unshift(result);
252
+ state.errors.push(...errors);
253
+ const reason = [subtype, startupFailure, errors[0]].filter(Boolean).join(": ");
254
+ state.terminal = { ok: false, reason };
255
+ events.push({ type: "warning", message: clip(reason, 200) });
256
+ return events;
257
+ }
258
+
259
+ /** Statuses read from typed fields, which win over text matching when they rank higher. */
260
+ function typedFailures(raw: { stderr: string }, state: ParserState): Array<[RunStatus, string]> {
261
+ const found: Array<[RunStatus, string]> = [];
262
+ for (const { kind, message } of (state.extra.apiErrors as ApiError[] | undefined) ?? []) {
263
+ const status = ERROR_KIND_STATUS[kind];
264
+ if (status) found.push([status, `${kind}: ${clip(message, 160)}`]);
265
+ }
266
+ const startupFailure = state.extra.startupFailure as string | undefined;
267
+ if (startupFailure) {
268
+ const status = STARTUP_AUTH_REASONS.has(startupFailure) ? "auth_required" : "unavailable";
269
+ found.push([status, `startup_failure: ${startupFailure}`]);
270
+ }
271
+ const rootLine = raw.stderr.split(/\r?\n/).find((line) => ROOT_REFUSAL.test(line));
272
+ if (rootLine) found.push(["unavailable", `root_refused: ${clip(rootLine, 160)}`]);
273
+ return found;
274
+ }
275
+
276
+ /** Replaces the outcome's status when `status` comes first in the precedence order. */
277
+ function escalate(outcome: AdapterOutcome, status: RunStatus, reason: string): void {
278
+ if (STATUS_PRECEDENCE.indexOf(status) < STATUS_PRECEDENCE.indexOf(outcome.status)) {
279
+ outcome.status = status;
280
+ outcome.reason = reason;
281
+ }
282
+ }
283
+
284
+ interface ApiError {
285
+ kind: string;
286
+ message: string;
287
+ }
288
+
289
+ /** Parses a whole (possibly pretty-printed) JSON object. */
290
+ function parseJsonObject(text: string): Record<string, unknown> | undefined {
291
+ try {
292
+ const value = JSON.parse(text.trim()) as unknown;
293
+ return isObject(value) ? value : undefined;
294
+ } catch {
295
+ return undefined;
296
+ }
297
+ }
298
+
299
+ function getContent(event: Record<string, unknown>): unknown[] {
300
+ const message = event.message;
301
+ if (!isObject(message) || !Array.isArray(message.content)) return [];
302
+ return message.content;
303
+ }
304
+
305
+ function summarizeInput(input: unknown): string {
306
+ if (!isObject(input)) return typeof input === "string" ? input : "";
307
+ for (const key of ["command", "file_path", "path", "pattern", "url", "query", "description"]) {
308
+ const value = getString(input, key);
309
+ if (value) return value;
310
+ }
311
+ return JSON.stringify(input);
312
+ }
313
+
314
+ function sumDefined(values: Array<number | undefined>): number | undefined {
315
+ const present = values.filter((value): value is number => value !== undefined);
316
+ return present.length > 0 ? present.reduce((sum, value) => sum + value, 0) : undefined;
317
+ }
@@ -0,0 +1,162 @@
1
+ import { join } from "node:path";
2
+ import {
3
+ clip,
4
+ detectByVersion,
5
+ getNumber,
6
+ getString,
7
+ isObject,
8
+ parseJsonAnswer,
9
+ parseJsonLine,
10
+ recordDenied,
11
+ recordSession,
12
+ recordText,
13
+ recordUsage,
14
+ standardFinalize,
15
+ } from "./common.ts";
16
+ import type { AgentAdapter, AuthStatus, HostEnv, Invocation, NormalizedEvent, ParserState, RunRequest } from "./types.ts";
17
+
18
+ const EFFORT_LEVELS = ["minimal", "low", "medium", "high", "xhigh"] as const;
19
+
20
+ /**
21
+ * Codex CLI (`codex exec`). Event schema: codex-rs/exec/src/exec_events.rs (thread.started, turn.*, item.*, error).
22
+ * Interrupts on SIGINT (exec installs a ctrl_c handler that ends the turn).
23
+ */
24
+ export const codexAdapter: AgentAdapter = {
25
+ id: "codex",
26
+ displayName: "Codex",
27
+ binary: "codex",
28
+ testedVersions: ">=0.163.0 <0.200.0",
29
+ stability: "experimental",
30
+ liveChecked: "codex-cli 0.172.0 on 2026-11-25: analyze, implement, follow-up, cancellation, auth failure, capacity reconnects",
31
+ stopSignal: "SIGINT",
32
+ capabilities: {
33
+ resume: true,
34
+ structuredOutput: true,
35
+ listModels: false,
36
+ effortLevels: EFFORT_LEVELS,
37
+ reportsCost: false,
38
+ },
39
+
40
+ detect(env: HostEnv) {
41
+ return detectByVersion(env, this.testedVersions);
42
+ },
43
+
44
+ async checkAuth(env: HostEnv): Promise<AuthStatus> {
45
+ const result = await env.exec(env.bin, ["login", "status"], { timeoutMs: 20_000 });
46
+ const text = `${result.stdout}\n${result.stderr}`.trim();
47
+ if (result.error) return { state: "unknown", detail: result.error };
48
+ if (result.code === 0 && /logged in/i.test(text) && !/not logged in/i.test(text)) {
49
+ return { state: "ok", detail: clip(text, 120) };
50
+ }
51
+ // A custom model provider configured with an API key works without a ChatGPT login.
52
+ return {
53
+ state: "unknown",
54
+ detail: `${clip(text, 120) || "no output"} (a custom model provider may still work; run \`codex login\` otherwise)`,
55
+ };
56
+ },
57
+
58
+ buildInvocation(req: RunRequest): Invocation {
59
+ const lastMessage = join(req.runDir, "last-message.md");
60
+ const files = [];
61
+ // Parent exec options go before the `resume` subcommand, which does not accept them.
62
+ const args = ["-a", "never", "exec", "-C", req.workspace, "--sandbox", "danger-full-access"];
63
+ if (req.sessionId) args.push("resume", req.sessionId);
64
+ args.push("--json", "--skip-git-repo-check", "--output-last-message", lastMessage);
65
+ if (req.model) args.push("-m", req.model);
66
+ if (req.effort) args.push("-c", `model_reasoning_effort="${req.effort}"`);
67
+ if (req.outputSchema) {
68
+ const schemaPath = join(req.runDir, "output-schema.json");
69
+ files.push({ path: schemaPath, content: JSON.stringify(req.outputSchema, null, 2) });
70
+ args.push("--output-schema", schemaPath);
71
+ }
72
+ args.push(...(req.extraArgs ?? []), "-");
73
+ return {
74
+ args,
75
+ cwd: req.workspace,
76
+ env: req.env,
77
+ stdin: req.prompt,
78
+ files,
79
+ outputFiles: { lastMessage },
80
+ };
81
+ },
82
+
83
+ parseEvent(line: string, state: ParserState): NormalizedEvent[] {
84
+ const event = parseJsonLine(line);
85
+ if (!event) {
86
+ if (line.trim()) state.nonJsonLines++;
87
+ return [];
88
+ }
89
+ const type = getString(event, "type");
90
+ switch (type) {
91
+ case "thread.started":
92
+ return recordSession(state, getString(event, "thread_id"));
93
+ case "turn.completed": {
94
+ state.terminal = { ok: true };
95
+ state.usage.turns = (state.usage.turns ?? 0) + 1;
96
+ const input = getNumber(event, "usage", "input_tokens");
97
+ const output = getNumber(event, "usage", "output_tokens");
98
+ return [recordUsage(state, { inputTokens: input, outputTokens: output })];
99
+ }
100
+ case "turn.failed": {
101
+ const message = getString(event, "error", "message") ?? "turn failed";
102
+ state.terminal = { ok: false, reason: message };
103
+ state.errors.push(message);
104
+ return [{ type: "warning", message: clip(message, 200) }];
105
+ }
106
+ case "error": {
107
+ const message = getString(event, "message") ?? "error";
108
+ state.errors.push(message);
109
+ return [{ type: "warning", message: clip(message, 200) }];
110
+ }
111
+ case "item.started":
112
+ case "item.updated":
113
+ case "item.completed":
114
+ return parseItem(event.item, type, state);
115
+ default:
116
+ return [];
117
+ }
118
+ },
119
+
120
+ finalize(raw, state) {
121
+ const outcome = standardFinalize(raw, state, { finalText: raw.outputFiles.lastMessage });
122
+ if (outcome.finalText) {
123
+ const structured = parseJsonAnswer(outcome.finalText);
124
+ if (structured !== undefined) outcome.structuredOutput = structured;
125
+ }
126
+ return outcome;
127
+ },
128
+ };
129
+
130
+ function parseItem(item: unknown, phase: string, state: ParserState): NormalizedEvent[] {
131
+ if (!isObject(item)) return [];
132
+ const itemType = getString(item, "type");
133
+ if (itemType === "agent_message") {
134
+ return phase === "item.completed" ? recordText(state, getString(item, "text")) : [];
135
+ }
136
+ if (itemType === "reasoning") {
137
+ const text = getString(item, "text");
138
+ return phase === "item.completed" && text ? [{ type: "activity", kind: "thinking", summary: clip(text) }] : [];
139
+ }
140
+ if (itemType === "command_execution") {
141
+ const command = getString(item, "command") ?? "command";
142
+ const status = getString(item, "status");
143
+ if (status === "declined") return [recordDenied(state, `command: ${clip(command, 160)}`)];
144
+ return phase === "item.started" ? [{ type: "activity", kind: "tool", summary: `$ ${clip(command, 90)}` }] : [];
145
+ }
146
+ if (itemType === "file_change" && phase === "item.completed") {
147
+ const changes = Array.isArray(item.changes) ? item.changes : [];
148
+ const paths = changes.map((change) => getString(change, "path")).filter(Boolean);
149
+ return [{ type: "activity", kind: "tool", summary: `edit ${clip(paths.join(", "), 90)}` }];
150
+ }
151
+ if (itemType === "mcp_tool_call" && phase === "item.started") {
152
+ return [{ type: "activity", kind: "tool", summary: `${getString(item, "server")}.${getString(item, "tool")}` }];
153
+ }
154
+ if (itemType === "web_search" && phase === "item.started") {
155
+ return [{ type: "activity", kind: "tool", summary: `search ${clip(getString(item, "query") ?? "", 80)}` }];
156
+ }
157
+ if (itemType === "error" && phase === "item.completed") {
158
+ const message = getString(item, "message");
159
+ if (message) return [{ type: "warning", message: clip(message, 200) }];
160
+ }
161
+ return [];
162
+ }
@@ -0,0 +1,211 @@
1
+ import semver from "semver";
2
+ import type { AdapterOutcome, Detection, HostEnv, NormalizedEvent, ParserState, RawRunResult, RunStatus } from "./types.ts";
3
+
4
+ export type JsonObject = Record<string, unknown>;
5
+
6
+ /** Parses one line of a JSON event stream. Returns undefined for blank or non-JSON lines. */
7
+ export function parseJsonLine(line: string): JsonObject | undefined {
8
+ const trimmed = line.trim();
9
+ if (!trimmed.startsWith("{")) return undefined;
10
+ try {
11
+ const value = JSON.parse(trimmed) as unknown;
12
+ return isObject(value) ? value : undefined;
13
+ } catch {
14
+ return undefined;
15
+ }
16
+ }
17
+
18
+ export function isObject(value: unknown): value is JsonObject {
19
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20
+ }
21
+
22
+ export function getString(value: unknown, ...path: string[]): string | undefined {
23
+ const found = getPath(value, path);
24
+ return typeof found === "string" ? found : undefined;
25
+ }
26
+
27
+ export function getNumber(value: unknown, ...path: string[]): number | undefined {
28
+ const found = getPath(value, path);
29
+ return typeof found === "number" && Number.isFinite(found) ? found : undefined;
30
+ }
31
+
32
+ export function getPath(value: unknown, path: string[]): unknown {
33
+ let current = value;
34
+ for (const key of path) {
35
+ if (!isObject(current)) return undefined;
36
+ current = current[key];
37
+ }
38
+ return current;
39
+ }
40
+
41
+ /** One-line excerpt for activity summaries. */
42
+ export function clip(text: string, max = 100): string {
43
+ const line = text.replace(/\s+/g, " ").trim();
44
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
45
+ }
46
+
47
+ export function unique(values: Iterable<string>): string[] {
48
+ return [...new Set(values)];
49
+ }
50
+
51
+ /** Records usage numbers in the state and returns the matching event. */
52
+ export function recordUsage(
53
+ state: ParserState,
54
+ usage: { inputTokens?: number; outputTokens?: number; costUsd?: number },
55
+ mode: "add" | "replace" = "add",
56
+ ): NormalizedEvent {
57
+ const target = state.usage;
58
+ for (const key of ["inputTokens", "outputTokens", "costUsd"] as const) {
59
+ const value = usage[key];
60
+ if (value === undefined) continue;
61
+ target[key] = mode === "add" ? (target[key] ?? 0) + value : value;
62
+ }
63
+ return { type: "usage", ...usage };
64
+ }
65
+
66
+ export function recordText(state: ParserState, text: string | undefined): NormalizedEvent[] {
67
+ if (!text || !text.trim()) return [];
68
+ state.texts.push(text);
69
+ return [{ type: "activity", kind: "text", summary: clip(text) }];
70
+ }
71
+
72
+ export function recordDenied(state: ParserState, action: string): NormalizedEvent {
73
+ state.denied.push(action);
74
+ return { type: "denied", action };
75
+ }
76
+
77
+ export function recordSession(state: ParserState, sessionId: string | undefined): NormalizedEvent[] {
78
+ if (!sessionId || state.sessionId === sessionId) return [];
79
+ state.sessionId = sessionId;
80
+ return [{ type: "session", sessionId }];
81
+ }
82
+
83
+ interface FailureClass {
84
+ status: Extract<RunStatus, "unavailable" | "auth_required" | "quota">;
85
+ code: string;
86
+ }
87
+
88
+ const FAILURE_PATTERNS: Array<{ cls: FailureClass; pattern: RegExp }> = [
89
+ {
90
+ cls: { status: "unavailable", code: "unsupported_flag" },
91
+ pattern:
92
+ /unexpected argument|unknown (option|flag|argument|command)|unrecognized (option|argument|arguments)|error: found argument|no such option|invalid value '[^']*' for/i,
93
+ },
94
+ {
95
+ cls: { status: "unavailable", code: "model_unavailable" },
96
+ pattern:
97
+ /model[^\n]{0,60}(not found|does not exist|is not supported|unsupported|not available|is invalid)|unknown model|invalid model|no such model/i,
98
+ },
99
+ {
100
+ cls: { status: "auth_required", code: "auth_required" },
101
+ pattern:
102
+ /not logged in|please (log ?in|sign ?in|login|authenticate)|login required|authentication (failed|required|error)|unauthori[sz]ed|\b401\b|invalid (api[_ ]?key|x-api-key|token|credentials)|api[_ ]key[^\n]{0,20}(missing|not set|invalid|required)|missing api[_ ]key|no api[_ ]key|sign in (at|to|with)|(token|credentials|session) (has )?expired|expired (token|credentials|session)|oauth token/i,
103
+ },
104
+ {
105
+ cls: { status: "quota", code: "quota" },
106
+ pattern:
107
+ /quota|rate[ -]?limit|\b429\b|too many requests|usage limit|insufficient (credit|balance|funds|quota)|credit balance|out of credits|resource[_ ]exhausted|billing|limit reached|at capacity|overloaded/i,
108
+ },
109
+ ];
110
+
111
+ /** Classifies error output into a status that a role's fallback chain reacts to. */
112
+ export function classifyFailureText(text: string): (FailureClass & { line: string }) | undefined {
113
+ const lines = text.split(/\r?\n/).filter((line) => line.trim());
114
+ for (const { cls, pattern } of FAILURE_PATTERNS) {
115
+ const line = lines.find((candidate) => pattern.test(candidate));
116
+ if (line) return { ...cls, line: clip(line, 200) };
117
+ }
118
+ return undefined;
119
+ }
120
+
121
+ export interface FinalizeOptions {
122
+ /** Final answer when the adapter found it somewhere other than the state (for example an output file). */
123
+ finalText?: string;
124
+ /** Denials end the run: a run with denials is `denied` even when it produced text. */
125
+ deniedEndsRun?: boolean;
126
+ /** Treat a non-zero exit with a final answer as completed. */
127
+ acceptNonZeroExit?: boolean;
128
+ /** Additional text to classify (for example a log file). */
129
+ extraFailureText?: string;
130
+ }
131
+
132
+ /**
133
+ * Shared classification: an exit code of zero never implies `completed`. A run completes only with a final
134
+ * answer, no failing end-of-run event and (by default) exit code 0.
135
+ */
136
+ export function standardFinalize(raw: RawRunResult, state: ParserState, options: FinalizeOptions = {}): AdapterOutcome {
137
+ const finalText = (options.finalText ?? state.finalText ?? state.texts.at(-1))?.trim() || undefined;
138
+ const usage = Object.keys(state.usage).length > 0 ? { ...state.usage } : undefined;
139
+ const base = { finalText, sessionId: state.sessionId, deniedActions: unique(state.denied), usage };
140
+
141
+ if (raw.spawnError) return { ...base, status: "unavailable", reason: `spawn_failed: ${raw.spawnError}` };
142
+
143
+ const exitOk = raw.exitCode === 0 || (options.acceptNonZeroExit === true && raw.exitCode !== null);
144
+ const terminalFailed = state.terminal?.ok === false;
145
+ const success = Boolean(finalText) && !terminalFailed && exitOk;
146
+
147
+ if (!success) {
148
+ const failureText = [...state.errors, state.terminal?.reason ?? "", options.extraFailureText ?? "", raw.stderr].join("\n");
149
+ const cls = classifyFailureText(failureText);
150
+ if (cls) return { ...base, status: cls.status, reason: `${cls.code}: ${cls.line}` };
151
+ if (state.denied.length > 0) {
152
+ return { ...base, status: "denied", reason: `denied: ${clip(state.denied.join("; "), 200)}` };
153
+ }
154
+ let reason: string;
155
+ if (terminalFailed) reason = `turn_failed: ${clip(state.terminal?.reason ?? "the agent reported a failed turn", 200)}`;
156
+ else if (raw.exitCode !== 0 && raw.exitCode !== null) reason = `exit_code: exited with ${raw.exitCode}`;
157
+ else if (raw.signal) reason = `signal: ended by ${raw.signal}`;
158
+ else reason = "empty_result: exit 0 without an answer";
159
+ const lastError = state.errors.at(-1);
160
+ if (lastError && !reason.includes(lastError)) reason += ` (last error: ${clip(lastError, 160)})`;
161
+ return { ...base, status: "failed", reason };
162
+ }
163
+
164
+ if (options.deniedEndsRun && state.denied.length > 0) {
165
+ return { ...base, status: "denied", reason: `denied: ${clip(state.denied.join("; "), 200)}` };
166
+ }
167
+ return { ...base, status: "completed" };
168
+ }
169
+
170
+ const VERSION_PATTERN = /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/;
171
+
172
+ /** Checks a version against a semver range, including prereleases. */
173
+ export function versionInRange(version: string, range: string): boolean {
174
+ const parsed = semver.valid(version) ?? semver.valid(semver.coerce(version, { includePrerelease: true }));
175
+ if (!parsed) return false;
176
+ return semver.satisfies(parsed, range, { includePrerelease: true });
177
+ }
178
+
179
+ /** Standard `detect`: resolves the executable and reads its version. */
180
+ export async function detectByVersion(
181
+ env: HostEnv,
182
+ testedVersions: string,
183
+ args: string[] = ["--version"],
184
+ pattern: RegExp = VERSION_PATTERN,
185
+ ): Promise<Detection> {
186
+ const path = await env.which(env.bin);
187
+ if (!path) return { available: false, error: `${env.bin} not found on PATH` };
188
+ const result = await env.exec(path, args, { timeoutMs: 20_000 });
189
+ if (result.error) return { available: false, path, error: result.error };
190
+ const match = `${result.stdout}\n${result.stderr}`.match(pattern);
191
+ const version = match?.[1];
192
+ return {
193
+ available: true,
194
+ path,
195
+ version,
196
+ inTestedRange: version ? versionInRange(version, testedVersions) : undefined,
197
+ error: result.code === 0 ? undefined : `${args.join(" ")} exited with ${result.code}`,
198
+ };
199
+ }
200
+
201
+ /** Parses the text of a final answer as JSON, accepting a fenced block. */
202
+ export function parseJsonAnswer(text: string | undefined): unknown {
203
+ if (!text) return undefined;
204
+ const fenced = text.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);
205
+ const candidate = (fenced ? fenced[1] : text).trim();
206
+ try {
207
+ return JSON.parse(candidate);
208
+ } catch {
209
+ return undefined;
210
+ }
211
+ }