@dadado/agent-kit-cli 6.25.0 → 6.26.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 (75) hide show
  1. package/dashboard/dashboard.html +3 -3
  2. package/dashboard/lib/guards.mjs +1 -0
  3. package/dist/{add-OYLOMCM6.js → add-G7KEZLWP.js} +7 -6
  4. package/dist/{chunk-7HDQEK6T.js → chunk-2G4K4ZI5.js} +7 -3
  5. package/dist/{chunk-QLTGHJB3.js → chunk-2GXN7HVG.js} +5 -5
  6. package/dist/{chunk-HSIHZWFF.js → chunk-5A72LTR3.js} +7 -7
  7. package/dist/{chunk-6WUKLS4D.js → chunk-BIFTTL2O.js} +1 -1
  8. package/dist/{chunk-NJ2SUSWX.js → chunk-BVZDPVUL.js} +1 -1
  9. package/dist/{chunk-QACMV46U.js → chunk-ENRXS5O6.js} +19 -12
  10. package/dist/{chunk-2F6NMQOA.js → chunk-FB6G6OD6.js} +3 -3
  11. package/dist/{chunk-MFKHIWEL.js → chunk-FOVHFMSH.js} +1 -1
  12. package/dist/{chunk-EO5NGAYV.js → chunk-FUSNEYGU.js} +29 -3
  13. package/dist/{chunk-GMG7ZH4E.js → chunk-H7KAXI5R.js} +13 -13
  14. package/dist/{chunk-SAQ3EE5R.js → chunk-HGB4DHXV.js} +3 -3
  15. package/dist/{chunk-IFBIO7VT.js → chunk-HXV6VQD4.js} +1402 -42
  16. package/dist/{chunk-XGZOU4DS.js → chunk-I3FGWNU5.js} +4 -4
  17. package/dist/{chunk-6M6UKECW.js → chunk-IHVJTGYR.js} +0 -32
  18. package/dist/{chunk-H7RAFRRZ.js → chunk-IUY24WPE.js} +68 -34
  19. package/dist/chunk-JG5MKMOM.js +248 -0
  20. package/dist/{chunk-KWYF7QNH.js → chunk-JWIJHO67.js} +17 -2
  21. package/dist/chunk-KMK4T4ZM.js +34 -0
  22. package/dist/{chunk-ZMYV6PRE.js → chunk-LEVNLHH3.js} +2 -1
  23. package/dist/{chunk-2XLI7XEY.js → chunk-MGVV6YC4.js} +1 -1
  24. package/dist/{chunk-C7SV7UP5.js → chunk-MWRYQLEG.js} +3 -3
  25. package/dist/{chunk-WKFE3RUC.js → chunk-NHJ4IAVN.js} +5 -3
  26. package/dist/{chunk-C4Q77GGJ.js → chunk-O7VMHCNN.js} +6 -0
  27. package/dist/{chunk-GQSSXDDK.js → chunk-OVRGTHZD.js} +1 -1
  28. package/dist/{chunk-CIV42JGT.js → chunk-PCIYXGB3.js} +2 -2
  29. package/dist/{chunk-7Y74KO7U.js → chunk-PLLXFSN2.js} +12 -12
  30. package/dist/{chunk-QX55T4UX.js → chunk-RJP47EGS.js} +6 -1
  31. package/dist/{chunk-JGG574RK.js → chunk-RRJVC35Y.js} +3 -3
  32. package/dist/{chunk-PIMGV3E5.js → chunk-SWJJW624.js} +1 -1
  33. package/dist/{chunk-G5MQRP6M.js → chunk-SYRJ5TTK.js} +13 -9
  34. package/dist/{chunk-L5V3W3DY.js → chunk-TTUFIE26.js} +60 -14
  35. package/dist/{chunk-JFS4GKP7.js → chunk-XXPI4H4D.js} +2 -2
  36. package/dist/{chunk-M4UL422I.js → chunk-Y5526WCN.js} +6 -6
  37. package/dist/{chunk-CXE6ASSX.js → chunk-Y575INEC.js} +1 -1
  38. package/dist/{chunk-JG3CNGQM.js → chunk-ZNZHDPS3.js} +6 -4
  39. package/dist/{commands-UW2C2ZN4.js → commands-K4HSDML5.js} +8 -6
  40. package/dist/{conflicts-RING6AHV.js → conflicts-4SUWIPWP.js} +9 -10
  41. package/dist/{contribute-LSY75JZH.js → contribute-HE4WCBRY.js} +7 -6
  42. package/dist/{countdown-SZ2P4XHB.js → countdown-TYQHVAIX.js} +74 -45
  43. package/dist/{dashboard-P65XHYCU.js → dashboard-6V6PCNYF.js} +1 -1
  44. package/dist/{dashboard-broadcast-GYK34QYL.js → dashboard-broadcast-PMVQ7PXU.js} +1 -1
  45. package/dist/{diff-NZVBVQSK.js → diff-3XUZM7ZT.js} +8 -7
  46. package/dist/{doctor-TJSXBVGV.js → doctor-KGUWU5SN.js} +16 -15
  47. package/dist/{engine-info-BBI5QO5Y.js → engine-info-VM4VPGQM.js} +2 -2
  48. package/dist/{ground-control-ZJXPUIQN.js → ground-control-ZIDHEOPW.js} +7 -4
  49. package/dist/{handoff-2OZSWGTE.js → handoff-LLT4CI6H.js} +2 -3
  50. package/dist/{hook-3VPKNSOO.js → hook-UPZ3CPYS.js} +22 -22
  51. package/dist/index.js +49 -32
  52. package/dist/{init-UW2BJBO2.js → init-ZHLVXEVT.js} +19 -18
  53. package/dist/{install-RQSI4CHG.js → install-XWOG64W3.js} +19 -18
  54. package/dist/{installs-7TR4H4QH.js → installs-2ROXPO6M.js} +5 -4
  55. package/dist/{mission-control-VSU6NT43.js → mission-control-IGOI3WHS.js} +2 -2
  56. package/dist/models-5BDXREWM.js +45 -0
  57. package/dist/paths-JTPV6SXH.js +107 -0
  58. package/dist/pi-DCMDOY65.js +248 -0
  59. package/dist/{plan-index-BNLUU6T5.js → plan-index-5QZJK4AG.js} +2 -3
  60. package/dist/{queue-JHYILLMX.js → queue-Z5VNNHM6.js} +11 -13
  61. package/dist/{run-CQF5RM5X.js → run-QURAXAR2.js} +24 -30
  62. package/dist/{run-plan-BEOCOJCF.js → run-plan-4MMHVCTS.js} +35 -23
  63. package/dist/{session-start-QV7CEFRX.js → session-start-NC2HE5X5.js} +16 -16
  64. package/dist/{sessions-AWAAO3DU.js → sessions-WWWLYPW6.js} +4 -4
  65. package/dist/{setup-global-ST4TT427.js → setup-global-WDMARD4Z.js} +11 -10
  66. package/dist/{status-HUBPBGUU.js → status-2WNJL7PP.js} +12 -11
  67. package/dist/update-YSVOYYK5.js +32 -0
  68. package/dist/{update-all-YYUTXHGR.js → update-all-5XLTCHPX.js} +20 -18
  69. package/package.json +14 -4
  70. package/pi/agent-kit.ts +224 -0
  71. package/dist/chunk-7ABY6DYH.js +0 -89
  72. package/dist/chunk-AQLBEEPD.js +0 -625
  73. package/dist/chunk-MUTTNRX4.js +0 -53
  74. package/dist/chunk-TOSAAQ5A.js +0 -71
  75. package/dist/update-DD5UZPGG.js +0 -31
@@ -10,6 +10,11 @@ import {
10
10
  unansweredStop,
11
11
  userEventLine
12
12
  } from "./chunk-P7732A25.js";
13
+ import {
14
+ extractHandoffNamedPlans,
15
+ namedPlanCandidatePaths,
16
+ parsePlanFrontmatter
17
+ } from "./chunk-TTUFIE26.js";
13
18
  import {
14
19
  findOnPath
15
20
  } from "./chunk-WGLPZXNU.js";
@@ -26,6 +31,15 @@ import {
26
31
  shouldUseWelcomeColor,
27
32
  withKoloristColor
28
33
  } from "./chunk-QTON2GQX.js";
34
+ import {
35
+ loadContextConfig
36
+ } from "./chunk-PFEUZXVT.js";
37
+ import {
38
+ HANDOFF_REL
39
+ } from "./chunk-O7VMHCNN.js";
40
+ import {
41
+ fileExists
42
+ } from "./chunk-5B4DVO6C.js";
29
43
 
30
44
  // src/plan-loop/stream-render.ts
31
45
  import { StringDecoder } from "string_decoder";
