@dadado/agent-kit-cli 6.25.0 → 6.26.1

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-IFBIO7VT.js → chunk-3KFLQE6Y.js} +1533 -52
  7. package/dist/{chunk-GQSSXDDK.js → chunk-ARJRICI2.js} +1 -1
  8. package/dist/{chunk-6WUKLS4D.js → chunk-BIFTTL2O.js} +1 -1
  9. package/dist/{chunk-QACMV46U.js → chunk-BSK6C4UO.js} +19 -12
  10. package/dist/{chunk-NJ2SUSWX.js → chunk-BVZDPVUL.js} +1 -1
  11. package/dist/{chunk-GMG7ZH4E.js → chunk-DOMBVLI4.js} +13 -13
  12. package/dist/{chunk-2F6NMQOA.js → chunk-FB6G6OD6.js} +3 -3
  13. package/dist/{chunk-MFKHIWEL.js → chunk-FOVHFMSH.js} +1 -1
  14. package/dist/{chunk-EO5NGAYV.js → chunk-FUSNEYGU.js} +29 -3
  15. package/dist/{chunk-SAQ3EE5R.js → chunk-HGB4DHXV.js} +3 -3
  16. package/dist/{chunk-6M6UKECW.js → chunk-IHVJTGYR.js} +0 -32
  17. package/dist/chunk-KMK4T4ZM.js +34 -0
  18. package/dist/{chunk-ZMYV6PRE.js → chunk-LEVNLHH3.js} +2 -1
  19. package/dist/{chunk-2XLI7XEY.js → chunk-MGVV6YC4.js} +1 -1
  20. package/dist/{chunk-C7SV7UP5.js → chunk-MWRYQLEG.js} +3 -3
  21. package/dist/{chunk-WKFE3RUC.js → chunk-NHJ4IAVN.js} +5 -3
  22. package/dist/{chunk-HSIHZWFF.js → chunk-NW5SWKJV.js} +7 -7
  23. package/dist/{chunk-C4Q77GGJ.js → chunk-O7VMHCNN.js} +6 -0
  24. package/dist/{chunk-CIV42JGT.js → chunk-PCIYXGB3.js} +2 -2
  25. package/dist/{chunk-7Y74KO7U.js → chunk-PLLXFSN2.js} +12 -12
  26. package/dist/{chunk-XGZOU4DS.js → chunk-QMCBXCP5.js} +4 -4
  27. package/dist/{chunk-QX55T4UX.js → chunk-RJP47EGS.js} +6 -1
  28. package/dist/{chunk-KWYF7QNH.js → chunk-RLVY6YD3.js} +17 -2
  29. package/dist/{chunk-JGG574RK.js → chunk-RRJVC35Y.js} +3 -3
  30. package/dist/{chunk-PIMGV3E5.js → chunk-SWJJW624.js} +1 -1
  31. package/dist/{chunk-G5MQRP6M.js → chunk-SYRJ5TTK.js} +13 -9
  32. package/dist/{chunk-L5V3W3DY.js → chunk-TTUFIE26.js} +60 -14
  33. package/dist/chunk-WOXTL43E.js +248 -0
  34. package/dist/{chunk-JFS4GKP7.js → chunk-XXPI4H4D.js} +2 -2
  35. package/dist/{chunk-M4UL422I.js → chunk-Y5526WCN.js} +6 -6
  36. package/dist/{chunk-CXE6ASSX.js → chunk-Y575INEC.js} +1 -1
  37. package/dist/{chunk-H7RAFRRZ.js → chunk-YFRG3CMS.js} +68 -34
  38. package/dist/{chunk-JG3CNGQM.js → chunk-ZNZHDPS3.js} +6 -4
  39. package/dist/{commands-UW2C2ZN4.js → commands-SCFSX4U4.js} +8 -6
  40. package/dist/{conflicts-RING6AHV.js → conflicts-4GLQOMJF.js} +9 -10
  41. package/dist/{contribute-LSY75JZH.js → contribute-HE4WCBRY.js} +7 -6
  42. package/dist/{countdown-SZ2P4XHB.js → countdown-VXOFV23S.js} +104 -57
  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-J4AMA4S4.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 +52 -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-SNB5Q3YU.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-HDR5ER25.js} +11 -13
  61. package/dist/{run-CQF5RM5X.js → run-RGIY5JTX.js} +24 -30
  62. package/dist/{run-plan-BEOCOJCF.js → run-plan-DHB3ZXJS.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-OXCWYN3Y.js +32 -0
  68. package/dist/{update-all-YYUTXHGR.js → update-all-E2MV6KME.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,87 @@ 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";
43
+
44
+ // src/plan-loop/result-nonce.ts
45
+ import { readSync } from "fs";
46
+ import { isatty } from "tty";
47
+ var RESULT_NONCE_STDIN_ENV = "AGENT_KIT_RESULT_NONCE_STDIN";
48
+ var NONCE_RE = /^[0-9a-f]{32,128}$/;
49
+ var READ_MAX_BYTES = 256;
50
+ var READ_DEADLINE_MS = 5e3;
51
+ var processNonce;
52
+ function readStdinLine() {
53
+ const buf = Buffer.alloc(READ_MAX_BYTES);
54
+ let len = 0;
55
+ const wait = new Int32Array(new SharedArrayBuffer(4));
56
+ const deadline = Date.now() + READ_DEADLINE_MS;
57
+ while (len < READ_MAX_BYTES) {
58
+ let n;
59
+ try {
60
+ n = readSync(0, buf, len, READ_MAX_BYTES - len, null);
61
+ } catch (err) {
62
+ if (err.code === "EAGAIN" && Date.now() < deadline) {
63
+ Atomics.wait(wait, 0, 0, 5);
64
+ continue;
65
+ }
66
+ break;
67
+ }
68
+ if (n === 0) break;
69
+ len += n;
70
+ if (buf.subarray(0, len).includes(10)) break;
71
+ }
72
+ return buf.subarray(0, len).toString("utf8").split("\n")[0] ?? "";
73
+ }
74
+ function takeResultNonce(opts = {}) {
75
+ const env = opts.env ?? process.env;
76
+ const flagged = env[RESULT_NONCE_STDIN_ENV] !== void 0;
77
+ delete env[RESULT_NONCE_STDIN_ENV];
78
+ processNonce = void 0;
79
+ if (!flagged) return void 0;
80
+ if (opts.read === void 0 && (opts.stdinIsTTY ?? isatty(0))) return void 0;
81
+ let line4 = "";
82
+ try {
83
+ line4 = (opts.read ?? readStdinLine)().trim();
84
+ } catch {
85
+ return void 0;
86
+ }
87
+ processNonce = NONCE_RE.test(line4) ? line4 : void 0;
88
+ return processNonce;
89
+ }
90
+ function resultNonce() {
91
+ return processNonce;
92
+ }
93
+ function createNonceStripper(nonce) {
94
+ let held = "";
95
+ return {
96
+ push(text) {
97
+ let joined = held + text;
98
+ while (joined.includes(nonce)) joined = joined.split(nonce).join("");
99
+ held = "";
100
+ for (let k = Math.min(nonce.length - 1, joined.length); k > 0; k--) {
101
+ if (nonce.startsWith(joined.slice(joined.length - k))) {
102
+ held = joined.slice(joined.length - k);
103
+ return joined.slice(0, joined.length - k);
104
+ }
105
+ }
106
+ return joined;
107
+ },
108
+ flush() {
109
+ const rest = held;
110
+ held = "";
111
+ return rest;
112
+ }
113
+ };
114
+ }
29
115
 
30
116
  // src/plan-loop/stream-render.ts
31
117
  import { StringDecoder } from "string_decoder";
@@ -71,8 +157,8 @@ function firstLineOfContent(content) {
71
157
  if (Array.isArray(content)) {
72
158
  for (const part of content) {
73
159
  if (isRecord(part) && typeof part.text === "string") {
74
- const line3 = firstNonEmptyLine(part.text);
75
- if (line3) return line3;
160
+ const line4 = firstNonEmptyLine(part.text);
161
+ if (line4) return line4;
76
162
  }
77
163
  }
78
164
  return "";
@@ -81,8 +167,8 @@ function firstLineOfContent(content) {
81
167
  return "";
82
168
  }
83
169
  function firstNonEmptyLine(text) {
84
- for (const line3 of text.split(/\r?\n/)) {
85
- const trimmed = line3.trim();
170
+ for (const line4 of text.split(/\r?\n/)) {
171
+ const trimmed = line4.trim();
86
172
  if (trimmed) return trimmed;
87
173
  }
88
174
  return "";
@@ -141,14 +227,21 @@ function parseUser(event) {
141
227
  if (promptChars > 0) out.push({ kind: "prompt", chars: promptChars });
142
228
  return out.length > 0 ? out : [{ kind: "silent" }];
143
229
  }
230
+ function hasUnknownCostBasis(event) {
231
+ const usage = event.modelUsage;
232
+ if (!isRecord(usage)) return false;
233
+ return Object.values(usage).some((entry) => isRecord(entry) && entry.costBasis === "unknown");
234
+ }
144
235
  function parseResult(event) {
145
236
  const isError = event.is_error === true;
146
237
  const subtype = asString(event.subtype);
238
+ const cost = asNumber(event.total_cost_usd);
239
+ const unpriced = hasUnknownCostBasis(event);
147
240
  return {
148
241
  kind: "result",
149
242
  ok: !isError,
150
243
  status: subtype ?? (isError ? "error" : "success"),
151
- costUsd: asNumber(event.total_cost_usd),
244
+ ...unpriced ? { costBasis: "unknown", reportedCostUsd: cost } : { costUsd: cost },
152
245
  durationMs: asNumber(event.duration_ms),
153
246
  apiMs: asNumber(event.duration_api_ms),
154
247
  turns: asNumber(event.num_turns)
@@ -199,19 +292,19 @@ function parseCursorToolCall(event) {
199
292
  if (subtype === "completed") {
200
293
  const result = isRecord(body.result) ? body.result : null;
201
294
  const failed = result !== null && ("error" in result || "failure" in result || "rejected" in result);
202
- let line3 = "";
295
+ let line4 = "";
203
296
  if (result) {
204
297
  const payload = failed ? result.error ?? result.failure ?? result.rejected : result.success;
205
- line3 = firstLineOfContent(
298
+ line4 = firstLineOfContent(
206
299
  typeof payload === "string" ? payload : payload === void 0 ? result : payload
207
300
  );
208
301
  }
209
- return { kind: "tool_result", ok: !failed, line: line3 };
302
+ return { kind: "tool_result", ok: !failed, line: line4 };
210
303
  }
211
304
  return { kind: "silent" };
212
305
  }
213
- function parseStreamLine(line3) {
214
- const trimmed = line3.trim();
306
+ function parseStreamLine(line4) {
307
+ const trimmed = line4.trim();
215
308
  if (!trimmed || !trimmed.startsWith("{")) return [{ kind: "unparsed" }];
216
309
  let event;
217
310
  try {
@@ -268,11 +361,16 @@ function formatCost(usd) {
268
361
  }
269
362
  var RESULT_LINE_HEAD = `${SPACE_MARKS.star} result `;
270
363
  var RESULT_COST_SESSION_TOTAL = "session total";
364
+ var RESULT_COST_UNKNOWN = "cost unknown";
271
365
  function formatResultLine(event, opts = {}) {
272
366
  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);
367
+ const total = opts.sessionTotal ? ` ${RESULT_COST_SESSION_TOTAL}` : "";
368
+ if (event.costBasis === "unknown") {
369
+ parts.push(
370
+ event.reportedCostUsd === void 0 ? RESULT_COST_UNKNOWN : `${RESULT_COST_UNKNOWN} (claude reported ${formatCost(event.reportedCostUsd)}${total})`
371
+ );
372
+ } else if (event.costUsd !== void 0) {
373
+ parts.push(`${formatCost(event.costUsd)}${total}`);
276
374
  }
277
375
  if (event.durationMs !== void 0) parts.push(formatDuration(event.durationMs));
278
376
  else if (event.apiMs !== void 0) parts.push(`${formatDuration(event.apiMs)} api`);
@@ -283,15 +381,35 @@ function formatResultLine(event, opts = {}) {
283
381
  }
284
382
  var ESC = String.fromCharCode(27);
285
383
  var ANSI_RE = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
384
+ var USD_RE = "\\$(\\d+(?:\\.\\d+)?)";
286
385
  var RESULT_LINE_RE = new RegExp(
287
- `^${RESULT_LINE_HEAD}(\\S+)(?: ${SPACE_MARKS.tick} \\$(\\d+(?:\\.\\d+)?)( ${RESULT_COST_SESSION_TOTAL})?)?(?: ${SPACE_MARKS.tick} .*)?$`
386
+ `^${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
387
  );
289
- function parseResultLine(line3) {
290
- const m = RESULT_LINE_RE.exec(line3.replace(ANSI_RE, "").replace(/\r$/, ""));
388
+ function parseResultLine(line4) {
389
+ const m = RESULT_LINE_RE.exec(line4.replace(ANSI_RE, "").replace(/\r$/, ""));
291
390
  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 };
391
+ const usd = (raw) => {
392
+ const value = raw === void 0 ? null : Number(raw);
393
+ return value !== null && Number.isFinite(value) ? value : null;
394
+ };
395
+ if (m[4] !== void 0) {
396
+ const reportedUsd = usd(m[5]);
397
+ return {
398
+ status: m[1] ?? "",
399
+ costUsd: null,
400
+ costBasis: "unknown",
401
+ reportedUsd,
402
+ sessionTotal: reportedUsd !== null && m[6] !== void 0
403
+ };
404
+ }
405
+ const costUsd = usd(m[2]);
406
+ return {
407
+ status: m[1] ?? "",
408
+ costUsd,
409
+ costBasis: null,
410
+ reportedUsd: costUsd,
411
+ sessionTotal: costUsd !== null && m[3] !== void 0
412
+ };
295
413
  }
296
414
  function renderStreamEvent(event, opts) {
297
415
  const width = Math.max(MIN_COLUMNS, opts.columns);
@@ -307,8 +425,8 @@ function renderStreamEvent(event, opts) {
307
425
  case "tool_result": {
308
426
  const label = event.ok ? "ok" : "error";
309
427
  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;
428
+ const line4 = truncate(oneLine(event.line), width - head.length - 3);
429
+ const text = line4 ? `${head} ${SPACE_MARKS.tick} ${line4}` : head;
312
430
  return paint(event.ok ? LABEL_MUTED : STATUS_ERR, text, color);
313
431
  }
314
432
  case "result":
@@ -353,7 +471,9 @@ var StreamRenderer = class {
353
471
  write;
354
472
  color;
355
473
  columns;
474
+ nonce;
356
475
  constructor(opts = {}) {
476
+ this.nonce = opts.resultNonce ?? (opts.write === void 0 ? resultNonce() ?? "" : "");
357
477
  this.write = opts.write ?? ((text) => process.stdout.write(text));
358
478
  this.color = shouldUseWelcomeColor({
359
479
  stdoutIsTTY: opts.isTTY ?? Boolean(process.stdout.isTTY),
@@ -368,12 +488,12 @@ var StreamRenderer = class {
368
488
  const combined = this.pending + text;
369
489
  const lines = combined.split("\n");
370
490
  this.pending = lines.pop() ?? "";
371
- for (const line3 of lines) {
491
+ for (const line4 of lines) {
372
492
  if (this.dropped) {
373
493
  this.dropped = false;
374
494
  continue;
375
495
  }
376
- this.renderLine(line3);
496
+ this.renderLine(line4);
377
497
  }
378
498
  if (this.pending.length > PENDING_MAX_CHARS) {
379
499
  this.pending = "";
@@ -392,9 +512,9 @@ var StreamRenderer = class {
392
512
  } catch {
393
513
  }
394
514
  }
395
- renderLine(line3) {
396
- for (const event of parseStreamLine(line3)) {
397
- const costed = event.kind === "result" && event.costUsd !== void 0;
515
+ renderLine(line4) {
516
+ for (const event of parseStreamLine(line4)) {
517
+ const costed = event.kind === "result" && (event.costUsd !== void 0 || event.reportedCostUsd !== void 0);
398
518
  const rendered = renderStreamEvent(event, {
399
519
  color: this.color,
400
520
  columns: this.columns,
@@ -408,7 +528,7 @@ var StreamRenderer = class {
408
528
  continue;
409
529
  }
410
530
  this.closeText();
411
- this.write(`${rendered}
531
+ this.write(`${event.kind === "result" ? this.nonce : ""}${rendered}
412
532
  `);
413
533
  }
414
534
  }
@@ -422,11 +542,14 @@ function createStreamRenderer(opts = {}) {
422
542
  return new StreamRenderer(opts);
423
543
  }
424
544
 
545
+ // src/plan-loop/local-models.ts
546
+ import { execFile } from "child_process";
547
+
425
548
  // src/plan-loop/backends.ts
426
549
  import { execFileSync as execFileSync2, spawn } from "child_process";
427
550
  import { createWriteStream as createWriteStream2 } from "fs";
428
551
  import { access as access2 } from "fs/promises";
429
- import path2 from "path";
552
+ import path4 from "path";
430
553
  import { StringDecoder as StringDecoder3 } from "string_decoder";
431
554
 
432
555
  // src/plan-loop/codex.ts
@@ -537,7 +660,7 @@ function codexSlashPointer(name) {
537
660
  "- Do not clone Cursor hooks or invent behavior beyond the SoT file."
538
661
  ].join("\n");
539
662
  }
540
- async function codexPrompt(workspace, prompt) {
663
+ async function codexPrompt(workspace, prompt, pointer = codexSlashPointer) {
541
664
  const m = /^\/([A-Za-z0-9][A-Za-z0-9_-]*)/.exec(prompt.trimStart());
542
665
  if (!m?.[1]) return { ok: true, prompt };
543
666
  const rel = path.join(".cursor", "commands", `${m[1]}.md`);
@@ -546,7 +669,7 @@ async function codexPrompt(workspace, prompt) {
546
669
  } catch {
547
670
  return { ok: false, missing: rel };
548
671
  }
549
- return { ok: true, prompt: `${codexSlashPointer(m[1])}
672
+ return { ok: true, prompt: `${pointer(m[1])}
550
673
 
551
674
  ${prompt}` };
552
675
  }
@@ -1132,13 +1255,1007 @@ var cursorAcpBackend = {
1132
1255
  run: runCursorAcp
1133
1256
  };
1134
1257
 
1258
+ // src/plan-loop/local.ts
1259
+ import { randomUUID } from "crypto";
1260
+ import { mkdir, mkdtemp, rm, writeFile } from "fs/promises";
1261
+ import { tmpdir } from "os";
1262
+ import path3 from "path";
1263
+
1264
+ // src/plan-loop/detect.ts
1265
+ var DETECT_ORDER = ["cursor-agent", "claude"];
1266
+ var EXPLICIT_ONLY_BACKENDS = [
1267
+ "codex",
1268
+ "cursor-acp",
1269
+ "openrouter",
1270
+ "local"
1271
+ ];
1272
+ var INSTALL_HINTS = {
1273
+ "cursor-agent": "Install the Cursor Agent CLI and ensure `cursor-agent` is on PATH (https://cursor.com/docs/cli).",
1274
+ claude: "Install Claude Code and ensure `claude` is on PATH (https://code.claude.com/docs/en/quickstart).",
1275
+ "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`.",
1276
+ codex: "Install the Codex CLI and ensure `codex` is on PATH (https://developers.openai.com/codex/cli).",
1277
+ 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.",
1278
+ 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."
1279
+ };
1280
+ var BACKEND_BIN = {
1281
+ "cursor-agent": "cursor-agent",
1282
+ claude: "claude",
1283
+ codex: "codex",
1284
+ "cursor-acp": "cursor-agent",
1285
+ openrouter: "ori",
1286
+ local: "pi"
1287
+ };
1288
+ function isBackendId(id) {
1289
+ return id === "cursor-agent" || id === "claude" || id === "codex" || id === "cursor-acp" || id === "openrouter" || id === "local";
1290
+ }
1291
+ function isRequestedBackend(id) {
1292
+ return id === "auto" || isBackendId(id);
1293
+ }
1294
+ function listDetectBackendIds() {
1295
+ return ["auto", ...DETECT_ORDER, ...EXPLICIT_ONLY_BACKENDS];
1296
+ }
1297
+ async function detectAgentBackend(requested, whichFn = whichBinary) {
1298
+ const id = requested.trim().toLowerCase();
1299
+ if (id === "glm" || id.startsWith("glm-") || id === "glm4") {
1300
+ return {
1301
+ ok: false,
1302
+ message: "No documented GLM CLI binary is registered. Refusing a stub that would claim to work. Use --backend auto, cursor-agent, or claude."
1303
+ };
1304
+ }
1305
+ if (!isRequestedBackend(id)) {
1306
+ return {
1307
+ ok: false,
1308
+ message: `Unknown backend '${requested}'. Supported: ${listDetectBackendIds().join(", ")}.`
1309
+ };
1310
+ }
1311
+ if (id === "auto") {
1312
+ for (const candidate of DETECT_ORDER) {
1313
+ const bin2 = await whichFn(candidate);
1314
+ if (bin2) return { ok: true, id: candidate, bin: bin2 };
1315
+ }
1316
+ return {
1317
+ ok: false,
1318
+ message: [
1319
+ "No agent CLI found on PATH (tried: cursor-agent, claude).",
1320
+ INSTALL_HINTS["cursor-agent"],
1321
+ INSTALL_HINTS.claude
1322
+ ].join(" ")
1323
+ };
1324
+ }
1325
+ const bin = await whichFn(BACKEND_BIN[id]);
1326
+ if (!bin) {
1327
+ return { ok: false, message: `${BACKEND_BIN[id]} not found on PATH. ${INSTALL_HINTS[id]}` };
1328
+ }
1329
+ return { ok: true, id, bin };
1330
+ }
1331
+
1332
+ // src/plan-loop/plan-state.ts
1333
+ import { readdir, readFile } from "fs/promises";
1334
+ import path2 from "path";
1335
+ function countPendingTodos(raw) {
1336
+ return parsePlanFrontmatter(raw).todos.filter(
1337
+ (t) => (t.status === "pending" || t.status === "in_progress") && t.id !== "dogfood-poc"
1338
+ ).length;
1339
+ }
1340
+ async function findActivePlanFile(plansDir) {
1341
+ if (!await fileExists(plansDir)) return null;
1342
+ const files = (await readdir(plansDir)).filter((f) => f.endsWith(".plan.md")).sort();
1343
+ return files[0] ? path2.join(plansDir, files[0]) : null;
1344
+ }
1345
+ async function readPlan(planPath) {
1346
+ return readFile(planPath, "utf8");
1347
+ }
1348
+ var QUEUE_CURSOR_RE = /^- \*\*Queue cursor:\*\*\s*(.+)$/m;
1349
+ var QUEUE_STATUS_RE = /^- \*\*Queue status:\*\*\s*(.+)$/m;
1350
+ var QUEUE_DONE_STATUSES = /* @__PURE__ */ new Set(["exhausted", "completed", "done"]);
1351
+ function readRunQueueState(handoff) {
1352
+ const queue = extractHandoffNamedPlans(handoff).runQueue;
1353
+ let cursorIndex = null;
1354
+ let cursorPlan = null;
1355
+ const cursorRaw = QUEUE_CURSOR_RE.exec(handoff)?.[1]?.trim() ?? "";
1356
+ const indexMatch = /^(\d+)\b/.exec(cursorRaw);
1357
+ if (indexMatch?.[1]) cursorIndex = Number(indexMatch[1]);
1358
+ const currentMatch = /current:\s*`?([^`()]+?)`?\s*\)/i.exec(cursorRaw);
1359
+ if (currentMatch?.[1]) {
1360
+ const base = currentMatch[1].trim().split("/").pop() ?? "";
1361
+ if (/\.plan\.md$/i.test(base)) cursorPlan = base;
1362
+ }
1363
+ const status = QUEUE_STATUS_RE.exec(handoff)?.[1]?.trim().split(/\s+/)[0]?.replace(/[`*]/g, "");
1364
+ const queueStatus = status ? status : null;
1365
+ const finished = queueStatus !== null && QUEUE_DONE_STATUSES.has(queueStatus.toLowerCase());
1366
+ let cursor = null;
1367
+ if (cursorIndex !== null && cursorIndex >= 0 && cursorIndex < queue.length) {
1368
+ cursor = cursorIndex;
1369
+ } else if (cursorPlan && queue.includes(cursorPlan)) {
1370
+ cursor = queue.indexOf(cursorPlan);
1371
+ }
1372
+ const current = cursor !== null ? queue[cursor] ?? null : cursorPlan;
1373
+ return { queue, cursor, current, status: queueStatus, finished };
1374
+ }
1375
+ function defaultPlanStateIo() {
1376
+ return {
1377
+ readFile: async (file) => {
1378
+ try {
1379
+ return await readFile(file, "utf8");
1380
+ } catch {
1381
+ return null;
1382
+ }
1383
+ },
1384
+ findActivePlan: findActivePlanFile
1385
+ };
1386
+ }
1387
+ async function resolveActivePlanFromHandoff(root, handoff, io = defaultPlanStateIo()) {
1388
+ const queue = readRunQueueState(handoff);
1389
+ const base = (queue.queue.length > 0 && !queue.finished ? queue.current : null) ?? extractHandoffNamedPlans(handoff).active;
1390
+ if (!base) return io.findActivePlan(path2.join(root, ".cursor", "plans"));
1391
+ for (const candidate of namedPlanCandidatePaths(root, base)) {
1392
+ if (await io.readFile(candidate) !== null) return candidate;
1393
+ }
1394
+ return null;
1395
+ }
1396
+ async function resolveActivePlanPath(root, io = defaultPlanStateIo()) {
1397
+ const handoff = await io.readFile(path2.join(root, HANDOFF_REL)) ?? "";
1398
+ return resolveActivePlanFromHandoff(root, handoff, io);
1399
+ }
1400
+
1401
+ // src/plan-loop/model-roles.ts
1402
+ var ROLE_CAPABILITIES = Object.freeze({
1403
+ claude: { workerModel: true, subworkerModel: true, reviewer: true },
1404
+ "cursor-agent": { workerModel: true, subworkerModel: false, reviewer: true },
1405
+ codex: { workerModel: true, subworkerModel: false, reviewer: false },
1406
+ openrouter: { workerModel: true, subworkerModel: false, reviewer: false },
1407
+ "cursor-acp": { workerModel: false, subworkerModel: false, reviewer: false },
1408
+ local: { workerModel: true, subworkerModel: false, reviewer: false }
1409
+ });
1410
+ var ROLE_MODEL_ID = /^[A-Za-z0-9._:/+=,[\]-]{1,128}$/;
1411
+ var ROLE_WORKER_TYPE_KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
1412
+ var SUBWORKER_AUTO = "auto";
1413
+ var REVIEWER_SCOPES = ["off", "tick", "plan"];
1414
+ var REVIEWER_BACKENDS = ["auto", "claude", "cursor-agent"];
1415
+ var CLAUDE_SUBAGENT_MODEL_ENV = "CLAUDE_CODE_SUBAGENT_MODEL";
1416
+ function isPlainObject(v) {
1417
+ return v !== null && typeof v === "object" && !Array.isArray(v);
1418
+ }
1419
+ function modelField(v, where) {
1420
+ if (v === void 0 || v === null || v === "") return {};
1421
+ if (typeof v !== "string" || !ROLE_MODEL_ID.test(v.trim())) {
1422
+ return { error: `${where} must be a model id (letters, digits, . _ : / + = , [ ] -)` };
1423
+ }
1424
+ return { value: v.trim() };
1425
+ }
1426
+ function parseModelRoles(raw) {
1427
+ if (raw === void 0 || raw === null) return { ok: true, roles: {} };
1428
+ if (!isPlainObject(raw)) return { ok: false, error: "roles must be an object" };
1429
+ const roles = {};
1430
+ for (const key of Object.keys(raw)) {
1431
+ if (key !== "worker" && key !== "subworker" && key !== "reviewer") {
1432
+ return { ok: false, error: `unknown roles key: ${key}` };
1433
+ }
1434
+ }
1435
+ if (raw.worker !== void 0 && raw.worker !== null) {
1436
+ const w = raw.worker;
1437
+ if (!isPlainObject(w)) return { ok: false, error: "roles.worker must be an object" };
1438
+ for (const key of Object.keys(w)) {
1439
+ if (key !== "backend" && key !== "model") {
1440
+ return { ok: false, error: `unknown roles.worker key: ${key}` };
1441
+ }
1442
+ }
1443
+ const worker = {};
1444
+ if (w.backend !== void 0 && w.backend !== null && w.backend !== "") {
1445
+ const b = typeof w.backend === "string" ? w.backend.trim().toLowerCase() : "";
1446
+ if (!isRequestedBackend(b)) {
1447
+ return {
1448
+ ok: false,
1449
+ error: `roles.worker.backend must be auto or a kit backend id (got ${JSON.stringify(w.backend)})`
1450
+ };
1451
+ }
1452
+ worker.backend = b;
1453
+ }
1454
+ const m = modelField(w.model, "roles.worker.model");
1455
+ if (m.error) return { ok: false, error: m.error };
1456
+ if (m.value) worker.model = m.value;
1457
+ roles.worker = worker;
1458
+ }
1459
+ if (raw.subworker !== void 0 && raw.subworker !== null) {
1460
+ const s = raw.subworker;
1461
+ if (!isPlainObject(s)) return { ok: false, error: "roles.subworker must be an object" };
1462
+ for (const key of Object.keys(s)) {
1463
+ if (key !== "model" && key !== "byWorkerType") {
1464
+ return { ok: false, error: `unknown roles.subworker key: ${key}` };
1465
+ }
1466
+ }
1467
+ const sub = {};
1468
+ const m = modelField(s.model, "roles.subworker.model");
1469
+ if (m.error) return { ok: false, error: m.error };
1470
+ if (m.value) sub.model = m.value;
1471
+ if (s.byWorkerType !== void 0 && s.byWorkerType !== null) {
1472
+ if (!isPlainObject(s.byWorkerType)) {
1473
+ return { ok: false, error: "roles.subworker.byWorkerType must be an object" };
1474
+ }
1475
+ const map = {};
1476
+ for (const [type, value] of Object.entries(s.byWorkerType)) {
1477
+ if (!ROLE_WORKER_TYPE_KEY.test(type)) {
1478
+ return {
1479
+ ok: false,
1480
+ error: `roles.subworker.byWorkerType key ${type} is not a worker_type`
1481
+ };
1482
+ }
1483
+ const mv = modelField(value, `roles.subworker.byWorkerType.${type}`);
1484
+ if (mv.error) return { ok: false, error: mv.error };
1485
+ if (mv.value) map[type] = mv.value;
1486
+ }
1487
+ sub.byWorkerType = map;
1488
+ }
1489
+ roles.subworker = sub;
1490
+ }
1491
+ if (raw.reviewer !== void 0 && raw.reviewer !== null) {
1492
+ const r = raw.reviewer;
1493
+ if (!isPlainObject(r)) return { ok: false, error: "roles.reviewer must be an object" };
1494
+ const reviewer = {};
1495
+ for (const key of Object.keys(r)) {
1496
+ if (!["enabled", "scope", "backend", "model", "advisorModel"].includes(key)) {
1497
+ return { ok: false, error: `unknown roles.reviewer key: ${key}` };
1498
+ }
1499
+ }
1500
+ if (r.enabled !== void 0 && r.enabled !== null) {
1501
+ if (typeof r.enabled !== "boolean") {
1502
+ return { ok: false, error: "roles.reviewer.enabled must be boolean" };
1503
+ }
1504
+ reviewer.enabled = r.enabled;
1505
+ }
1506
+ if (r.scope !== void 0 && r.scope !== null) {
1507
+ if (typeof r.scope !== "string" || !REVIEWER_SCOPES.includes(r.scope)) {
1508
+ return { ok: false, error: "roles.reviewer.scope must be off, tick, or plan" };
1509
+ }
1510
+ reviewer.scope = r.scope;
1511
+ }
1512
+ if (r.backend !== void 0 && r.backend !== null) {
1513
+ if (typeof r.backend !== "string" || !REVIEWER_BACKENDS.includes(r.backend)) {
1514
+ return { ok: false, error: "roles.reviewer.backend must be auto, claude, or cursor-agent" };
1515
+ }
1516
+ reviewer.backend = r.backend;
1517
+ }
1518
+ for (const key of ["model", "advisorModel"]) {
1519
+ const mv = modelField(r[key], `roles.reviewer.${key}`);
1520
+ if (mv.error) return { ok: false, error: mv.error };
1521
+ if (mv.value) reviewer[key] = mv.value;
1522
+ }
1523
+ roles.reviewer = reviewer;
1524
+ }
1525
+ return { ok: true, roles };
1526
+ }
1527
+ function frontmatterBlock(planText) {
1528
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(planText);
1529
+ return m?.[1] ?? null;
1530
+ }
1531
+ function unquote(v) {
1532
+ const t = v.trim();
1533
+ if (t.length >= 2 && (t[0] === '"' || t[0] === "'") && t[t.length - 1] === t[0]) {
1534
+ return t.slice(1, -1).trim();
1535
+ }
1536
+ return t;
1537
+ }
1538
+ function readPlanRoleOverrides(planText) {
1539
+ const block = frontmatterBlock(planText);
1540
+ if (!block) return {};
1541
+ const out = {};
1542
+ const top = (key) => {
1543
+ const m = new RegExp(`^${key}:[ \\t]*(.+)$`, "m").exec(block);
1544
+ const v = m?.[1] ? unquote(m[1]) : "";
1545
+ return v ? v : void 0;
1546
+ };
1547
+ const wb = top("worker_backend");
1548
+ if (wb) out.workerBackend = wb;
1549
+ const wm = top("worker_model");
1550
+ if (wm) out.workerModel = wm;
1551
+ const sm = top("subworker_model");
1552
+ if (sm) out.subworkerModel = sm;
1553
+ const items = block.split(/^\s*- id:/m).slice(1);
1554
+ for (const item of items) {
1555
+ const status = /^\s*status:\s*(\S+)/m.exec(item)?.[1];
1556
+ if (status !== "pending" && status !== "in_progress") continue;
1557
+ if (unquote(item.split("\n")[0] ?? "") === "dogfood-poc") continue;
1558
+ const type = /^\s*worker_type:\s*(.+)$/m.exec(item)?.[1];
1559
+ if (type) out.nextWorkerType = unquote(type);
1560
+ break;
1561
+ }
1562
+ return out;
1563
+ }
1564
+ var RANK = { flag: 3, plan: 2, config: 1, default: 0 };
1565
+ function resolveWorkerRole(input) {
1566
+ const warnings = [];
1567
+ const layers = [
1568
+ {
1569
+ source: "flag",
1570
+ backend: input.flagBackend?.trim() || void 0,
1571
+ model: input.flagModel?.trim() || void 0
1572
+ },
1573
+ { source: "plan", backend: input.plan?.workerBackend, model: input.plan?.workerModel },
1574
+ { source: "config", backend: input.roles?.worker?.backend, model: input.roles?.worker?.model },
1575
+ { source: "default", backend: input.defaultBackend }
1576
+ ];
1577
+ const bLayer = layers.find((l) => l.backend) ?? {
1578
+ source: "default",
1579
+ backend: input.defaultBackend
1580
+ };
1581
+ const backend = bLayer.backend.trim().toLowerCase();
1582
+ let model;
1583
+ let modelSource;
1584
+ for (const l of layers) {
1585
+ if (!l.model) continue;
1586
+ if (RANK[l.source] < RANK[bLayer.source]) {
1587
+ warnings.push(
1588
+ `${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`
1589
+ );
1590
+ break;
1591
+ }
1592
+ model = l.model;
1593
+ modelSource = l.source;
1594
+ break;
1595
+ }
1596
+ if (model && modelSource !== "flag" && isBackendId(backend) && !ROLE_CAPABILITIES[backend].workerModel) {
1597
+ warnings.push(
1598
+ `${modelSource} model ${model} ignored: ${backend} cannot select a model (docs/model-roles-capability-matrix.md)`
1599
+ );
1600
+ model = void 0;
1601
+ modelSource = void 0;
1602
+ }
1603
+ return {
1604
+ backend,
1605
+ ...model ? { model, modelSource } : {},
1606
+ backendSource: bLayer.source,
1607
+ warnings
1608
+ };
1609
+ }
1610
+ function resolveSubworkerModel(input) {
1611
+ const sub = input.roles?.subworker;
1612
+ const type = input.plan?.nextWorkerType;
1613
+ let model;
1614
+ let source;
1615
+ if (input.plan?.subworkerModel) {
1616
+ model = input.plan.subworkerModel;
1617
+ source = "plan";
1618
+ } else if (type && sub?.byWorkerType?.[type]) {
1619
+ model = sub.byWorkerType[type];
1620
+ source = "worker_type";
1621
+ } else if (sub?.model) {
1622
+ model = sub.model;
1623
+ source = "config";
1624
+ }
1625
+ if (!model) return {};
1626
+ if (model === SUBWORKER_AUTO) {
1627
+ return {
1628
+ warning: "subworker model auto is reserved and not implemented yet (auto tier routing); no subworker model set"
1629
+ };
1630
+ }
1631
+ if (!ROLE_MODEL_ID.test(model)) {
1632
+ return {
1633
+ warning: `subworker model ${JSON.stringify(model)} is not a model id; no subworker model set`
1634
+ };
1635
+ }
1636
+ if (!ROLE_CAPABILITIES[input.backend].subworkerModel) {
1637
+ const how = input.backend === "cursor-agent" ? "Cursor subagents follow the worker model (model: inherit)" : "subagents keep the backend default";
1638
+ return {
1639
+ warning: `subworker model ${model} is not supported on ${input.backend}; ${how} (docs/model-roles-capability-matrix.md)`
1640
+ };
1641
+ }
1642
+ return { model, source };
1643
+ }
1644
+ function describeResolvedRoles(input) {
1645
+ const model = input.model ? `${input.model} (${input.modelSource ?? "flag"})` : "backend default";
1646
+ const sub = input.subworker?.model ? `, subworker ${input.subworker.model} (${input.subworker.source})` : "";
1647
+ return `roles: worker ${input.backendId} (${input.backendSource}), model ${model}${sub}`;
1648
+ }
1649
+ function resolveReviewerRole(roles, externalPlanReview) {
1650
+ const r = roles?.reviewer;
1651
+ const legacyOn = isPlainObject(externalPlanReview) && externalPlanReview.enabled === true;
1652
+ const fields = {
1653
+ ...r?.backend ? { backend: r.backend } : {},
1654
+ ...r?.model ? { model: r.model } : {},
1655
+ ...r?.advisorModel ? { advisorModel: r.advisorModel } : {}
1656
+ };
1657
+ if (r?.enabled === false || r?.scope === "off") {
1658
+ return { scope: "off", source: "roles", ...fields };
1659
+ }
1660
+ const on = r?.enabled === true || legacyOn;
1661
+ const source = r?.enabled === true ? "roles" : legacyOn ? "externalPlanReview" : "default";
1662
+ if (!on) return { scope: "off", source, ...fields };
1663
+ return { scope: r?.scope ?? "plan", source, ...fields };
1664
+ }
1665
+ function normalizeReviewModelId(raw) {
1666
+ const id = (raw ?? "").toLowerCase().replace(/\s+/g, "").replace(/\[.*$/, "");
1667
+ if (id === "" || id === "auto" || id === "cursor-auto" || id === "cursorauto" || id === "default")
1668
+ return "auto";
1669
+ return id;
1670
+ }
1671
+ var FAMILY_PATTERNS = [
1672
+ [
1673
+ "haiku",
1674
+ /^(haiku|claude-haiku|claude-3-haiku.*|claude-3\.5-haiku.*|claude-3-5-haiku.*|claude-haiku-.*|claude-4-haiku.*|claude-4\.5-haiku.*)$/
1675
+ ],
1676
+ [
1677
+ "opus",
1678
+ /^(opus|claude-opus|claude-3-opus.*|claude-opus-.*|claude-4-opus.*|claude-4\.5-opus.*)$/
1679
+ ],
1680
+ [
1681
+ "sonnet",
1682
+ /^(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.*)$/
1683
+ ],
1684
+ ["fable", /^(fable|claude-fable|claude-fable-.*)$/],
1685
+ ["composer", /^(composer|composer-.*|cursor-composer.*)$/],
1686
+ ["grok", /^(grok|grok-.*)$/]
1687
+ ];
1688
+ function reviewModelFamily(raw) {
1689
+ const id = normalizeReviewModelId(raw);
1690
+ for (const [family, pattern] of FAMILY_PATTERNS) if (pattern.test(id)) return family;
1691
+ return id;
1692
+ }
1693
+ function isFamilyAlias(id, family) {
1694
+ return id === family || id === `claude-${family}` || id === `cursor-${family}`;
1695
+ }
1696
+ function reviewModelRelation(implementer, reviewer) {
1697
+ const a = normalizeReviewModelId(implementer);
1698
+ const b = normalizeReviewModelId(reviewer);
1699
+ if (a === b) return "identical";
1700
+ const fa = reviewModelFamily(a);
1701
+ const fb = reviewModelFamily(b);
1702
+ if (fa !== fb) return "different";
1703
+ if (isFamilyAlias(a, fa) || isFamilyAlias(b, fb)) return "identical";
1704
+ return "same-family";
1705
+ }
1706
+ function describeIdenticalReviewModel(implementer, reviewer) {
1707
+ 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`;
1708
+ }
1709
+ function describeSameFamilyReviewModel(implementer, reviewer) {
1710
+ 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`;
1711
+ }
1712
+ function resolveReviewJobRole(input) {
1713
+ const flagBackend = input.flagBackend?.trim() ?? "";
1714
+ const flagModel = input.flagModel?.trim() ?? "";
1715
+ const reviewer = input.roles?.reviewer;
1716
+ const backend = flagBackend || reviewer?.backend || "auto";
1717
+ const backendSource = flagBackend ? "flag" : reviewer?.backend ? "config" : "default";
1718
+ const model = flagModel || (flagBackend ? "" : reviewer?.model ?? "");
1719
+ const out = {
1720
+ backend,
1721
+ backendSource,
1722
+ ...model ? { model, modelSource: flagModel ? "flag" : "config" } : {}
1723
+ };
1724
+ const implementer = input.roles?.worker?.model;
1725
+ if (model && implementer) {
1726
+ const relation = reviewModelRelation(implementer, model);
1727
+ if (relation === "identical") out.refusal = describeIdenticalReviewModel(implementer, model);
1728
+ else if (relation === "same-family") {
1729
+ out.warning = describeSameFamilyReviewModel(implementer, model);
1730
+ }
1731
+ }
1732
+ return out;
1733
+ }
1734
+ function checkPlanRoleOverrides(plan) {
1735
+ if (plan.workerBackend && !isRequestedBackend(plan.workerBackend.toLowerCase())) {
1736
+ return `plan frontmatter worker_backend must be auto or a kit backend id (got ${JSON.stringify(plan.workerBackend)})`;
1737
+ }
1738
+ for (const [key, value] of [
1739
+ ["worker_model", plan.workerModel],
1740
+ ["subworker_model", plan.subworkerModel]
1741
+ ]) {
1742
+ if (value && !ROLE_MODEL_ID.test(value)) {
1743
+ return `plan frontmatter ${key} must be a model id (got ${JSON.stringify(value)})`;
1744
+ }
1745
+ }
1746
+ return null;
1747
+ }
1748
+ async function loadRolesContext(root, usePlan) {
1749
+ const config = await loadContextConfig(root);
1750
+ const parsed = parseModelRoles(config?.roles);
1751
+ if (!parsed.ok) return { ok: false, error: `.cursor/context/config.json: ${parsed.error}` };
1752
+ let plan = {};
1753
+ if (usePlan) {
1754
+ const planPath = await resolveActivePlanPath(root);
1755
+ if (planPath) {
1756
+ plan = readPlanRoleOverrides(await readPlan(planPath).catch(() => ""));
1757
+ const problem = checkPlanRoleOverrides(plan);
1758
+ if (problem) return { ok: false, error: `${planPath}: ${problem}` };
1759
+ }
1760
+ }
1761
+ return {
1762
+ ok: true,
1763
+ roles: parsed.roles,
1764
+ plan,
1765
+ reviewer: resolveReviewerRole(parsed.roles, config?.externalPlanReview)
1766
+ };
1767
+ }
1768
+
1769
+ // src/plan-loop/local.ts
1770
+ var LOCAL_PROVIDER = "agent-kit-local";
1771
+ var LOCAL_PLACEHOLDER_KEY = "agent-kit-local-no-key";
1772
+ var LOCAL_DEFAULT_CONTEXT_WINDOW = 32768;
1773
+ var LOCAL_DEFAULT_MAX_TOKENS = 8192;
1774
+ var OMARCHY_START_TIMEOUT_MS = 10 * 6e4;
1775
+ var OMARCHY_OVERLAY_TIMEOUT_MS = 3e4;
1776
+ var OMARCHY_STATUS_TIMEOUT_MS = 1e4;
1777
+ var LOADING_HEARTBEAT_MS = 5e3;
1778
+ var STATUS_POLL_MS = 2e3;
1779
+ var OMARCHY_RECIPE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1780
+ var modelsHint = "List the models on this machine with `agent-kit models`.";
1781
+ function parseLocalModelId(raw) {
1782
+ const id = (raw ?? "").trim();
1783
+ const sources = LOCAL_MODEL_SOURCES.join(", ");
1784
+ if (!id) {
1785
+ return {
1786
+ ok: false,
1787
+ message: `local backend: --model <source>:<id> is required (sources: ${sources}). ${modelsHint}`
1788
+ };
1789
+ }
1790
+ const colon = id.indexOf(":");
1791
+ const source = colon > 0 ? id.slice(0, colon) : "";
1792
+ const sourceId = colon > 0 ? id.slice(colon + 1) : "";
1793
+ if (!LOCAL_MODEL_SOURCES.includes(source) || !sourceId) {
1794
+ return {
1795
+ ok: false,
1796
+ message: `local backend: model ${JSON.stringify(id)} is not <source>:<id> with a source among ${sources}. ${modelsHint}`
1797
+ };
1798
+ }
1799
+ if (!ROLE_MODEL_ID.test(id)) {
1800
+ return {
1801
+ ok: false,
1802
+ 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\`.`
1803
+ };
1804
+ }
1805
+ if (source === "omarchy" && !OMARCHY_RECIPE.test(sourceId)) {
1806
+ return {
1807
+ ok: false,
1808
+ 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}`
1809
+ };
1810
+ }
1811
+ return { ok: true, id, source, sourceId };
1812
+ }
1813
+ function findRunnableLocalModel(id, report) {
1814
+ const model = report.models.find((m) => m.id === id);
1815
+ if (!model) {
1816
+ const listed = report.models.map((m) => m.id);
1817
+ return {
1818
+ ok: false,
1819
+ 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.`
1820
+ };
1821
+ }
1822
+ if (!model.runnable) {
1823
+ return {
1824
+ ok: false,
1825
+ message: `local backend: ${id} is not runnable (${model.reason ?? model.state}). ${modelsHint} The kit does not fall back to another engine.`
1826
+ };
1827
+ }
1828
+ return { ok: true, model };
1829
+ }
1830
+ function localProviderSource(model, sourceId) {
1831
+ const config = {
1832
+ name: "Agent Kit local model",
1833
+ baseUrl: model.endpoint,
1834
+ apiKey: LOCAL_PLACEHOLDER_KEY,
1835
+ api: "openai-completions",
1836
+ models: [
1837
+ {
1838
+ type: "chat",
1839
+ id: sourceId,
1840
+ name: model.label,
1841
+ reasoning: false,
1842
+ input: ["text"],
1843
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1844
+ contextWindow: model.contextWindow ?? LOCAL_DEFAULT_CONTEXT_WINDOW,
1845
+ maxTokens: LOCAL_DEFAULT_MAX_TOKENS
1846
+ }
1847
+ ]
1848
+ };
1849
+ return [
1850
+ "// Generated by agent-kit for one local-model tick (ADR 2026-11-28_local-model-backend-pi point 6); removed when the tick ends.",
1851
+ `const config = ${JSON.stringify(config, null, 2)};`,
1852
+ "export default function (pi) {",
1853
+ ` pi.registerProvider(${JSON.stringify(LOCAL_PROVIDER)}, config);`,
1854
+ "}",
1855
+ ""
1856
+ ].join("\n");
1857
+ }
1858
+ function execFailure(what, run, timeoutMs) {
1859
+ if (run.reason === "missing") return `${what}: omarchy-models not on PATH`;
1860
+ if (run.reason === "timeout")
1861
+ return `${what}: no answer within ${Math.round(timeoutMs / 1e3)} s`;
1862
+ return `${what} failed${run.detail ? `: ${run.detail}` : ""}`;
1863
+ }
1864
+ async function startOmarchyRecipe(bin, model, recipe, deps, progress) {
1865
+ const exec = deps.execFn ?? defaultExecFn;
1866
+ const now = deps.now ?? Date.now;
1867
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1868
+ const timeoutMs = deps.startTimeoutMs ?? OMARCHY_START_TIMEOUT_MS;
1869
+ const t0 = now();
1870
+ const report = (phase, detail) => progress({
1871
+ kind: "model_loading",
1872
+ model: model.id,
1873
+ phase,
1874
+ elapsedMs: now() - t0,
1875
+ ...detail ? { detail } : {}
1876
+ });
1877
+ report("starting");
1878
+ const heartbeat = setInterval(() => report("loading"), deps.heartbeatMs ?? LOADING_HEARTBEAT_MS);
1879
+ heartbeat.unref?.();
1880
+ try {
1881
+ const started = await exec(bin, ["start", recipe], timeoutMs);
1882
+ if (!started.ok)
1883
+ throw new Error(execFailure(`omarchy-models start ${recipe}`, started, timeoutMs));
1884
+ for (; ; ) {
1885
+ const status = await exec(bin, ["status", "--json"], OMARCHY_STATUS_TIMEOUT_MS);
1886
+ if (status.ok) {
1887
+ let state;
1888
+ try {
1889
+ state = parseOmarchyStatus(JSON.parse(status.stdout)).models.find(
1890
+ (m) => m.id === model.id
1891
+ )?.state;
1892
+ } catch {
1893
+ state = void 0;
1894
+ }
1895
+ if (state === "running") break;
1896
+ if (state === "not-fit") throw new Error(`${model.id} does not fit this machine now`);
1897
+ }
1898
+ if (now() - t0 >= timeoutMs) {
1899
+ throw new Error(
1900
+ `${model.id} did not report running within ${Math.round(timeoutMs / 1e3)} s`
1901
+ );
1902
+ }
1903
+ await sleep(deps.pollMs ?? STATUS_POLL_MS);
1904
+ }
1905
+ report("ready");
1906
+ } catch (err) {
1907
+ const detail = err instanceof Error ? err.message : String(err);
1908
+ report("failed", detail);
1909
+ throw new Error(`local backend: ${detail}. The kit does not fall back to another engine.`);
1910
+ } finally {
1911
+ clearInterval(heartbeat);
1912
+ }
1913
+ }
1914
+ async function prepareLocalProvider(model, parsed, deps = {}, progress = () => {
1915
+ }) {
1916
+ if (!isLoopbackUrl(model.endpoint)) {
1917
+ throw new Error(`local backend: ${model.id} is not served from a loopback address`);
1918
+ }
1919
+ if (parsed.source === "omarchy") {
1920
+ const bin = await (deps.whichFn ?? whichBinary)("omarchy-models");
1921
+ if (!bin) throw new Error("local backend: omarchy-models not on PATH");
1922
+ if (model.state === "stopped") {
1923
+ await startOmarchyRecipe(bin, model, parsed.sourceId, deps, progress);
1924
+ }
1925
+ const exec = deps.execFn ?? defaultExecFn;
1926
+ const run = await exec(bin, ["overlay", "pi", parsed.sourceId], OMARCHY_OVERLAY_TIMEOUT_MS);
1927
+ if (!run.ok) {
1928
+ throw new Error(
1929
+ `local backend: ${execFailure(`omarchy-models overlay pi ${parsed.sourceId}`, run, OMARCHY_OVERLAY_TIMEOUT_MS)}`
1930
+ );
1931
+ }
1932
+ const lines = run.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
1933
+ const [extension, provider, piModel] = lines;
1934
+ if (lines.length !== 3 || !extension || !provider || !piModel || !path3.isAbsolute(extension)) {
1935
+ throw new Error(
1936
+ `local backend: omarchy-models overlay pi ${parsed.sourceId} did not print an extension path, a provider and a model (got ${lines.length} line(s))`
1937
+ );
1938
+ }
1939
+ return withTempDir(deps, async () => ({ extensions: [extension], provider, model: piModel }));
1940
+ }
1941
+ return withTempDir(deps, async (dir) => {
1942
+ const file = path3.join(dir, "provider.ts");
1943
+ await writeFile(file, localProviderSource(model, parsed.sourceId), { mode: 384 });
1944
+ return { extensions: [file], provider: LOCAL_PROVIDER, model: parsed.sourceId };
1945
+ });
1946
+ }
1947
+ async function withTempDir(deps, fill) {
1948
+ const dir = await mkdtemp(path3.join(deps.tmpRoot ?? tmpdir(), "agent-kit-local-"));
1949
+ try {
1950
+ const agentDir = path3.join(dir, "pi-agent");
1951
+ await mkdir(agentDir, { mode: 448 });
1952
+ return { ...await fill(dir), tempDir: dir, agentDir };
1953
+ } catch (err) {
1954
+ await rm(dir, { recursive: true, force: true });
1955
+ throw err;
1956
+ }
1957
+ }
1958
+ async function cleanupLocalProvider(setup) {
1959
+ if (!setup.tempDir) return;
1960
+ await rm(setup.tempDir, { recursive: true, force: true }).catch(() => void 0);
1961
+ }
1962
+ function localPiArgs(setup) {
1963
+ return [
1964
+ "--mode",
1965
+ "rpc",
1966
+ "--no-session",
1967
+ "--offline",
1968
+ "--no-extensions",
1969
+ ...setup.extensions.flatMap((file) => ["--extension", file]),
1970
+ "--no-skills",
1971
+ "--no-prompt-templates",
1972
+ "--no-approve",
1973
+ "--provider",
1974
+ setup.provider,
1975
+ "--model",
1976
+ setup.model
1977
+ ];
1978
+ }
1979
+ function localChildEnv(overrides, agentDir) {
1980
+ return {
1981
+ ...mergeChildEnv(overrides),
1982
+ PI_OFFLINE: "1",
1983
+ PI_SKIP_VERSION_CHECK: "1",
1984
+ PI_TELEMETRY: "0",
1985
+ ...agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}
1986
+ };
1987
+ }
1988
+ function piRpcPromptLine(text) {
1989
+ return `${JSON.stringify({ type: "prompt", message: text })}
1990
+ `;
1991
+ }
1992
+ function piSlashPointer(name) {
1993
+ return [
1994
+ `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).`,
1995
+ "",
1996
+ "Adapter rules (pi, headless):",
1997
+ "- 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.",
1998
+ "- Skip or cancel means stop.",
1999
+ "- Never `/git-prod` without an explicit operator yes.",
2000
+ "- Do not clone Cursor hooks or invent behavior beyond the SoT file."
2001
+ ].join("\n");
2002
+ }
2003
+ var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2004
+ var line3 = (event) => JSON.stringify(event);
2005
+ var num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
2006
+ function messageText(content) {
2007
+ if (typeof content === "string") return content;
2008
+ if (!Array.isArray(content)) return "";
2009
+ return content.filter((c) => isRecord4(c) && c.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n");
2010
+ }
2011
+ function createPiTranslator(opts) {
2012
+ const sessionId = opts.sessionId ?? `pi-${randomUUID()}`;
2013
+ let started = false;
2014
+ let lastText = "";
2015
+ let lastError = null;
2016
+ let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
2017
+ const result = (error) => {
2018
+ const out = line3({
2019
+ type: "result",
2020
+ subtype: error ? "error_during_execution" : "success",
2021
+ is_error: error !== null,
2022
+ result: lastText,
2023
+ session_id: sessionId,
2024
+ usage: {
2025
+ input_tokens: usage.input,
2026
+ output_tokens: usage.output,
2027
+ cache_read_input_tokens: usage.cacheRead,
2028
+ cache_creation_input_tokens: usage.cacheWrite
2029
+ },
2030
+ ...error ? { errors: [error] } : {}
2031
+ });
2032
+ lastText = "";
2033
+ lastError = null;
2034
+ usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
2035
+ return out;
2036
+ };
2037
+ return (raw) => {
2038
+ const text = raw.trim();
2039
+ if (!text) return [];
2040
+ if (!text.startsWith("{")) return [raw];
2041
+ let event;
2042
+ try {
2043
+ event = JSON.parse(text);
2044
+ } catch {
2045
+ return [raw];
2046
+ }
2047
+ if (!isRecord4(event)) return [];
2048
+ switch (event.type) {
2049
+ case "response": {
2050
+ if (event.command !== "prompt") return [];
2051
+ if (event.success === false) {
2052
+ const why = typeof event.error === "string" ? event.error : "rejected";
2053
+ return [result(`pi refused the prompt: ${why}`)];
2054
+ }
2055
+ const data = isRecord4(event.data) ? event.data : null;
2056
+ if (data?.disposition === "handled") {
2057
+ return [result("pi handled the prompt without running the model")];
2058
+ }
2059
+ return [];
2060
+ }
2061
+ case "agent_start":
2062
+ if (started) return [];
2063
+ started = true;
2064
+ return [
2065
+ line3({ type: "system", subtype: "init", session_id: sessionId, model: opts.model })
2066
+ ];
2067
+ case "message_end": {
2068
+ const message = isRecord4(event.message) ? event.message : null;
2069
+ if (!message) return [];
2070
+ if (message.role === "user") {
2071
+ const said2 = messageText(message.content);
2072
+ if (!said2) return [];
2073
+ return [
2074
+ line3({
2075
+ type: "user",
2076
+ isReplay: true,
2077
+ message: { role: "user", content: [{ type: "text", text: said2 }] }
2078
+ })
2079
+ ];
2080
+ }
2081
+ if (message.role !== "assistant") return [];
2082
+ const u = isRecord4(message.usage) ? message.usage : {};
2083
+ usage.input += num(u.input);
2084
+ usage.output += num(u.output);
2085
+ usage.cacheRead += num(u.cacheRead);
2086
+ usage.cacheWrite += num(u.cacheWrite);
2087
+ const stop = message.stopReason;
2088
+ if (stop === "error" || stop === "aborted") {
2089
+ lastError = typeof message.errorMessage === "string" && message.errorMessage ? message.errorMessage : `model turn ended with ${stop}`;
2090
+ } else {
2091
+ lastError = null;
2092
+ }
2093
+ const blocks = [];
2094
+ const content = Array.isArray(message.content) ? message.content : [];
2095
+ for (const part of content) {
2096
+ if (!isRecord4(part)) continue;
2097
+ if (part.type === "text" && typeof part.text === "string" && part.text) {
2098
+ blocks.push({ type: "text", text: part.text });
2099
+ } else if (part.type === "toolCall" && typeof part.name === "string") {
2100
+ blocks.push({
2101
+ type: "tool_use",
2102
+ id: typeof part.id === "string" ? part.id : "",
2103
+ name: part.name,
2104
+ input: isRecord4(part.arguments) ? part.arguments : {}
2105
+ });
2106
+ }
2107
+ }
2108
+ const said = messageText(content);
2109
+ if (said) lastText = said;
2110
+ if (blocks.length === 0) return [];
2111
+ return [line3({ type: "assistant", message: { role: "assistant", content: blocks } })];
2112
+ }
2113
+ case "tool_execution_end": {
2114
+ const res = isRecord4(event.result) ? event.result : {};
2115
+ return [
2116
+ line3({
2117
+ type: "user",
2118
+ message: {
2119
+ role: "user",
2120
+ content: [
2121
+ {
2122
+ type: "tool_result",
2123
+ tool_use_id: typeof event.toolCallId === "string" ? event.toolCallId : "",
2124
+ content: messageText(res.content),
2125
+ is_error: event.isError === true
2126
+ }
2127
+ ]
2128
+ }
2129
+ })
2130
+ ];
2131
+ }
2132
+ case "auto_retry_end":
2133
+ if (event.success === false) {
2134
+ lastError = typeof event.finalError === "string" && event.finalError ? event.finalError : "model request failed after retries";
2135
+ }
2136
+ return [];
2137
+ case "agent_settled":
2138
+ return [result(event.aborted === true ? lastError ?? "pi run aborted" : lastError)];
2139
+ default:
2140
+ return [];
2141
+ }
2142
+ };
2143
+ }
2144
+ function describeProgress(p) {
2145
+ const s = Math.round(p.elapsedMs / 1e3);
2146
+ switch (p.phase) {
2147
+ case "starting":
2148
+ return `local: starting ${p.model} (omarchy-models start); the tick runs once it is loaded.`;
2149
+ case "loading":
2150
+ return `local: ${p.model} still loading (${s} s).`;
2151
+ case "ready":
2152
+ return `local: ${p.model} is running (${s} s).`;
2153
+ default:
2154
+ return `local: ${p.model} did not start${p.detail ? `: ${p.detail}` : ""}.`;
2155
+ }
2156
+ }
2157
+ function createLocalBackend(deps = {}) {
2158
+ return {
2159
+ id: "local",
2160
+ async resolve() {
2161
+ return (deps.whichFn ?? whichBinary)("pi");
2162
+ },
2163
+ async run(opts) {
2164
+ const log = opts.log ?? ((text) => console.log(text));
2165
+ const parsed = parseLocalModelId(opts.model);
2166
+ if (!parsed.ok) throw new Error(parsed.message);
2167
+ const report = await (deps.discover ?? (() => discoverLocalModels({
2168
+ ...deps.whichFn ? { whichFn: deps.whichFn } : {},
2169
+ ...deps.execFn ? { execFn: deps.execFn } : {}
2170
+ })))();
2171
+ const found = findRunnableLocalModel(parsed.id, report);
2172
+ if (!found.ok) throw new Error(found.message);
2173
+ const prepared = await codexPrompt(opts.workspace, opts.prompt, piSlashPointer);
2174
+ if (!prepared.ok) {
2175
+ throw new Error(
2176
+ `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.`
2177
+ );
2178
+ }
2179
+ const progress = (p) => {
2180
+ log(describeProgress(p));
2181
+ opts.onProgress?.(p);
2182
+ };
2183
+ const setup = await prepareLocalProvider(found.model, parsed, deps, progress);
2184
+ try {
2185
+ const env = localChildEnv(opts.env, setup.agentDir);
2186
+ const redact = claudeRedactions(env);
2187
+ log(
2188
+ `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).`
2189
+ );
2190
+ try {
2191
+ return await spawnLogged("pi", localPiArgs(setup), opts.logPath, {
2192
+ cwd: opts.workspace,
2193
+ env,
2194
+ redact,
2195
+ spawnFn: opts.spawnFn,
2196
+ hitl: resolveHitlRunOptions(opts.hitl, {
2197
+ kind: "stdin-stream-json",
2198
+ firstPrompt: prepared.prompt,
2199
+ encode: piRpcPromptLine
2200
+ }),
2201
+ render: opts.render,
2202
+ onSpawn: opts.onSpawn,
2203
+ backendId: "local",
2204
+ translate: createPiTranslator({ model: parsed.id })
2205
+ });
2206
+ } catch (err) {
2207
+ throw new Error(`local backend failed to start: ${redactSecrets(String(err), redact)}`);
2208
+ }
2209
+ } finally {
2210
+ await cleanupLocalProvider(setup);
2211
+ }
2212
+ }
2213
+ };
2214
+ }
2215
+ var localBackend = createLocalBackend();
2216
+
1135
2217
  // src/plan-loop/backends.ts
2218
+ function isResultEventLine(line4) {
2219
+ const text = line4.trim();
2220
+ if (!text.startsWith("{")) return false;
2221
+ try {
2222
+ const event = JSON.parse(text);
2223
+ return typeof event === "object" && event !== null && event.type === "result";
2224
+ } catch {
2225
+ return false;
2226
+ }
2227
+ }
2228
+ function createStderrSinkFilter() {
2229
+ const decoder = new StringDecoder3("utf8");
2230
+ const lines = new LineSplitter();
2231
+ const keep = (line4, out) => {
2232
+ if (!isResultEventLine(line4)) out.push(`${line4}
2233
+ `);
2234
+ };
2235
+ return {
2236
+ push(chunk) {
2237
+ const out = [];
2238
+ lines.feed(
2239
+ typeof chunk === "string" ? chunk : decoder.write(chunk),
2240
+ (line4) => keep(line4, out)
2241
+ );
2242
+ return out.join("");
2243
+ },
2244
+ end() {
2245
+ const out = [];
2246
+ lines.feed(decoder.end(), (line4) => keep(line4, out));
2247
+ const rest = lines.end();
2248
+ if (rest && !isResultEventLine(rest)) out.push(rest);
2249
+ return out.join("");
2250
+ }
2251
+ };
2252
+ }
1136
2253
  function createLineTranslator(translate) {
1137
2254
  const decoder = new StringDecoder3("utf8");
1138
2255
  const lines = new LineSplitter();
1139
- const run = (line3, out) => {
2256
+ const run = (line4, out) => {
1140
2257
  try {
1141
- out.push(...translate(line3));
2258
+ out.push(...translate(line4));
1142
2259
  } catch {
1143
2260
  }
1144
2261
  };
@@ -1146,13 +2263,13 @@ function createLineTranslator(translate) {
1146
2263
  push(chunk) {
1147
2264
  const text = typeof chunk === "string" ? chunk : decoder.write(chunk);
1148
2265
  const out = [];
1149
- lines.feed(text, (line3) => run(line3, out));
2266
+ lines.feed(text, (line4) => run(line4, out));
1150
2267
  return out.length ? `${out.join("\n")}
1151
2268
  ` : "";
1152
2269
  },
1153
2270
  end() {
1154
2271
  const out = [];
1155
- lines.feed(decoder.end(), (line3) => run(line3, out));
2272
+ lines.feed(decoder.end(), (line4) => run(line4, out));
1156
2273
  const rest = lines.end();
1157
2274
  if (rest.trim()) run(rest, out);
1158
2275
  return out.length ? `${out.join("\n")}
@@ -1376,10 +2493,17 @@ function spawnLogged(command, args, logPath, options = {}) {
1376
2493
  render.feed(text);
1377
2494
  relay?.feed(text);
1378
2495
  };
1379
- const emit = (text) => {
2496
+ const stderrFilter = translator ? null : createStderrSinkFilter();
2497
+ const emit = (text, fromStderr) => {
1380
2498
  if (text.length === 0) return;
1381
2499
  out.write(text);
1382
- sinks(translator ? translator.push(text) : text);
2500
+ if (translator) {
2501
+ sinks(translator.push(text));
2502
+ return;
2503
+ }
2504
+ const shown = fromStderr && stderrFilter ? stderrFilter.push(text) : text;
2505
+ if (shown.length > 0) render.feed(shown);
2506
+ relay?.feed(text);
1383
2507
  };
1384
2508
  if (options.stdinText !== void 0 && !stdinTransport) {
1385
2509
  const stdin = child.stdin;
@@ -1409,24 +2533,26 @@ function spawnLogged(command, args, logPath, options = {}) {
1409
2533
  }
1410
2534
  });
1411
2535
  const buffers = [];
1412
- const tee = (stream) => {
2536
+ const tee = (stream, fromStderr) => {
1413
2537
  if (!stream) return;
1414
2538
  if (redact.length === 0) {
1415
- stream.on("data", (chunk) => emit(chunk));
2539
+ stream.on("data", (chunk) => emit(chunk, fromStderr));
1416
2540
  return;
1417
2541
  }
1418
2542
  const buffer = new RedactingStreamBuffer(redact);
1419
- buffers.push(buffer);
1420
- stream.on("data", (chunk) => emit(buffer.push(chunk)));
2543
+ buffers.push({ buffer, fromStderr });
2544
+ stream.on("data", (chunk) => emit(buffer.push(chunk), fromStderr));
1421
2545
  };
1422
- tee(child.stdout);
1423
- tee(child.stderr);
2546
+ tee(child.stdout, false);
2547
+ tee(child.stderr, true);
1424
2548
  child.on("error", (err) => {
1425
2549
  out.end();
1426
2550
  reject(redactedError(err));
1427
2551
  });
1428
2552
  child.on("close", (code) => {
1429
- for (const buffer of buffers) emit(buffer.flush());
2553
+ for (const { buffer, fromStderr } of buffers) emit(buffer.flush(), fromStderr);
2554
+ const stderrRest = stderrFilter?.end() ?? "";
2555
+ if (stderrRest) render.feed(stderrRest);
1430
2556
  if (translator) sinks(translator.end());
1431
2557
  render.end();
1432
2558
  relay?.finish();
@@ -1470,14 +2596,15 @@ function createRelay(hitl, child, redactedError) {
1470
2596
  resolveClosed = resolve;
1471
2597
  });
1472
2598
  const stdin = child.stdin;
2599
+ const encode = hitl.transport.kind === "stdin-stream-json" ? hitl.transport.encode ?? userEventLine : userEventLine;
1473
2600
  if (hitl.transport.kind === "stdin-stream-json") {
1474
2601
  if (!stdin) {
1475
- startError = new Error("claude child has no writable stdin (stream-json transport)");
2602
+ startError = new Error("agent child has no writable stdin (stdin relay transport)");
1476
2603
  } else {
1477
2604
  stdin.on("error", () => {
1478
2605
  });
1479
2606
  try {
1480
- stdin.write(userEventLine(hitl.transport.firstPrompt));
2607
+ stdin.write(encode(hitl.transport.firstPrompt));
1481
2608
  } catch (err) {
1482
2609
  startError = redactedError(err);
1483
2610
  }
@@ -1555,7 +2682,7 @@ function createRelay(hitl, child, redactedError) {
1555
2682
  record.replies.push(outcome.stamp);
1556
2683
  hitl.write(`\u2192 ${outcome.stamp.line}
1557
2684
  `);
1558
- stdin.write(userEventLine(outcome.stamp.line));
2685
+ stdin.write(encode(outcome.stamp.line));
1559
2686
  },
1560
2687
  (err) => {
1561
2688
  record.stop = unansweredStop(gate.askId, "child exited");
@@ -1743,9 +2870,9 @@ function claudeReviewArgs(opts = {}) {
1743
2870
  async function missingClaudeAdapter(workspace, prompt) {
1744
2871
  const m = /^\/([A-Za-z0-9][A-Za-z0-9_-]*)/.exec(prompt.trimStart());
1745
2872
  if (!m?.[1]) return null;
1746
- const rel = path2.join(".claude", "commands", `${m[1]}.md`);
2873
+ const rel = path4.join(".claude", "commands", `${m[1]}.md`);
1747
2874
  try {
1748
- await access2(path2.join(workspace, rel));
2875
+ await access2(path4.join(workspace, rel));
1749
2876
  return null;
1750
2877
  } catch {
1751
2878
  return rel;
@@ -1757,7 +2884,7 @@ var claudeBackend = {
1757
2884
  return whichBinary("claude");
1758
2885
  },
1759
2886
  async run(opts) {
1760
- const log = opts.log ?? ((line3) => console.log(line3));
2887
+ const log = opts.log ?? ((line4) => console.log(line4));
1761
2888
  const env = claudeChildEnv(opts.env);
1762
2889
  const redact = claudeRedactions(env);
1763
2890
  const version = checkClaudeVersion("claude", opts.versionFn);
@@ -1810,7 +2937,7 @@ var openrouterBackend = {
1810
2937
  return whichBinary("ori");
1811
2938
  },
1812
2939
  async run(opts) {
1813
- const log = opts.log ?? ((line3) => console.log(line3));
2940
+ const log = opts.log ?? ((line4) => console.log(line4));
1814
2941
  const env = claudeChildEnv(opts.env);
1815
2942
  const redact = claudeRedactions(env);
1816
2943
  const adapter = await missingClaudeAdapter(opts.workspace, opts.prompt);
@@ -1860,7 +2987,8 @@ function backends() {
1860
2987
  claude: claudeBackend,
1861
2988
  codex: codexBackend,
1862
2989
  "cursor-acp": cursorAcpBackend,
1863
- openrouter: openrouterBackend
2990
+ openrouter: openrouterBackend,
2991
+ local: localBackend
1864
2992
  };
1865
2993
  }
1866
2994
  function getBackend(id) {
@@ -1872,13 +3000,367 @@ function getBackend(id) {
1872
3000
  return backend;
1873
3001
  }
1874
3002
 
3003
+ // src/plan-loop/local-models.ts
3004
+ var LOCAL_MODELS_SCHEMA_VERSION = 1;
3005
+ var DEFAULT_SOURCE_TIMEOUT_MS = 1500;
3006
+ var LOCAL_MODEL_SOURCES = [
3007
+ "omarchy",
3008
+ "ollama",
3009
+ "lmstudio",
3010
+ "llamacpp"
3011
+ ];
3012
+ var OLLAMA_BASE = "http://127.0.0.1:11434";
3013
+ var LMSTUDIO_BASE = "http://127.0.0.1:1234";
3014
+ var LLAMACPP_BASE = "http://127.0.0.1:8080";
3015
+ var defaultExecFn = (file, args, timeoutMs) => new Promise((resolve) => {
3016
+ try {
3017
+ execFile(
3018
+ file,
3019
+ args,
3020
+ { encoding: "utf8", timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024, windowsHide: true },
3021
+ (error, stdout) => {
3022
+ if (!error) {
3023
+ resolve({ ok: true, stdout: String(stdout ?? "") });
3024
+ return;
3025
+ }
3026
+ const err = error;
3027
+ if (err.code === "ENOENT") resolve({ ok: false, reason: "missing" });
3028
+ else if (err.killed) resolve({ ok: false, reason: "timeout" });
3029
+ else resolve({ ok: false, reason: "failed", detail: firstLine(err.message) });
3030
+ }
3031
+ );
3032
+ } catch (err) {
3033
+ resolve({ ok: false, reason: "failed", detail: firstLine(String(err)) });
3034
+ }
3035
+ });
3036
+ var defaultFetchFn = (url, init) => fetch(url, init);
3037
+ function firstLine(text) {
3038
+ return (text.split("\n")[0] ?? "").trim().slice(0, 200);
3039
+ }
3040
+ function isLoopbackUrl(raw) {
3041
+ let url;
3042
+ try {
3043
+ url = new URL(raw);
3044
+ } catch {
3045
+ return false;
3046
+ }
3047
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
3048
+ const host = url.hostname.toLowerCase();
3049
+ return host === "localhost" || host === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(host);
3050
+ }
3051
+ function hostPort(url) {
3052
+ try {
3053
+ return new URL(url).host;
3054
+ } catch {
3055
+ return url;
3056
+ }
3057
+ }
3058
+ function errorCode(err) {
3059
+ const e = err;
3060
+ if (e && typeof e.cause?.code === "string") return e.cause.code;
3061
+ if (e && typeof e.code === "string") return e.code;
3062
+ return void 0;
3063
+ }
3064
+ async function getLoopbackJson(url, fetchFn, timeoutMs) {
3065
+ if (!isLoopbackUrl(url)) return { ok: false, note: `not a loopback address: ${url}` };
3066
+ const controller = new AbortController();
3067
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
3068
+ try {
3069
+ const res = await fetchFn(url, {
3070
+ signal: controller.signal,
3071
+ redirect: "manual",
3072
+ headers: { accept: "application/json" }
3073
+ });
3074
+ if (res.status >= 300 && res.status < 400) {
3075
+ return { ok: false, note: `redirect refused (HTTP ${res.status} from ${hostPort(url)})` };
3076
+ }
3077
+ if (res.status !== 200) return { ok: false, note: `HTTP ${res.status} from ${hostPort(url)}` };
3078
+ const body = await res.text();
3079
+ try {
3080
+ return { ok: true, value: JSON.parse(body) };
3081
+ } catch {
3082
+ return { ok: false, note: `malformed JSON from ${hostPort(url)}` };
3083
+ }
3084
+ } catch (err) {
3085
+ if (controller.signal.aborted) {
3086
+ return { ok: false, note: `no answer within ${timeoutMs} ms (${hostPort(url)})` };
3087
+ }
3088
+ const code = errorCode(err);
3089
+ if (code === "ECONNREFUSED")
3090
+ return { ok: false, note: `connection refused (${hostPort(url)})` };
3091
+ return {
3092
+ ok: false,
3093
+ note: `request failed (${hostPort(url)}${code ? `, ${code}` : ""})`
3094
+ };
3095
+ } finally {
3096
+ clearTimeout(timer);
3097
+ controller.abort();
3098
+ }
3099
+ }
3100
+ function isRecord5(v) {
3101
+ return typeof v === "object" && v !== null && !Array.isArray(v);
3102
+ }
3103
+ function str(v) {
3104
+ return typeof v === "string" && v.trim() !== "" ? v.trim() : void 0;
3105
+ }
3106
+ function positiveInt(v) {
3107
+ return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : void 0;
3108
+ }
3109
+ function joinNotes(notes) {
3110
+ return notes.length > 0 ? notes.join("; ") : void 0;
3111
+ }
3112
+ function plural(n, word) {
3113
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
3114
+ }
3115
+ function parseOmarchyStatus(value) {
3116
+ const source = "omarchy";
3117
+ if (!isRecord5(value) || !isRecord5(value.models)) {
3118
+ return {
3119
+ status: { source, ok: false, note: "unexpected JSON shape (no models object)" },
3120
+ models: []
3121
+ };
3122
+ }
3123
+ const models = [];
3124
+ let nonLoopback = 0;
3125
+ let noEndpoint = 0;
3126
+ for (const [key, raw] of Object.entries(value.models)) {
3127
+ if (!isRecord5(raw) || raw.kind !== "text") continue;
3128
+ const recipe = str(raw.recipe) ?? str(key);
3129
+ if (!recipe) continue;
3130
+ const endpoint = str(raw.endpoint);
3131
+ if (!endpoint) {
3132
+ noEndpoint += 1;
3133
+ continue;
3134
+ }
3135
+ if (!isLoopbackUrl(endpoint)) {
3136
+ nonLoopback += 1;
3137
+ continue;
3138
+ }
3139
+ const running = raw.unit === "active" && raw.sub_state === "running";
3140
+ const state = running ? "running" : raw.fits === false ? "not-fit" : "stopped";
3141
+ const reason = state === "not-fit" ? str(raw.fit_reason) ?? "does not fit" : void 0;
3142
+ const model = {
3143
+ id: `${source}:${recipe}`,
3144
+ label: str(raw.name) ?? recipe,
3145
+ source,
3146
+ endpoint: endpoint.replace(/\/+$/, ""),
3147
+ state
3148
+ };
3149
+ const ctx = positiveInt(raw.ctx);
3150
+ if (ctx) model.contextWindow = ctx;
3151
+ const vendor = str(raw.vendor);
3152
+ if (vendor) model.vendor = vendor;
3153
+ if (reason) model.reason = reason;
3154
+ models.push(model);
3155
+ }
3156
+ const notes = [];
3157
+ if (nonLoopback > 0) notes.push(`skipped ${plural(nonLoopback, "non-loopback model")}`);
3158
+ if (noEndpoint > 0) notes.push(`skipped ${plural(noEndpoint, "model")} without an endpoint`);
3159
+ const note = joinNotes(notes);
3160
+ return { status: note ? { source, ok: true, note } : { source, ok: true }, models };
3161
+ }
3162
+ function isOllamaCloudModel(entry, name) {
3163
+ return name.endsWith(":cloud") || name.endsWith("-cloud") || str(entry.remote_host) !== void 0;
3164
+ }
3165
+ function parseOllamaTags(value) {
3166
+ const source = "ollama";
3167
+ if (!isRecord5(value) || !Array.isArray(value.models)) {
3168
+ return {
3169
+ status: { source, ok: false, note: "unexpected JSON shape (no models array)" },
3170
+ models: []
3171
+ };
3172
+ }
3173
+ const models = [];
3174
+ let cloud = 0;
3175
+ let notText = 0;
3176
+ for (const raw of value.models) {
3177
+ if (!isRecord5(raw)) continue;
3178
+ const name = str(raw.name) ?? str(raw.model);
3179
+ if (!name) continue;
3180
+ if (isOllamaCloudModel(raw, name)) {
3181
+ cloud += 1;
3182
+ continue;
3183
+ }
3184
+ if (Array.isArray(raw.capabilities) && !raw.capabilities.includes("completion")) {
3185
+ notText += 1;
3186
+ continue;
3187
+ }
3188
+ const model = {
3189
+ id: `${source}:${name}`,
3190
+ label: name,
3191
+ source,
3192
+ endpoint: `${OLLAMA_BASE}/v1`,
3193
+ state: "running"
3194
+ };
3195
+ const details = isRecord5(raw.details) ? raw.details : void 0;
3196
+ const family = details ? str(details.family) : void 0;
3197
+ if (family) model.vendor = family;
3198
+ models.push(model);
3199
+ }
3200
+ const notes = [];
3201
+ if (cloud > 0) notes.push(`skipped ${plural(cloud, "cloud model")}`);
3202
+ if (notText > 0) notes.push(`skipped ${plural(notText, "non-text model")}`);
3203
+ const note = joinNotes(notes);
3204
+ return { status: note ? { source, ok: true, note } : { source, ok: true }, models };
3205
+ }
3206
+ function parseOpenAiModels(source, base, value) {
3207
+ if (!isRecord5(value) || !Array.isArray(value.data)) {
3208
+ return {
3209
+ status: { source, ok: false, note: "unexpected JSON shape (no data array)" },
3210
+ models: []
3211
+ };
3212
+ }
3213
+ const models = [];
3214
+ for (const raw of value.data) {
3215
+ if (!isRecord5(raw)) continue;
3216
+ const id = str(raw.id);
3217
+ if (!id) continue;
3218
+ const model = {
3219
+ id: `${source}:${id}`,
3220
+ label: id,
3221
+ source,
3222
+ endpoint: `${base}/v1`,
3223
+ state: "running"
3224
+ };
3225
+ const owner = str(raw.owned_by);
3226
+ if (owner && owner !== "organization_owner" && owner !== "llamacpp") model.vendor = owner;
3227
+ models.push(model);
3228
+ }
3229
+ return { status: { source, ok: true }, models };
3230
+ }
3231
+ async function probeOmarchy(deps) {
3232
+ const source = "omarchy";
3233
+ const bin = await deps.whichFn("omarchy-models");
3234
+ if (!bin)
3235
+ return { status: { source, ok: false, note: "omarchy-models not on PATH" }, models: [] };
3236
+ const run = await deps.execFn(bin, ["status", "--json"], deps.timeoutMs);
3237
+ if (!run.ok) {
3238
+ 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}` : ""}`;
3239
+ return { status: { source, ok: false, note }, models: [] };
3240
+ }
3241
+ let value;
3242
+ try {
3243
+ value = JSON.parse(run.stdout);
3244
+ } catch {
3245
+ return {
3246
+ status: { source, ok: false, note: "malformed JSON from omarchy-models status" },
3247
+ models: []
3248
+ };
3249
+ }
3250
+ return parseOmarchyStatus(value);
3251
+ }
3252
+ async function probeHttp(source, deps) {
3253
+ const url = source === "ollama" ? `${OLLAMA_BASE}/api/tags` : `${source === "lmstudio" ? LMSTUDIO_BASE : LLAMACPP_BASE}/v1/models`;
3254
+ const got = await getLoopbackJson(url, deps.fetchFn, deps.timeoutMs);
3255
+ if (!got.ok) return { status: { source, ok: false, note: got.note }, models: [] };
3256
+ if (source === "ollama") return parseOllamaTags(got.value);
3257
+ return parseOpenAiModels(
3258
+ source,
3259
+ source === "lmstudio" ? LMSTUDIO_BASE : LLAMACPP_BASE,
3260
+ got.value
3261
+ );
3262
+ }
3263
+ async function safely(source, run) {
3264
+ try {
3265
+ return await run();
3266
+ } catch (err) {
3267
+ return {
3268
+ status: { source, ok: false, note: `probe failed: ${firstLine(String(err))}` },
3269
+ models: []
3270
+ };
3271
+ }
3272
+ }
3273
+ async function discoverLocalModels(deps = {}) {
3274
+ const full = {
3275
+ whichFn: deps.whichFn ?? whichBinary,
3276
+ execFn: deps.execFn ?? defaultExecFn,
3277
+ fetchFn: deps.fetchFn ?? defaultFetchFn,
3278
+ timeoutMs: deps.timeoutMs ?? DEFAULT_SOURCE_TIMEOUT_MS
3279
+ };
3280
+ const [piPath, ...outcomes] = await Promise.all([
3281
+ full.whichFn("pi").catch(() => null),
3282
+ safely("omarchy", () => probeOmarchy(full)),
3283
+ safely("ollama", () => probeHttp("ollama", full)),
3284
+ safely("lmstudio", () => probeHttp("lmstudio", full)),
3285
+ safely("llamacpp", () => probeHttp("llamacpp", full))
3286
+ ]);
3287
+ const piFound = Boolean(piPath);
3288
+ const models = outcomes.flatMap(
3289
+ (o) => o.models.map((m) => {
3290
+ const runnable = piFound && m.state !== "not-fit";
3291
+ const { id, label, source, endpoint, state, ...optional } = m;
3292
+ const out = { id, label, source, endpoint, state, runnable, ...optional };
3293
+ if (!runnable && !out.reason) out.reason = "pi not on PATH";
3294
+ return out;
3295
+ })
3296
+ );
3297
+ return {
3298
+ schemaVersion: LOCAL_MODELS_SCHEMA_VERSION,
3299
+ models,
3300
+ sources: outcomes.map((o) => o.status),
3301
+ pi: { found: piFound }
3302
+ };
3303
+ }
3304
+ function renderLocalModels(report) {
3305
+ const lines = [];
3306
+ if (report.models.length === 0) {
3307
+ lines.push("No local text models found.");
3308
+ } else {
3309
+ const rows = report.models.map((m) => [
3310
+ m.id,
3311
+ m.state,
3312
+ m.runnable ? "yes" : "no",
3313
+ m.endpoint,
3314
+ m.reason ?? ""
3315
+ ]);
3316
+ const header = ["ID", "STATE", "RUNNABLE", "ENDPOINT", "NOTE"];
3317
+ const widths = header.map(
3318
+ (h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length))
3319
+ );
3320
+ const fmt = (cells) => cells.map((c, i) => i === cells.length - 1 ? c : c.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
3321
+ lines.push(fmt(header), ...rows.map(fmt));
3322
+ }
3323
+ lines.push("");
3324
+ for (const s of report.sources) {
3325
+ lines.push(`${s.source}: ${s.ok ? "ok" : "unavailable"}${s.note ? ` (${s.note})` : ""}`);
3326
+ }
3327
+ lines.push(`pi: ${report.pi.found ? "found" : "not on PATH (no model is runnable)"}`);
3328
+ return lines.join("\n");
3329
+ }
3330
+
1875
3331
  export {
1876
3332
  codexBackend,
3333
+ RESULT_NONCE_STDIN_ENV,
3334
+ takeResultNonce,
3335
+ createNonceStripper,
1877
3336
  parseStreamLine,
1878
3337
  parseResultLine,
1879
3338
  renderStreamEvent,
1880
3339
  createStreamRenderer,
1881
3340
  cursorAcpBackend,
3341
+ discoverLocalModels,
3342
+ renderLocalModels,
3343
+ INSTALL_HINTS,
3344
+ listDetectBackendIds,
3345
+ detectAgentBackend,
3346
+ countPendingTodos,
3347
+ findActivePlanFile,
3348
+ readPlan,
3349
+ readRunQueueState,
3350
+ resolveActivePlanFromHandoff,
3351
+ resolveActivePlanPath,
3352
+ CLAUDE_SUBAGENT_MODEL_ENV,
3353
+ readPlanRoleOverrides,
3354
+ resolveWorkerRole,
3355
+ resolveSubworkerModel,
3356
+ describeResolvedRoles,
3357
+ reviewModelRelation,
3358
+ describeIdenticalReviewModel,
3359
+ describeSameFamilyReviewModel,
3360
+ resolveReviewJobRole,
3361
+ loadRolesContext,
3362
+ parseLocalModelId,
3363
+ localBackend,
1882
3364
  resolveHitlRunOptions,
1883
3365
  redactSecrets,
1884
3366
  RedactingStreamBuffer,
@@ -1888,7 +3370,6 @@ export {
1888
3370
  CLAUDE_MAX_BUDGET_USD_ENV,
1889
3371
  claudeRunCaps,
1890
3372
  claudeRedactions,
1891
- whichBinary,
1892
3373
  spawnLogged,
1893
3374
  cursorAgentHeadlessArgs,
1894
3375
  cursorAgentReviewArgs,