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.
- package/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/README.md +174 -2
- package/package.json +56 -4
- package/src/adapters/agy.ts +285 -0
- package/src/adapters/claude.ts +317 -0
- package/src/adapters/codex.ts +162 -0
- package/src/adapters/common.ts +211 -0
- package/src/adapters/cursor.ts +242 -0
- package/src/adapters/dsh.ts +356 -0
- package/src/adapters/fake-agent.mjs +50 -0
- package/src/adapters/fake.ts +88 -0
- package/src/adapters/gemini.ts +225 -0
- package/src/adapters/grok.ts +328 -0
- package/src/adapters/muse.ts +281 -0
- package/src/adapters/omp.ts +119 -0
- package/src/adapters/opencode.ts +228 -0
- package/src/adapters/pi.ts +284 -0
- package/src/adapters/registry.ts +31 -0
- package/src/adapters/types.ts +201 -0
- package/src/config/load.ts +290 -0
- package/src/config/profiles.ts +64 -0
- package/src/config/schema.ts +158 -0
- package/src/config/write.ts +83 -0
- package/src/engine/artifacts.ts +145 -0
- package/src/engine/baseline.ts +132 -0
- package/src/engine/execute.ts +437 -0
- package/src/engine/git.ts +32 -0
- package/src/engine/hostenv.ts +54 -0
- package/src/engine/registry.ts +280 -0
- package/src/engine/runner.ts +203 -0
- package/src/engine/types.ts +55 -0
- package/src/engine/verify.ts +100 -0
- package/src/index.ts +602 -0
- package/src/prompts/envelope.ts +29 -0
- package/src/prompts/templates.ts +389 -0
- package/src/ui/configure.ts +174 -0
- package/src/ui/dialogs.ts +88 -0
- package/src/ui/doctor.ts +120 -0
- package/src/ui/format.ts +94 -0
- package/src/ui/host.ts +100 -0
- package/src/ui/render.ts +86 -0
- package/src/ui/widget.ts +70 -0
- package/src/workflows/budget.ts +66 -0
- package/src/workflows/common.ts +100 -0
- package/src/workflows/debate.ts +488 -0
- package/src/workflows/host.ts +78 -0
- package/src/workflows/plan-exec.ts +807 -0
- package/src/workflows/plan.ts +407 -0
- package/src/workflows/planfile.ts +380 -0
- package/src/workflows/planstate.ts +229 -0
- package/src/workflows/verdict.ts +74 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import {
|
|
3
|
+
classifyFailureText,
|
|
4
|
+
clip,
|
|
5
|
+
detectByVersion,
|
|
6
|
+
getNumber,
|
|
7
|
+
getString,
|
|
8
|
+
isObject,
|
|
9
|
+
parseJsonAnswer,
|
|
10
|
+
parseJsonLine,
|
|
11
|
+
recordDenied,
|
|
12
|
+
recordSession,
|
|
13
|
+
recordUsage,
|
|
14
|
+
standardFinalize,
|
|
15
|
+
} from "./common.ts";
|
|
16
|
+
import type {
|
|
17
|
+
AdapterOutcome,
|
|
18
|
+
AgentAdapter,
|
|
19
|
+
HostEnv,
|
|
20
|
+
Invocation,
|
|
21
|
+
InvocationFile,
|
|
22
|
+
NormalizedEvent,
|
|
23
|
+
ParserState,
|
|
24
|
+
RawRunResult,
|
|
25
|
+
RunRequest,
|
|
26
|
+
RunStatus,
|
|
27
|
+
} from "./types.ts";
|
|
28
|
+
|
|
29
|
+
const EFFORT_LEVELS = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"] as const;
|
|
30
|
+
|
|
31
|
+
/** The launcher updates the binary in the background at most once an hour; this keeps the installed build. */
|
|
32
|
+
const NO_AUTO_UPDATE = { MUSE_NO_AUTO_UPDATE: "1" };
|
|
33
|
+
|
|
34
|
+
/** Failure texts the shared classifier does not recognize, in status precedence order. */
|
|
35
|
+
const MUSE_FAILURE_PATTERNS: Array<{ status: RunStatus; code: string; pattern: RegExp }> = [
|
|
36
|
+
{ status: "unavailable", code: "unknown_profile", pattern: /profile does not exist/i },
|
|
37
|
+
{
|
|
38
|
+
status: "unavailable",
|
|
39
|
+
code: "unsupported_flag",
|
|
40
|
+
pattern: /cannot be used with|may only be provided once|cannot be combined with|unknown effort tier|unknown option/i,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
status: "unavailable",
|
|
44
|
+
code: "model_unavailable",
|
|
45
|
+
pattern: /unsupported_provider_or_model|does not exist or you lack access|no matching model|model catalog has no visible models/i,
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
status: "auth_required",
|
|
49
|
+
code: "auth_required",
|
|
50
|
+
pattern: /API error 40[13]\b|muse login|run \/login|starting logged out|saved Meta credentials|no longer authorizes/i,
|
|
51
|
+
},
|
|
52
|
+
{ status: "quota", code: "quota", pattern: /API error 402\b|billing_error|no_allowance/i },
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Muse Code (`muse exec --json`). Stdout is JSONL; every record is an envelope with `stream`, `payload_type` and
|
|
57
|
+
* `payload`. The session id is `stream.id` of the records whose `stream.kind` is `session`. The first
|
|
58
|
+
* `run.lifecycle.started` is the assignment's run; only its `run.terminal.*` record decides the outcome (background
|
|
59
|
+
* wakes start further runs). Exit 0 only with a `completed` terminal; 1 for failed or cancelled runs, 2 for usage
|
|
60
|
+
* errors. Needs SIGTERM to stop.
|
|
61
|
+
*/
|
|
62
|
+
export const museAdapter: AgentAdapter = {
|
|
63
|
+
id: "muse",
|
|
64
|
+
displayName: "Muse Code",
|
|
65
|
+
binary: "muse",
|
|
66
|
+
testedVersions: ">=1.4.11 <1.5.0",
|
|
67
|
+
stability: "experimental",
|
|
68
|
+
liveChecked: "1.4.25 on 2026-11-25: auth failure and billing failure only (no working account)",
|
|
69
|
+
stopSignal: "SIGTERM",
|
|
70
|
+
trustFlag: "--trust-workspace",
|
|
71
|
+
capabilities: {
|
|
72
|
+
resume: true,
|
|
73
|
+
structuredOutput: true,
|
|
74
|
+
listModels: true,
|
|
75
|
+
effortLevels: EFFORT_LEVELS,
|
|
76
|
+
reportsCost: false,
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
detect(env: HostEnv) {
|
|
80
|
+
return detectByVersion(withoutAutoUpdate(env), this.testedVersions);
|
|
81
|
+
},
|
|
82
|
+
|
|
83
|
+
/** `muse exec --list-models` prints the provider's discoverable model ids and exits without a turn. */
|
|
84
|
+
async listModels(env: HostEnv): Promise<string[]> {
|
|
85
|
+
const result = await withoutAutoUpdate(env).exec(env.bin, ["exec", "--list-models"], { timeoutMs: 30_000 });
|
|
86
|
+
if (result.error) throw new Error(result.error);
|
|
87
|
+
if (result.code !== 0) {
|
|
88
|
+
throw new Error(`muse exec --list-models exited with ${result.code}: ${clip(`${result.stderr}\n${result.stdout}`, 200)}`);
|
|
89
|
+
}
|
|
90
|
+
const models = parseModelList(result.stdout);
|
|
91
|
+
if (models.length === 0) throw new Error(`no model ids in muse exec --list-models output: ${clip(result.stdout, 200)}`);
|
|
92
|
+
return models;
|
|
93
|
+
},
|
|
94
|
+
|
|
95
|
+
buildInvocation(req: RunRequest): Invocation {
|
|
96
|
+
const promptFile = join(req.runDir, "muse-prompt.md");
|
|
97
|
+
const files: InvocationFile[] = [{ path: promptFile, content: req.prompt }];
|
|
98
|
+
// A profile is always passed: without one the run uses the user's remembered or configured default.
|
|
99
|
+
const args = [
|
|
100
|
+
"exec", "--json",
|
|
101
|
+
"--workspace", req.workspace,
|
|
102
|
+
"--permission-profile", ":unrestricted",
|
|
103
|
+
"--disable-sandbox",
|
|
104
|
+
];
|
|
105
|
+
if (req.projectTrusted) args.push("--trust-workspace");
|
|
106
|
+
// A follow-up must use the same workspace: Muse refuses to resume a session in another one.
|
|
107
|
+
if (req.sessionId) args.push("--session-id", req.sessionId);
|
|
108
|
+
if (req.model) args.push("--model", req.model);
|
|
109
|
+
if (req.effort) args.push("--reasoning-effort", req.effort);
|
|
110
|
+
if (req.outputSchema) {
|
|
111
|
+
const schemaPath = join(req.runDir, "output-schema.json");
|
|
112
|
+
files.push({ path: schemaPath, content: JSON.stringify(req.outputSchema, null, 2) });
|
|
113
|
+
args.push("--output-schema", schemaPath);
|
|
114
|
+
}
|
|
115
|
+
args.push("--prompt-file", promptFile, ...(req.extraArgs ?? []));
|
|
116
|
+
return {
|
|
117
|
+
args,
|
|
118
|
+
cwd: req.workspace,
|
|
119
|
+
env: { ...req.env, ...NO_AUTO_UPDATE },
|
|
120
|
+
files,
|
|
121
|
+
};
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
parseEvent(line: string, state: ParserState): NormalizedEvent[] {
|
|
125
|
+
const record = parseJsonLine(line);
|
|
126
|
+
if (!record) {
|
|
127
|
+
if (line.trim()) state.nonJsonLines++;
|
|
128
|
+
return [];
|
|
129
|
+
}
|
|
130
|
+
const events: NormalizedEvent[] = [];
|
|
131
|
+
if (getString(record, "stream", "kind") === "session") {
|
|
132
|
+
events.push(...recordSession(state, getString(record, "stream", "id")));
|
|
133
|
+
}
|
|
134
|
+
const type = getString(record, "payload_type") ?? "";
|
|
135
|
+
const payload = isObject(record.payload) ? record.payload : {};
|
|
136
|
+
const runId = runStreamId(payload);
|
|
137
|
+
|
|
138
|
+
if (type === "run.lifecycle.started") {
|
|
139
|
+
if (state.extra.runId === undefined && runId) state.extra.runId = runId;
|
|
140
|
+
return events;
|
|
141
|
+
}
|
|
142
|
+
if (type.startsWith("run.terminal.")) {
|
|
143
|
+
if (!isAssignmentRun(state, runId)) return events;
|
|
144
|
+
const kind = type.slice("run.terminal.".length);
|
|
145
|
+
const reason = field(payload, "reason");
|
|
146
|
+
state.finalText = field(payload, "text") ?? "";
|
|
147
|
+
state.extra.terminalKind = kind;
|
|
148
|
+
if (kind === "completed") {
|
|
149
|
+
state.terminal = { ok: true };
|
|
150
|
+
} else {
|
|
151
|
+
const message = reason ?? `run ${kind}`;
|
|
152
|
+
state.terminal = { ok: false, reason: `${kind}: ${message}` };
|
|
153
|
+
state.errors.push(message);
|
|
154
|
+
}
|
|
155
|
+
return events;
|
|
156
|
+
}
|
|
157
|
+
switch (type) {
|
|
158
|
+
case "run.model.configured": {
|
|
159
|
+
const model = field(payload, "model_id");
|
|
160
|
+
if (model) state.extra.model = model;
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
case "run.usage":
|
|
164
|
+
if (isAssignmentRun(state, runId, true)) events.push(...parseUsage(payload, state));
|
|
165
|
+
break;
|
|
166
|
+
case "task.lifecycle.side_effect_intent": {
|
|
167
|
+
const operation = field(payload, "operation") ?? "tool";
|
|
168
|
+
const decision = field(payload, "policy_decision");
|
|
169
|
+
if (decision?.startsWith("deny")) {
|
|
170
|
+
state.extra.deniedOperation = operation;
|
|
171
|
+
events.push(recordDenied(state, clip(`${operation}: ${decision}`, 200)));
|
|
172
|
+
} else {
|
|
173
|
+
events.push({ type: "activity", kind: "tool", summary: clip(operation, 100) });
|
|
174
|
+
}
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
case "task.lifecycle.rejected": {
|
|
178
|
+
const reason = field(payload, "reason") ?? "rejected";
|
|
179
|
+
events.push(recordDenied(state, clip(`${taskLabel(payload)}: ${reason}`, 200)));
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
case "task.lifecycle.failed": {
|
|
183
|
+
// Failed tasks of background reminder agents do not fail the run, so they are warnings, not errors.
|
|
184
|
+
const reason = field(payload, "reason") ?? "task failed";
|
|
185
|
+
const kind = field(payload, "failure_kind");
|
|
186
|
+
if (kind && /^policy_?denied$/i.test(kind)) {
|
|
187
|
+
// The denied intent of the same operation was already recorded.
|
|
188
|
+
const label = taskLabel(payload);
|
|
189
|
+
if (state.extra.deniedOperation === label) state.extra.deniedOperation = undefined;
|
|
190
|
+
else events.push(recordDenied(state, clip(`${label}: ${reason}`, 200)));
|
|
191
|
+
} else {
|
|
192
|
+
const message = `task failed: ${reason}`;
|
|
193
|
+
state.warnings.push(message);
|
|
194
|
+
events.push({ type: "warning", message: clip(message, 200) });
|
|
195
|
+
}
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return events;
|
|
200
|
+
},
|
|
201
|
+
|
|
202
|
+
finalize(raw: RawRunResult, state: ParserState): AdapterOutcome {
|
|
203
|
+
let effective = state;
|
|
204
|
+
if (!state.terminal && raw.exitCode === 0) {
|
|
205
|
+
effective = { ...state, terminal: { ok: false, reason: "no terminal record for the assignment run" } };
|
|
206
|
+
}
|
|
207
|
+
let outcome = standardFinalize(raw, effective);
|
|
208
|
+
outcome = refineFailure(outcome, [...state.errors, effective.terminal?.reason ?? "", raw.stderr].join("\n"));
|
|
209
|
+
if (outcome.status === "failed" && raw.exitCode === 2 && state.extra.runId === undefined) {
|
|
210
|
+
// Usage errors (an unknown or conflicting flag) exit 2 before any run starts.
|
|
211
|
+
const line = raw.stderr.split(/\r?\n/).find((candidate) => candidate.trim());
|
|
212
|
+
outcome = { ...outcome, status: "unavailable", reason: `usage_error: ${clip(line ?? "exit code 2", 200)}` };
|
|
213
|
+
}
|
|
214
|
+
const structured = parseJsonAnswer(outcome.finalText);
|
|
215
|
+
if (structured !== undefined) outcome.structuredOutput = structured;
|
|
216
|
+
return outcome;
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
function withoutAutoUpdate(env: HostEnv): HostEnv {
|
|
221
|
+
return {
|
|
222
|
+
...env,
|
|
223
|
+
exec: (command, args, options) => env.exec(command, args, { ...options, env: { ...options?.env, ...NO_AUTO_UPDATE } }),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Payload fields sit at the top level, or under `event` or `record` in some record types. */
|
|
228
|
+
function field(payload: Record<string, unknown>, key: string): string | undefined {
|
|
229
|
+
return getString(payload, key) ?? getString(payload, "event", key) ?? getString(payload, "record", key);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function runStreamId(payload: Record<string, unknown>): string | undefined {
|
|
233
|
+
return (
|
|
234
|
+
getString(payload, "run_stream", "id") ??
|
|
235
|
+
getString(payload, "event", "run_stream", "id") ??
|
|
236
|
+
getString(payload, "record", "run_stream", "id")
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Whether a record belongs to the assignment's run. Records without a run id count only when `lenient`. */
|
|
241
|
+
function isAssignmentRun(state: ParserState, runId: string | undefined, lenient = false): boolean {
|
|
242
|
+
const assignment = state.extra.runId as string | undefined;
|
|
243
|
+
if (!runId || !assignment) return lenient || state.extra.terminalKind === undefined;
|
|
244
|
+
return runId === assignment;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function taskLabel(payload: Record<string, unknown>): string {
|
|
248
|
+
return field(payload, "operation") ?? field(payload, "task_kind") ?? field(payload, "tool_name") ?? "task";
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** `run.usage` carries `input_tokens`, `cached_tokens` and `output_tokens` for the run so far. */
|
|
252
|
+
function parseUsage(payload: Record<string, unknown>, state: ParserState): NormalizedEvent[] {
|
|
253
|
+
const source = isObject(payload.record) ? payload.record : payload;
|
|
254
|
+
const input = getNumber(source, "input_tokens") ?? getNumber(source, "usage", "input_tokens");
|
|
255
|
+
const output = getNumber(source, "output_tokens") ?? getNumber(source, "usage", "output_tokens");
|
|
256
|
+
if (input === undefined && output === undefined) return [];
|
|
257
|
+
return [recordUsage(state, { inputTokens: input, outputTokens: output }, "replace")];
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Second classification pass for failures the shared patterns left as `failed` (or as an answerless denial). */
|
|
261
|
+
function refineFailure(outcome: AdapterOutcome, text: string): AdapterOutcome {
|
|
262
|
+
const unclassified = outcome.status === "failed" || (outcome.status === "denied" && !outcome.finalText);
|
|
263
|
+
if (!unclassified || !text.trim()) return outcome;
|
|
264
|
+
const lines = text.split(/\r?\n/).filter((line) => line.trim());
|
|
265
|
+
for (const { status, code, pattern } of MUSE_FAILURE_PATTERNS) {
|
|
266
|
+
const line = lines.find((candidate) => pattern.test(candidate));
|
|
267
|
+
if (line) return { ...outcome, status, reason: `${code}: ${clip(line, 200)}` };
|
|
268
|
+
}
|
|
269
|
+
const cls = classifyFailureText(text);
|
|
270
|
+
return cls ? { ...outcome, status: cls.status, reason: `${cls.code}: ${cls.line}` } : outcome;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** One model id per line, optionally bulleted or followed by a parenthesized note; anything else is ignored. */
|
|
274
|
+
function parseModelList(stdout: string): string[] {
|
|
275
|
+
const models: string[] = [];
|
|
276
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
277
|
+
const match = line.match(/^\s*(?:[*-]\s+)?([A-Za-z0-9][\w.:/@-]*)\s*(?:\([^)]*\))?\s*$/);
|
|
278
|
+
if (match) models.push(match[1]);
|
|
279
|
+
}
|
|
280
|
+
return [...new Set(models)];
|
|
281
|
+
}
|
|
@@ -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, 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",
|
|
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
|
+
}
|