master-orchestrator 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +174 -2
  4. package/package.json +56 -4
  5. package/src/adapters/agy.ts +285 -0
  6. package/src/adapters/claude.ts +317 -0
  7. package/src/adapters/codex.ts +162 -0
  8. package/src/adapters/common.ts +211 -0
  9. package/src/adapters/cursor.ts +242 -0
  10. package/src/adapters/dsh.ts +356 -0
  11. package/src/adapters/fake-agent.mjs +50 -0
  12. package/src/adapters/fake.ts +88 -0
  13. package/src/adapters/gemini.ts +225 -0
  14. package/src/adapters/grok.ts +328 -0
  15. package/src/adapters/muse.ts +281 -0
  16. package/src/adapters/omp.ts +119 -0
  17. package/src/adapters/opencode.ts +228 -0
  18. package/src/adapters/pi.ts +284 -0
  19. package/src/adapters/registry.ts +31 -0
  20. package/src/adapters/types.ts +201 -0
  21. package/src/config/load.ts +290 -0
  22. package/src/config/profiles.ts +64 -0
  23. package/src/config/schema.ts +158 -0
  24. package/src/config/write.ts +83 -0
  25. package/src/engine/artifacts.ts +145 -0
  26. package/src/engine/baseline.ts +132 -0
  27. package/src/engine/execute.ts +437 -0
  28. package/src/engine/git.ts +32 -0
  29. package/src/engine/hostenv.ts +54 -0
  30. package/src/engine/registry.ts +280 -0
  31. package/src/engine/runner.ts +203 -0
  32. package/src/engine/types.ts +55 -0
  33. package/src/engine/verify.ts +100 -0
  34. package/src/index.ts +602 -0
  35. package/src/prompts/envelope.ts +29 -0
  36. package/src/prompts/templates.ts +389 -0
  37. package/src/ui/configure.ts +174 -0
  38. package/src/ui/dialogs.ts +88 -0
  39. package/src/ui/doctor.ts +120 -0
  40. package/src/ui/format.ts +94 -0
  41. package/src/ui/host.ts +100 -0
  42. package/src/ui/render.ts +86 -0
  43. package/src/ui/widget.ts +70 -0
  44. package/src/workflows/budget.ts +66 -0
  45. package/src/workflows/common.ts +100 -0
  46. package/src/workflows/debate.ts +488 -0
  47. package/src/workflows/host.ts +78 -0
  48. package/src/workflows/plan-exec.ts +807 -0
  49. package/src/workflows/plan.ts +407 -0
  50. package/src/workflows/planfile.ts +380 -0
  51. package/src/workflows/planstate.ts +229 -0
  52. package/src/workflows/verdict.ts +74 -0
