master-orchestrator 0.0.0-stage → 0.2.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 (50) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -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/dsh.ts +356 -0
  10. package/src/adapters/fake-agent.mjs +50 -0
  11. package/src/adapters/fake.ts +88 -0
  12. package/src/adapters/gemini.ts +239 -0
  13. package/src/adapters/grok.ts +328 -0
  14. package/src/adapters/omp.ts +119 -0
  15. package/src/adapters/opencode.ts +228 -0
  16. package/src/adapters/pi.ts +284 -0
  17. package/src/adapters/registry.ts +27 -0
  18. package/src/adapters/types.ts +201 -0
  19. package/src/config/load.ts +290 -0
  20. package/src/config/profiles.ts +64 -0
  21. package/src/config/schema.ts +158 -0
  22. package/src/config/write.ts +83 -0
  23. package/src/engine/artifacts.ts +145 -0
  24. package/src/engine/baseline.ts +132 -0
  25. package/src/engine/execute.ts +437 -0
  26. package/src/engine/git.ts +32 -0
  27. package/src/engine/hostenv.ts +54 -0
  28. package/src/engine/registry.ts +280 -0
  29. package/src/engine/runner.ts +249 -0
  30. package/src/engine/types.ts +55 -0
  31. package/src/engine/verify.ts +100 -0
  32. package/src/index.ts +602 -0
  33. package/src/prompts/envelope.ts +29 -0
  34. package/src/prompts/templates.ts +389 -0
  35. package/src/ui/configure.ts +174 -0
  36. package/src/ui/dialogs.ts +88 -0
  37. package/src/ui/doctor.ts +120 -0
  38. package/src/ui/format.ts +94 -0
  39. package/src/ui/host.ts +100 -0
  40. package/src/ui/render.ts +86 -0
  41. package/src/ui/widget.ts +70 -0
  42. package/src/workflows/budget.ts +66 -0
  43. package/src/workflows/common.ts +100 -0
  44. package/src/workflows/debate.ts +488 -0
  45. package/src/workflows/host.ts +78 -0
  46. package/src/workflows/plan-exec.ts +807 -0
  47. package/src/workflows/plan.ts +407 -0
  48. package/src/workflows/planfile.ts +380 -0
  49. package/src/workflows/planstate.ts +229 -0
  50. package/src/workflows/verdict.ts +74 -0
