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,88 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { clip, getNumber, getString, parseJsonLine, recordDenied, recordSession, recordText, recordUsage, standardFinalize } from "./common.ts";
|
|
4
|
+
import type { AgentAdapter, Invocation, NormalizedEvent, ParserState, RunRequest } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
export const FAKE_AGENT_SCRIPT = join(import.meta.dirname, "fake-agent.mjs");
|
|
7
|
+
|
|
8
|
+
export interface FakeScenario {
|
|
9
|
+
steps?: Array<Record<string, unknown>>;
|
|
10
|
+
exitCode?: number;
|
|
11
|
+
recordPrompt?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface FakeAdapterOptions {
|
|
15
|
+
id?: string;
|
|
16
|
+
stopSignal?: "SIGINT" | "SIGTERM";
|
|
17
|
+
resume?: boolean;
|
|
18
|
+
/** Picks the scenario of a run; defaults to `options.scenario` of the profile. */
|
|
19
|
+
scenarioFor?: (req: RunRequest) => FakeScenario;
|
|
20
|
+
watchStderr?: AgentAdapter["watchStderr"];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Scripted adapter for tests: runs `fake-agent.mjs` under the current Node with a scenario file. */
|
|
24
|
+
export function createFakeAdapter(options: FakeAdapterOptions = {}): AgentAdapter {
|
|
25
|
+
return {
|
|
26
|
+
id: options.id ?? "fake",
|
|
27
|
+
displayName: "Fake agent",
|
|
28
|
+
binary: process.execPath,
|
|
29
|
+
testedVersions: ">=1.0.0",
|
|
30
|
+
stability: "stable",
|
|
31
|
+
stopSignal: options.stopSignal ?? "SIGTERM",
|
|
32
|
+
watchStderr: options.watchStderr,
|
|
33
|
+
optionsSchema: Type.Object({ scenario: Type.Optional(Type.Unknown()) }, { additionalProperties: false }),
|
|
34
|
+
capabilities: { resume: options.resume ?? true, structuredOutput: false, listModels: false, reportsCost: false },
|
|
35
|
+
|
|
36
|
+
async detect() {
|
|
37
|
+
return { available: true, path: process.execPath, version: "1.0.0", inTestedRange: true };
|
|
38
|
+
},
|
|
39
|
+
|
|
40
|
+
buildInvocation(req: RunRequest): Invocation {
|
|
41
|
+
const scenario = options.scenarioFor?.(req) ?? ((req.options?.scenario as FakeScenario | undefined) ?? { steps: [] });
|
|
42
|
+
const scenarioPath = join(req.runDir, "scenario.json");
|
|
43
|
+
return {
|
|
44
|
+
args: [FAKE_AGENT_SCRIPT, scenarioPath, ...(req.sessionId ? ["--resume", req.sessionId] : [])],
|
|
45
|
+
cwd: req.workspace,
|
|
46
|
+
stdin: req.prompt,
|
|
47
|
+
files: [{ path: scenarioPath, content: JSON.stringify(scenario) }],
|
|
48
|
+
};
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
parseEvent(line: string, state: ParserState): NormalizedEvent[] {
|
|
52
|
+
const event = parseJsonLine(line);
|
|
53
|
+
if (!event) {
|
|
54
|
+
if (line.trim()) state.nonJsonLines++;
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
switch (getString(event, "type")) {
|
|
58
|
+
case "session":
|
|
59
|
+
return recordSession(state, getString(event, "id"));
|
|
60
|
+
case "text":
|
|
61
|
+
return recordText(state, getString(event, "text"));
|
|
62
|
+
case "tool":
|
|
63
|
+
return [{ type: "activity", kind: "tool", summary: clip(getString(event, "name") ?? "tool") }];
|
|
64
|
+
case "denied":
|
|
65
|
+
return [recordDenied(state, getString(event, "action") ?? "action")];
|
|
66
|
+
case "usage":
|
|
67
|
+
return [recordUsage(state, { inputTokens: getNumber(event, "input"), outputTokens: getNumber(event, "output") })];
|
|
68
|
+
case "error":
|
|
69
|
+
state.errors.push(getString(event, "message") ?? "error");
|
|
70
|
+
return [{ type: "warning", message: getString(event, "message") ?? "error" }];
|
|
71
|
+
case "result": {
|
|
72
|
+
const ok = event.ok !== false;
|
|
73
|
+
state.terminal = { ok, reason: ok ? undefined : getString(event, "text") };
|
|
74
|
+
if (ok) state.finalText = getString(event, "text");
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
default:
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
finalize(raw, state) {
|
|
83
|
+
return standardFinalize(raw, state);
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export const fakeAdapter = createFakeAdapter();
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import {
|
|
2
|
+
classifyFailureText,
|
|
3
|
+
clip,
|
|
4
|
+
detectByVersion,
|
|
5
|
+
getNumber,
|
|
6
|
+
getString,
|
|
7
|
+
isObject,
|
|
8
|
+
parseJsonLine,
|
|
9
|
+
recordDenied,
|
|
10
|
+
recordSession,
|
|
11
|
+
recordText,
|
|
12
|
+
recordUsage,
|
|
13
|
+
standardFinalize,
|
|
14
|
+
} from "./common.ts";
|
|
15
|
+
import type { AdapterOutcome, AgentAdapter, HostEnv, Invocation, NormalizedEvent, ParserState, RawRunResult, RunRequest, RunStatus } from "./types.ts";
|
|
16
|
+
|
|
17
|
+
/** Fatal exit codes of `packages/core` (`ExitCodes`, `Fatal*Error.exitCode`) with a fixed meaning. */
|
|
18
|
+
const EXIT_CODES: Record<number, { status: RunStatus; code: string }> = {
|
|
19
|
+
41: { status: "auth_required", code: "auth_required" },
|
|
20
|
+
42: { status: "failed", code: "input_error" },
|
|
21
|
+
44: { status: "unavailable", code: "sandbox_error" },
|
|
22
|
+
52: { status: "unavailable", code: "config_error" },
|
|
23
|
+
53: { status: "failed", code: "turn_limit" },
|
|
24
|
+
54: { status: "failed", code: "fatal_tool_error" },
|
|
25
|
+
55: { status: "unavailable", code: "untrusted_workspace" },
|
|
26
|
+
// An API error exits with its HTTP status (`extractErrorCode`), which the OS truncates to 8 bits.
|
|
27
|
+
145: { status: "auth_required", code: "auth_required" }, // 401
|
|
28
|
+
173: { status: "quota", code: "quota" }, // 429
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const RESUME_ERROR = /Error resuming session|Invalid session identifier|No previous sessions found/i;
|
|
32
|
+
const BLOCKED = /^Agent execution blocked:/;
|
|
33
|
+
const MAX_TURNS = /^Maximum session turns exceeded/;
|
|
34
|
+
/** Notices printed at every start; never the reason a run failed. */
|
|
35
|
+
const APPROVAL_OVERRIDDEN = /^Approval mode overridden to "?(\w+)"? because the current folder is not trusted/m;
|
|
36
|
+
const STARTUP_NOTICE = /^(YOLO mode is enabled|Approval mode overridden|Loaded cached credentials|Data collection is disabled)/;
|
|
37
|
+
|
|
38
|
+
interface GeminiExtra {
|
|
39
|
+
/** Assistant text since the last tool event. */
|
|
40
|
+
segment?: string;
|
|
41
|
+
sawResult?: boolean;
|
|
42
|
+
maxTurns?: boolean;
|
|
43
|
+
stoppedByHook?: string;
|
|
44
|
+
calls?: Record<string, string>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Gemini CLI (`gemini -o stream-json -p ""`, prompt on stdin). Event schema: `StreamJsonFormatter` and
|
|
49
|
+
* `runNonInteractive` of the 0.51.0 bundle (init, message deltas, tool_use, tool_result, error, result).
|
|
50
|
+
* SIGINT, SIGTERM and SIGHUP all run a graceful shutdown that exits 0, so a stopped run can exit 0
|
|
51
|
+
* without a `result` event.
|
|
52
|
+
*/
|
|
53
|
+
export const geminiAdapter: AgentAdapter = {
|
|
54
|
+
id: "gemini",
|
|
55
|
+
displayName: "Gemini CLI",
|
|
56
|
+
binary: "gemini",
|
|
57
|
+
testedVersions: ">=0.51.0 <0.60.0",
|
|
58
|
+
stability: "experimental",
|
|
59
|
+
liveChecked: "0.51.0 on 2026-11-25: auth failure only (no working auth method)",
|
|
60
|
+
stopSignal: "SIGTERM",
|
|
61
|
+
capabilities: {
|
|
62
|
+
resume: true,
|
|
63
|
+
structuredOutput: false,
|
|
64
|
+
listModels: false,
|
|
65
|
+
reportsCost: false,
|
|
66
|
+
},
|
|
67
|
+
trustFlag: "--skip-trust",
|
|
68
|
+
|
|
69
|
+
detect(env: HostEnv) {
|
|
70
|
+
return detectByVersion(env, this.testedVersions);
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
buildInvocation(req: RunRequest): Invocation {
|
|
74
|
+
// `--approval-mode yolo` alone: combining it with `-y` is rejected. With folder trust enabled and an
|
|
75
|
+
// untrusted folder, the CLI overrides yolo to the default approval mode (observed in 0.51.0, see finalize).
|
|
76
|
+
const args = ["-o", "stream-json", "--approval-mode", "yolo"];
|
|
77
|
+
if (req.projectTrusted) args.push("--skip-trust");
|
|
78
|
+
// `--resume` takes the exact session UUID; `--session-id` only names a new session.
|
|
79
|
+
if (req.sessionId) args.push("--resume", req.sessionId);
|
|
80
|
+
if (req.model) args.push("-m", req.model);
|
|
81
|
+
// An empty `-p` selects headless mode; the prompt is read from stdin (`-p` text would be appended to it).
|
|
82
|
+
args.push(...(req.extraArgs ?? []), "-p", "");
|
|
83
|
+
return {
|
|
84
|
+
args,
|
|
85
|
+
cwd: req.workspace,
|
|
86
|
+
// GEMINI_SANDBOX overrides both argv and settings: no relaunch inside docker or podman.
|
|
87
|
+
env: { ...req.env, GEMINI_SANDBOX: "false" },
|
|
88
|
+
stdin: req.prompt,
|
|
89
|
+
files: [],
|
|
90
|
+
outputFiles: {},
|
|
91
|
+
};
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
parseEvent(line: string, state: ParserState): NormalizedEvent[] {
|
|
95
|
+
const event = parseJsonLine(line);
|
|
96
|
+
if (!event) {
|
|
97
|
+
if (line.trim()) state.nonJsonLines++;
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
const extra = state.extra as GeminiExtra;
|
|
101
|
+
switch (getString(event, "type")) {
|
|
102
|
+
case "init":
|
|
103
|
+
return recordSession(state, getString(event, "session_id"));
|
|
104
|
+
case "message": {
|
|
105
|
+
if (getString(event, "role") !== "assistant") return [];
|
|
106
|
+
extra.segment = (extra.segment ?? "") + (getString(event, "content") ?? "");
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
case "tool_use": {
|
|
110
|
+
const events = flushSegment(state, extra);
|
|
111
|
+
const summary = toolSummary(getString(event, "tool_name") ?? "tool", event.parameters);
|
|
112
|
+
const toolId = getString(event, "tool_id");
|
|
113
|
+
if (toolId) extra.calls = { ...extra.calls, [toolId]: summary };
|
|
114
|
+
return [...events, { type: "activity", kind: "tool", summary }];
|
|
115
|
+
}
|
|
116
|
+
case "tool_result":
|
|
117
|
+
return parseToolResult(event, state, extra);
|
|
118
|
+
case "error": {
|
|
119
|
+
const message = getString(event, "message") ?? "error";
|
|
120
|
+
if (BLOCKED.test(message)) return [recordDenied(state, clip(message, 200))];
|
|
121
|
+
if (MAX_TURNS.test(message)) extra.maxTurns = true;
|
|
122
|
+
if (getString(event, "severity") === "error") state.errors.push(message);
|
|
123
|
+
else state.warnings.push(message);
|
|
124
|
+
return [{ type: "warning", message: clip(message, 200) }];
|
|
125
|
+
}
|
|
126
|
+
case "result": {
|
|
127
|
+
const final = extra.segment ?? "";
|
|
128
|
+
const events = flushSegment(state, extra);
|
|
129
|
+
extra.sawResult = true;
|
|
130
|
+
state.finalText = final;
|
|
131
|
+
if (getString(event, "status") === "success") {
|
|
132
|
+
state.terminal = { ok: true };
|
|
133
|
+
} else {
|
|
134
|
+
const type = getString(event, "error", "type") ?? "error";
|
|
135
|
+
const message = getString(event, "error", "message") ?? "the run failed";
|
|
136
|
+
state.terminal = { ok: false, reason: `${type}: ${message}` };
|
|
137
|
+
state.errors.push(message);
|
|
138
|
+
}
|
|
139
|
+
if (!isObject(event.stats)) return events;
|
|
140
|
+
state.usage.turns = (state.usage.turns ?? 0) + 1;
|
|
141
|
+
const usage = recordUsage(
|
|
142
|
+
state,
|
|
143
|
+
{ inputTokens: getNumber(event, "stats", "input_tokens"), outputTokens: getNumber(event, "stats", "output_tokens") },
|
|
144
|
+
"replace",
|
|
145
|
+
);
|
|
146
|
+
return [...events, usage];
|
|
147
|
+
}
|
|
148
|
+
default:
|
|
149
|
+
return [];
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
finalize(raw, state) {
|
|
154
|
+
const outcome = finalizeRun(raw, state);
|
|
155
|
+
const overridden = APPROVAL_OVERRIDDEN.exec(raw.stderr);
|
|
156
|
+
if (!overridden) return outcome;
|
|
157
|
+
const warning = `Gemini CLI ran in its "${overridden[1]}" approval mode because the folder is not trusted: tool calls that need approval are refused. Trusting the project in pi passes --skip-trust.`;
|
|
158
|
+
return { ...outcome, warnings: [...(outcome.warnings ?? []), warning] };
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
function finalizeRun(raw: RawRunResult, state: ParserState): AdapterOutcome {
|
|
163
|
+
const extra = state.extra as GeminiExtra;
|
|
164
|
+
if (raw.spawnError) return standardFinalize(raw, state);
|
|
165
|
+
// The final answer is the text after the last tool event; a stream without `result` was cut short.
|
|
166
|
+
const finalText = extra.sawResult ? state.finalText : extra.segment;
|
|
167
|
+
if (extra.stoppedByHook) {
|
|
168
|
+
state.terminal = { ok: false, reason: `stopped by hook: ${extra.stoppedByHook}` };
|
|
169
|
+
} else if (extra.maxTurns) {
|
|
170
|
+
state.terminal = { ok: false, reason: "turn_limit: Maximum session turns exceeded" };
|
|
171
|
+
} else if (!extra.sawResult) {
|
|
172
|
+
state.terminal = { ok: false, reason: "no result event: the CLI stopped before the run finished" };
|
|
173
|
+
}
|
|
174
|
+
const outcome = standardFinalize(raw, state, { finalText: finalText ?? "" });
|
|
175
|
+
const fixed = raw.exitCode === null ? undefined : EXIT_CODES[raw.exitCode];
|
|
176
|
+
if (!fixed || outcome.status === "completed") return outcome;
|
|
177
|
+
const failureText = [...state.errors, raw.stderr].join("\n");
|
|
178
|
+
const line =
|
|
179
|
+
classifyFailureText(failureText)?.line ??
|
|
180
|
+
clip(failureText.split(/\r?\n/).find((candidate) => candidate.trim() && !STARTUP_NOTICE.test(candidate)) ?? `exited with ${raw.exitCode}`, 200);
|
|
181
|
+
if (raw.exitCode === 42 && RESUME_ERROR.test(failureText)) {
|
|
182
|
+
const resumeLine = failureText.split(/\r?\n/).find((candidate) => RESUME_ERROR.test(candidate)) ?? line;
|
|
183
|
+
return { ...outcome, status: "failed", reason: `resume_failed: ${clip(resumeLine, 200)}` };
|
|
184
|
+
}
|
|
185
|
+
// Exit codes with a fixed class win over text classification; failure codes only refine a failed run.
|
|
186
|
+
if (fixed.status !== "failed") return { ...outcome, status: fixed.status, reason: `${fixed.code}: ${line}` };
|
|
187
|
+
if (outcome.status === "failed") return { ...outcome, reason: `${fixed.code}: ${line}` };
|
|
188
|
+
return outcome;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function flushSegment(state: ParserState, extra: GeminiExtra): NormalizedEvent[] {
|
|
192
|
+
const segment = extra.segment ?? "";
|
|
193
|
+
extra.segment = "";
|
|
194
|
+
return recordText(state, segment);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function parseToolResult(event: Record<string, unknown>, state: ParserState, extra: GeminiExtra): NormalizedEvent[] {
|
|
198
|
+
if (getString(event, "status") !== "error") return [];
|
|
199
|
+
const toolId = getString(event, "tool_id");
|
|
200
|
+
const tool = (toolId && extra.calls?.[toolId]) || "tool";
|
|
201
|
+
const type = getString(event, "error", "type");
|
|
202
|
+
const message = getString(event, "error", "message") ?? "";
|
|
203
|
+
// policy_violation: a policy rule or a BeforeTool hook blocked the call. stop_execution: a hook ended the run.
|
|
204
|
+
// permission_denied is a file-system error, not a rule of the user's.
|
|
205
|
+
if (type === "policy_violation") return [recordDenied(state, `${clip(tool, 120)}: ${clip(message, 120)}`)];
|
|
206
|
+
if (type === "stop_execution") {
|
|
207
|
+
extra.stoppedByHook = clip(message, 160);
|
|
208
|
+
return [recordDenied(state, `${clip(tool, 120)}: ${clip(message, 120)}`)];
|
|
209
|
+
}
|
|
210
|
+
return [];
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function toolSummary(tool: string, parameters: unknown): string {
|
|
214
|
+
const command = getString(parameters, "command");
|
|
215
|
+
if (command) return `$ ${clip(command, 90)}`;
|
|
216
|
+
const path =
|
|
217
|
+
getString(parameters, "file_path") ??
|
|
218
|
+
getString(parameters, "absolute_path") ??
|
|
219
|
+
getString(parameters, "path") ??
|
|
220
|
+
getString(parameters, "dir_path");
|
|
221
|
+
if (path) return `${tool} ${clip(path, 90)}`;
|
|
222
|
+
const pattern = getString(parameters, "pattern") ?? getString(parameters, "query");
|
|
223
|
+
if (pattern) return `${tool} ${clip(pattern, 80)}`;
|
|
224
|
+
return tool;
|
|
225
|
+
}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
classifyFailureText,
|
|
5
|
+
clip,
|
|
6
|
+
detectByVersion,
|
|
7
|
+
getNumber,
|
|
8
|
+
getString,
|
|
9
|
+
isObject,
|
|
10
|
+
parseJsonAnswer,
|
|
11
|
+
parseJsonLine,
|
|
12
|
+
recordDenied,
|
|
13
|
+
recordSession,
|
|
14
|
+
recordText,
|
|
15
|
+
recordUsage,
|
|
16
|
+
standardFinalize,
|
|
17
|
+
} from "./common.ts";
|
|
18
|
+
import type {
|
|
19
|
+
AdapterOutcome,
|
|
20
|
+
AgentAdapter,
|
|
21
|
+
HostEnv,
|
|
22
|
+
Invocation,
|
|
23
|
+
InvocationFile,
|
|
24
|
+
NormalizedEvent,
|
|
25
|
+
ParserState,
|
|
26
|
+
RawRunResult,
|
|
27
|
+
RunRequest,
|
|
28
|
+
RunStatus,
|
|
29
|
+
} from "./types.ts";
|
|
30
|
+
|
|
31
|
+
const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
32
|
+
|
|
33
|
+
/** Failure texts the shared classifier does not recognize, in status precedence order. */
|
|
34
|
+
const GROK_FAILURE_PATTERNS: Array<{ status: RunStatus; code: string; pattern: RegExp }> = [
|
|
35
|
+
{ status: "unavailable", code: "model_unavailable", pattern: /couldn't set model|run 'grok models'/i },
|
|
36
|
+
{ status: "unavailable", code: "unsupported_flag", pattern: /unknown effort level/i },
|
|
37
|
+
{
|
|
38
|
+
status: "auth_required",
|
|
39
|
+
code: "auth_required",
|
|
40
|
+
pattern:
|
|
41
|
+
/not signed in|grok login|open this URL (in your browser|to sign in)|then enter this code|confirm this code in your browser|waiting for authorization|sign-in is not available/i,
|
|
42
|
+
},
|
|
43
|
+
{ status: "quota", code: "quota", pattern: /hit (the|your( team.s)?) (api )?rate limit|free grok build usage|free-usage-exhausted/i },
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
const LOGIN_WAIT = /open this URL (in your browser|to sign in)|then enter this code|confirm this code in your browser|waiting for authorization/i;
|
|
47
|
+
|
|
48
|
+
/** Tool results that mean a user rule or hook blocked the call (`--always-approve` keeps them in force). */
|
|
49
|
+
const DENIAL_TEXT = /(?:denied by permission policy|denied by hook|blocked by hook)[^"\\]{0,120}/i;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Grok Build (`grok`) in headless single-turn mode with `--output-format streaming-json`: one ACP-derived object per
|
|
53
|
+
* line (`text`, `thought`, `tool_call`, `tool_call_update`, `usage`, `error`, ...) and a terminal `end` line with
|
|
54
|
+
* `stopReason`, `sessionId`, usage and spend. A turn that ends with `stopReason: cancelled` still exits 0.
|
|
55
|
+
* Interrupts on SIGINT (exit 130, no `end` line); the session is kept.
|
|
56
|
+
*/
|
|
57
|
+
export const grokAdapter: AgentAdapter = {
|
|
58
|
+
id: "grok",
|
|
59
|
+
displayName: "Grok Build",
|
|
60
|
+
binary: "grok",
|
|
61
|
+
testedVersions: ">=1.0.62 <1.1.0",
|
|
62
|
+
stability: "experimental",
|
|
63
|
+
liveChecked: "1.0.77 on 2026-11-25: analyze, implement, follow-up, cancellation, auth failure",
|
|
64
|
+
stopSignal: "SIGINT",
|
|
65
|
+
watchStderr(stderr) {
|
|
66
|
+
// Without a stored login, grok prints a sign-in URL or device code and waits for the browser.
|
|
67
|
+
return LOGIN_WAIT.test(stderr) ? { status: "auth_required", reason: "auth_required: grok is waiting for an interactive login; run `grok login`" } : undefined;
|
|
68
|
+
},
|
|
69
|
+
capabilities: {
|
|
70
|
+
resume: true,
|
|
71
|
+
structuredOutput: true,
|
|
72
|
+
listModels: true,
|
|
73
|
+
effortLevels: EFFORT_LEVELS,
|
|
74
|
+
reportsCost: true,
|
|
75
|
+
},
|
|
76
|
+
// `--trust` persists the grant in the user's trust store, so it is not a per-run trust flag.
|
|
77
|
+
|
|
78
|
+
detect(env: HostEnv) {
|
|
79
|
+
return detectByVersion(env, this.testedVersions);
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
/** `grok models` lists the account's models without starting a turn. */
|
|
83
|
+
async listModels(env: HostEnv): Promise<string[]> {
|
|
84
|
+
const result = await env.exec(env.bin, ["models"], { timeoutMs: 30_000 });
|
|
85
|
+
if (result.error) throw new Error(result.error);
|
|
86
|
+
const text = `${result.stdout}\n${result.stderr}`;
|
|
87
|
+
if (result.code !== 0) throw new Error(`grok models exited with ${result.code}: ${clip(text, 200)}`);
|
|
88
|
+
return parseModelList(result.stdout);
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
buildInvocation(req: RunRequest): Invocation {
|
|
92
|
+
// A `.json` prompt file is parsed as ACP content blocks, so the prompt goes in a Markdown file.
|
|
93
|
+
const promptFile = join(req.runDir, "grok-prompt.md");
|
|
94
|
+
const files: InvocationFile[] = [{ path: promptFile, content: req.prompt }];
|
|
95
|
+
const args = [
|
|
96
|
+
"--prompt-file", promptFile,
|
|
97
|
+
"--cwd", req.workspace,
|
|
98
|
+
"--output-format", "streaming-json",
|
|
99
|
+
"--always-approve",
|
|
100
|
+
];
|
|
101
|
+
// The session id only appears on the final `end` line, which an interrupted run never prints. A first run gets a
|
|
102
|
+
// deterministic id chosen up front (keeping this function pure); the id is also left in a file for `finalize`.
|
|
103
|
+
const sessionId = req.sessionId ?? sessionUuid(req.runDir);
|
|
104
|
+
const sessionFile = join(req.runDir, "grok-session-id.txt");
|
|
105
|
+
files.push({ path: sessionFile, content: sessionId });
|
|
106
|
+
args.push(req.sessionId ? "--resume" : "--session-id", sessionId);
|
|
107
|
+
if (req.model) args.push("--model", req.model);
|
|
108
|
+
if (req.effort) args.push("--reasoning-effort", req.effort);
|
|
109
|
+
if (req.outputSchema) args.push("--json-schema", JSON.stringify(req.outputSchema));
|
|
110
|
+
if (req.projectTrusted && req.agentConfig?.persistTrust === true) args.push("--trust");
|
|
111
|
+
args.push(...(req.extraArgs ?? []));
|
|
112
|
+
return {
|
|
113
|
+
args,
|
|
114
|
+
cwd: req.workspace,
|
|
115
|
+
env: { ...req.env, GROK_SANDBOX: null },
|
|
116
|
+
files,
|
|
117
|
+
outputFiles: { sessionId: sessionFile },
|
|
118
|
+
};
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
parseEvent(line: string, state: ParserState): NormalizedEvent[] {
|
|
122
|
+
const event = parseJsonLine(line);
|
|
123
|
+
if (!event) {
|
|
124
|
+
if (line.trim()) state.nonJsonLines++;
|
|
125
|
+
return [];
|
|
126
|
+
}
|
|
127
|
+
state.extra.sawEvents = true;
|
|
128
|
+
const type = getString(event, "type");
|
|
129
|
+
const text = textState(state);
|
|
130
|
+
// `text` and `thought` lines are streamed chunks: thinking is summarized once the next kind of line arrives.
|
|
131
|
+
if (type === "thought") {
|
|
132
|
+
text.thought += getString(event, "data") ?? "";
|
|
133
|
+
return [];
|
|
134
|
+
}
|
|
135
|
+
const events: NormalizedEvent[] = [];
|
|
136
|
+
if (text.thought.trim()) events.push({ type: "activity", kind: "thinking", summary: clip(text.thought) });
|
|
137
|
+
text.thought = "";
|
|
138
|
+
switch (type) {
|
|
139
|
+
case "text":
|
|
140
|
+
text.current += getString(event, "data") ?? "";
|
|
141
|
+
break;
|
|
142
|
+
case "usage": {
|
|
143
|
+
// A per-response usage line closes the current assistant message.
|
|
144
|
+
const closesResponse = ["messageId", "stopReason", "signature"].some((key) => event[key] !== undefined);
|
|
145
|
+
if (closesResponse || text.current) events.push(...closeResponse(state));
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
case "tool_call":
|
|
149
|
+
events.push(...parseToolCall(event, state));
|
|
150
|
+
break;
|
|
151
|
+
case "tool_call_update":
|
|
152
|
+
events.push(...parseToolUpdate(event, state));
|
|
153
|
+
break;
|
|
154
|
+
case "max_turns_reached":
|
|
155
|
+
events.push(failTurn(state, "max turns reached"));
|
|
156
|
+
break;
|
|
157
|
+
case "error":
|
|
158
|
+
events.push(failTurn(state, getString(event, "message") ?? "error"));
|
|
159
|
+
break;
|
|
160
|
+
case "auto_compact_failed": {
|
|
161
|
+
const message = `auto compaction failed: ${getString(event, "error") ?? "unknown error"}`;
|
|
162
|
+
state.warnings.push(message);
|
|
163
|
+
events.push({ type: "warning", message: clip(message, 200) });
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
case "end":
|
|
167
|
+
events.push(...parseEnd(event, state));
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
return events;
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
finalize(raw: RawRunResult, state: ParserState): AdapterOutcome {
|
|
174
|
+
const text = textState(state);
|
|
175
|
+
const finalText = text.current || text.last;
|
|
176
|
+
const stopReason = state.extra.stopReason as string | undefined;
|
|
177
|
+
let effective = state;
|
|
178
|
+
if (stopReason === "cancelled") {
|
|
179
|
+
// Exit 0: a headless permission request that no option could answer is cancelled and ends the turn.
|
|
180
|
+
const pending = pendingTool(state);
|
|
181
|
+
const denied = pending ? [...state.denied, `${pending}: permission request cancelled`] : state.denied;
|
|
182
|
+
effective = { ...state, denied, terminal: { ok: false, reason: "cancelled: the turn was cancelled" } };
|
|
183
|
+
} else if (!state.terminal && raw.exitCode === 0) {
|
|
184
|
+
effective = { ...state, terminal: { ok: false, reason: "the stream ended without an end line" } };
|
|
185
|
+
}
|
|
186
|
+
if (!effective.sessionId && state.extra.sawEvents && raw.outputFiles.sessionId?.trim()) {
|
|
187
|
+
effective = { ...effective, sessionId: raw.outputFiles.sessionId.trim() };
|
|
188
|
+
}
|
|
189
|
+
let outcome = standardFinalize(raw, effective, { finalText });
|
|
190
|
+
outcome = refineFailure(outcome, [...effective.errors, effective.terminal?.reason ?? "", raw.stderr].join("\n"));
|
|
191
|
+
const structured = state.extra.structuredOutput ?? parseJsonAnswer(outcome.finalText);
|
|
192
|
+
if (structured !== undefined) outcome.structuredOutput = structured;
|
|
193
|
+
return outcome;
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
interface TextState {
|
|
198
|
+
/** Text of the assistant message being streamed. */
|
|
199
|
+
current: string;
|
|
200
|
+
/** Text of the last closed assistant message. */
|
|
201
|
+
last: string;
|
|
202
|
+
thought: string;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function textState(state: ParserState): TextState {
|
|
206
|
+
if (!isObject(state.extra.text)) state.extra.text = { current: "", last: "", thought: "" };
|
|
207
|
+
return state.extra.text as unknown as TextState;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function failTurn(state: ParserState, message: string): NormalizedEvent {
|
|
211
|
+
state.errors.push(message);
|
|
212
|
+
state.terminal = { ok: false, reason: message };
|
|
213
|
+
return { type: "warning", message: clip(message, 200) };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function closeResponse(state: ParserState): NormalizedEvent[] {
|
|
217
|
+
const text = textState(state);
|
|
218
|
+
if (!text.current) return [];
|
|
219
|
+
text.last = text.current;
|
|
220
|
+
text.current = "";
|
|
221
|
+
return recordText(state, text.last);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
interface ToolInfo {
|
|
225
|
+
name: string;
|
|
226
|
+
status?: string;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function tools(state: ParserState): Map<string, ToolInfo> {
|
|
230
|
+
if (!(state.extra.tools instanceof Map)) state.extra.tools = new Map<string, ToolInfo>();
|
|
231
|
+
return state.extra.tools as Map<string, ToolInfo>;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function parseToolCall(event: Record<string, unknown>, state: ParserState): NormalizedEvent[] {
|
|
235
|
+
const events = closeResponse(state);
|
|
236
|
+
const id = getString(event, "toolCallId") ?? `call-${tools(state).size}`;
|
|
237
|
+
const name = getString(event, "toolName") ?? getString(event, "kind") ?? "tool";
|
|
238
|
+
const status = getString(event, "status");
|
|
239
|
+
tools(state).set(id, { name, status });
|
|
240
|
+
const title = getString(event, "title");
|
|
241
|
+
events.push({ type: "activity", kind: "tool", summary: clip(title && title !== name ? `${name}: ${title}` : name, 100) });
|
|
242
|
+
return events;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function parseToolUpdate(event: Record<string, unknown>, state: ParserState): NormalizedEvent[] {
|
|
246
|
+
const id = getString(event, "toolCallId");
|
|
247
|
+
const status = getString(event, "status");
|
|
248
|
+
const info = id ? tools(state).get(id) : undefined;
|
|
249
|
+
if (info && status) info.status = status;
|
|
250
|
+
if (status !== "failed") return [];
|
|
251
|
+
const match = JSON.stringify([event.content ?? null, event.rawOutput ?? null]).match(DENIAL_TEXT);
|
|
252
|
+
if (!match) return [];
|
|
253
|
+
return [recordDenied(state, clip(`${info?.name ?? "tool"}: ${match[0]}`, 200))];
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function pendingTool(state: ParserState): string | undefined {
|
|
257
|
+
const open = [...tools(state).values()].filter((tool) => tool.status !== "completed" && tool.status !== "failed");
|
|
258
|
+
return open.at(-1)?.name;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function parseEnd(event: Record<string, unknown>, state: ParserState): NormalizedEvent[] {
|
|
262
|
+
const events = closeResponse(state);
|
|
263
|
+
events.push(...recordSession(state, getString(event, "sessionId")));
|
|
264
|
+
const stopReason = getString(event, "stopReason") ?? "end_turn";
|
|
265
|
+
state.extra.stopReason = stopReason;
|
|
266
|
+
// An earlier `error` or `max_turns_reached` line keeps the turn failed.
|
|
267
|
+
if (state.terminal?.ok !== false || stopReason !== "end_turn") {
|
|
268
|
+
state.terminal = stopReason === "end_turn" ? { ok: true } : { ok: false, reason: `stop reason ${stopReason}` };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// `usage.input_tokens` counts uncached input only; cache reads and writes are added back.
|
|
272
|
+
const input = ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"]
|
|
273
|
+
.map((key) => getNumber(event, "usage", key))
|
|
274
|
+
.filter((value) => value !== undefined);
|
|
275
|
+
const output = getNumber(event, "usage", "output_tokens");
|
|
276
|
+
const cost = getNumber(event, "total_cost_usd");
|
|
277
|
+
const turns = getNumber(event, "num_turns");
|
|
278
|
+
if (turns !== undefined) state.usage.turns = turns;
|
|
279
|
+
if (input.length > 0 || output !== undefined || cost !== undefined) {
|
|
280
|
+
const inputTokens = input.length > 0 ? input.reduce((sum, value) => sum + value, 0) : undefined;
|
|
281
|
+
events.push(recordUsage(state, { inputTokens, outputTokens: output, costUsd: cost }, "replace"));
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (event.structuredOutput !== undefined && event.structuredOutput !== null) {
|
|
285
|
+
state.extra.structuredOutput = event.structuredOutput;
|
|
286
|
+
}
|
|
287
|
+
const schemaError = getString(event, "structuredOutputError");
|
|
288
|
+
if (schemaError) {
|
|
289
|
+
const message = `structured output: ${schemaError}`;
|
|
290
|
+
state.warnings.push(message);
|
|
291
|
+
events.push({ type: "warning", message: clip(message, 200) });
|
|
292
|
+
}
|
|
293
|
+
return events;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Second classification pass for failures the shared patterns left as `failed` (or as an answerless denial). */
|
|
297
|
+
function refineFailure(outcome: AdapterOutcome, text: string): AdapterOutcome {
|
|
298
|
+
const unclassified = outcome.status === "failed" || (outcome.status === "denied" && !outcome.finalText);
|
|
299
|
+
if (!unclassified || !text.trim()) return outcome;
|
|
300
|
+
const lines = text.split(/\r?\n/).filter((line) => line.trim());
|
|
301
|
+
for (const { status, code, pattern } of GROK_FAILURE_PATTERNS) {
|
|
302
|
+
const line = lines.find((candidate) => pattern.test(candidate));
|
|
303
|
+
if (line) return { ...outcome, status, reason: `${code}: ${clip(line, 200)}` };
|
|
304
|
+
}
|
|
305
|
+
const cls = classifyFailureText(text);
|
|
306
|
+
return cls ? { ...outcome, status: cls.status, reason: `${cls.code}: ${cls.line}` } : outcome;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** `grok models` prints ` * id (default)` and ` - id` lines under "Available models:". */
|
|
310
|
+
function parseModelList(stdout: string): string[] {
|
|
311
|
+
const lines = stdout.split(/\r?\n/);
|
|
312
|
+
const start = lines.findIndex((line) => /available models/i.test(line));
|
|
313
|
+
const models: string[] = [];
|
|
314
|
+
for (const line of start >= 0 ? lines.slice(start + 1) : lines) {
|
|
315
|
+
const match = line.match(/^\s*[*-]\s+(\S+)/);
|
|
316
|
+
if (match) models.push(match[1]);
|
|
317
|
+
}
|
|
318
|
+
return [...new Set(models)];
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** RFC 4122 version 4 layout derived from the run directory, so the same request always gets the same id. */
|
|
322
|
+
function sessionUuid(seed: string): string {
|
|
323
|
+
const bytes = createHash("sha256").update(`master-orchestrator:grok:${seed}`).digest().subarray(0, 16);
|
|
324
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
325
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
326
|
+
const hex = bytes.toString("hex");
|
|
327
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
328
|
+
}
|