@@ -0,0 +1,242 @@
1
+ import {
2
+ clip,
3
+ detectByVersion,
4
+ getNumber,
5
+ getString,
6
+ isObject,
7
+ parseJsonLine,
8
+ recordDenied,
9
+ recordSession,
10
+ recordText,
11
+ recordUsage,
12
+ standardFinalize,
13
+ } from "./common.ts";
14
+ import type { AgentAdapter, AuthStatus, HostEnv, Invocation, NormalizedEvent, ParserState, RunRequest, RunStatus } from "./types.ts";
15
+
16
+ /** Startup refusals printed to stderr (exit 1, no stream event) that no other profile setting can fix. */
17
+ const STARTUP_FAILURES: Array<{ pattern: RegExp; status: RunStatus; code: string }> = [
18
+ { pattern: /Workspace Trust Required/, status: "unavailable", code: "untrusted_workspace" },
19
+ { pattern: /administrator has disabled headless Cursor CLI usage/, status: "unavailable", code: "headless_disabled" },
20
+ { pattern: /Sandbox mode is enabled but not available/, status: "unavailable", code: "sandbox_unavailable" },
21
+ ];
22
+ const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
23
+
24
+ interface CursorExtra {
25
+ /** Assistant text since the last tool call. */
26
+ segment?: string;
27
+ sawResult?: boolean;
28
+ thinking?: string;
29
+ }
30
+
31
+ /**
32
+ * Cursor Agent (`cursor-agent -p --output-format stream-json`). Event schema: `src/headless.ts` of the
33
+ * 2026.11.22 bundle (system/init, user, assistant, thinking, tool_call started/completed, result, retry,
34
+ * connection). Failures are not stream events: the CLI prints the error to stderr and exits 1.
35
+ * The prompt goes on stdin: with no positional prompt and a non-TTY stdin, `build-prompt.ts` reads stdin to EOF.
36
+ * SIGTERM exits 143 after cleanup, without a result event.
37
+ */
38
+ export const cursorAdapter: AgentAdapter = {
39
+ id: "cursor",
40
+ displayName: "Cursor Agent",
41
+ binary: "cursor-agent",
42
+ testedVersions: ">=2026.11.22-0 <2027.0.0-0",
43
+ stability: "experimental",
44
+ liveChecked: "2026.11.22 on 2026-11-25: auth failure only (not logged in)",
45
+ stopSignal: "SIGTERM",
46
+ capabilities: {
47
+ resume: true,
48
+ structuredOutput: false,
49
+ listModels: true,
50
+ reportsCost: false,
51
+ },
52
+ trustFlag: "--trust",
53
+
54
+ detect(env: HostEnv) {
55
+ return detectByVersion(env, this.testedVersions);
56
+ },
57
+
58
+ async checkAuth(env: HostEnv): Promise<AuthStatus> {
59
+ const result = await env.exec(env.bin, ["status", "--format", "json"], { timeoutMs: 20_000 });
60
+ if (result.error) return { state: "unknown", detail: result.error };
61
+ let status: unknown;
62
+ try {
63
+ status = JSON.parse(result.stdout) as unknown;
64
+ } catch {
65
+ return { state: "unknown", detail: clip(`${result.stdout}\n${result.stderr}`.replace(ANSI, ""), 120) || "no output" };
66
+ }
67
+ if (getString(status, "status") === "authenticated") return { state: "ok", detail: "logged in" };
68
+ // `status` reports only the stored login; a CURSOR_API_KEY in the environment authenticates runs too.
69
+ if (env.env.CURSOR_API_KEY) return { state: "unknown", detail: "no stored login; CURSOR_API_KEY is set" };
70
+ const message = getString(status, "message") ?? "not logged in";
71
+ if (getString(status, "status") === "error") return { state: "unknown", detail: clip(message, 120) };
72
+ return { state: "missing", detail: `${clip(message, 80)} (run \`cursor-agent login\` or set CURSOR_API_KEY)` };
73
+ },
74
+
75
+ async listModels(env: HostEnv): Promise<string[]> {
76
+ const result = await env.exec(env.bin, ["models"], { timeoutMs: 30_000 });
77
+ if (result.error) throw new Error(result.error);
78
+ if (result.code !== 0) {
79
+ throw new Error(`cursor-agent models exited with ${result.code}: ${clip(result.stderr.replace(ANSI, "") || result.stdout, 160)}`);
80
+ }
81
+ return parseModelList(result.stdout);
82
+ },
83
+
84
+ buildInvocation(req: RunRequest): Invocation {
85
+ // `--force` runs every command not explicitly denied and also skips the headless workspace-trust gate;
86
+ // `--sandbox disabled` keeps commands out of the sandbox a user or server default may enable.
87
+ const args = ["-p", "--output-format", "stream-json", "--workspace", req.workspace, "--force", "--sandbox", "disabled"];
88
+ // `--trust` persists the grant: it writes a `.workspace-trusted` marker in Cursor's per-project directory.
89
+ if (req.projectTrusted) args.push("--trust");
90
+ // Chats are stored per workspace directory, so a follow-up must run in the same workspace.
91
+ if (req.sessionId) args.push("--resume", req.sessionId);
92
+ if (req.model) args.push("--model", modelWithEffort(req.model, req.effort));
93
+ args.push(...(req.extraArgs ?? []));
94
+ return {
95
+ args,
96
+ cwd: req.workspace,
97
+ env: req.env,
98
+ stdin: req.prompt,
99
+ files: [],
100
+ outputFiles: {},
101
+ };
102
+ },
103
+
104
+ parseEvent(line: string, state: ParserState): NormalizedEvent[] {
105
+ const event = parseJsonLine(line);
106
+ if (!event) {
107
+ if (line.trim()) state.nonJsonLines++;
108
+ return [];
109
+ }
110
+ const extra = state.extra as CursorExtra;
111
+ switch (getString(event, "type")) {
112
+ case "system":
113
+ return getString(event, "subtype") === "init" ? recordSession(state, getString(event, "session_id")) : [];
114
+ case "assistant": {
115
+ const text = messageText(event.message);
116
+ extra.segment = (extra.segment ?? "") + text;
117
+ return recordText(state, text);
118
+ }
119
+ case "thinking": {
120
+ if (getString(event, "subtype") === "delta") {
121
+ extra.thinking = (extra.thinking ?? "") + (getString(event, "text") ?? "");
122
+ return [];
123
+ }
124
+ const thinking = extra.thinking ?? "";
125
+ extra.thinking = "";
126
+ return thinking.trim() ? [{ type: "activity", kind: "thinking", summary: clip(thinking) }] : [];
127
+ }
128
+ case "tool_call":
129
+ return parseToolCall(event, state, extra);
130
+ case "retry": {
131
+ if (getString(event, "subtype") !== "starting") return [];
132
+ const message = `retrying the model request (attempt ${getNumber(event, "attempt") ?? "?"})`;
133
+ state.warnings.push(message);
134
+ return [{ type: "warning", message }];
135
+ }
136
+ case "connection": {
137
+ if (getString(event, "subtype") !== "reconnecting") return [];
138
+ const message = `connection lost, reconnecting (attempt ${getNumber(event, "attempt") ?? "?"})`;
139
+ state.warnings.push(message);
140
+ return [{ type: "warning", message }];
141
+ }
142
+ case "result": {
143
+ extra.sawResult = true;
144
+ state.usage.turns = (state.usage.turns ?? 0) + 1;
145
+ const ok = getString(event, "subtype") === "success" && event.is_error !== true;
146
+ state.terminal = ok ? { ok: true } : { ok: false, reason: getString(event, "result") ?? "the run reported an error" };
147
+ // `result.result` concatenates every text delta of the run; the answer is the text after the last tool call.
148
+ state.finalText = extra.segment ?? getString(event, "result") ?? "";
149
+ if (!isObject(event.usage)) return [];
150
+ return [
151
+ recordUsage(
152
+ state,
153
+ { inputTokens: getNumber(event, "usage", "inputTokens"), outputTokens: getNumber(event, "usage", "outputTokens") },
154
+ "replace",
155
+ ),
156
+ ];
157
+ }
158
+ default:
159
+ return [];
160
+ }
161
+ },
162
+
163
+ finalize(raw, state) {
164
+ const extra = state.extra as CursorExtra;
165
+ if (raw.spawnError) return standardFinalize(raw, state);
166
+ const stderr = raw.stderr.replace(ANSI, "");
167
+ if (!extra.sawResult) {
168
+ const lastLine = stderr.split(/\r?\n/).filter((line) => line.trim()).at(-1);
169
+ state.terminal = { ok: false, reason: lastLine ? clip(lastLine, 200) : "no result event: the CLI stopped before the run finished" };
170
+ }
171
+ const outcome = standardFinalize({ ...raw, stderr }, state, { finalText: state.finalText ?? "" });
172
+ if (outcome.status === "completed" || state.sessionId) return outcome;
173
+ for (const { pattern, status, code } of STARTUP_FAILURES) {
174
+ const line = stderr.split(/\r?\n/).find((candidate) => pattern.test(candidate));
175
+ if (line) return { ...outcome, status, reason: `${code}: ${clip(line.trim(), 200)}` };
176
+ }
177
+ return outcome;
178
+ },
179
+ };
180
+
181
+ function parseToolCall(event: Record<string, unknown>, state: ParserState, extra: CursorExtra): NormalizedEvent[] {
182
+ const call = toolCall(event.tool_call);
183
+ const subtype = getString(event, "subtype");
184
+ if (subtype === "started") {
185
+ extra.segment = "";
186
+ return [{ type: "activity", kind: "tool", summary: call.summary }];
187
+ }
188
+ if (subtype !== "completed") return [];
189
+ // `rejected` is the result of a call a deny rule, hook or the user refused; `permissionDenied` is an OS error.
190
+ const rejected = isObject(call.result) ? call.result.rejected : undefined;
191
+ if (!isObject(rejected)) return [];
192
+ const reason = getString(rejected, "reason");
193
+ return [recordDenied(state, `${clip(call.summary, 120)}${reason ? `: ${clip(reason, 120)}` : ""}`)];
194
+ }
195
+
196
+ /** The proto3 JSON form of an `agent.v1.ToolCall`: one `<name>ToolCall` key with `args` and, once completed, `result`. */
197
+ function toolCall(value: unknown): { summary: string; result: unknown } {
198
+ if (!isObject(value)) return { summary: "tool", result: undefined };
199
+ const key = Object.keys(value).find((name) => name.endsWith("ToolCall")) ?? Object.keys(value)[0];
200
+ if (!key) return { summary: "tool", result: undefined };
201
+ const body = value[key];
202
+ const name = key.replace(/ToolCall$/, "");
203
+ const args = isObject(body) ? body.args : undefined;
204
+ const command = getString(args, "command");
205
+ const path = getString(args, "path") ?? getString(args, "filePath");
206
+ const pattern = getString(args, "pattern") ?? getString(args, "globPattern") ?? getString(args, "query");
207
+ let summary = name;
208
+ if (command) summary = `$ ${clip(command, 90)}`;
209
+ else if (path) summary = `${name} ${clip(path, 90)}`;
210
+ else if (pattern) summary = `${name} ${clip(pattern, 80)}`;
211
+ return { summary, result: isObject(body) ? body.result : undefined };
212
+ }
213
+
214
+ function messageText(message: unknown): string {
215
+ const content = isObject(message) && Array.isArray(message.content) ? message.content : [];
216
+ return content.map((part) => (getString(part, "type") === "text" ? (getString(part, "text") ?? "") : "")).join("");
217
+ }
218
+
219
+ /**
220
+ * Parameterized models take overrides in brackets (`claude-opus-4-8[context=1m,effort=high]`); the effort
221
+ * is added there unless the model id already sets one. Without a model there is nothing to parameterize.
222
+ */
223
+ function modelWithEffort(model: string, effort: string | undefined): string {
224
+ if (!effort || /[[,]\s*effort\s*=/.test(model)) return model;
225
+ if (model.endsWith("]") && model.includes("[")) {
226
+ const inner = model.slice(model.lastIndexOf("[") + 1, -1).trim();
227
+ return `${model.slice(0, model.lastIndexOf("[") + 1)}${inner ? `${inner},` : ""}effort=${effort}]`;
228
+ }
229
+ return `${model}[effort=${effort}]`;
230
+ }
231
+
232
+ /** Parses `cursor-agent models`: a heading, one `<id> - <name> (current, default)` line per model, a tip. */
233
+ export function parseModelList(stdout: string): string[] {
234
+ const ids: string[] = [];
235
+ for (const raw of stdout.replace(ANSI, "").split(/\r?\n/)) {
236
+ const line = raw.trim();
237
+ if (!line || /^(Available models|No models available|Tip:)/.test(line)) continue;
238
+ const id = line.split(/\s+/)[0];
239
+ if (id) ids.push(id);
240
+ }
241
+ return ids;
242
+ }
@@ -0,0 +1,356 @@
1
+ import { join } from "node:path";
2
+ import { Type } from "typebox";
3
+ import {
4
+ classifyFailureText,
5
+ clip,
6
+ detectByVersion,
7
+ getNumber,
8
+ getString,
9
+ isObject,
10
+ parseJsonLine,
11
+ recordDenied,
12
+ recordSession,
13
+ recordText,
14
+ recordUsage,
15
+ standardFinalize,
16
+ } from "./common.ts";
17
+ import type {
18
+ AdapterOutcome,
19
+ AgentAdapter,
20
+ HostEnv,
21
+ Invocation,
22
+ NormalizedEvent,
23
+ ParserState,
24
+ RawRunResult,
25
+ RunRequest,
26
+ RunStatus,
27
+ } from "./types.ts";
28
+
29
+ const optionsSchema = Type.Object(
30
+ {
31
+ patchFile: Type.Optional(
32
+ Type.String({
33
+ description:
34
+ "Absolute path of a dsh patch-list overlay (YAML) passed as `--patch` on every run, follow-ups included; " +
35
+ "it supplies the model route (`llm-pi-ai` providers and the `agent-default-model` row)",
36
+ }),
37
+ ),
38
+ },
39
+ { additionalProperties: false },
40
+ );
41
+
42
+ type ClassifiedStatus = Extract<RunStatus, "unavailable" | "auth_required" | "quota">;
43
+
44
+ /** LLM failure codes of `dsh-llm/src/error.ts` that a role's fallback chain reacts to. */
45
+ const FAILURE_CODES: Record<string, { status: ClassifiedStatus; code: string }> = {
46
+ MISSING_CREDENTIAL: { status: "auth_required", code: "auth_required" },
47
+ INVALID_CREDENTIAL: { status: "auth_required", code: "auth_required" },
48
+ AUTH: { status: "auth_required", code: "auth_required" },
49
+ ACCOUNT_SIGN_IN_REQUIRED: { status: "auth_required", code: "auth_required" },
50
+ ACCOUNT_TOKEN_INVALID: { status: "auth_required", code: "auth_required" },
51
+ NO_CREDENTIAL_STORE: { status: "auth_required", code: "auth_required" },
52
+ HTTP_401: { status: "auth_required", code: "auth_required" },
53
+ HTTP_403: { status: "auth_required", code: "auth_required" },
54
+ QUOTA: { status: "quota", code: "quota" },
55
+ ACCOUNT_QUOTA: { status: "quota", code: "quota" },
56
+ RATE_LIMIT: { status: "quota", code: "quota" },
57
+ HTTP_429: { status: "quota", code: "quota" },
58
+ UNKNOWN_MODEL: { status: "unavailable", code: "model_unavailable" },
59
+ MODEL_UNSUPPORTED: { status: "unavailable", code: "model_unavailable" },
60
+ UNSUPPORTED_REASONING_EFFORT: { status: "unavailable", code: "model_unavailable" },
61
+ INVALID_MODEL_CONTEXT: { status: "unavailable", code: "model_unavailable" },
62
+ INVALID_MODEL_INFO: { status: "unavailable", code: "model_unavailable" },
63
+ INVALID_MODEL_MAX_TOKENS: { status: "unavailable", code: "model_unavailable" },
64
+ INVALID_MODEL_REASONING: { status: "unavailable", code: "model_unavailable" },
65
+ NO_ADAPTER: { status: "unavailable", code: "config_invalid" },
66
+ INVALID_CONFIG: { status: "unavailable", code: "config_invalid" },
67
+ UNSUPPORTED_OPTION: { status: "unavailable", code: "config_invalid" },
68
+ CLIENT_UPGRADE_REQUIRED: { status: "unavailable", code: "client_upgrade_required" },
69
+ };
70
+
71
+ /** Tool error code of a call the auto-reviewer refused (AUTO_REVIEW_FAILED is a reviewer failure, not a denial). */
72
+ const DENIED_TOOL_CODES = new Set(["AUTO_REVIEW_DENIED"]);
73
+ const DENIED_RESULT = /\[sandbox:[^\]]*denied|no approval channel is available/i;
74
+ const HOME_NOT_WRITABLE = /\b(EACCES|EROFS|EPERM)\b/;
75
+ const RESUME_ERROR = /--session-id|session "[^"]*" does not exist|another (directory|folder)/i;
76
+
77
+ interface TurnEnd {
78
+ turn?: number;
79
+ kind?: string;
80
+ code?: string;
81
+ message?: string;
82
+ }
83
+
84
+ interface DshExtra {
85
+ lastTurnStart?: number;
86
+ lastTurnEnd?: TurnEnd;
87
+ sawFinal?: boolean;
88
+ finalWithoutTurn?: boolean;
89
+ sawError?: boolean;
90
+ calls?: Record<string, string>;
91
+ }
92
+
93
+ /**
94
+ * DeepSeek Harness (`dsh --profile headless --json`). Event schema: `dsh-headless/src/json-stream.ts`
95
+ * (session, status turn/step phases, thinking, text, tool_call, tool_result, final, error).
96
+ * The headless profile has no model flag: the model comes from the composed `agent-default-model` row,
97
+ * which the profile option `patchFile` or a generated overlay replaces.
98
+ * SIGTERM ends the run with a partial `final` and no matching `turn_end` (exit 0); SIGINT exits 130.
99
+ */
100
+ export const dshAdapter: AgentAdapter = {
101
+ id: "dsh",
102
+ displayName: "DeepSeek Harness",
103
+ binary: "dsh",
104
+ testedVersions: ">=0.2.1-rc.3 <0.3.0-0",
105
+ stability: "experimental",
106
+ liveChecked: "0.2.2-rc.3 on 2026-11-25: analyze, implement, follow-up, cancellation, auth failure (route from a patchFile)",
107
+ stopSignal: "SIGTERM",
108
+ optionsSchema,
109
+ capabilities: {
110
+ resume: true,
111
+ structuredOutput: false,
112
+ listModels: false,
113
+ reportsCost: false,
114
+ },
115
+
116
+ detect(env: HostEnv) {
117
+ return detectByVersion(env, this.testedVersions);
118
+ },
119
+
120
+ buildInvocation(req: RunRequest): Invocation {
121
+ const files = [];
122
+ const outputFiles: Record<string, string> = {};
123
+ // Launcher flags (`--profile`, `--patch`) come first; the first unknown token starts the app's arguments.
124
+ const args = ["--profile", "headless"];
125
+ const patchFile = typeof req.options?.patchFile === "string" ? req.options.patchFile : undefined;
126
+ if (patchFile) args.push("--patch", patchFile);
127
+ const overlay = modelOverlay(req.model, req.effort);
128
+ if (overlay !== undefined) {
129
+ // Patches apply in argv order, so the per-run model row replaces the one from `patchFile`.
130
+ const overlayPath = join(req.runDir, "dsh-model.yml");
131
+ files.push({ path: overlayPath, content: overlay });
132
+ args.push("--patch", overlayPath);
133
+ outputFiles.modelOverlay = overlayPath;
134
+ }
135
+ args.push("--json");
136
+ if (req.sessionId) args.push("--session-id", req.sessionId);
137
+ // `-` reads the task from stdin.
138
+ args.push(...(req.extraArgs ?? []), "-");
139
+ return {
140
+ args,
141
+ cwd: req.workspace,
142
+ // The user's DSH_HOME stays: it holds the sessions a follow-up resumes, the `.env` credential fallback,
143
+ // and the user's profile patches and skills. An unwritable home fails the boot and reads as `unavailable`.
144
+ env: { ...req.env, DSH_PERMISSION_MODE: "danger-full-access" },
145
+ stdin: req.prompt,
146
+ files,
147
+ outputFiles,
148
+ };
149
+ },
150
+
151
+ parseEvent(line: string, state: ParserState): NormalizedEvent[] {
152
+ const event = parseJsonLine(line);
153
+ if (!event) {
154
+ if (line.trim()) state.nonJsonLines++;
155
+ return [];
156
+ }
157
+ const extra = state.extra as DshExtra;
158
+ switch (getString(event, "type")) {
159
+ case "session":
160
+ return recordSession(state, getString(event, "sessionId"));
161
+ case "status":
162
+ return parseStatus(event, state, extra);
163
+ case "thinking": {
164
+ const text = getString(event, "text");
165
+ return text?.trim() ? [{ type: "activity", kind: "thinking", summary: clip(text) }] : [];
166
+ }
167
+ case "text":
168
+ return recordText(state, getString(event, "text"));
169
+ case "tool_call": {
170
+ const summary = toolSummary(getString(event, "tool") ?? "tool", event.input);
171
+ const callId = getString(event, "callId");
172
+ if (callId) extra.calls = { ...extra.calls, [callId]: summary };
173
+ return [{ type: "activity", kind: "tool", summary }];
174
+ }
175
+ case "tool_result":
176
+ return parseToolResult(event, state, extra);
177
+ case "final": {
178
+ extra.sawFinal = true;
179
+ state.finalText = getString(event, "text") ?? "";
180
+ // 0.2.2 adds `reason`; null means the run ended without a terminal turn (interrupted).
181
+ if ("reason" in event && event.reason === null) extra.finalWithoutTurn = true;
182
+ return [];
183
+ }
184
+ case "error": {
185
+ const message = getString(event, "message") ?? "error";
186
+ extra.sawError = true;
187
+ state.errors.push(message);
188
+ return [{ type: "warning", message: clip(message, 200) }];
189
+ }
190
+ default:
191
+ return [];
192
+ }
193
+ },
194
+
195
+ finalize(raw, state) {
196
+ const extra = state.extra as DshExtra;
197
+ const overlay = raw.outputFiles.modelOverlay;
198
+ if (raw.spawnError) return standardFinalize(raw, state);
199
+
200
+ // A boot failure (profile plugins, unwritable DSH_HOME) prints only to stderr and emits no JSON.
201
+ if (!state.sessionId && !extra.sawError && !extra.sawFinal && raw.exitCode !== null && raw.exitCode !== 0) {
202
+ return startupFailure(raw, state, overlay);
203
+ }
204
+
205
+ // A failure outside a turn: unknown option, empty task, unusable `--session-id`.
206
+ if (extra.sawError && !extra.sawFinal) {
207
+ const message = state.errors.join("\n");
208
+ if (!classifyFailureText(message) && RESUME_ERROR.test(message)) {
209
+ return { ...baseOutcome(state), status: "failed", reason: `resume_failed: ${clip(state.errors.at(-1) ?? message, 200)}` };
210
+ }
211
+ }
212
+
213
+ const end = extra.lastTurnEnd;
214
+ const matched = end !== undefined && extra.lastTurnStart !== undefined && end.turn === extra.lastTurnStart;
215
+ if (extra.lastTurnStart !== undefined && (!matched || extra.finalWithoutTurn)) {
216
+ state.terminal = { ok: false, reason: "interrupted: the last turn has no turn_end" };
217
+ } else if (end) {
218
+ state.terminal = turnTerminal(end, state);
219
+ }
220
+
221
+ const outcome = standardFinalize(raw, state, { finalText: state.finalText });
222
+ const cls = end?.code ? FAILURE_CODES[end.code] : undefined;
223
+ if (cls && outcome.status !== "completed") {
224
+ outcome.status = cls.status;
225
+ outcome.reason = `${cls.code}: ${end?.code}: ${clip(end?.message ?? "", 160)}`;
226
+ if (cls.code === "model_unavailable" && overlay) outcome.reason += ` (${overlayHint(overlay)})`;
227
+ }
228
+ return outcome;
229
+ },
230
+ };
231
+
232
+ function parseStatus(event: Record<string, unknown>, state: ParserState, extra: DshExtra): NormalizedEvent[] {
233
+ const phase = getString(event, "phase");
234
+ const turn = getNumber(event, "turn");
235
+ if (phase === "turn_start") {
236
+ extra.lastTurnStart = turn;
237
+ return [];
238
+ }
239
+ if (phase === "step_end" && isObject(event.usage)) {
240
+ return [
241
+ recordUsage(state, {
242
+ inputTokens: getNumber(event, "usage", "inputTokens"),
243
+ outputTokens: getNumber(event, "usage", "outputTokens"),
244
+ }),
245
+ ];
246
+ }
247
+ if (phase === "turn_end") {
248
+ state.usage.turns = (state.usage.turns ?? 0) + 1;
249
+ const end: TurnEnd = {
250
+ turn,
251
+ kind: getString(event, "reason", "kind"),
252
+ code: getString(event, "reason", "error", "code"),
253
+ message: getString(event, "reason", "error", "message"),
254
+ };
255
+ extra.lastTurnEnd = end;
256
+ if (end.kind === "blocked") {
257
+ return [recordDenied(state, `turn ${turn ?? "?"} blocked by a hook or policy before its next step`)];
258
+ }
259
+ if (end.kind === "error") {
260
+ const message = `${end.code ?? "UNKNOWN"}: ${end.message ?? "turn failed"}`;
261
+ state.errors.push(message);
262
+ return [{ type: "warning", message: clip(message, 200) }];
263
+ }
264
+ }
265
+ return [];
266
+ }
267
+
268
+ function parseToolResult(event: Record<string, unknown>, state: ParserState, extra: DshExtra): NormalizedEvent[] {
269
+ if (getString(event, "status") !== "error") return [];
270
+ const callId = getString(event, "callId");
271
+ const tool = (callId && extra.calls?.[callId]) || "tool";
272
+ const code = getString(event, "error", "code");
273
+ const result = getString(event, "result") ?? "";
274
+ if ((code && DENIED_TOOL_CODES.has(code)) || DENIED_RESULT.test(result)) {
275
+ const detail = getString(event, "error", "reason") ?? result;
276
+ return [recordDenied(state, `${clip(tool, 120)}: ${clip(detail, 120)}`)];
277
+ }
278
+ return [];
279
+ }
280
+
281
+ function turnTerminal(end: TurnEnd, state: ParserState): ParserState["terminal"] {
282
+ switch (end.kind) {
283
+ case "completed":
284
+ return { ok: true };
285
+ case "blocked":
286
+ return { ok: false, reason: "blocked: a hook or policy rejected the next step" };
287
+ case "error":
288
+ return { ok: false, reason: state.errors.at(-1) ?? "error" };
289
+ case "max-tokens":
290
+ return { ok: false, reason: "max_tokens: the turn hit the output token limit" };
291
+ default:
292
+ return { ok: false, reason: `${end.kind ?? "unknown"}: the turn did not complete` };
293
+ }
294
+ }
295
+
296
+ function startupFailure(raw: RawRunResult, state: ParserState, overlay: string | undefined): AdapterOutcome {
297
+ const base = baseOutcome(state);
298
+ const cls = classifyFailureText(raw.stderr);
299
+ if (cls) return { ...base, status: cls.status, reason: `${cls.code}: ${cls.line}` };
300
+ const lines = raw.stderr.split(/\r?\n/).filter((line) => line.trim());
301
+ const notWritable = lines.find((line) => HOME_NOT_WRITABLE.test(line));
302
+ if (notWritable) return { ...base, status: "unavailable", reason: `dsh_home_not_writable: ${clip(notWritable, 200)}` };
303
+ let reason = `startup_failed: ${clip(lines.at(-1) ?? `exited with ${raw.exitCode} before the session started`, 200)}`;
304
+ if (overlay) reason += ` (${overlayHint(overlay)})`;
305
+ return { ...base, status: "unavailable", reason };
306
+ }
307
+
308
+ function baseOutcome(state: ParserState) {
309
+ const usage = Object.keys(state.usage).length > 0 ? { ...state.usage } : undefined;
310
+ return { sessionId: state.sessionId, deniedActions: [...new Set(state.denied)], usage };
311
+ }
312
+
313
+ function overlayHint(overlay: string): string {
314
+ const provider = overlayValue(overlay, "provider");
315
+ const model = overlayValue(overlay, "model");
316
+ const route = provider && model ? `${provider}/${model}` : `model ${model ?? "?"} without a provider`;
317
+ return `model overlay selects ${route}; dsh takes the model as <provider>/<model> of a route declared in the patchFile`;
318
+ }
319
+
320
+ function overlayValue(overlay: string, key: string): string | undefined {
321
+ const raw = overlay.match(new RegExp(`^\\s+${key}: (.*)$`, "m"))?.[1];
322
+ if (raw === undefined) return undefined;
323
+ try {
324
+ const value = JSON.parse(raw) as unknown;
325
+ return typeof value === "string" ? value : raw;
326
+ } catch {
327
+ return raw;
328
+ }
329
+ }
330
+
331
+ /**
332
+ * The `agent-default-model` row for `req.model` (`provider/model`, split at the first `/`) and `req.effort`.
333
+ * A user patch replaces the whole row, so the overlay restates every field. A model without a provider is
334
+ * written as given and fails the boot (`unavailable`); an effort without a model cannot be applied to the
335
+ * configured default and is left out.
336
+ */
337
+ function modelOverlay(model: string | undefined, effort: string | undefined): string | undefined {
338
+ if (!model) return undefined;
339
+ const slash = model.indexOf("/");
340
+ const lines = ["- id: agent-default-model", " config:"];
341
+ if (slash > 0) {
342
+ lines.push(` provider: ${JSON.stringify(model.slice(0, slash))}`, ` model: ${JSON.stringify(model.slice(slash + 1))}`);
343
+ } else {
344
+ lines.push(` model: ${JSON.stringify(model)}`);
345
+ }
346
+ if (effort) lines.push(` reasoningEffort: ${JSON.stringify(effort)}`);
347
+ return `${lines.join("\n")}\n`;
348
+ }
349
+
350
+ function toolSummary(tool: string, input: unknown): string {
351
+ const command = getString(input, "command");
352
+ if (command) return `$ ${clip(command, 90)}`;
353
+ const path = getString(input, "path") ?? getString(input, "file_path") ?? getString(input, "filePath");
354
+ if (path) return `${tool} ${clip(path, 90)}`;
355
+ return tool;
356
+ }
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ // Scripted stand-in for an agent CLI, driven by a scenario file. Used by the engine tests through the fake adapter.
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname, resolve } from "node:path";
6
+
7
+ const scenario = JSON.parse(readFileSync(process.argv[2], "utf8"));
8
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
9
+ const line = (value) => process.stdout.write(`${JSON.stringify(value)}\n`);
10
+
11
+ let prompt = "";
12
+ if (!process.stdin.isTTY) {
13
+ for await (const chunk of process.stdin) prompt += chunk;
14
+ }
15
+ if (scenario.recordPrompt) writeFileSync(scenario.recordPrompt, prompt);
16
+
17
+ for (const step of scenario.steps ?? []) {
18
+ if (step.ignoreSignals) for (const name of step.ignoreSignals) process.on(name, () => {});
19
+ if (step.onSignal) {
20
+ process.on(step.onSignal.signal, () => {
21
+ line({ type: "result", text: step.onSignal.text ?? "interrupted", ok: false });
22
+ process.exit(step.onSignal.exit ?? 130);
23
+ });
24
+ }
25
+ if (step.session) line({ type: "session", id: step.session });
26
+ if (step.text !== undefined) line({ type: "text", text: step.text });
27
+ if (step.tool) line({ type: "tool", name: step.tool });
28
+ if (step.denied) line({ type: "denied", action: step.denied });
29
+ if (step.usage) line({ type: "usage", ...step.usage });
30
+ if (step.error) line({ type: "error", message: step.error });
31
+ if (step.emit) line(step.emit);
32
+ if (step.raw !== undefined) process.stdout.write(step.raw);
33
+ if (step.stderr) process.stderr.write(step.stderr);
34
+ if (step.write) {
35
+ const target = resolve(process.cwd(), step.write.path);
36
+ mkdirSync(dirname(target), { recursive: true });
37
+ writeFileSync(target, step.write.content ?? "");
38
+ }
39
+ if (step.spawnSleeper) {
40
+ const child = spawn("sleep", [String(step.spawnSleeper.seconds ?? 60)], { stdio: "ignore" });
41
+ if (step.spawnSleeper.pidFile) writeFileSync(step.spawnSleeper.pidFile, String(child.pid));
42
+ }
43
+ if (step.envToFile) writeFileSync(step.envToFile.path, process.env[step.envToFile.name] ?? "");
44
+ if (step.argsToFile) writeFileSync(step.argsToFile, JSON.stringify(process.argv.slice(3)));
45
+ if (step.run) spawnSync(step.run[0], step.run.slice(1), { stdio: "ignore" });
46
+ if (step.result !== undefined) line({ type: "result", text: step.result, ok: step.ok ?? true });
47
+ if (step.sleep) await sleep(step.sleep);
48
+ if (step.exit !== undefined) process.exit(step.exit);
49
+ }
50
+ process.exit(scenario.exitCode ?? 0);