@@ -0,0 +1,119 @@
1
+ import { join } from "node:path";
2
+ import { clip, detectByVersion, getString, isObject } from "./common.ts";
3
+ import { finalizePiFamily, parsePiFamilyEvent, type PiFamilyOptions } from "./pi.ts";
4
+ import type { AgentAdapter, AuthStatus, HostEnv, Invocation, NormalizedEvent, ParserState, RunRequest } from "./types.ts";
5
+
6
+ const EFFORT_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max", "auto"] as const;
7
+
8
+ /**
9
+ * Settings overlay for every run. `autoResume: true` in the user's config would make a fresh run continue the most
10
+ * recent session of the workspace instead of starting a new one; an overlay ranks above project and global config.
11
+ */
12
+ const OVERLAY = "autoResume: false\n";
13
+
14
+ const OMP_OPTIONS: PiFamilyOptions = {
15
+ // Tool errors raised by approval policy (src/tools/approval.ts), the headless approval gate and extension or hook
16
+ // blocks (src/extensibility/extensions/wrapper.ts, hooks/tool-wrapper.ts).
17
+ denialPattern:
18
+ /is blocked by (user|tool) policy|requires approval but no interactive UI|no interactive UI is available|^Tool call denied by user|was blocked by (an extension|a hook|a preflight rule)|blocking execution/i,
19
+ stderrRules: [
20
+ {
21
+ pattern: /No default model selected|No models available|No model available matching enabledModels/,
22
+ status: "auth_required",
23
+ code: "auth_required",
24
+ },
25
+ { pattern: /Invalid --[\w-]+ value/, status: "unavailable", code: "invalid_flag_value" },
26
+ { pattern: /Session "[^"]*" not found/, status: "failed", code: "session_not_found" },
27
+ ],
28
+ };
29
+
30
+ /**
31
+ * oh-my-pi (`omp -p --mode json`), a pi fork that keeps pi's JSON stream: a `session` header (UUIDv7 id), then
32
+ * agent events (`message_end`, `tool_execution_*`, `turn_end`, `auto_retry_*`, `notice`, `agent_end`). Print mode
33
+ * exits 1 when the last assistant message stopped with `error` or `aborted`. SIGINT, SIGTERM and SIGHUP all dispose
34
+ * the session through the same teardown (exit 130/143/129); SIGTERM is used. Established from the fork's source
35
+ * (src/modes/print-mode.ts, src/main.ts, src/cli/args.ts), not from a live run.
36
+ */
37
+ export const ompAdapter: AgentAdapter = {
38
+ id: "omp",
39
+ displayName: "oh-my-pi",
40
+ binary: "omp",
41
+ testedVersions: ">=18.11.1 <20.0.0",
42
+ stability: "experimental",
43
+ liveChecked: "19.1.1 on 2026-11-25: analyze, implement, follow-up, cancellation, timeout, auth failure",
44
+ stopSignal: "SIGTERM",
45
+ capabilities: {
46
+ resume: true,
47
+ structuredOutput: false,
48
+ listModels: true,
49
+ effortLevels: EFFORT_LEVELS,
50
+ reportsCost: true,
51
+ },
52
+
53
+ detect(env: HostEnv) {
54
+ return detectByVersion(env, this.testedVersions);
55
+ },
56
+
57
+ /** `omp models` lists only models whose provider has credentials (or needs none), and starts no model turn. */
58
+ async checkAuth(env: HostEnv): Promise<AuthStatus> {
59
+ const listing = await readModels(env);
60
+ if ("error" in listing) return { state: "unknown", detail: listing.error };
61
+ if (listing.models.length > 0) {
62
+ const providers = [...new Set(listing.models.map((model) => model.split("/")[0]))];
63
+ return { state: "ok", detail: `${listing.models.length} models from ${providers.join(", ")}` };
64
+ }
65
+ return { state: "missing", detail: "no provider with usable credentials (run `omp` and /login, or set a provider API key)" };
66
+ },
67
+
68
+ async listModels(env: HostEnv): Promise<string[]> {
69
+ const listing = await readModels(env);
70
+ return "error" in listing ? [] : listing.models;
71
+ },
72
+
73
+ buildInvocation(req: RunRequest): Invocation {
74
+ const overlay = join(req.runDir, "omp-overlay.yml");
75
+ // `--auto-approve` forces the yolo approval mode over any configured mode; explicit deny and prompt policies of
76
+ // the user still apply and surface as denials. The prompt goes on stdin (read when stdin is not a TTY).
77
+ // omp always trusts the project, so there is no per-run trust flag. `--no-title` skips the title side turn.
78
+ const args = ["-p", "--mode", "json", "--cwd", req.workspace, "--auto-approve", "--no-title", "--config", overlay];
79
+ if (req.sessionId) args.push("--resume", req.sessionId);
80
+ if (req.model) args.push("--model", req.model);
81
+ if (req.effort) args.push("--thinking", req.effort);
82
+ args.push(...(req.extraArgs ?? []));
83
+ return {
84
+ args,
85
+ cwd: req.workspace,
86
+ env: req.env,
87
+ stdin: req.prompt,
88
+ files: [{ path: overlay, content: OVERLAY }],
89
+ };
90
+ },
91
+
92
+ parseEvent(line: string, state: ParserState): NormalizedEvent[] {
93
+ return parsePiFamilyEvent(line, state, OMP_OPTIONS);
94
+ },
95
+
96
+ finalize(raw, state) {
97
+ return finalizePiFamily(raw, state, OMP_OPTIONS);
98
+ },
99
+ };
100
+
101
+ /** Runs `omp models --json` (`{"models":[{"selector":"provider/id",...}]}`). */
102
+ async function readModels(env: HostEnv): Promise<{ models: string[] } | { error: string }> {
103
+ const result = await env.exec(env.bin, ["models", "--json"], { cwd: env.cwd, timeoutMs: 60_000 });
104
+ if (result.error) return { error: result.error };
105
+ const line = result.stdout.split(/\r?\n/).find((candidate) => candidate.trim().startsWith("{"));
106
+ let parsed: unknown;
107
+ try {
108
+ parsed = line ? JSON.parse(line) : undefined;
109
+ } catch {
110
+ parsed = undefined;
111
+ }
112
+ if (!isObject(parsed) || !Array.isArray(parsed.models)) {
113
+ return { error: clip(`${result.stdout}\n${result.stderr}`.trim() || `exited with ${result.code}`, 120) };
114
+ }
115
+ const models = parsed.models
116
+ .map((model) => getString(model, "selector") ?? [getString(model, "provider"), getString(model, "id")].filter(Boolean).join("/"))
117
+ .filter((model) => model.includes("/"));
118
+ return { models: [...new Set(models)].sort() };
119
+ }
@@ -0,0 +1,228 @@
1
+ import {
2
+ clip,
3
+ detectByVersion,
4
+ getNumber,
5
+ getString,
6
+ isObject,
7
+ parseJsonAnswer,
8
+ parseJsonLine,
9
+ recordDenied,
10
+ recordSession,
11
+ recordText,
12
+ recordUsage,
13
+ standardFinalize,
14
+ } from "./common.ts";
15
+ import {
16
+ STATUS_PRECEDENCE,
17
+ type AdapterOutcome,
18
+ type AgentAdapter,
19
+ type AuthStatus,
20
+ type HostEnv,
21
+ type Invocation,
22
+ type NormalizedEvent,
23
+ type ParserState,
24
+ type RunRequest,
25
+ type RunStatus,
26
+ } from "./types.ts";
27
+
28
+ /** `error.type` of opencode's run errors and the status each one means. Unlisted types are plain failures. */
29
+ const ERROR_TYPE_STATUS: Record<string, RunStatus> = {
30
+ "provider.auth": "auth_required",
31
+ "provider.rate-limit": "quota",
32
+ "provider.quota": "quota",
33
+ "provider.free-limit": "quota",
34
+ "provider.no-route": "unavailable",
35
+ "provider.unknown": "unavailable",
36
+ "permission.rejected": "denied",
37
+ };
38
+
39
+ /** Tool errors that come from a permission rule rather than from the tool itself. */
40
+ const DENIAL_PATTERN = /Blocked by configuration policy|^Permission denied:|cannot ask the user for permission/i;
41
+
42
+ /** effect/cli rejects unknown flags with a message the shared patterns do not cover. */
43
+ const UNRECOGNIZED_FLAG = /Unrecognized flag: \S+/;
44
+
45
+ /**
46
+ * OpenCode (`opencode run --format json`). Events carry `type`, `timestamp` and `sessionID`: `step_start`, `text`,
47
+ * `reasoning`, `tool_use`, `step_finish` (cost and tokens per step) and `error` (typed `error.type`).
48
+ * Interrupts on SIGINT (the session is aborted and the process exits 130).
49
+ */
50
+ export const opencodeAdapter: AgentAdapter = {
51
+ id: "opencode",
52
+ displayName: "OpenCode",
53
+ binary: "opencode",
54
+ testedVersions: ">=2.1.3 <2.4.0",
55
+ stability: "experimental",
56
+ liveChecked: "2.3.0 on 2026-11-25: analyze, implement, follow-up, cancellation, timeout",
57
+ stopSignal: "SIGINT",
58
+ capabilities: {
59
+ resume: true,
60
+ structuredOutput: false,
61
+ listModels: true,
62
+ // No effort flag: effort is the model variant (`provider/model#variant`), whose names depend on the model.
63
+ reportsCost: true,
64
+ },
65
+
66
+ detect(env: HostEnv) {
67
+ return detectByVersion(env, this.testedVersions);
68
+ },
69
+
70
+ async checkAuth(env: HostEnv): Promise<AuthStatus> {
71
+ const result = await env.exec(env.bin, ["auth", "list", "--format", "json", "--standalone"], { timeoutMs: 30_000 });
72
+ if (result.error) return { state: "unknown", detail: result.error };
73
+ let integrations: unknown;
74
+ try {
75
+ integrations = JSON.parse(result.stdout.trim());
76
+ } catch {
77
+ return { state: "unknown", detail: clip(`${result.stdout}\n${result.stderr}`.trim() || "no output", 120) };
78
+ }
79
+ const connected = (Array.isArray(integrations) ? integrations : [])
80
+ .filter((item) => isObject(item) && Array.isArray(item.connections) && item.connections.length > 0)
81
+ .map((item) => getString(item, "id") ?? "?");
82
+ // Only integration ids: connection labels can be account names.
83
+ if (connected.length > 0) return { state: "ok", detail: `credentials for ${connected.join(", ")}` };
84
+ // Free providers and providers configured with an inline key in opencode.json work without stored credentials.
85
+ return { state: "unknown", detail: "no stored credentials (free or config-defined providers may still work; run `opencode auth login` otherwise)" };
86
+ },
87
+
88
+ async listModels(env: HostEnv): Promise<string[]> {
89
+ const result = await env.exec(env.bin, ["models", "--standalone"], { cwd: env.cwd, timeoutMs: 60_000 });
90
+ if (result.error || result.code !== 0) return [];
91
+ const models = result.stdout
92
+ .split(/\r?\n/)
93
+ .map((line) => line.trim())
94
+ .filter((line) => /^[^\s/]+\/\S+$/.test(line));
95
+ return [...new Set(models)].sort();
96
+ },
97
+
98
+ buildInvocation(req: RunRequest): Invocation {
99
+ // `--standalone` runs a private server so the run never attaches to (or waits for) the user's background service.
100
+ // `--auto` approves every permission that a rule does not explicitly deny.
101
+ const args = ["run", "--standalone", "--format", "json", "--auto"];
102
+ if (req.sessionId) args.push("--session", req.sessionId);
103
+ const model = modelWithVariant(req.model, req.effort);
104
+ if (model) args.push("--model", model);
105
+ args.push(...(req.extraArgs ?? []));
106
+ return {
107
+ args,
108
+ cwd: req.workspace,
109
+ // opencode resolves the project from PWD, which a spawn with a different cwd would otherwise leave stale.
110
+ env: { ...req.env, PWD: req.workspace },
111
+ stdin: req.prompt,
112
+ files: [],
113
+ };
114
+ },
115
+
116
+ parseEvent(line: string, state: ParserState): NormalizedEvent[] {
117
+ const event = parseJsonLine(line);
118
+ if (!event) {
119
+ if (line.trim()) state.nonJsonLines++;
120
+ return [];
121
+ }
122
+ const events: NormalizedEvent[] = [...recordSession(state, getString(event, "sessionID") || undefined)];
123
+ const part = isObject(event.part) ? event.part : {};
124
+ switch (getString(event, "type")) {
125
+ case "step_start":
126
+ // The answer is the text of the last step; remember where it starts.
127
+ state.extra.stepTextStart = state.texts.length;
128
+ break;
129
+ case "text":
130
+ events.push(...recordText(state, getString(part, "text")));
131
+ break;
132
+ case "reasoning": {
133
+ const text = getString(part, "text");
134
+ if (text?.trim()) events.push({ type: "activity", kind: "thinking", summary: clip(text) });
135
+ break;
136
+ }
137
+ case "tool_use":
138
+ events.push(...parseToolUse(part, state));
139
+ break;
140
+ case "step_finish": {
141
+ state.usage.turns = (state.usage.turns ?? 0) + 1;
142
+ const input = sumDefined([
143
+ getNumber(part, "tokens", "input"),
144
+ getNumber(part, "tokens", "cache", "read"),
145
+ getNumber(part, "tokens", "cache", "write"),
146
+ ]);
147
+ events.push(recordUsage(state, { inputTokens: input, outputTokens: getNumber(part, "tokens", "output"), costUsd: getNumber(part, "cost") }));
148
+ break;
149
+ }
150
+ case "error": {
151
+ const errorType = getString(event, "error", "type") ?? "unknown";
152
+ const message = getString(event, "error", "message") ?? errorType;
153
+ state.errors.push(message);
154
+ const types = (state.extra.errorTypes as string[] | undefined) ?? [];
155
+ types.push(errorType);
156
+ state.extra.errorTypes = types;
157
+ state.terminal = { ok: false, reason: `${errorType}: ${message}` };
158
+ events.push({ type: "warning", message: clip(`${errorType}: ${message}`, 200) });
159
+ break;
160
+ }
161
+ }
162
+ return events;
163
+ },
164
+
165
+ finalize(raw, state) {
166
+ const start = typeof state.extra.stepTextStart === "number" ? state.extra.stepTextStart : 0;
167
+ const finalText = state.texts.slice(start).join("\n\n");
168
+ const outcome = standardFinalize(raw, state, { finalText });
169
+ if (outcome.status !== "completed") {
170
+ for (const errorType of (state.extra.errorTypes as string[] | undefined) ?? []) {
171
+ const status = ERROR_TYPE_STATUS[errorType];
172
+ if (status) escalate(outcome, status, `${errorType}: ${clip(state.errors.at(-1) ?? errorType, 160)}`);
173
+ }
174
+ const flagLine = raw.stderr.match(UNRECOGNIZED_FLAG);
175
+ if (flagLine) escalate(outcome, "unavailable", `unsupported_flag: ${flagLine[0]}`);
176
+ return outcome;
177
+ }
178
+ const structured = parseJsonAnswer(outcome.finalText);
179
+ if (structured !== undefined) outcome.structuredOutput = structured;
180
+ return outcome;
181
+ },
182
+ };
183
+
184
+ /**
185
+ * Applies the effort as the model variant. It needs a model: opencode refuses a variant without one ("Cannot select
186
+ * a variant before selecting a model"), so an effort without a model is dropped. A model that already names a
187
+ * variant keeps it.
188
+ */
189
+ function modelWithVariant(model: string | undefined, effort: string | undefined): string | undefined {
190
+ if (!model) return undefined;
191
+ if (!effort || model.includes("#")) return model;
192
+ return `${model}#${effort}`;
193
+ }
194
+
195
+ function parseToolUse(part: Record<string, unknown>, state: ParserState): NormalizedEvent[] {
196
+ const tool = getString(part, "tool") ?? "tool";
197
+ const status = getString(part, "state", "status");
198
+ const input = isObject(part.state) ? summarizeInput(part.state.input) : "";
199
+ if (status === "error") {
200
+ const error = getString(part, "state", "error") ?? "error";
201
+ if (DENIAL_PATTERN.test(error)) return [recordDenied(state, `${tool}: ${clip(input || error, 160)}`)];
202
+ return [{ type: "warning", message: clip(`${tool} failed: ${error}`, 200) }];
203
+ }
204
+ if (status === "completed") return [{ type: "activity", kind: "tool", summary: `${tool} ${clip(input, 80)}`.trim() }];
205
+ return [];
206
+ }
207
+
208
+ /** Replaces the outcome's status when `status` comes first in the precedence order. */
209
+ function escalate(outcome: AdapterOutcome, status: RunStatus, reason: string): void {
210
+ if (STATUS_PRECEDENCE.indexOf(status) < STATUS_PRECEDENCE.indexOf(outcome.status)) {
211
+ outcome.status = status;
212
+ outcome.reason = reason;
213
+ }
214
+ }
215
+
216
+ function summarizeInput(input: unknown): string {
217
+ if (!isObject(input)) return typeof input === "string" ? input : "";
218
+ for (const key of ["command", "filePath", "path", "pattern", "url", "query", "description"]) {
219
+ const value = getString(input, key);
220
+ if (value) return value;
221
+ }
222
+ return JSON.stringify(input);
223
+ }
224
+
225
+ function sumDefined(values: Array<number | undefined>): number | undefined {
226
+ const present = values.filter((value): value is number => value !== undefined);
227
+ return present.length > 0 ? present.reduce((sum, value) => sum + value, 0) : undefined;
228
+ }
@@ -0,0 +1,284 @@
1
+ import { sessionUuidFromRunDir } from "./claude.ts";
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 RawRunResult,
26
+ type RunRequest,
27
+ type RunStatus,
28
+ } from "./types.ts";
29
+
30
+ const EFFORT_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
31
+
32
+ /** A stderr line that means a status the shared patterns do not recognise. */
33
+ export interface StderrRule {
34
+ pattern: RegExp;
35
+ status: RunStatus;
36
+ code: string;
37
+ }
38
+
39
+ /** What differs between pi and the forks that keep its JSON event stream (oh-my-pi). */
40
+ export interface PiFamilyOptions {
41
+ /** Tool error texts that come from a rule, hook or extension that blocked the call. */
42
+ denialPattern: RegExp;
43
+ stderrRules: StderrRule[];
44
+ }
45
+
46
+ interface LastAssistant {
47
+ stopReason: string;
48
+ text: string;
49
+ errorMessage?: string;
50
+ errorStatus?: number;
51
+ }
52
+
53
+ const PI_OPTIONS: PiFamilyOptions = {
54
+ denialPattern: /^(tool execution was blocked|blocked\b)|\bblocked by\b/i,
55
+ stderrRules: [
56
+ { pattern: /Unknown provider "[^"]*"/, status: "unavailable", code: "model_unavailable" },
57
+ { pattern: /No models available|No model selected/, status: "auth_required", code: "auth_required" },
58
+ ],
59
+ };
60
+
61
+ /**
62
+ * pi (`pi --mode json`). Events: a `session` header, then agent events (`message_end`, `tool_execution_*`,
63
+ * `turn_end`, `auto_retry_*`, `agent_settled`). The run succeeded when the last assistant message stopped with
64
+ * `stop`; an API failure is an assistant message with `stopReason: "error"` and the process still exits 0.
65
+ * SIGTERM disposes the session cleanly.
66
+ */
67
+ export const piAdapter: AgentAdapter = {
68
+ id: "pi",
69
+ displayName: "pi",
70
+ binary: "pi",
71
+ testedVersions: ">=1.4.0 <1.7.0",
72
+ stability: "experimental",
73
+ liveChecked: "1.6.1 on 2026-11-25: analyze, implement, follow-up, cancellation, timeout, auth failure",
74
+ stopSignal: "SIGTERM",
75
+ trustFlag: "--approve",
76
+ capabilities: {
77
+ resume: true,
78
+ structuredOutput: false,
79
+ listModels: true,
80
+ effortLevels: EFFORT_LEVELS,
81
+ reportsCost: true,
82
+ },
83
+
84
+ detect(env: HostEnv) {
85
+ return detectByVersion(env, this.testedVersions);
86
+ },
87
+
88
+ /** `--list-models` lists only models whose provider has credentials, and starts no model turn. */
89
+ async checkAuth(env: HostEnv): Promise<AuthStatus> {
90
+ const result = await env.exec(env.bin, ["--list-models"], { cwd: env.cwd, timeoutMs: 60_000 });
91
+ if (result.error) return { state: "unknown", detail: result.error };
92
+ const models = parseModelTable(result.stdout);
93
+ if (models.length > 0) {
94
+ const providers = [...new Set(models.map((model) => model.split("/")[0]))];
95
+ return { state: "ok", detail: `${models.length} models from ${providers.join(", ")}` };
96
+ }
97
+ if (/No models available/i.test(`${result.stdout}\n${result.stderr}`)) {
98
+ return { state: "missing", detail: "no provider credentials (run `pi` and /login, or set a provider API key)" };
99
+ }
100
+ return { state: "unknown", detail: clip(`${result.stdout}\n${result.stderr}`.trim() || "no output", 120) };
101
+ },
102
+
103
+ async listModels(env: HostEnv): Promise<string[]> {
104
+ const result = await env.exec(env.bin, ["--list-models"], { cwd: env.cwd, timeoutMs: 60_000 });
105
+ if (result.error || result.code !== 0) return [];
106
+ return parseModelTable(result.stdout);
107
+ },
108
+
109
+ buildInvocation(req: RunRequest): Invocation {
110
+ // A first run names its session up front (pi creates it and warns "No project session found with id ...,
111
+ // creating"), so the id is known even when the run dies before the session header. pi has no cwd flag: the
112
+ // workspace is the spawn cwd. Model and thinking are restated on every run.
113
+ const args = ["--mode", "json", "--session-id", req.sessionId ?? sessionUuidFromRunDir(req.runDir)];
114
+ if (req.model) args.push("--model", req.model);
115
+ if (req.effort) args.push("--thinking", req.effort);
116
+ // Project-local extensions, skills and settings load only when the user trusts the project.
117
+ args.push(req.projectTrusted ? "--approve" : "--no-approve");
118
+ args.push(...(req.extraArgs ?? []));
119
+ return { args, cwd: req.workspace, env: req.env, stdin: req.prompt, files: [] };
120
+ },
121
+
122
+ parseEvent(line: string, state: ParserState): NormalizedEvent[] {
123
+ return parsePiFamilyEvent(line, state, PI_OPTIONS);
124
+ },
125
+
126
+ finalize(raw, state) {
127
+ return finalizePiFamily(raw, state, PI_OPTIONS);
128
+ },
129
+ };
130
+
131
+ /** Parses one line of the pi JSON event stream. */
132
+ export function parsePiFamilyEvent(line: string, state: ParserState, options: PiFamilyOptions): NormalizedEvent[] {
133
+ const event = parseJsonLine(line);
134
+ if (!event) {
135
+ if (line.trim()) state.nonJsonLines++;
136
+ return [];
137
+ }
138
+ switch (getString(event, "type")) {
139
+ case "session":
140
+ return recordSession(state, getString(event, "id"));
141
+ case "message_end":
142
+ return parseMessageEnd(event.message, state);
143
+ case "tool_execution_start": {
144
+ const tool = getString(event, "toolName") ?? "tool";
145
+ return [{ type: "activity", kind: "tool", summary: `${tool} ${clip(summarizeArgs(event.args), 80)}`.trim() }];
146
+ }
147
+ case "tool_execution_end": {
148
+ if (event.isError !== true) return [];
149
+ const text = resultText(event.result);
150
+ if (!options.denialPattern.test(text)) return [];
151
+ return [recordDenied(state, `${getString(event, "toolName") ?? "tool"}: ${clip(text, 160)}`)];
152
+ }
153
+ case "turn_end":
154
+ state.usage.turns = (state.usage.turns ?? 0) + 1;
155
+ return [];
156
+ case "auto_retry_start": {
157
+ const message = `retry ${getNumber(event, "attempt") ?? "?"}/${getNumber(event, "maxAttempts") ?? "?"}: ${getString(event, "errorMessage") ?? "error"}`;
158
+ state.warnings.push(message);
159
+ return [{ type: "warning", message: clip(message, 200) }];
160
+ }
161
+ case "auto_retry_end": {
162
+ const finalError = getString(event, "finalError");
163
+ if (event.success === false && finalError) state.errors.push(finalError);
164
+ return [];
165
+ }
166
+ case "compaction_end":
167
+ case "auto_compaction_end": {
168
+ const message = getString(event, "errorMessage");
169
+ if (!message) return [];
170
+ state.warnings.push(message);
171
+ return [{ type: "warning", message: clip(`compaction failed: ${message}`, 200) }];
172
+ }
173
+ case "notice": {
174
+ const level = getString(event, "level");
175
+ const message = getString(event, "message");
176
+ if (!message || (level !== "warning" && level !== "error")) return [];
177
+ state.warnings.push(message);
178
+ return [{ type: "warning", message: clip(message, 200) }];
179
+ }
180
+ case "agent_settled":
181
+ if (event.aborted === true) state.extra.aborted = true;
182
+ return [];
183
+ default:
184
+ return [];
185
+ }
186
+ }
187
+
188
+ /** Classifies a pi-family run from the last assistant message, the exit code and stderr. */
189
+ export function finalizePiFamily(raw: RawRunResult, state: ParserState, options: PiFamilyOptions): AdapterOutcome {
190
+ const last = state.extra.lastAssistant as LastAssistant | undefined;
191
+ if (last?.stopReason === "stop") {
192
+ state.finalText = last.text;
193
+ state.terminal = { ok: true };
194
+ } else if (last) {
195
+ // `length`, `toolUse`, `error`, `aborted`: the run ended without a complete answer.
196
+ const detail = last.errorMessage || `stopped with ${last.stopReason}`;
197
+ state.terminal = { ok: false, reason: `${last.stopReason}: ${detail}` };
198
+ if (last.errorMessage) state.errors.push(last.errorMessage);
199
+ }
200
+ if (state.extra.aborted === true) state.terminal = { ok: false, reason: "aborted: the agent run was aborted" };
201
+
202
+ const outcome = standardFinalize(raw, state, { finalText: state.finalText ?? "" });
203
+ if (outcome.status === "completed") {
204
+ const structured = parseJsonAnswer(outcome.finalText);
205
+ if (structured !== undefined) outcome.structuredOutput = structured;
206
+ return outcome;
207
+ }
208
+ const status = last?.errorStatus;
209
+ if (status === 401 || status === 403) escalate(outcome, "auth_required", `http_${status}: ${clip(last?.errorMessage ?? "", 160)}`);
210
+ if (status === 402 || status === 429) escalate(outcome, "quota", `http_${status}: ${clip(last?.errorMessage ?? "", 160)}`);
211
+ for (const rule of options.stderrRules) {
212
+ const match = raw.stderr.split(/\r?\n/).find((line) => rule.pattern.test(line));
213
+ if (!match) continue;
214
+ const reason = `${rule.code}: ${clip(match, 160)}`;
215
+ // A failed run keeps its status but gets the more precise reason.
216
+ if (rule.status === "failed" && outcome.status === "failed") outcome.reason = reason;
217
+ else escalate(outcome, rule.status, reason);
218
+ }
219
+ return outcome;
220
+ }
221
+
222
+ /** Parses `--list-models` output: a table with the columns provider, model, context, max-out, thinking, images. */
223
+ export function parseModelTable(stdout: string): string[] {
224
+ const models: string[] = [];
225
+ for (const line of stdout.split(/\r?\n/)) {
226
+ const match = line.trim().match(/^(\S+)\s+(\S+)\s+\S+\s+\S+\s+(?:yes|no)\s+(?:yes|no)$/);
227
+ if (match) models.push(`${match[1]}/${match[2]}`);
228
+ }
229
+ return models;
230
+ }
231
+
232
+ function parseMessageEnd(message: unknown, state: ParserState): NormalizedEvent[] {
233
+ if (!isObject(message) || getString(message, "role") !== "assistant") return [];
234
+ const content = Array.isArray(message.content) ? message.content : [];
235
+ const text = content
236
+ .filter((block) => getString(block, "type") === "text")
237
+ .map((block) => getString(block, "text") ?? "")
238
+ .join("\n")
239
+ .trim();
240
+ state.extra.lastAssistant = {
241
+ stopReason: getString(message, "stopReason") ?? "unknown",
242
+ text,
243
+ errorMessage: getString(message, "errorMessage"),
244
+ errorStatus: getNumber(message, "errorStatus"),
245
+ } satisfies LastAssistant;
246
+ const events: NormalizedEvent[] = [...recordText(state, text)];
247
+ const usage = isObject(message.usage) ? message.usage : undefined;
248
+ if (usage) {
249
+ const input = sumDefined([getNumber(usage, "input"), getNumber(usage, "cacheRead"), getNumber(usage, "cacheWrite")]);
250
+ events.push(recordUsage(state, { inputTokens: input, outputTokens: getNumber(usage, "output"), costUsd: getNumber(usage, "cost", "total") }));
251
+ }
252
+ return events;
253
+ }
254
+
255
+ function resultText(result: unknown): string {
256
+ if (typeof result === "string") return result;
257
+ const content = isObject(result) && Array.isArray(result.content) ? result.content : [];
258
+ return content
259
+ .map((block) => getString(block, "text") ?? "")
260
+ .join("\n")
261
+ .trim();
262
+ }
263
+
264
+ function summarizeArgs(args: unknown): string {
265
+ if (!isObject(args)) return typeof args === "string" ? args : "";
266
+ for (const key of ["command", "path", "file_path", "pattern", "url", "query"]) {
267
+ const value = getString(args, key);
268
+ if (value) return value;
269
+ }
270
+ return JSON.stringify(args);
271
+ }
272
+
273
+ /** Replaces the outcome's status when `status` comes first in the precedence order. */
274
+ function escalate(outcome: AdapterOutcome, status: RunStatus, reason: string): void {
275
+ if (STATUS_PRECEDENCE.indexOf(status) < STATUS_PRECEDENCE.indexOf(outcome.status)) {
276
+ outcome.status = status;
277
+ outcome.reason = reason;
278
+ }
279
+ }
280
+
281
+ function sumDefined(values: Array<number | undefined>): number | undefined {
282
+ const present = values.filter((value): value is number => value !== undefined);
283
+ return present.length > 0 ? present.reduce((sum, value) => sum + value, 0) : undefined;
284
+ }
@@ -0,0 +1,27 @@
1
+ import { agyAdapter } from "./agy.ts";
2
+ import { claudeAdapter } from "./claude.ts";
3
+ import { codexAdapter } from "./codex.ts";
4
+ import { dshAdapter } from "./dsh.ts";
5
+ import { geminiAdapter } from "./gemini.ts";
6
+ import { grokAdapter } from "./grok.ts";
7
+ import { ompAdapter } from "./omp.ts";
8
+ import { opencodeAdapter } from "./opencode.ts";
9
+ import { piAdapter } from "./pi.ts";
10
+ import type { AgentAdapter } from "./types.ts";
11
+
12
+ /** The adapters that ship with the package, in the order `doctor` lists them. */
13
+ export const BUILTIN_ADAPTERS: readonly AgentAdapter[] = [
14
+ codexAdapter,
15
+ claudeAdapter,
16
+ opencodeAdapter,
17
+ piAdapter,
18
+ ompAdapter,
19
+ agyAdapter,
20
+ grokAdapter,
21
+ dshAdapter,
22
+ geminiAdapter,
23
+ ];
24
+
25
+ export function adapterMap(adapters: readonly AgentAdapter[] = BUILTIN_ADAPTERS): Map<string, AgentAdapter> {
26
+ return new Map(adapters.map((adapter) => [adapter.id, adapter]));
27
+ }