@@ -71,8 +85,8 @@ function firstLineOfContent(content) {
71
85
  if (Array.isArray(content)) {
72
86
  for (const part of content) {
73
87
  if (isRecord(part) && typeof part.text === "string") {
74
- const line3 = firstNonEmptyLine(part.text);
75
- if (line3) return line3;
88
+ const line4 = firstNonEmptyLine(part.text);
89
+ if (line4) return line4;
76
90
  }
77
91
  }
78
92
  return "";
@@ -81,8 +95,8 @@ function firstLineOfContent(content) {
81
95
  return "";
82
96
  }
83
97
  function firstNonEmptyLine(text) {
84
- for (const line3 of text.split(/\r?\n/)) {
85
- const trimmed = line3.trim();
98
+ for (const line4 of text.split(/\r?\n/)) {
99
+ const trimmed = line4.trim();
86
100
  if (trimmed) return trimmed;
87
101
  }
88
102
  return "";
@@ -141,14 +155,21 @@ function parseUser(event) {
141
155
  if (promptChars > 0) out.push({ kind: "prompt", chars: promptChars });
142
156
  return out.length > 0 ? out : [{ kind: "silent" }];
143
157
  }
158
+ function hasUnknownCostBasis(event) {
159
+ const usage = event.modelUsage;
160
+ if (!isRecord(usage)) return false;
161
+ return Object.values(usage).some((entry) => isRecord(entry) && entry.costBasis === "unknown");
162
+ }
144
163
  function parseResult(event) {
145
164
  const isError = event.is_error === true;
146
165
  const subtype = asString(event.subtype);
166
+ const cost = asNumber(event.total_cost_usd);
167
+ const unpriced = hasUnknownCostBasis(event);
147
168
  return {
148
169
  kind: "result",
149
170
  ok: !isError,
150
171
  status: subtype ?? (isError ? "error" : "success"),
151
- costUsd: asNumber(event.total_cost_usd),
172
+ ...unpriced ? { costBasis: "unknown", reportedCostUsd: cost } : { costUsd: cost },
152
173
  durationMs: asNumber(event.duration_ms),
153
174
  apiMs: asNumber(event.duration_api_ms),
154
175
  turns: asNumber(event.num_turns)
@@ -199,19 +220,19 @@ function parseCursorToolCall(event) {
199
220
  if (subtype === "completed") {
200
221
  const result = isRecord(body.result) ? body.result : null;
201
222
  const failed = result !== null && ("error" in result || "failure" in result || "rejected" in result);
202
- let line3 = "";
223
+ let line4 = "";
203
224
  if (result) {
204
225
  const payload = failed ? result.error ?? result.failure ?? result.rejected : result.success;
205
- line3 = firstLineOfContent(
226
+ line4 = firstLineOfContent(
206
227
  typeof payload === "string" ? payload : payload === void 0 ? result : payload
207
228
  );
208
229
  }
209
- return { kind: "tool_result", ok: !failed, line: line3 };
230
+ return { kind: "tool_result", ok: !failed, line: line4 };
210
231
  }
211
232
  return { kind: "silent" };
212
233
  }
213
- function parseStreamLine(line3) {
214
- const trimmed = line3.trim();
234
+ function parseStreamLine(line4) {
235
+ const trimmed = line4.trim();
215
236
  if (!trimmed || !trimmed.startsWith("{")) return [{ kind: "unparsed" }];
216
237
  let event;
217
238
  try {
@@ -268,11 +289,16 @@ function formatCost(usd) {
268
289
  }
269
290
  var RESULT_LINE_HEAD = `${SPACE_MARKS.star} result `;
270
291
  var RESULT_COST_SESSION_TOTAL = "session total";
292
+ var RESULT_COST_UNKNOWN = "cost unknown";
271
293
  function formatResultLine(event, opts = {}) {
272
294
  const parts = [`${RESULT_LINE_HEAD}${event.status}`];
273
- if (event.costUsd !== void 0) {
274
- const cost = formatCost(event.costUsd);
275
- parts.push(opts.sessionTotal ? `${cost} ${RESULT_COST_SESSION_TOTAL}` : cost);
295
+ const total = opts.sessionTotal ? ` ${RESULT_COST_SESSION_TOTAL}` : "";
296
+ if (event.costBasis === "unknown") {
297
+ parts.push(
298
+ event.reportedCostUsd === void 0 ? RESULT_COST_UNKNOWN : `${RESULT_COST_UNKNOWN} (claude reported ${formatCost(event.reportedCostUsd)}${total})`
299
+ );
300
+ } else if (event.costUsd !== void 0) {
301
+ parts.push(`${formatCost(event.costUsd)}${total}`);
276
302
  }
277
303
  if (event.durationMs !== void 0) parts.push(formatDuration(event.durationMs));
278
304
  else if (event.apiMs !== void 0) parts.push(`${formatDuration(event.apiMs)} api`);
@@ -283,15 +309,35 @@ function formatResultLine(event, opts = {}) {
283
309
  }
284
310
  var ESC = String.fromCharCode(27);
285
311
  var ANSI_RE = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
312
+ var USD_RE = "\\$(\\d+(?:\\.\\d+)?)";
286
313
  var RESULT_LINE_RE = new RegExp(
287
- `^${RESULT_LINE_HEAD}(\\S+)(?: ${SPACE_MARKS.tick} \\$(\\d+(?:\\.\\d+)?)( ${RESULT_COST_SESSION_TOTAL})?)?(?: ${SPACE_MARKS.tick} .*)?$`
314
+ `^${RESULT_LINE_HEAD}(\\S+)(?: ${SPACE_MARKS.tick} (?:${USD_RE}( ${RESULT_COST_SESSION_TOTAL})?|(${RESULT_COST_UNKNOWN})(?: \\(claude reported ${USD_RE}( ${RESULT_COST_SESSION_TOTAL})?\\))?))?(?: ${SPACE_MARKS.tick} .*)?$`
288
315
  );
289
- function parseResultLine(line3) {
290
- const m = RESULT_LINE_RE.exec(line3.replace(ANSI_RE, "").replace(/\r$/, ""));
316
+ function parseResultLine(line4) {
317
+ const m = RESULT_LINE_RE.exec(line4.replace(ANSI_RE, "").replace(/\r$/, ""));
291
318
  if (!m) return null;
292
- const cost = m[2] === void 0 ? null : Number(m[2]);
293
- const costUsd = cost !== null && Number.isFinite(cost) ? cost : null;
294
- return { status: m[1] ?? "", costUsd, sessionTotal: costUsd !== null && m[3] !== void 0 };
319
+ const usd = (raw) => {
320
+ const value = raw === void 0 ? null : Number(raw);
321
+ return value !== null && Number.isFinite(value) ? value : null;
322
+ };
323
+ if (m[4] !== void 0) {
324
+ const reportedUsd = usd(m[5]);
325
+ return {
326
+ status: m[1] ?? "",
327
+ costUsd: null,
328
+ costBasis: "unknown",
329
+ reportedUsd,
330
+ sessionTotal: reportedUsd !== null && m[6] !== void 0
331
+ };
332
+ }
333
+ const costUsd = usd(m[2]);
334
+ return {
335
+ status: m[1] ?? "",
336
+ costUsd,
337
+ costBasis: null,
338
+ reportedUsd: costUsd,
339
+ sessionTotal: costUsd !== null && m[3] !== void 0
340
+ };
295
341
  }
296
342
  function renderStreamEvent(event, opts) {
297
343
  const width = Math.max(MIN_COLUMNS, opts.columns);
@@ -307,8 +353,8 @@ function renderStreamEvent(event, opts) {
307
353
  case "tool_result": {
308
354
  const label = event.ok ? "ok" : "error";
309
355
  const head = ` ${SPACE_MARKS.tick} ${label}`;
310
- const line3 = truncate(oneLine(event.line), width - head.length - 3);
311
- const text = line3 ? `${head} ${SPACE_MARKS.tick} ${line3}` : head;
356
+ const line4 = truncate(oneLine(event.line), width - head.length - 3);
357
+ const text = line4 ? `${head} ${SPACE_MARKS.tick} ${line4}` : head;
312
358
  return paint(event.ok ? LABEL_MUTED : STATUS_ERR, text, color);
313
359
  }
314
360
  case "result":
@@ -368,12 +414,12 @@ var StreamRenderer = class {
368
414
  const combined = this.pending + text;
369
415
  const lines = combined.split("\n");
370
416
  this.pending = lines.pop() ?? "";
371
- for (const line3 of lines) {
417
+ for (const line4 of lines) {
372
418
  if (this.dropped) {
373
419
  this.dropped = false;
374
420
  continue;
375
421
  }
376
- this.renderLine(line3);
422
+ this.renderLine(line4);
377
423
  }
378
424
  if (this.pending.length > PENDING_MAX_CHARS) {
379
425
  this.pending = "";
@@ -392,9 +438,9 @@ var StreamRenderer = class {
392
438
  } catch {
393
439
  }
394
440
  }
395
- renderLine(line3) {
396
- for (const event of parseStreamLine(line3)) {
397
- const costed = event.kind === "result" && event.costUsd !== void 0;
441
+ renderLine(line4) {
442
+ for (const event of parseStreamLine(line4)) {
443
+ const costed = event.kind === "result" && (event.costUsd !== void 0 || event.reportedCostUsd !== void 0);
398
444
  const rendered = renderStreamEvent(event, {
399
445
  color: this.color,
400
446
  columns: this.columns,
@@ -422,11 +468,14 @@ function createStreamRenderer(opts = {}) {
422
468
  return new StreamRenderer(opts);
423
469
  }
424
470
 
471
+ // src/plan-loop/local-models.ts
472
+ import { execFile } from "child_process";
473
+
425
474
  // src/plan-loop/backends.ts
426
475
  import { execFileSync as execFileSync2, spawn } from "child_process";
427
476
  import { createWriteStream as createWriteStream2 } from "fs";
428
477
  import { access as access2 } from "fs/promises";
429
- import path2 from "path";
478
+ import path4 from "path";
430
479
  import { StringDecoder as StringDecoder3 } from "string_decoder";
431
480
 
432
481
  // src/plan-loop/codex.ts
@@ -537,7 +586,7 @@ function codexSlashPointer(name) {
537
586
  "- Do not clone Cursor hooks or invent behavior beyond the SoT file."
538
587
  ].join("\n");
539
588
  }
540
- async function codexPrompt(workspace, prompt) {
589
+ async function codexPrompt(workspace, prompt, pointer = codexSlashPointer) {
541
590
  const m = /^\/([A-Za-z0-9][A-Za-z0-9_-]*)/.exec(prompt.trimStart());
542
591
  if (!m?.[1]) return { ok: true, prompt };
543
592
  const rel = path.join(".cursor", "commands", `${m[1]}.md`);
@@ -546,7 +595,7 @@ async function codexPrompt(workspace, prompt) {
546
595
  } catch {
547
596
  return { ok: false, missing: rel };
548
597
  }
549
- return { ok: true, prompt: `${codexSlashPointer(m[1])}
598
+ return { ok: true, prompt: `${pointer(m[1])}
550
599
 
551
600
  ${prompt}` };
552
601
  }
@@ -1132,13 +1181,972 @@ var cursorAcpBackend = {
1132
1181
  run: runCursorAcp
1133
1182
  };
1134
1183
 
1184
+ // src/plan-loop/local.ts
1185
+ import { randomUUID } from "crypto";
1186
+ import { mkdir, mkdtemp, rm, writeFile } from "fs/promises";
1187
+ import { tmpdir } from "os";
1188
+ import path3 from "path";
1189
+
1190
+ // src/plan-loop/detect.ts
1191
+ var DETECT_ORDER = ["cursor-agent", "claude"];
1192
+ var EXPLICIT_ONLY_BACKENDS = [
1193
+ "codex",
1194
+ "cursor-acp",
1195
+ "openrouter",
1196
+ "local"
1197
+ ];
1198
+ var INSTALL_HINTS = {
1199
+ "cursor-agent": "Install the Cursor Agent CLI and ensure `cursor-agent` is on PATH (https://cursor.com/docs/cli).",
1200
+ claude: "Install Claude Code and ensure `claude` is on PATH (https://code.claude.com/docs/en/quickstart).",
1201
+ "cursor-acp": "Install the Cursor Agent CLI and ensure `cursor-agent` is on PATH (https://cursor.com/docs/cli/acp); sign in with `cursor-agent login`.",
1202
+ codex: "Install the Codex CLI and ensure `codex` is on PATH (https://developers.openai.com/codex/cli).",
1203
+ openrouter: "Install Ori and ensure `ori` is on PATH, then sign in with `ori login` (OpenRouter credentials). The kit never falls back to a first-party `claude` here: that would bill Anthropic instead of OpenRouter.",
1204
+ local: "Install pi (the coding agent Omarchy opens for local models) and ensure `pi` is on PATH, then pick a model from `agent-kit models` with `--model <source>:<id>`. The kit never falls back to a paid engine here."
1205
+ };
1206
+ var BACKEND_BIN = {
1207
+ "cursor-agent": "cursor-agent",
1208
+ claude: "claude",
1209
+ codex: "codex",
1210
+ "cursor-acp": "cursor-agent",
1211
+ openrouter: "ori",
1212
+ local: "pi"
1213
+ };
1214
+ function isBackendId(id) {
1215
+ return id === "cursor-agent" || id === "claude" || id === "codex" || id === "cursor-acp" || id === "openrouter" || id === "local";
1216
+ }
1217
+ function isRequestedBackend(id) {
1218
+ return id === "auto" || isBackendId(id);
1219
+ }
1220
+ function listDetectBackendIds() {
1221
+ return ["auto", ...DETECT_ORDER, ...EXPLICIT_ONLY_BACKENDS];
1222
+ }
1223
+ async function detectAgentBackend(requested, whichFn = whichBinary) {
1224
+ const id = requested.trim().toLowerCase();
1225
+ if (id === "glm" || id.startsWith("glm-") || id === "glm4") {
1226
+ return {
1227
+ ok: false,
1228
+ message: "No documented GLM CLI binary is registered. Refusing a stub that would claim to work. Use --backend auto, cursor-agent, or claude."
1229
+ };
1230
+ }
1231
+ if (!isRequestedBackend(id)) {
1232
+ return {
1233
+ ok: false,
1234
+ message: `Unknown backend '${requested}'. Supported: ${listDetectBackendIds().join(", ")}.`
1235
+ };
1236
+ }
1237
+ if (id === "auto") {
1238
+ for (const candidate of DETECT_ORDER) {
1239
+ const bin2 = await whichFn(candidate);
1240
+ if (bin2) return { ok: true, id: candidate, bin: bin2 };
1241
+ }
1242
+ return {
1243
+ ok: false,
1244
+ message: [
1245
+ "No agent CLI found on PATH (tried: cursor-agent, claude).",
1246
+ INSTALL_HINTS["cursor-agent"],
1247
+ INSTALL_HINTS.claude
1248
+ ].join(" ")
1249
+ };
1250
+ }
1251
+ const bin = await whichFn(BACKEND_BIN[id]);
1252
+ if (!bin) {
1253
+ return { ok: false, message: `${BACKEND_BIN[id]} not found on PATH. ${INSTALL_HINTS[id]}` };
1254
+ }
1255
+ return { ok: true, id, bin };
1256
+ }
1257
+
1258
+ // src/plan-loop/plan-state.ts
1259
+ import { readdir, readFile } from "fs/promises";
1260
+ import path2 from "path";
1261
+ function countPendingTodos(raw) {
1262
+ return parsePlanFrontmatter(raw).todos.filter(
1263
+ (t) => (t.status === "pending" || t.status === "in_progress") && t.id !== "dogfood-poc"
1264
+ ).length;
1265
+ }
1266
+ async function findActivePlanFile(plansDir) {
1267
+ if (!await fileExists(plansDir)) return null;
1268
+ const files = (await readdir(plansDir)).filter((f) => f.endsWith(".plan.md")).sort();
1269
+ return files[0] ? path2.join(plansDir, files[0]) : null;
1270
+ }
1271
+ async function readPlan(planPath) {
1272
+ return readFile(planPath, "utf8");
1273
+ }
1274
+ var QUEUE_CURSOR_RE = /^- \*\*Queue cursor:\*\*\s*(.+)$/m;
1275
+ var QUEUE_STATUS_RE = /^- \*\*Queue status:\*\*\s*(.+)$/m;
1276
+ var QUEUE_DONE_STATUSES = /* @__PURE__ */ new Set(["exhausted", "completed", "done"]);
1277
+ function readRunQueueState(handoff) {
1278
+ const queue = extractHandoffNamedPlans(handoff).runQueue;
1279
+ let cursorIndex = null;
1280
+ let cursorPlan = null;
1281
+ const cursorRaw = QUEUE_CURSOR_RE.exec(handoff)?.[1]?.trim() ?? "";
1282
+ const indexMatch = /^(\d+)\b/.exec(cursorRaw);
1283
+ if (indexMatch?.[1]) cursorIndex = Number(indexMatch[1]);
1284
+ const currentMatch = /current:\s*`?([^`()]+?)`?\s*\)/i.exec(cursorRaw);
1285
+ if (currentMatch?.[1]) {
1286
+ const base = currentMatch[1].trim().split("/").pop() ?? "";
1287
+ if (/\.plan\.md$/i.test(base)) cursorPlan = base;
1288
+ }
1289
+ const status = QUEUE_STATUS_RE.exec(handoff)?.[1]?.trim().split(/\s+/)[0]?.replace(/[`*]/g, "");
1290
+ const queueStatus = status ? status : null;
1291
+ const finished = queueStatus !== null && QUEUE_DONE_STATUSES.has(queueStatus.toLowerCase());
1292
+ let cursor = null;
1293
+ if (cursorIndex !== null && cursorIndex >= 0 && cursorIndex < queue.length) {
1294
+ cursor = cursorIndex;
1295
+ } else if (cursorPlan && queue.includes(cursorPlan)) {
1296
+ cursor = queue.indexOf(cursorPlan);
1297
+ }
1298
+ const current = cursor !== null ? queue[cursor] ?? null : cursorPlan;
1299
+ return { queue, cursor, current, status: queueStatus, finished };
1300
+ }
1301
+ function defaultPlanStateIo() {
1302
+ return {
1303
+ readFile: async (file) => {
1304
+ try {
1305
+ return await readFile(file, "utf8");
1306
+ } catch {
1307
+ return null;
1308
+ }
1309
+ },
1310
+ findActivePlan: findActivePlanFile
1311
+ };
1312
+ }
1313
+ async function resolveActivePlanFromHandoff(root, handoff, io = defaultPlanStateIo()) {
1314
+ const queue = readRunQueueState(handoff);
1315
+ const base = (queue.queue.length > 0 && !queue.finished ? queue.current : null) ?? extractHandoffNamedPlans(handoff).active;
1316
+ if (!base) return io.findActivePlan(path2.join(root, ".cursor", "plans"));
1317
+ for (const candidate of namedPlanCandidatePaths(root, base)) {
1318
+ if (await io.readFile(candidate) !== null) return candidate;
1319
+ }
1320
+ return null;
1321
+ }
1322
+ async function resolveActivePlanPath(root, io = defaultPlanStateIo()) {
1323
+ const handoff = await io.readFile(path2.join(root, HANDOFF_REL)) ?? "";
1324
+ return resolveActivePlanFromHandoff(root, handoff, io);
1325
+ }
1326
+
1327
+ // src/plan-loop/model-roles.ts
1328
+ var ROLE_CAPABILITIES = Object.freeze({
1329
+ claude: { workerModel: true, subworkerModel: true, reviewer: true },
1330
+ "cursor-agent": { workerModel: true, subworkerModel: false, reviewer: true },
1331
+ codex: { workerModel: true, subworkerModel: false, reviewer: false },
1332
+ openrouter: { workerModel: true, subworkerModel: false, reviewer: false },
1333
+ "cursor-acp": { workerModel: false, subworkerModel: false, reviewer: false },
1334
+ local: { workerModel: true, subworkerModel: false, reviewer: false }
1335
+ });
1336
+ var ROLE_MODEL_ID = /^[A-Za-z0-9._:/+=,[\]-]{1,128}$/;
1337
+ var ROLE_WORKER_TYPE_KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
1338
+ var SUBWORKER_AUTO = "auto";
1339
+ var REVIEWER_SCOPES = ["off", "tick", "plan"];
1340
+ var REVIEWER_BACKENDS = ["auto", "claude", "cursor-agent"];
1341
+ var CLAUDE_SUBAGENT_MODEL_ENV = "CLAUDE_CODE_SUBAGENT_MODEL";
1342
+ function isPlainObject(v) {
1343
+ return v !== null && typeof v === "object" && !Array.isArray(v);
1344
+ }
1345
+ function modelField(v, where) {
1346
+ if (v === void 0 || v === null || v === "") return {};
1347
+ if (typeof v !== "string" || !ROLE_MODEL_ID.test(v.trim())) {
1348
+ return { error: `${where} must be a model id (letters, digits, . _ : / + = , [ ] -)` };
1349
+ }
1350
+ return { value: v.trim() };
1351
+ }
1352
+ function parseModelRoles(raw) {
1353
+ if (raw === void 0 || raw === null) return { ok: true, roles: {} };
1354
+ if (!isPlainObject(raw)) return { ok: false, error: "roles must be an object" };
1355
+ const roles = {};
1356
+ for (const key of Object.keys(raw)) {
1357
+ if (key !== "worker" && key !== "subworker" && key !== "reviewer") {
1358
+ return { ok: false, error: `unknown roles key: ${key}` };
1359
+ }
1360
+ }
1361
+ if (raw.worker !== void 0 && raw.worker !== null) {
1362
+ const w = raw.worker;
1363
+ if (!isPlainObject(w)) return { ok: false, error: "roles.worker must be an object" };
1364
+ for (const key of Object.keys(w)) {
1365
+ if (key !== "backend" && key !== "model") {
1366
+ return { ok: false, error: `unknown roles.worker key: ${key}` };
1367
+ }
1368
+ }
1369
+ const worker = {};
1370
+ if (w.backend !== void 0 && w.backend !== null && w.backend !== "") {
1371
+ const b = typeof w.backend === "string" ? w.backend.trim().toLowerCase() : "";
1372
+ if (!isRequestedBackend(b)) {
1373
+ return {
1374
+ ok: false,
1375
+ error: `roles.worker.backend must be auto or a kit backend id (got ${JSON.stringify(w.backend)})`
1376
+ };
1377
+ }
1378
+ worker.backend = b;
1379
+ }
1380
+ const m = modelField(w.model, "roles.worker.model");
1381
+ if (m.error) return { ok: false, error: m.error };
1382
+ if (m.value) worker.model = m.value;
1383
+ roles.worker = worker;
1384
+ }
1385
+ if (raw.subworker !== void 0 && raw.subworker !== null) {
1386
+ const s = raw.subworker;
1387
+ if (!isPlainObject(s)) return { ok: false, error: "roles.subworker must be an object" };
1388
+ for (const key of Object.keys(s)) {
1389
+ if (key !== "model" && key !== "byWorkerType") {
1390
+ return { ok: false, error: `unknown roles.subworker key: ${key}` };
1391
+ }
1392
+ }
1393
+ const sub = {};
1394
+ const m = modelField(s.model, "roles.subworker.model");
1395
+ if (m.error) return { ok: false, error: m.error };
1396
+ if (m.value) sub.model = m.value;
1397
+ if (s.byWorkerType !== void 0 && s.byWorkerType !== null) {
1398
+ if (!isPlainObject(s.byWorkerType)) {
1399
+ return { ok: false, error: "roles.subworker.byWorkerType must be an object" };
1400
+ }
1401
+ const map = {};
1402
+ for (const [type, value] of Object.entries(s.byWorkerType)) {
1403
+ if (!ROLE_WORKER_TYPE_KEY.test(type)) {
1404
+ return {
1405
+ ok: false,
1406
+ error: `roles.subworker.byWorkerType key ${type} is not a worker_type`
1407
+ };
1408
+ }
1409
+ const mv = modelField(value, `roles.subworker.byWorkerType.${type}`);
1410
+ if (mv.error) return { ok: false, error: mv.error };
1411
+ if (mv.value) map[type] = mv.value;
1412
+ }
1413
+ sub.byWorkerType = map;
1414
+ }
1415
+ roles.subworker = sub;
1416
+ }
1417
+ if (raw.reviewer !== void 0 && raw.reviewer !== null) {
1418
+ const r = raw.reviewer;
1419
+ if (!isPlainObject(r)) return { ok: false, error: "roles.reviewer must be an object" };
1420
+ const reviewer = {};
1421
+ for (const key of Object.keys(r)) {
1422
+ if (!["enabled", "scope", "backend", "model", "advisorModel"].includes(key)) {
1423
+ return { ok: false, error: `unknown roles.reviewer key: ${key}` };
1424
+ }
1425
+ }
1426
+ if (r.enabled !== void 0 && r.enabled !== null) {
1427
+ if (typeof r.enabled !== "boolean") {
1428
+ return { ok: false, error: "roles.reviewer.enabled must be boolean" };
1429
+ }
1430
+ reviewer.enabled = r.enabled;
1431
+ }
1432
+ if (r.scope !== void 0 && r.scope !== null) {
1433
+ if (typeof r.scope !== "string" || !REVIEWER_SCOPES.includes(r.scope)) {
1434
+ return { ok: false, error: "roles.reviewer.scope must be off, tick, or plan" };
1435
+ }
1436
+ reviewer.scope = r.scope;
1437
+ }
1438
+ if (r.backend !== void 0 && r.backend !== null) {
1439
+ if (typeof r.backend !== "string" || !REVIEWER_BACKENDS.includes(r.backend)) {
1440
+ return { ok: false, error: "roles.reviewer.backend must be auto, claude, or cursor-agent" };
1441
+ }
1442
+ reviewer.backend = r.backend;
1443
+ }
1444
+ for (const key of ["model", "advisorModel"]) {
1445
+ const mv = modelField(r[key], `roles.reviewer.${key}`);
1446
+ if (mv.error) return { ok: false, error: mv.error };
1447
+ if (mv.value) reviewer[key] = mv.value;
1448
+ }
1449
+ roles.reviewer = reviewer;
1450
+ }
1451
+ return { ok: true, roles };
1452
+ }
1453
+ function frontmatterBlock(planText) {
1454
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(planText);
1455
+ return m?.[1] ?? null;
1456
+ }
1457
+ function unquote(v) {
1458
+ const t = v.trim();
1459
+ if (t.length >= 2 && (t[0] === '"' || t[0] === "'") && t[t.length - 1] === t[0]) {
1460
+ return t.slice(1, -1).trim();
1461
+ }
1462
+ return t;
1463
+ }
1464
+ function readPlanRoleOverrides(planText) {
1465
+ const block = frontmatterBlock(planText);
1466
+ if (!block) return {};
1467
+ const out = {};
1468
+ const top = (key) => {
1469
+ const m = new RegExp(`^${key}:[ \\t]*(.+)$`, "m").exec(block);
1470
+ const v = m?.[1] ? unquote(m[1]) : "";
1471
+ return v ? v : void 0;
1472
+ };
1473
+ const wb = top("worker_backend");
1474
+ if (wb) out.workerBackend = wb;
1475
+ const wm = top("worker_model");
1476
+ if (wm) out.workerModel = wm;
1477
+ const sm = top("subworker_model");
1478
+ if (sm) out.subworkerModel = sm;
1479
+ const items = block.split(/^\s*- id:/m).slice(1);
1480
+ for (const item of items) {
1481
+ const status = /^\s*status:\s*(\S+)/m.exec(item)?.[1];
1482
+ if (status !== "pending" && status !== "in_progress") continue;
1483
+ if (unquote(item.split("\n")[0] ?? "") === "dogfood-poc") continue;
1484
+ const type = /^\s*worker_type:\s*(.+)$/m.exec(item)?.[1];
1485
+ if (type) out.nextWorkerType = unquote(type);
1486
+ break;
1487
+ }
1488
+ return out;
1489
+ }
1490
+ var RANK = { flag: 3, plan: 2, config: 1, default: 0 };
1491
+ function resolveWorkerRole(input) {
1492
+ const warnings = [];
1493
+ const layers = [
1494
+ {
1495
+ source: "flag",
1496
+ backend: input.flagBackend?.trim() || void 0,
1497
+ model: input.flagModel?.trim() || void 0
1498
+ },
1499
+ { source: "plan", backend: input.plan?.workerBackend, model: input.plan?.workerModel },
1500
+ { source: "config", backend: input.roles?.worker?.backend, model: input.roles?.worker?.model },
1501
+ { source: "default", backend: input.defaultBackend }
1502
+ ];
1503
+ const bLayer = layers.find((l) => l.backend) ?? {
1504
+ source: "default",
1505
+ backend: input.defaultBackend
1506
+ };
1507
+ const backend = bLayer.backend.trim().toLowerCase();
1508
+ let model;
1509
+ let modelSource;
1510
+ for (const l of layers) {
1511
+ if (!l.model) continue;
1512
+ if (RANK[l.source] < RANK[bLayer.source]) {
1513
+ warnings.push(
1514
+ `${l.source} model ${l.model} ignored: the backend ${backend} came from the ${bLayer.source} layer, and a model only applies to its own backend or a lower layer's`
1515
+ );
1516
+ break;
1517
+ }
1518
+ model = l.model;
1519
+ modelSource = l.source;
1520
+ break;
1521
+ }
1522
+ if (model && modelSource !== "flag" && isBackendId(backend) && !ROLE_CAPABILITIES[backend].workerModel) {
1523
+ warnings.push(
1524
+ `${modelSource} model ${model} ignored: ${backend} cannot select a model (docs/model-roles-capability-matrix.md)`
1525
+ );
1526
+ model = void 0;
1527
+ modelSource = void 0;
1528
+ }
1529
+ return {
1530
+ backend,
1531
+ ...model ? { model, modelSource } : {},
1532
+ backendSource: bLayer.source,
1533
+ warnings
1534
+ };
1535
+ }
1536
+ function resolveSubworkerModel(input) {
1537
+ const sub = input.roles?.subworker;
1538
+ const type = input.plan?.nextWorkerType;
1539
+ let model;
1540
+ let source;
1541
+ if (input.plan?.subworkerModel) {
1542
+ model = input.plan.subworkerModel;
1543
+ source = "plan";
1544
+ } else if (type && sub?.byWorkerType?.[type]) {
1545
+ model = sub.byWorkerType[type];
1546
+ source = "worker_type";
1547
+ } else if (sub?.model) {
1548
+ model = sub.model;
1549
+ source = "config";
1550
+ }
1551
+ if (!model) return {};
1552
+ if (model === SUBWORKER_AUTO) {
1553
+ return {
1554
+ warning: "subworker model auto is reserved and not implemented yet (auto tier routing); no subworker model set"
1555
+ };
1556
+ }
1557
+ if (!ROLE_MODEL_ID.test(model)) {
1558
+ return {
1559
+ warning: `subworker model ${JSON.stringify(model)} is not a model id; no subworker model set`
1560
+ };
1561
+ }
1562
+ if (!ROLE_CAPABILITIES[input.backend].subworkerModel) {
1563
+ const how = input.backend === "cursor-agent" ? "Cursor subagents follow the worker model (model: inherit)" : "subagents keep the backend default";
1564
+ return {
1565
+ warning: `subworker model ${model} is not supported on ${input.backend}; ${how} (docs/model-roles-capability-matrix.md)`
1566
+ };
1567
+ }
1568
+ return { model, source };
1569
+ }
1570
+ function describeResolvedRoles(input) {
1571
+ const model = input.model ? `${input.model} (${input.modelSource ?? "flag"})` : "backend default";
1572
+ const sub = input.subworker?.model ? `, subworker ${input.subworker.model} (${input.subworker.source})` : "";
1573
+ return `roles: worker ${input.backendId} (${input.backendSource}), model ${model}${sub}`;
1574
+ }
1575
+ function resolveReviewerRole(roles, externalPlanReview) {
1576
+ const r = roles?.reviewer;
1577
+ const legacyOn = isPlainObject(externalPlanReview) && externalPlanReview.enabled === true;
1578
+ const fields = {
1579
+ ...r?.backend ? { backend: r.backend } : {},
1580
+ ...r?.model ? { model: r.model } : {},
1581
+ ...r?.advisorModel ? { advisorModel: r.advisorModel } : {}
1582
+ };
1583
+ if (r?.enabled === false || r?.scope === "off") {
1584
+ return { scope: "off", source: "roles", ...fields };
1585
+ }
1586
+ const on = r?.enabled === true || legacyOn;
1587
+ const source = r?.enabled === true ? "roles" : legacyOn ? "externalPlanReview" : "default";
1588
+ if (!on) return { scope: "off", source, ...fields };
1589
+ return { scope: r?.scope ?? "plan", source, ...fields };
1590
+ }
1591
+ function normalizeReviewModelId(raw) {
1592
+ const id = (raw ?? "").toLowerCase().replace(/\s+/g, "").replace(/\[.*$/, "");
1593
+ if (id === "" || id === "auto" || id === "cursor-auto" || id === "cursorauto" || id === "default")
1594
+ return "auto";
1595
+ return id;
1596
+ }
1597
+ var FAMILY_PATTERNS = [
1598
+ [
1599
+ "haiku",
1600
+ /^(haiku|claude-haiku|claude-3-haiku.*|claude-3\.5-haiku.*|claude-3-5-haiku.*|claude-haiku-.*|claude-4-haiku.*|claude-4\.5-haiku.*)$/
1601
+ ],
1602
+ [
1603
+ "opus",
1604
+ /^(opus|claude-opus|claude-3-opus.*|claude-opus-.*|claude-4-opus.*|claude-4\.5-opus.*)$/
1605
+ ],
1606
+ [
1607
+ "sonnet",
1608
+ /^(sonnet|claude-sonnet|claude-3-sonnet.*|claude-3\.5-sonnet.*|claude-3-5-sonnet.*|claude-3-7-sonnet.*|claude-sonnet-.*|claude-4-sonnet.*|claude-4\.5-sonnet.*)$/
1609
+ ],
1610
+ ["fable", /^(fable|claude-fable|claude-fable-.*)$/],
1611
+ ["composer", /^(composer|composer-.*|cursor-composer.*)$/],
1612
+ ["grok", /^(grok|grok-.*)$/]
1613
+ ];
1614
+ function reviewModelFamily(raw) {
1615
+ const id = normalizeReviewModelId(raw);
1616
+ for (const [family, pattern] of FAMILY_PATTERNS) if (pattern.test(id)) return family;
1617
+ return id;
1618
+ }
1619
+ function isFamilyAlias(id, family) {
1620
+ return id === family || id === `claude-${family}` || id === `cursor-${family}`;
1621
+ }
1622
+ function reviewModelRelation(implementer, reviewer) {
1623
+ const a = normalizeReviewModelId(implementer);
1624
+ const b = normalizeReviewModelId(reviewer);
1625
+ if (a === b) return "identical";
1626
+ const fa = reviewModelFamily(a);
1627
+ const fb = reviewModelFamily(b);
1628
+ if (fa !== fb) return "different";
1629
+ if (isFamilyAlias(a, fa) || isFamilyAlias(b, fb)) return "identical";
1630
+ return "same-family";
1631
+ }
1632
+ function describeIdenticalReviewModel(implementer, reviewer) {
1633
+ return `reviewer model ${reviewer} is the implementer model (${implementer}): identical-model review is refused, Auto/Auto and a family alias against an id of that family included. This is not a silent self-review; set roles.reviewer.model to a different model`;
1634
+ }
1635
+ function describeSameFamilyReviewModel(implementer, reviewer) {
1636
+ return `reviewer model ${reviewer} and implementer model ${implementer} are the same family (${reviewModelFamily(reviewer)}): the review runs, as a second read by a different model of one family`;
1637
+ }
1638
+ function resolveReviewJobRole(input) {
1639
+ const flagBackend = input.flagBackend?.trim() ?? "";
1640
+ const flagModel = input.flagModel?.trim() ?? "";
1641
+ const reviewer = input.roles?.reviewer;
1642
+ const backend = flagBackend || reviewer?.backend || "auto";
1643
+ const backendSource = flagBackend ? "flag" : reviewer?.backend ? "config" : "default";
1644
+ const model = flagModel || (flagBackend ? "" : reviewer?.model ?? "");
1645
+ const out = {
1646
+ backend,
1647
+ backendSource,
1648
+ ...model ? { model, modelSource: flagModel ? "flag" : "config" } : {}
1649
+ };
1650
+ const implementer = input.roles?.worker?.model;
1651
+ if (model && implementer) {
1652
+ const relation = reviewModelRelation(implementer, model);
1653
+ if (relation === "identical") out.refusal = describeIdenticalReviewModel(implementer, model);
1654
+ else if (relation === "same-family") {
1655
+ out.warning = describeSameFamilyReviewModel(implementer, model);
1656
+ }
1657
+ }
1658
+ return out;
1659
+ }
1660
+ function checkPlanRoleOverrides(plan) {
1661
+ if (plan.workerBackend && !isRequestedBackend(plan.workerBackend.toLowerCase())) {
1662
+ return `plan frontmatter worker_backend must be auto or a kit backend id (got ${JSON.stringify(plan.workerBackend)})`;
1663
+ }
1664
+ for (const [key, value] of [
1665
+ ["worker_model", plan.workerModel],
1666
+ ["subworker_model", plan.subworkerModel]
1667
+ ]) {
1668
+ if (value && !ROLE_MODEL_ID.test(value)) {
1669
+ return `plan frontmatter ${key} must be a model id (got ${JSON.stringify(value)})`;
1670
+ }
1671
+ }
1672
+ return null;
1673
+ }
1674
+ async function loadRolesContext(root, usePlan) {
1675
+ const config = await loadContextConfig(root);
1676
+ const parsed = parseModelRoles(config?.roles);
1677
+ if (!parsed.ok) return { ok: false, error: `.cursor/context/config.json: ${parsed.error}` };
1678
+ let plan = {};
1679
+ if (usePlan) {
1680
+ const planPath = await resolveActivePlanPath(root);
1681
+ if (planPath) {
1682
+ plan = readPlanRoleOverrides(await readPlan(planPath).catch(() => ""));
1683
+ const problem = checkPlanRoleOverrides(plan);
1684
+ if (problem) return { ok: false, error: `${planPath}: ${problem}` };
1685
+ }
1686
+ }
1687
+ return {
1688
+ ok: true,
1689
+ roles: parsed.roles,
1690
+ plan,
1691
+ reviewer: resolveReviewerRole(parsed.roles, config?.externalPlanReview)
1692
+ };
1693
+ }
1694
+
1695
+ // src/plan-loop/local.ts
1696
+ var LOCAL_PROVIDER = "agent-kit-local";
1697
+ var LOCAL_PLACEHOLDER_KEY = "agent-kit-local-no-key";
1698
+ var LOCAL_DEFAULT_CONTEXT_WINDOW = 32768;
1699
+ var LOCAL_DEFAULT_MAX_TOKENS = 8192;
1700
+ var OMARCHY_START_TIMEOUT_MS = 10 * 6e4;
1701
+ var OMARCHY_OVERLAY_TIMEOUT_MS = 3e4;
1702
+ var OMARCHY_STATUS_TIMEOUT_MS = 1e4;
1703
+ var LOADING_HEARTBEAT_MS = 5e3;
1704
+ var STATUS_POLL_MS = 2e3;
1705
+ var OMARCHY_RECIPE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1706
+ var modelsHint = "List the models on this machine with `agent-kit models`.";
1707
+ function parseLocalModelId(raw) {
1708
+ const id = (raw ?? "").trim();
1709
+ const sources = LOCAL_MODEL_SOURCES.join(", ");
1710
+ if (!id) {
1711
+ return {
1712
+ ok: false,
1713
+ message: `local backend: --model <source>:<id> is required (sources: ${sources}). ${modelsHint}`
1714
+ };
1715
+ }
1716
+ const colon = id.indexOf(":");
1717
+ const source = colon > 0 ? id.slice(0, colon) : "";
1718
+ const sourceId = colon > 0 ? id.slice(colon + 1) : "";
1719
+ if (!LOCAL_MODEL_SOURCES.includes(source) || !sourceId) {
1720
+ return {
1721
+ ok: false,
1722
+ message: `local backend: model ${JSON.stringify(id)} is not <source>:<id> with a source among ${sources}. ${modelsHint}`
1723
+ };
1724
+ }
1725
+ if (!ROLE_MODEL_ID.test(id)) {
1726
+ return {
1727
+ ok: false,
1728
+ message: `local backend: model ${JSON.stringify(id)} has characters the kit does not pass to a model (allowed: letters, digits and . _ : / + = , [ ] -, at most 128). Give the model a plain name in its server, then pick it from \`agent-kit models\`.`
1729
+ };
1730
+ }
1731
+ if (source === "omarchy" && !OMARCHY_RECIPE.test(sourceId)) {
1732
+ return {
1733
+ ok: false,
1734
+ message: `local backend: ${JSON.stringify(id)} is not an Omarchy recipe on this machine (a model shared by another host is out of scope). ${modelsHint}`
1735
+ };
1736
+ }
1737
+ return { ok: true, id, source, sourceId };
1738
+ }
1739
+ function findRunnableLocalModel(id, report) {
1740
+ const model = report.models.find((m) => m.id === id);
1741
+ if (!model) {
1742
+ const listed = report.models.map((m) => m.id);
1743
+ return {
1744
+ ok: false,
1745
+ message: `local backend: ${id} is not listed on this machine (${listed.length > 0 ? `listed: ${listed.join(", ")}` : "no local text models found"}). ${modelsHint} The kit does not fall back to another engine.`
1746
+ };
1747
+ }
1748
+ if (!model.runnable) {
1749
+ return {
1750
+ ok: false,
1751
+ message: `local backend: ${id} is not runnable (${model.reason ?? model.state}). ${modelsHint} The kit does not fall back to another engine.`
1752
+ };
1753
+ }
1754
+ return { ok: true, model };
1755
+ }
1756
+ function localProviderSource(model, sourceId) {
1757
+ const config = {
1758
+ name: "Agent Kit local model",
1759
+ baseUrl: model.endpoint,
1760
+ apiKey: LOCAL_PLACEHOLDER_KEY,
1761
+ api: "openai-completions",
1762
+ models: [
1763
+ {
1764
+ type: "chat",
1765
+ id: sourceId,
1766
+ name: model.label,
1767
+ reasoning: false,
1768
+ input: ["text"],
1769
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1770
+ contextWindow: model.contextWindow ?? LOCAL_DEFAULT_CONTEXT_WINDOW,
1771
+ maxTokens: LOCAL_DEFAULT_MAX_TOKENS
1772
+ }
1773
+ ]
1774
+ };
1775
+ return [
1776
+ "// Generated by agent-kit for one local-model tick (ADR 2026-11-28_local-model-backend-pi point 6); removed when the tick ends.",
1777
+ `const config = ${JSON.stringify(config, null, 2)};`,
1778
+ "export default function (pi) {",
1779
+ ` pi.registerProvider(${JSON.stringify(LOCAL_PROVIDER)}, config);`,
1780
+ "}",
1781
+ ""
1782
+ ].join("\n");
1783
+ }
1784
+ function execFailure(what, run, timeoutMs) {
1785
+ if (run.reason === "missing") return `${what}: omarchy-models not on PATH`;
1786
+ if (run.reason === "timeout")
1787
+ return `${what}: no answer within ${Math.round(timeoutMs / 1e3)} s`;
1788
+ return `${what} failed${run.detail ? `: ${run.detail}` : ""}`;
1789
+ }
1790
+ async function startOmarchyRecipe(bin, model, recipe, deps, progress) {
1791
+ const exec = deps.execFn ?? defaultExecFn;
1792
+ const now = deps.now ?? Date.now;
1793
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1794
+ const timeoutMs = deps.startTimeoutMs ?? OMARCHY_START_TIMEOUT_MS;
1795
+ const t0 = now();
1796
+ const report = (phase, detail) => progress({
1797
+ kind: "model_loading",
1798
+ model: model.id,
1799
+ phase,
1800
+ elapsedMs: now() - t0,
1801
+ ...detail ? { detail } : {}
1802
+ });
1803
+ report("starting");
1804
+ const heartbeat = setInterval(() => report("loading"), deps.heartbeatMs ?? LOADING_HEARTBEAT_MS);
1805
+ heartbeat.unref?.();
1806
+ try {
1807
+ const started = await exec(bin, ["start", recipe], timeoutMs);
1808
+ if (!started.ok)
1809
+ throw new Error(execFailure(`omarchy-models start ${recipe}`, started, timeoutMs));
1810
+ for (; ; ) {
1811
+ const status = await exec(bin, ["status", "--json"], OMARCHY_STATUS_TIMEOUT_MS);
1812
+ if (status.ok) {
1813
+ let state;
1814
+ try {
1815
+ state = parseOmarchyStatus(JSON.parse(status.stdout)).models.find(
1816
+ (m) => m.id === model.id
1817
+ )?.state;
1818
+ } catch {
1819
+ state = void 0;
1820
+ }
1821
+ if (state === "running") break;
1822
+ if (state === "not-fit") throw new Error(`${model.id} does not fit this machine now`);
1823
+ }
1824
+ if (now() - t0 >= timeoutMs) {
1825
+ throw new Error(
1826
+ `${model.id} did not report running within ${Math.round(timeoutMs / 1e3)} s`
1827
+ );
1828
+ }
1829
+ await sleep(deps.pollMs ?? STATUS_POLL_MS);
1830
+ }
1831
+ report("ready");
1832
+ } catch (err) {
1833
+ const detail = err instanceof Error ? err.message : String(err);
1834
+ report("failed", detail);
1835
+ throw new Error(`local backend: ${detail}. The kit does not fall back to another engine.`);
1836
+ } finally {
1837
+ clearInterval(heartbeat);
1838
+ }
1839
+ }
1840
+ async function prepareLocalProvider(model, parsed, deps = {}, progress = () => {
1841
+ }) {
1842
+ if (!isLoopbackUrl(model.endpoint)) {
1843
+ throw new Error(`local backend: ${model.id} is not served from a loopback address`);
1844
+ }
1845
+ if (parsed.source === "omarchy") {
1846
+ const bin = await (deps.whichFn ?? whichBinary)("omarchy-models");
1847
+ if (!bin) throw new Error("local backend: omarchy-models not on PATH");
1848
+ if (model.state === "stopped") {
1849
+ await startOmarchyRecipe(bin, model, parsed.sourceId, deps, progress);
1850
+ }
1851
+ const exec = deps.execFn ?? defaultExecFn;
1852
+ const run = await exec(bin, ["overlay", "pi", parsed.sourceId], OMARCHY_OVERLAY_TIMEOUT_MS);
1853
+ if (!run.ok) {
1854
+ throw new Error(
1855
+ `local backend: ${execFailure(`omarchy-models overlay pi ${parsed.sourceId}`, run, OMARCHY_OVERLAY_TIMEOUT_MS)}`
1856
+ );
1857
+ }
1858
+ const lines = run.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
1859
+ const [extension, provider, piModel] = lines;
1860
+ if (lines.length !== 3 || !extension || !provider || !piModel || !path3.isAbsolute(extension)) {
1861
+ throw new Error(
1862
+ `local backend: omarchy-models overlay pi ${parsed.sourceId} did not print an extension path, a provider and a model (got ${lines.length} line(s))`
1863
+ );
1864
+ }
1865
+ return withTempDir(deps, async () => ({ extensions: [extension], provider, model: piModel }));
1866
+ }
1867
+ return withTempDir(deps, async (dir) => {
1868
+ const file = path3.join(dir, "provider.ts");
1869
+ await writeFile(file, localProviderSource(model, parsed.sourceId), { mode: 384 });
1870
+ return { extensions: [file], provider: LOCAL_PROVIDER, model: parsed.sourceId };
1871
+ });
1872
+ }
1873
+ async function withTempDir(deps, fill) {
1874
+ const dir = await mkdtemp(path3.join(deps.tmpRoot ?? tmpdir(), "agent-kit-local-"));
1875
+ try {
1876
+ const agentDir = path3.join(dir, "pi-agent");
1877
+ await mkdir(agentDir, { mode: 448 });
1878
+ return { ...await fill(dir), tempDir: dir, agentDir };
1879
+ } catch (err) {
1880
+ await rm(dir, { recursive: true, force: true });
1881
+ throw err;
1882
+ }
1883
+ }
1884
+ async function cleanupLocalProvider(setup) {
1885
+ if (!setup.tempDir) return;
1886
+ await rm(setup.tempDir, { recursive: true, force: true }).catch(() => void 0);
1887
+ }
1888
+ function localPiArgs(setup) {
1889
+ return [
1890
+ "--mode",
1891
+ "rpc",
1892
+ "--no-session",
1893
+ "--offline",
1894
+ "--no-extensions",
1895
+ ...setup.extensions.flatMap((file) => ["--extension", file]),
1896
+ "--no-skills",
1897
+ "--no-prompt-templates",
1898
+ "--no-approve",
1899
+ "--provider",
1900
+ setup.provider,
1901
+ "--model",
1902
+ setup.model
1903
+ ];
1904
+ }
1905
+ function localChildEnv(overrides, agentDir) {
1906
+ return {
1907
+ ...mergeChildEnv(overrides),
1908
+ PI_OFFLINE: "1",
1909
+ PI_SKIP_VERSION_CHECK: "1",
1910
+ PI_TELEMETRY: "0",
1911
+ ...agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}
1912
+ };
1913
+ }
1914
+ function piRpcPromptLine(text) {
1915
+ return `${JSON.stringify({ type: "prompt", message: text })}
1916
+ `;
1917
+ }
1918
+ function piSlashPointer(name) {
1919
+ return [
1920
+ `Read \`.cursor/commands/${name}.md\` now and follow that contract exactly \u2014 it is the source of truth for /${name}; this paragraph is only a thin adapter for pi (local model, headless).`,
1921
+ "",
1922
+ "Adapter rules (pi, headless):",
1923
+ "- Ask questions is unavailable here: print one line `HITL_GATE: <ask-id> | <label 1> | <label 2> | ...` immediately followed by the same labels as one numbered list, one list per message, then end your turn and WAIT for the answer (ask-id and labels: `.cursor/skills/core/hitl-gates/SKILL.md`). The answer arrives as your next prompt, `HITL_REPLY: <ask-id> | operator reply <n> | <label>`; cite that line as the Ask provenance.",
1924
+ "- Skip or cancel means stop.",
1925
+ "- Never `/git-prod` without an explicit operator yes.",
1926
+ "- Do not clone Cursor hooks or invent behavior beyond the SoT file."
1927
+ ].join("\n");
1928
+ }
1929
+ var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1930
+ var line3 = (event) => JSON.stringify(event);
1931
+ var num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
1932
+ function messageText(content) {
1933
+ if (typeof content === "string") return content;
1934
+ if (!Array.isArray(content)) return "";
1935
+ return content.filter((c) => isRecord4(c) && c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
1936
+ }
1937
+ function createPiTranslator(opts) {
1938
+ const sessionId = opts.sessionId ?? `pi-${randomUUID()}`;
1939
+ let started = false;
1940
+ let lastText = "";
1941
+ let lastError = null;
1942
+ let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1943
+ const result = (error) => {
1944
+ const out = line3({
1945
+ type: "result",
1946
+ subtype: error ? "error_during_execution" : "success",
1947
+ is_error: error !== null,
1948
+ result: lastText,
1949
+ session_id: sessionId,
1950
+ usage: {
1951
+ input_tokens: usage.input,
1952
+ output_tokens: usage.output,
1953
+ cache_read_input_tokens: usage.cacheRead,
1954
+ cache_creation_input_tokens: usage.cacheWrite
1955
+ },
1956
+ ...error ? { errors: [error] } : {}
1957
+ });
1958
+ lastText = "";
1959
+ lastError = null;
1960
+ usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1961
+ return out;
1962
+ };
1963
+ return (raw) => {
1964
+ const text = raw.trim();
1965
+ if (!text) return [];
1966
+ if (!text.startsWith("{")) return [raw];
1967
+ let event;
1968
+ try {
1969
+ event = JSON.parse(text);
1970
+ } catch {
1971
+ return [raw];
1972
+ }
1973
+ if (!isRecord4(event)) return [];
1974
+ switch (event.type) {
1975
+ case "response": {
1976
+ if (event.command !== "prompt") return [];
1977
+ if (event.success === false) {
1978
+ const why = typeof event.error === "string" ? event.error : "rejected";
1979
+ return [result(`pi refused the prompt: ${why}`)];
1980
+ }
1981
+ const data = isRecord4(event.data) ? event.data : null;
1982
+ if (data?.disposition === "handled") {
1983
+ return [result("pi handled the prompt without running the model")];
1984
+ }
1985
+ return [];
1986
+ }
1987
+ case "agent_start":
1988
+ if (started) return [];
1989
+ started = true;
1990
+ return [
1991
+ line3({ type: "system", subtype: "init", session_id: sessionId, model: opts.model })
1992
+ ];
1993
+ case "message_end": {
1994
+ const message = isRecord4(event.message) ? event.message : null;
1995
+ if (!message) return [];
1996
+ if (message.role === "user") {
1997
+ const said2 = messageText(message.content);
1998
+ if (!said2) return [];
1999
+ return [
2000
+ line3({
2001
+ type: "user",
2002
+ isReplay: true,
2003
+ message: { role: "user", content: [{ type: "text", text: said2 }] }
2004
+ })
2005
+ ];
2006
+ }
2007
+ if (message.role !== "assistant") return [];
2008
+ const u = isRecord4(message.usage) ? message.usage : {};
2009
+ usage.input += num(u.input);
2010
+ usage.output += num(u.output);
2011
+ usage.cacheRead += num(u.cacheRead);
2012
+ usage.cacheWrite += num(u.cacheWrite);
2013
+ const stop = message.stopReason;
2014
+ if (stop === "error" || stop === "aborted") {
2015
+ lastError = typeof message.errorMessage === "string" && message.errorMessage ? message.errorMessage : `model turn ended with ${stop}`;
2016
+ } else {
2017
+ lastError = null;
2018
+ }
2019
+ const blocks = [];
2020
+ const content = Array.isArray(message.content) ? message.content : [];
2021
+ for (const part of content) {
2022
+ if (!isRecord4(part)) continue;
2023
+ if (part.type === "text" && typeof part.text === "string" && part.text) {
2024
+ blocks.push({ type: "text", text: part.text });
2025
+ } else if (part.type === "toolCall" && typeof part.name === "string") {
2026
+ blocks.push({
2027
+ type: "tool_use",
2028
+ id: typeof part.id === "string" ? part.id : "",
2029
+ name: part.name,
2030
+ input: isRecord4(part.arguments) ? part.arguments : {}
2031
+ });
2032
+ }
2033
+ }
2034
+ const said = messageText(content);
2035
+ if (said) lastText = said;
2036
+ if (blocks.length === 0) return [];
2037
+ return [line3({ type: "assistant", message: { role: "assistant", content: blocks } })];
2038
+ }
2039
+ case "tool_execution_end": {
2040
+ const res = isRecord4(event.result) ? event.result : {};
2041
+ return [
2042
+ line3({
2043
+ type: "user",
2044
+ message: {
2045
+ role: "user",
2046
+ content: [
2047
+ {
2048
+ type: "tool_result",
2049
+ tool_use_id: typeof event.toolCallId === "string" ? event.toolCallId : "",
2050
+ content: messageText(res.content),
2051
+ is_error: event.isError === true
2052
+ }
2053
+ ]
2054
+ }
2055
+ })
2056
+ ];
2057
+ }
2058
+ case "auto_retry_end":
2059
+ if (event.success === false) {
2060
+ lastError = typeof event.finalError === "string" && event.finalError ? event.finalError : "model request failed after retries";
2061
+ }
2062
+ return [];
2063
+ case "agent_settled":
2064
+ return [result(event.aborted === true ? lastError ?? "pi run aborted" : lastError)];
2065
+ default:
2066
+ return [];
2067
+ }
2068
+ };
2069
+ }
2070
+ function describeProgress(p) {
2071
+ const s = Math.round(p.elapsedMs / 1e3);
2072
+ switch (p.phase) {
2073
+ case "starting":
2074
+ return `local: starting ${p.model} (omarchy-models start); the tick runs once it is loaded.`;
2075
+ case "loading":
2076
+ return `local: ${p.model} still loading (${s} s).`;
2077
+ case "ready":
2078
+ return `local: ${p.model} is running (${s} s).`;
2079
+ default:
2080
+ return `local: ${p.model} did not start${p.detail ? `: ${p.detail}` : ""}.`;
2081
+ }
2082
+ }
2083
+ function createLocalBackend(deps = {}) {
2084
+ return {
2085
+ id: "local",
2086
+ async resolve() {
2087
+ return (deps.whichFn ?? whichBinary)("pi");
2088
+ },
2089
+ async run(opts) {
2090
+ const log = opts.log ?? ((text) => console.log(text));
2091
+ const parsed = parseLocalModelId(opts.model);
2092
+ if (!parsed.ok) throw new Error(parsed.message);
2093
+ const report = await (deps.discover ?? (() => discoverLocalModels({
2094
+ ...deps.whichFn ? { whichFn: deps.whichFn } : {},
2095
+ ...deps.execFn ? { execFn: deps.execFn } : {}
2096
+ })))();
2097
+ const found = findRunnableLocalModel(parsed.id, report);
2098
+ if (!found.ok) throw new Error(found.message);
2099
+ const prepared = await codexPrompt(opts.workspace, opts.prompt, piSlashPointer);
2100
+ if (!prepared.ok) {
2101
+ throw new Error(
2102
+ `local backend: ${prepared.missing} is missing in the workspace, so the tick's leading slash has no contract to point pi at. Install the kit (\`agent-kit install\`) and retry.`
2103
+ );
2104
+ }
2105
+ const progress = (p) => {
2106
+ log(describeProgress(p));
2107
+ opts.onProgress?.(p);
2108
+ };
2109
+ const setup = await prepareLocalProvider(found.model, parsed, deps, progress);
2110
+ try {
2111
+ const env = localChildEnv(opts.env, setup.agentDir);
2112
+ const redact = claudeRedactions(env);
2113
+ log(
2114
+ `local tick: pi --mode rpc on ${parsed.id} (provider ${setup.provider}, model ${setup.model}; only the kit's provider extension, temporary pi agent dir, no session file, offline, stdin relay).`
2115
+ );
2116
+ try {
2117
+ return await spawnLogged("pi", localPiArgs(setup), opts.logPath, {
2118
+ cwd: opts.workspace,
2119
+ env,
2120
+ redact,
2121
+ spawnFn: opts.spawnFn,
2122
+ hitl: resolveHitlRunOptions(opts.hitl, {
2123
+ kind: "stdin-stream-json",
2124
+ firstPrompt: prepared.prompt,
2125
+ encode: piRpcPromptLine
2126
+ }),
2127
+ render: opts.render,
2128
+ onSpawn: opts.onSpawn,
2129
+ backendId: "local",
2130
+ translate: createPiTranslator({ model: parsed.id })
2131
+ });
2132
+ } catch (err) {
2133
+ throw new Error(`local backend failed to start: ${redactSecrets(String(err), redact)}`);
2134
+ }
2135
+ } finally {
2136
+ await cleanupLocalProvider(setup);
2137
+ }
2138
+ }
2139
+ };
2140
+ }
2141
+ var localBackend = createLocalBackend();
2142
+
1135
2143
  // src/plan-loop/backends.ts
1136
2144
  function createLineTranslator(translate) {
1137
2145
  const decoder = new StringDecoder3("utf8");
1138
2146
  const lines = new LineSplitter();
1139
- const run = (line3, out) => {
2147
+ const run = (line4, out) => {
1140
2148
  try {
1141
- out.push(...translate(line3));
2149
+ out.push(...translate(line4));
1142
2150
  } catch {
1143
2151
  }
1144
2152
  };
@@ -1146,13 +2154,13 @@ function createLineTranslator(translate) {
1146
2154
  push(chunk) {
1147
2155
  const text = typeof chunk === "string" ? chunk : decoder.write(chunk);
1148
2156
  const out = [];
1149
- lines.feed(text, (line3) => run(line3, out));
2157
+ lines.feed(text, (line4) => run(line4, out));
1150
2158
  return out.length ? `${out.join("\n")}
1151
2159
  ` : "";
1152
2160
  },
1153
2161
  end() {
1154
2162
  const out = [];
1155
- lines.feed(decoder.end(), (line3) => run(line3, out));
2163
+ lines.feed(decoder.end(), (line4) => run(line4, out));
1156
2164
  const rest = lines.end();
1157
2165
  if (rest.trim()) run(rest, out);
1158
2166
  return out.length ? `${out.join("\n")}
@@ -1470,14 +2478,15 @@ function createRelay(hitl, child, redactedError) {
1470
2478
  resolveClosed = resolve;
1471
2479
  });
1472
2480
  const stdin = child.stdin;
2481
+ const encode = hitl.transport.kind === "stdin-stream-json" ? hitl.transport.encode ?? userEventLine : userEventLine;
1473
2482
  if (hitl.transport.kind === "stdin-stream-json") {
1474
2483
  if (!stdin) {
1475
- startError = new Error("claude child has no writable stdin (stream-json transport)");
2484
+ startError = new Error("agent child has no writable stdin (stdin relay transport)");
1476
2485
  } else {
1477
2486
  stdin.on("error", () => {
1478
2487
  });
1479
2488
  try {
1480
- stdin.write(userEventLine(hitl.transport.firstPrompt));
2489
+ stdin.write(encode(hitl.transport.firstPrompt));
1481
2490
  } catch (err) {
1482
2491
  startError = redactedError(err);
1483
2492
  }
@@ -1555,7 +2564,7 @@ function createRelay(hitl, child, redactedError) {
1555
2564
  record.replies.push(outcome.stamp);
1556
2565
  hitl.write(`\u2192 ${outcome.stamp.line}
1557
2566
  `);
1558
- stdin.write(userEventLine(outcome.stamp.line));
2567
+ stdin.write(encode(outcome.stamp.line));
1559
2568
  },
1560
2569
  (err) => {
1561
2570
  record.stop = unansweredStop(gate.askId, "child exited");
@@ -1743,9 +2752,9 @@ function claudeReviewArgs(opts = {}) {
1743
2752
  async function missingClaudeAdapter(workspace, prompt) {
1744
2753
  const m = /^\/([A-Za-z0-9][A-Za-z0-9_-]*)/.exec(prompt.trimStart());
1745
2754
  if (!m?.[1]) return null;
1746
- const rel = path2.join(".claude", "commands", `${m[1]}.md`);
2755
+ const rel = path4.join(".claude", "commands", `${m[1]}.md`);
1747
2756
  try {
1748
- await access2(path2.join(workspace, rel));
2757
+ await access2(path4.join(workspace, rel));
1749
2758
  return null;
1750
2759
  } catch {
1751
2760
  return rel;
@@ -1757,7 +2766,7 @@ var claudeBackend = {
1757
2766
  return whichBinary("claude");
1758
2767
  },
1759
2768
  async run(opts) {
1760
- const log = opts.log ?? ((line3) => console.log(line3));
2769
+ const log = opts.log ?? ((line4) => console.log(line4));
1761
2770
  const env = claudeChildEnv(opts.env);
1762
2771
  const redact = claudeRedactions(env);
1763
2772
  const version = checkClaudeVersion("claude", opts.versionFn);
@@ -1810,7 +2819,7 @@ var openrouterBackend = {
1810
2819
  return whichBinary("ori");
1811
2820
  },
1812
2821
  async run(opts) {
1813
- const log = opts.log ?? ((line3) => console.log(line3));
2822
+ const log = opts.log ?? ((line4) => console.log(line4));
1814
2823
  const env = claudeChildEnv(opts.env);
1815
2824
  const redact = claudeRedactions(env);
1816
2825
  const adapter = await missingClaudeAdapter(opts.workspace, opts.prompt);
@@ -1860,7 +2869,8 @@ function backends() {
1860
2869
  claude: claudeBackend,
1861
2870
  codex: codexBackend,
1862
2871
  "cursor-acp": cursorAcpBackend,
1863
- openrouter: openrouterBackend
2872
+ openrouter: openrouterBackend,
2873
+ local: localBackend
1864
2874
  };
1865
2875
  }
1866
2876
  function getBackend(id) {
@@ -1872,6 +2882,334 @@ function getBackend(id) {
1872
2882
  return backend;
1873
2883
  }
1874
2884
 
2885
+ // src/plan-loop/local-models.ts
2886
+ var LOCAL_MODELS_SCHEMA_VERSION = 1;
2887
+ var DEFAULT_SOURCE_TIMEOUT_MS = 1500;
2888
+ var LOCAL_MODEL_SOURCES = [
2889
+ "omarchy",
2890
+ "ollama",
2891
+ "lmstudio",
2892
+ "llamacpp"
2893
+ ];
2894
+ var OLLAMA_BASE = "http://127.0.0.1:11434";
2895
+ var LMSTUDIO_BASE = "http://127.0.0.1:1234";
2896
+ var LLAMACPP_BASE = "http://127.0.0.1:8080";
2897
+ var defaultExecFn = (file, args, timeoutMs) => new Promise((resolve) => {
2898
+ try {
2899
+ execFile(
2900
+ file,
2901
+ args,
2902
+ { encoding: "utf8", timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024, windowsHide: true },
2903
+ (error, stdout) => {
2904
+ if (!error) {
2905
+ resolve({ ok: true, stdout: String(stdout ?? "") });
2906
+ return;
2907
+ }
2908
+ const err = error;
2909
+ if (err.code === "ENOENT") resolve({ ok: false, reason: "missing" });
2910
+ else if (err.killed) resolve({ ok: false, reason: "timeout" });
2911
+ else resolve({ ok: false, reason: "failed", detail: firstLine(err.message) });
2912
+ }
2913
+ );
2914
+ } catch (err) {
2915
+ resolve({ ok: false, reason: "failed", detail: firstLine(String(err)) });
2916
+ }
2917
+ });
2918
+ var defaultFetchFn = (url, init) => fetch(url, init);
2919
+ function firstLine(text) {
2920
+ return (text.split("\n")[0] ?? "").trim().slice(0, 200);
2921
+ }
2922
+ function isLoopbackUrl(raw) {
2923
+ let url;
2924
+ try {
2925
+ url = new URL(raw);
2926
+ } catch {
2927
+ return false;
2928
+ }
2929
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
2930
+ const host = url.hostname.toLowerCase();
2931
+ return host === "localhost" || host === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(host);
2932
+ }
2933
+ function hostPort(url) {
2934
+ try {
2935
+ return new URL(url).host;
2936
+ } catch {
2937
+ return url;
2938
+ }
2939
+ }
2940
+ function errorCode(err) {
2941
+ const e = err;
2942
+ if (e && typeof e.cause?.code === "string") return e.cause.code;
2943
+ if (e && typeof e.code === "string") return e.code;
2944
+ return void 0;
2945
+ }
2946
+ async function getLoopbackJson(url, fetchFn, timeoutMs) {
2947
+ if (!isLoopbackUrl(url)) return { ok: false, note: `not a loopback address: ${url}` };
2948
+ const controller = new AbortController();
2949
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2950
+ try {
2951
+ const res = await fetchFn(url, {
2952
+ signal: controller.signal,
2953
+ redirect: "manual",
2954
+ headers: { accept: "application/json" }
2955
+ });
2956
+ if (res.status >= 300 && res.status < 400) {
2957
+ return { ok: false, note: `redirect refused (HTTP ${res.status} from ${hostPort(url)})` };
2958
+ }
2959
+ if (res.status !== 200) return { ok: false, note: `HTTP ${res.status} from ${hostPort(url)}` };
2960
+ const body = await res.text();
2961
+ try {
2962
+ return { ok: true, value: JSON.parse(body) };
2963
+ } catch {
2964
+ return { ok: false, note: `malformed JSON from ${hostPort(url)}` };
2965
+ }
2966
+ } catch (err) {
2967
+ if (controller.signal.aborted) {
2968
+ return { ok: false, note: `no answer within ${timeoutMs} ms (${hostPort(url)})` };
2969
+ }
2970
+ const code = errorCode(err);
2971
+ if (code === "ECONNREFUSED")
2972
+ return { ok: false, note: `connection refused (${hostPort(url)})` };
2973
+ return {
2974
+ ok: false,
2975
+ note: `request failed (${hostPort(url)}${code ? `, ${code}` : ""})`
2976
+ };
2977
+ } finally {
2978
+ clearTimeout(timer);
2979
+ controller.abort();
2980
+ }
2981
+ }
2982
+ function isRecord5(v) {
2983
+ return typeof v === "object" && v !== null && !Array.isArray(v);
2984
+ }
2985
+ function str(v) {
2986
+ return typeof v === "string" && v.trim() !== "" ? v.trim() : void 0;
2987
+ }
2988
+ function positiveInt(v) {
2989
+ return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : void 0;
2990
+ }
2991
+ function joinNotes(notes) {
2992
+ return notes.length > 0 ? notes.join("; ") : void 0;
2993
+ }
2994
+ function plural(n, word) {
2995
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
2996
+ }
2997
+ function parseOmarchyStatus(value) {
2998
+ const source = "omarchy";
2999
+ if (!isRecord5(value) || !isRecord5(value.models)) {
3000
+ return {
3001
+ status: { source, ok: false, note: "unexpected JSON shape (no models object)" },
3002
+ models: []
3003
+ };
3004
+ }
3005
+ const models = [];
3006
+ let nonLoopback = 0;
3007
+ let noEndpoint = 0;
3008
+ for (const [key, raw] of Object.entries(value.models)) {
3009
+ if (!isRecord5(raw) || raw.kind !== "text") continue;
3010
+ const recipe = str(raw.recipe) ?? str(key);
3011
+ if (!recipe) continue;
3012
+ const endpoint = str(raw.endpoint);
3013
+ if (!endpoint) {
3014
+ noEndpoint += 1;
3015
+ continue;
3016
+ }
3017
+ if (!isLoopbackUrl(endpoint)) {
3018
+ nonLoopback += 1;
3019
+ continue;
3020
+ }
3021
+ const running = raw.unit === "active" && raw.sub_state === "running";
3022
+ const state = running ? "running" : raw.fits === false ? "not-fit" : "stopped";
3023
+ const reason = state === "not-fit" ? str(raw.fit_reason) ?? "does not fit" : void 0;
3024
+ const model = {
3025
+ id: `${source}:${recipe}`,
3026
+ label: str(raw.name) ?? recipe,
3027
+ source,
3028
+ endpoint: endpoint.replace(/\/+$/, ""),
3029
+ state
3030
+ };
3031
+ const ctx = positiveInt(raw.ctx);
3032
+ if (ctx) model.contextWindow = ctx;
3033
+ const vendor = str(raw.vendor);
3034
+ if (vendor) model.vendor = vendor;
3035
+ if (reason) model.reason = reason;
3036
+ models.push(model);
3037
+ }
3038
+ const notes = [];
3039
+ if (nonLoopback > 0) notes.push(`skipped ${plural(nonLoopback, "non-loopback model")}`);
3040
+ if (noEndpoint > 0) notes.push(`skipped ${plural(noEndpoint, "model")} without an endpoint`);
3041
+ const note = joinNotes(notes);
3042
+ return { status: note ? { source, ok: true, note } : { source, ok: true }, models };
3043
+ }
3044
+ function isOllamaCloudModel(entry, name) {
3045
+ return name.endsWith(":cloud") || name.endsWith("-cloud") || str(entry.remote_host) !== void 0;
3046
+ }
3047
+ function parseOllamaTags(value) {
3048
+ const source = "ollama";
3049
+ if (!isRecord5(value) || !Array.isArray(value.models)) {
3050
+ return {
3051
+ status: { source, ok: false, note: "unexpected JSON shape (no models array)" },
3052
+ models: []
3053
+ };
3054
+ }
3055
+ const models = [];
3056
+ let cloud = 0;
3057
+ let notText = 0;
3058
+ for (const raw of value.models) {
3059
+ if (!isRecord5(raw)) continue;
3060
+ const name = str(raw.name) ?? str(raw.model);
3061
+ if (!name) continue;
3062
+ if (isOllamaCloudModel(raw, name)) {
3063
+ cloud += 1;
3064
+ continue;
3065
+ }
3066
+ if (Array.isArray(raw.capabilities) && !raw.capabilities.includes("completion")) {
3067
+ notText += 1;
3068
+ continue;
3069
+ }
3070
+ const model = {
3071
+ id: `${source}:${name}`,
3072
+ label: name,
3073
+ source,
3074
+ endpoint: `${OLLAMA_BASE}/v1`,
3075
+ state: "running"
3076
+ };
3077
+ const details = isRecord5(raw.details) ? raw.details : void 0;
3078
+ const family = details ? str(details.family) : void 0;
3079
+ if (family) model.vendor = family;
3080
+ models.push(model);
3081
+ }
3082
+ const notes = [];
3083
+ if (cloud > 0) notes.push(`skipped ${plural(cloud, "cloud model")}`);
3084
+ if (notText > 0) notes.push(`skipped ${plural(notText, "non-text model")}`);
3085
+ const note = joinNotes(notes);
3086
+ return { status: note ? { source, ok: true, note } : { source, ok: true }, models };
3087
+ }
3088
+ function parseOpenAiModels(source, base, value) {
3089
+ if (!isRecord5(value) || !Array.isArray(value.data)) {
3090
+ return {
3091
+ status: { source, ok: false, note: "unexpected JSON shape (no data array)" },
3092
+ models: []
3093
+ };
3094
+ }
3095
+ const models = [];
3096
+ for (const raw of value.data) {
3097
+ if (!isRecord5(raw)) continue;
3098
+ const id = str(raw.id);
3099
+ if (!id) continue;
3100
+ const model = {
3101
+ id: `${source}:${id}`,
3102
+ label: id,
3103
+ source,
3104
+ endpoint: `${base}/v1`,
3105
+ state: "running"
3106
+ };
3107
+ const owner = str(raw.owned_by);
3108
+ if (owner && owner !== "organization_owner" && owner !== "llamacpp") model.vendor = owner;
3109
+ models.push(model);
3110
+ }
3111
+ return { status: { source, ok: true }, models };
3112
+ }
3113
+ async function probeOmarchy(deps) {
3114
+ const source = "omarchy";
3115
+ const bin = await deps.whichFn("omarchy-models");
3116
+ if (!bin)
3117
+ return { status: { source, ok: false, note: "omarchy-models not on PATH" }, models: [] };
3118
+ const run = await deps.execFn(bin, ["status", "--json"], deps.timeoutMs);
3119
+ if (!run.ok) {
3120
+ const note = run.reason === "missing" ? "omarchy-models not on PATH" : run.reason === "timeout" ? `omarchy-models status gave no answer within ${deps.timeoutMs} ms` : `omarchy-models status failed${run.detail ? `: ${run.detail}` : ""}`;
3121
+ return { status: { source, ok: false, note }, models: [] };
3122
+ }
3123
+ let value;
3124
+ try {
3125
+ value = JSON.parse(run.stdout);
3126
+ } catch {
3127
+ return {
3128
+ status: { source, ok: false, note: "malformed JSON from omarchy-models status" },
3129
+ models: []
3130
+ };
3131
+ }
3132
+ return parseOmarchyStatus(value);
3133
+ }
3134
+ async function probeHttp(source, deps) {
3135
+ const url = source === "ollama" ? `${OLLAMA_BASE}/api/tags` : `${source === "lmstudio" ? LMSTUDIO_BASE : LLAMACPP_BASE}/v1/models`;
3136
+ const got = await getLoopbackJson(url, deps.fetchFn, deps.timeoutMs);
3137
+ if (!got.ok) return { status: { source, ok: false, note: got.note }, models: [] };
3138
+ if (source === "ollama") return parseOllamaTags(got.value);
3139
+ return parseOpenAiModels(
3140
+ source,
3141
+ source === "lmstudio" ? LMSTUDIO_BASE : LLAMACPP_BASE,
3142
+ got.value
3143
+ );
3144
+ }
3145
+ async function safely(source, run) {
3146
+ try {
3147
+ return await run();
3148
+ } catch (err) {
3149
+ return {
3150
+ status: { source, ok: false, note: `probe failed: ${firstLine(String(err))}` },
3151
+ models: []
3152
+ };
3153
+ }
3154
+ }
3155
+ async function discoverLocalModels(deps = {}) {
3156
+ const full = {
3157
+ whichFn: deps.whichFn ?? whichBinary,
3158
+ execFn: deps.execFn ?? defaultExecFn,
3159
+ fetchFn: deps.fetchFn ?? defaultFetchFn,
3160
+ timeoutMs: deps.timeoutMs ?? DEFAULT_SOURCE_TIMEOUT_MS
3161
+ };
3162
+ const [piPath, ...outcomes] = await Promise.all([
3163
+ full.whichFn("pi").catch(() => null),
3164
+ safely("omarchy", () => probeOmarchy(full)),
3165
+ safely("ollama", () => probeHttp("ollama", full)),
3166
+ safely("lmstudio", () => probeHttp("lmstudio", full)),
3167
+ safely("llamacpp", () => probeHttp("llamacpp", full))
3168
+ ]);
3169
+ const piFound = Boolean(piPath);
3170
+ const models = outcomes.flatMap(
3171
+ (o) => o.models.map((m) => {
3172
+ const runnable = piFound && m.state !== "not-fit";
3173
+ const { id, label, source, endpoint, state, ...optional } = m;
3174
+ const out = { id, label, source, endpoint, state, runnable, ...optional };
3175
+ if (!runnable && !out.reason) out.reason = "pi not on PATH";
3176
+ return out;
3177
+ })
3178
+ );
3179
+ return {
3180
+ schemaVersion: LOCAL_MODELS_SCHEMA_VERSION,
3181
+ models,
3182
+ sources: outcomes.map((o) => o.status),
3183
+ pi: { found: piFound }
3184
+ };
3185
+ }
3186
+ function renderLocalModels(report) {
3187
+ const lines = [];
3188
+ if (report.models.length === 0) {
3189
+ lines.push("No local text models found.");
3190
+ } else {
3191
+ const rows = report.models.map((m) => [
3192
+ m.id,
3193
+ m.state,
3194
+ m.runnable ? "yes" : "no",
3195
+ m.endpoint,
3196
+ m.reason ?? ""
3197
+ ]);
3198
+ const header = ["ID", "STATE", "RUNNABLE", "ENDPOINT", "NOTE"];
3199
+ const widths = header.map(
3200
+ (h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length))
3201
+ );
3202
+ const fmt = (cells) => cells.map((c, i) => i === cells.length - 1 ? c : c.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
3203
+ lines.push(fmt(header), ...rows.map(fmt));
3204
+ }
3205
+ lines.push("");
3206
+ for (const s of report.sources) {
3207
+ lines.push(`${s.source}: ${s.ok ? "ok" : "unavailable"}${s.note ? ` (${s.note})` : ""}`);
3208
+ }
3209
+ lines.push(`pi: ${report.pi.found ? "found" : "not on PATH (no model is runnable)"}`);
3210
+ return lines.join("\n");
3211
+ }
3212
+
1875
3213
  export {
1876
3214
  codexBackend,
1877
3215
  parseStreamLine,
@@ -1879,6 +3217,29 @@ export {
1879
3217
  renderStreamEvent,
1880
3218
  createStreamRenderer,
1881
3219
  cursorAcpBackend,
3220
+ discoverLocalModels,
3221
+ renderLocalModels,
3222
+ INSTALL_HINTS,
3223
+ listDetectBackendIds,
3224
+ detectAgentBackend,
3225
+ countPendingTodos,
3226
+ findActivePlanFile,
3227
+ readPlan,
3228
+ readRunQueueState,
3229
+ resolveActivePlanFromHandoff,
3230
+ resolveActivePlanPath,
3231
+ CLAUDE_SUBAGENT_MODEL_ENV,
3232
+ readPlanRoleOverrides,
3233
+ resolveWorkerRole,
3234
+ resolveSubworkerModel,
3235
+ describeResolvedRoles,
3236
+ reviewModelRelation,
3237
+ describeIdenticalReviewModel,
3238
+ describeSameFamilyReviewModel,
3239
+ resolveReviewJobRole,
3240
+ loadRolesContext,
3241
+ parseLocalModelId,
3242
+ localBackend,
1882
3243
  resolveHitlRunOptions,
1883
3244
  redactSecrets,
1884
3245
  RedactingStreamBuffer,
@@ -1888,7 +3249,6 @@ export {
1888
3249
  CLAUDE_MAX_BUDGET_USD_ENV,
1889
3250
  claudeRunCaps,
1890
3251
  claudeRedactions,
1891
- whichBinary,
1892
3252
  spawnLogged,
1893
3253
  cursorAgentHeadlessArgs,
1894
3254
  cursorAgentReviewArgs,