@tekmidian/pai 0.66.7 → 0.66.8

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 (93) hide show
  1. package/dist/{aibroker-client-BevXY1Zz.mjs → aibroker-client-BfnVwGZl.mjs} +3 -3
  2. package/dist/{aibroker-client-BevXY1Zz.mjs.map → aibroker-client-BfnVwGZl.mjs.map} +1 -1
  3. package/dist/{aibroker-client-CxTpL_u7.mjs → aibroker-client-C-O3Fflh.mjs} +1 -1
  4. package/dist/{auto-route-BVeAp0fl.mjs → auto-route-D8TBDNqb.mjs} +3 -3
  5. package/dist/{auto-route-BVeAp0fl.mjs.map → auto-route-D8TBDNqb.mjs.map} +1 -1
  6. package/dist/auto-route-DCxTKz19.mjs +7 -0
  7. package/dist/{chain-8hFKr23C.mjs → chain-BL4khGgy.mjs} +4 -3
  8. package/dist/{chain-8hFKr23C.mjs.map → chain-BL4khGgy.mjs.map} +1 -1
  9. package/dist/cli/index.mjs +20 -17
  10. package/dist/cli/index.mjs.map +1 -1
  11. package/dist/cli/program.mjs +19 -16
  12. package/dist/{config-sfaArCsl.mjs → config-DjZELvoA.mjs} +2 -2
  13. package/dist/{config-sfaArCsl.mjs.map → config-DjZELvoA.mjs.map} +1 -1
  14. package/dist/{run-env-CkAmx3lb.mjs → config-Dpe2JlbY.mjs} +5 -114
  15. package/dist/config-Dpe2JlbY.mjs.map +1 -0
  16. package/dist/{config-UWtzLpXi.mjs → config-yomayAwe.mjs} +1 -1
  17. package/dist/{context-handover-cache-Bb-H_mTa.mjs → context-handover-cache-DFqxNh-H.mjs} +27 -12
  18. package/dist/context-handover-cache-DFqxNh-H.mjs.map +1 -0
  19. package/dist/daemon/index.mjs +20 -16
  20. package/dist/daemon/index.mjs.map +1 -1
  21. package/dist/{daemon-CkbX-hV7.mjs → daemon-CsR1S_Qr.mjs} +20 -19
  22. package/dist/{daemon-CkbX-hV7.mjs.map → daemon-CsR1S_Qr.mjs.map} +1 -1
  23. package/dist/daemon-WrncnGua.mjs +23 -0
  24. package/dist/daemon-mcp/index.mjs +15 -13
  25. package/dist/daemon-mcp/index.mjs.map +1 -1
  26. package/dist/{embedding-gate-BVrr0BgS.mjs → embedding-gate-DqbKvn56.mjs} +4 -4
  27. package/dist/{embedding-gate-BVrr0BgS.mjs.map → embedding-gate-DqbKvn56.mjs.map} +1 -1
  28. package/dist/{embedding-gate-Crj8awk7.mjs → embedding-gate-SJMCPwxG.mjs} +3 -3
  29. package/dist/{embeddings-DFl88_y-.mjs → embeddings-BUjZMD9F.mjs} +1 -1
  30. package/dist/{embeddings-DFl88_y-.mjs.map → embeddings-BUjZMD9F.mjs.map} +1 -1
  31. package/dist/{embeddings-BuA7v4lk.mjs → embeddings-DrJ-ewfi.mjs} +1 -1
  32. package/dist/{env-DqTjeKoA.mjs → env-CPCNHz3i.mjs} +1 -1
  33. package/dist/{env-DqTjeKoA.mjs.map → env-CPCNHz3i.mjs.map} +1 -1
  34. package/dist/factory-DjtXElOI.mjs +9 -0
  35. package/dist/{factory-mNBitkL_.mjs → factory-yElzJc6f.mjs} +10 -10
  36. package/dist/{factory-mNBitkL_.mjs.map → factory-yElzJc6f.mjs.map} +1 -1
  37. package/dist/{fallback-DdC1_s2d.mjs → fallback-2yWDDYiT.mjs} +5 -4
  38. package/dist/{fallback-DdC1_s2d.mjs.map → fallback-2yWDDYiT.mjs.map} +1 -1
  39. package/dist/{helpers-CZsi_49C.mjs → helpers-B9LHRJ8R.mjs} +1 -1
  40. package/dist/{helpers-CZsi_49C.mjs.map → helpers-B9LHRJ8R.mjs.map} +1 -1
  41. package/dist/index.d.mts.map +1 -1
  42. package/dist/index.mjs +7 -4
  43. package/dist/{ipc-client-BgSzY9QJ.mjs → ipc-client-DVZ_EGnu.mjs} +2 -2
  44. package/dist/{ipc-client-BgSzY9QJ.mjs.map → ipc-client-DVZ_EGnu.mjs.map} +1 -1
  45. package/dist/main-resolver-DjQsexge.mjs +8 -0
  46. package/dist/{main-resolver-DEXky_Km.mjs → main-resolver-Dxvn4Mv8.mjs} +7 -6
  47. package/dist/{main-resolver-DEXky_Km.mjs.map → main-resolver-Dxvn4Mv8.mjs.map} +1 -1
  48. package/dist/{pai-marker-DXVpFsYz.mjs → pai-marker-1B7iC7oq.mjs} +121 -3
  49. package/dist/pai-marker-1B7iC7oq.mjs.map +1 -0
  50. package/dist/{planner-DBoB5GtC.mjs → planner-CspP59ya.mjs} +13 -11
  51. package/dist/{planner-DBoB5GtC.mjs.map → planner-CspP59ya.mjs.map} +1 -1
  52. package/dist/{postgres-D-96lgE1.mjs → postgres-CCAGq1qp.mjs} +5 -5
  53. package/dist/{postgres-D-96lgE1.mjs.map → postgres-CCAGq1qp.mjs.map} +1 -1
  54. package/dist/postgres-CzkEPfAm.mjs +7 -0
  55. package/dist/{program-BXns_5kO.mjs → program-cWqZI0_L.mjs} +77 -119
  56. package/dist/program-cWqZI0_L.mjs.map +1 -0
  57. package/dist/{query-feedback-VI7Cl-Lr.mjs → query-feedback-GPeVGvIa.mjs} +2 -2
  58. package/dist/{query-feedback-VI7Cl-Lr.mjs.map → query-feedback-GPeVGvIa.mjs.map} +1 -1
  59. package/dist/{reranker-3lnggwgq.mjs → reranker-BTiOia8Y.mjs} +1 -1
  60. package/dist/{reranker-3lnggwgq.mjs.map → reranker-BTiOia8Y.mjs.map} +1 -1
  61. package/dist/{reranker-CZ2mP4cf.mjs → reranker-YwDT2n5e.mjs} +1 -1
  62. package/dist/{router-dfjlaOMI.mjs → router-Bk_ySIZT.mjs} +2 -2
  63. package/dist/{router-dfjlaOMI.mjs.map → router-Bk_ySIZT.mjs.map} +1 -1
  64. package/dist/router-DyiZNI6o.mjs +3 -0
  65. package/dist/{run-DPwQkRwh.mjs → run-BZNdpUGQ.mjs} +126 -1795
  66. package/dist/run-BZNdpUGQ.mjs.map +1 -0
  67. package/dist/run-env-Cd0Son-Y.mjs +115 -0
  68. package/dist/run-env-Cd0Son-Y.mjs.map +1 -0
  69. package/dist/{runtime-paths-BiEi_gaG.mjs → runtime-paths-DkZoxofH.mjs} +1 -1
  70. package/dist/{runtime-paths-BiEi_gaG.mjs.map → runtime-paths-DkZoxofH.mjs.map} +1 -1
  71. package/dist/{search-CNAGTiJP.mjs → search-cPDj-9fO.mjs} +2 -2
  72. package/dist/{search-CNAGTiJP.mjs.map → search-cPDj-9fO.mjs.map} +1 -1
  73. package/dist/{sources-BxXbzpAJ.mjs → sources-CvvzNZad.mjs} +1 -1
  74. package/dist/{sources-BxXbzpAJ.mjs.map → sources-CvvzNZad.mjs.map} +1 -1
  75. package/dist/{stop-words-DtxaTWU_.mjs → stop-words-LtkS-Pej.mjs} +1 -1
  76. package/dist/{stop-words-DtxaTWU_.mjs.map → stop-words-LtkS-Pej.mjs.map} +1 -1
  77. package/dist/worktree-CwMRTa0H.mjs +1578 -0
  78. package/dist/worktree-CwMRTa0H.mjs.map +1 -0
  79. package/dist/{zettelkasten-wh2Yy1nS.mjs → zettelkasten-DSIe6wpF.mjs} +4 -4
  80. package/dist/{zettelkasten-wh2Yy1nS.mjs.map → zettelkasten-DSIe6wpF.mjs.map} +1 -1
  81. package/dist/{zettelkasten-CzcPzEsL.mjs → zettelkasten-DtkAvA18.mjs} +5 -5
  82. package/package.json +1 -1
  83. package/dist/auto-route-CboBqsN3.mjs +0 -3
  84. package/dist/context-handover-cache-Bb-H_mTa.mjs.map +0 -1
  85. package/dist/daemon-BXTn2EgV.mjs +0 -19
  86. package/dist/factory-XrH66erA.mjs +0 -9
  87. package/dist/main-resolver-CobQGm2B.mjs +0 -7
  88. package/dist/pai-marker-DXVpFsYz.mjs.map +0 -1
  89. package/dist/postgres-TedJP3yF.mjs +0 -7
  90. package/dist/program-BXns_5kO.mjs.map +0 -1
  91. package/dist/router-CKn9e0fo.mjs +0 -3
  92. package/dist/run-DPwQkRwh.mjs.map +0 -1
  93. package/dist/run-env-CkAmx3lb.mjs.map +0 -1
@@ -1,11 +1,12 @@
1
- import { i as getRegistryBackend } from "./factory-mNBitkL_.mjs";
2
- import { d as resolvePaiFile, u as paiHomePath } from "./runtime-paths-BiEi_gaG.mjs";
3
- import { A as resolveProviderKey, D as readWorkersSection, E as providerKeyPath, O as resolveCapability, T as providerCostTier, _ as classModelCapability, b as getProviderOrNative, f as NATIVE_ANTHROPIC_MODELS, g as assertProviderRunnable, h as WorkersConfigError, k as resolveModelCapability, m as WORKER_CLASSES, n as claudeCommand, o as DEFAULT_LOG_DIR, r as ANTHROPIC_NATIVE, t as buildRunEnv, x as isModelCapability, y as expandHome } from "./run-env-CkAmx3lb.mjs";
4
- import { appendFileSync, closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
5
- import { homedir, platform, tmpdir } from "node:os";
6
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
- import { fileURLToPath } from "node:url";
1
+ import { C as providerCostTier, D as resolveModelCapability, E as resolveCapability, O as resolveProviderKey, T as readWorkersSection, f as WORKER_CLASSES, h as classModelCapability, m as assertProviderRunnable, p as WorkersConfigError, t as ANTHROPIC_NATIVE, u as NATIVE_ANTHROPIC_MODELS, v as getProviderOrNative, w as providerKeyPath, y as isModelCapability } from "./config-Dpe2JlbY.mjs";
2
+ import { A as newWorkerId, B as shortText, D as isLive, G as panesDir, H as ensureNoMcpConfig, K as routingStatePath, L as appendSystemPromptArgs, N as parseSleepSecs, O as loadStatus, P as saveStatus, U as eventsPath, V as stripPromptValues, W as ledgerPath, _ as appendLedger, c as recordWorktree, d as worktreeSystemPrompt, f as worktreeWanted, i as gcWorktreesThrottled, j as nowStamp, k as loadStatuses, l as salvageOnExit, o as inPlaceSystemPrompt, q as workersLogDir, t as addWorktree, w as describeTool, y as UNLABELED, z as parseRunnerArgs } from "./worktree-CwMRTa0H.mjs";
3
+ import { i as getRegistryBackend } from "./factory-yElzJc6f.mjs";
4
+ import { n as claudeCommand, t as buildRunEnv } from "./run-env-Cd0Son-Y.mjs";
5
+ import { appendFileSync, closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
6
+ import { homedir, tmpdir } from "node:os";
7
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
8
8
  import { execFileSync, spawn } from "node:child_process";
9
+ import { fileURLToPath } from "node:url";
9
10
  import { connect, createServer } from "node:net";
10
11
  import { createServer as createServer$1 } from "node:http";
11
12
  import { createInterface } from "node:readline";
@@ -225,59 +226,6 @@ function pinNotices(launch, claudeJson) {
225
226
  return lines;
226
227
  }
227
228
 
228
- //#endregion
229
- //#region src/workers/paths.ts
230
- /**
231
- * paths.ts — where worker run artefacts live.
232
- *
233
- * Everything a run writes (event mirror, status file, pane registry, routing
234
- * state, the empty MCP config) sits under one logDir so the whole tree is
235
- * disposable and configurable: `workers.logDir`, default ~/.claude/logs/workers.
236
- */
237
- /**
238
- * Absolute logDir for the given config. An explicit `logDir` in workers.yaml
239
- * is honored verbatim (the user chose it). Otherwise this resolves like every
240
- * other PAI_HOME file: PAI_HOME/logs/workers if it exists, else the old
241
- * ~/.claude/logs/workers (with a one-time notice), else the new path.
242
- */
243
- function workersLogDir(config) {
244
- const expanded = expandHome(config.logDir);
245
- if (config.logDir !== DEFAULT_LOG_DIR) return expanded;
246
- return resolvePaiFile(paiHomePath("logs", "workers"), [expanded], "pai config migrate --logs");
247
- }
248
- /** The strict empty MCP config for headless runs, written on demand. */
249
- function ensureNoMcpConfig(logDir) {
250
- const path = noMcpConfigPath(logDir);
251
- if (!existsSync(path)) {
252
- mkdirSync(logDir, { recursive: true });
253
- writeFileSync(path, "{ \"mcpServers\": {} }\n", "utf8");
254
- }
255
- return path;
256
- }
257
- function statusPath(logDir, id) {
258
- return join(logDir, `${id}.status`);
259
- }
260
- function eventsPath(logDir, id) {
261
- return join(logDir, `${id}.jsonl`);
262
- }
263
- function ledgerPath(logDir) {
264
- return join(logDir, "ledger.log");
265
- }
266
- function routingStatePath(logDir) {
267
- return join(logDir, "routing-state.json");
268
- }
269
- function panesDir(logDir) {
270
- return join(logDir, "panes");
271
- }
272
- /**
273
- * The strict empty MCP config handed to headless workers. Written into the
274
- * logDir on demand (never into the user's vendor config directory — this is
275
- * PAI state, not vendor state).
276
- */
277
- function noMcpConfigPath(logDir) {
278
- return join(logDir, "no-mcp.json");
279
- }
280
-
281
229
  //#endregion
282
230
  //#region src/workers/routing.ts
283
231
  /**
@@ -618,1522 +566,6 @@ function stopProxy(logDir) {
618
566
  return `proxy pid ${pid} stopped`;
619
567
  }
620
568
 
621
- //#endregion
622
- //#region src/workers/args.ts
623
- function parseRunnerArgs(argv) {
624
- let prompt = null;
625
- let outputFormat = "text";
626
- const rest = [];
627
- let headless = false;
628
- let callerModel = false;
629
- let callerMcpConfig = false;
630
- let callerSystemPrompt = false;
631
- const callerSystemPrompts = [];
632
- let callerTools = false;
633
- const mcp = [];
634
- const allowedTools = [];
635
- let i = 0;
636
- while (i < argv.length) {
637
- const a = argv[i];
638
- if (a === "-p" || a === "--print") {
639
- headless = true;
640
- rest.push(a);
641
- if (i + 1 < argv.length && !argv[i + 1].startsWith("-")) {
642
- prompt = argv[i + 1];
643
- rest.push(prompt);
644
- i += 1;
645
- }
646
- } else if (a === "--output-format") {
647
- const v = argv[i + 1];
648
- if (v === "json" || v === "stream-json") outputFormat = v;
649
- i += 1;
650
- } else if (a.startsWith("--output-format=")) {
651
- const v = a.slice(16);
652
- if (v === "json" || v === "stream-json") outputFormat = v;
653
- } else if (a === "--verbose") {} else if (a === "--append-system-prompt") {
654
- callerSystemPrompt = true;
655
- if (i + 1 < argv.length) callerSystemPrompts.push(argv[++i]);
656
- } else if (a.startsWith("--append-system-prompt=")) {
657
- callerSystemPrompt = true;
658
- callerSystemPrompts.push(a.slice(23));
659
- } else if (a === "--mcp") {
660
- const v = argv[i + 1];
661
- if (v !== void 0 && !v.startsWith("-")) {
662
- mcp.push(v);
663
- i += 1;
664
- }
665
- } else if (a.startsWith("--mcp=")) mcp.push(a.slice(6));
666
- else if (a === "--allowedTools") {
667
- rest.push(a);
668
- const v = argv[i + 1];
669
- if (v !== void 0 && !v.startsWith("-")) {
670
- allowedTools.push(v);
671
- rest.push(v);
672
- i += 1;
673
- }
674
- } else if (a.startsWith("--allowedTools=")) {
675
- allowedTools.push(a.slice(15));
676
- rest.push(a);
677
- } else {
678
- if (a === "--model") callerModel = true;
679
- if (a.startsWith("--model=")) callerModel = true;
680
- if (a === "--mcp-config") callerMcpConfig = true;
681
- if (a.startsWith("--mcp-config=")) callerMcpConfig = true;
682
- if (a === "--tools") callerTools = true;
683
- if (a.startsWith("--tools=")) callerTools = true;
684
- if (prompt === null && !a.startsWith("-") && rest.length > 0 && (rest[rest.length - 1] === "-p" || rest[rest.length - 1] === "--print")) prompt = a;
685
- rest.push(a);
686
- }
687
- i += 1;
688
- }
689
- return {
690
- prompt,
691
- outputFormat,
692
- rest,
693
- headless,
694
- callerModel,
695
- callerMcpConfig,
696
- callerSystemPrompt,
697
- callerSystemPrompts,
698
- callerTools,
699
- mcp,
700
- allowedTools
701
- };
702
- }
703
- /**
704
- * The one --append-system-prompt flag for a spawn: claude keeps only the LAST
705
- * occurrence, so every piece is joined (blank line between) into a single flag.
706
- * Empty parts are dropped; no parts, no flag.
707
- */
708
- function appendSystemPromptArgs(parts) {
709
- const text = parts.filter((p) => p.trim()).join("\n\n");
710
- return text ? ["--append-system-prompt", text] : [];
711
- }
712
- /**
713
- * Turn `-p "<prompt>"` into bare `-p` (same for --print): for stream-json
714
- * stdin runs the prompt moves to the first user message on stdin, so the
715
- * value must not stay on the command line. Only prompt values directly
716
- * following the flag are touched; everything else passes through.
717
- */
718
- function stripPromptValues(argv) {
719
- const out = [];
720
- for (let i = 0; i < argv.length; i++) {
721
- const a = argv[i];
722
- const isPrint = a === "-p" || a === "--print";
723
- out.push(a);
724
- if (isPrint && i + 1 < argv.length && !argv[i + 1].startsWith("-")) i += 1;
725
- }
726
- return out;
727
- }
728
- /**
729
- * A one-line stderr hint (never blocking) for an inline -p prompt long or
730
- * multi-line enough to be a shell-quoting risk — write it to a file and pass
731
- * --spec instead. null when the prompt is short/simple enough to be fine.
732
- */
733
- function longInlinePromptHint(prompt) {
734
- if (!prompt) return null;
735
- const newlines = (prompt.match(/\n/g) ?? []).length;
736
- if (prompt.length > 600 || newlines > 3) return "hint: long inline prompts break on shell quoting — write the spec to a file and use --spec <file>";
737
- return null;
738
- }
739
- /** Collapse whitespace and cut to n chars with an ellipsis (label rendering). */
740
- function shortText(s, n) {
741
- const t = String(s ?? "").split(/\s+/).filter(Boolean).join(" ");
742
- return t.length <= n ? t : t.slice(0, n - 1) + "…";
743
- }
744
-
745
- //#endregion
746
- //#region src/workers/status.ts
747
- /**
748
- * status.ts — the live per-worker status file.
749
- *
750
- * One JSON file per run, rewritten atomically on every turn, read by `ps`,
751
- * `follow`, the status line and the pane logic. Same field set the Python
752
- * runner wrote, plus `provider` (routing is multi-provider now) and `session`
753
- * (the AIBroker identity of the launching session, see scope.ts).
754
- */
755
- /** Label a worker gets when launched with neither --label nor a prompt. */
756
- const UNLABELED = "unlabeled";
757
- /**
758
- * Whether a status is the terminal's interactive chat pane, not a spawned
759
- * task worker. `origin` is the real discriminator; the fallback catches
760
- * running entries from before the flag existed (unlabeled, no turns yet).
761
- * Removable once every pane runs code that writes `origin`.
762
- */
763
- function isChatPane(s) {
764
- return s.origin === "chat" || !s.origin && (s.label === UNLABELED || s.label === "(no prompt)") && s.turns === 0;
765
- }
766
- /** Context-meter percentage 0–100, null when the numbers are missing. */
767
- function contextPercent(s) {
768
- if (!s.contextTokens || !s.contextWindow) return null;
769
- return Math.round(s.contextTokens / s.contextWindow * 100);
770
- }
771
- /** Compact token count: 84k, 200k, 900. */
772
- function fmtContextK(n) {
773
- return n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(n);
774
- }
775
- /**
776
- * The one context-meter label, shared by every renderer so identical
777
- * numbers always render identically: `ctx 84k/200k (42%)` — used-style
778
- * percent. Empty when the numbers are missing (callers drop the part).
779
- */
780
- function contextLabel(s) {
781
- const pct = contextPercent(s);
782
- if (pct === null) return "";
783
- return `ctx ${fmtContextK(s.contextTokens ?? 0)}/${fmtContextK(s.contextWindow ?? 0)} (${pct}%)`;
784
- }
785
- /** Timestamp format shared by status files and the ledger. */
786
- function nowStamp(d = /* @__PURE__ */ new Date()) {
787
- const p = (n) => String(n).padStart(2, "0");
788
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
789
- }
790
- let lastId = "";
791
- let idSeq = 0;
792
- function newWorkerId(d = /* @__PURE__ */ new Date(), pid = process.pid) {
793
- const p = (n) => String(n).padStart(2, "0");
794
- const base = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${pid}`;
795
- if (base === lastId) {
796
- idSeq += 1;
797
- return `${base}-${String(idSeq).padStart(2, "0")}`;
798
- }
799
- lastId = base;
800
- idSeq = 0;
801
- return base;
802
- }
803
- let tmpSeq = 0;
804
- /** A temp path only this call owns — never the same string twice. */
805
- function statusTmpPath(logDir, id) {
806
- return `${statusPath(logDir, id)}.${process.pid}.${tmpSeq++}.tmp`;
807
- }
808
- const firstWrittenLabel = /* @__PURE__ */ new Map();
809
- /** Write status atomically (temp + rename) and stamp `updated`. */
810
- function saveStatus(logDir, status, d = /* @__PURE__ */ new Date()) {
811
- status.updated = nowStamp(d);
812
- const path = statusPath(logDir, status.id);
813
- const baseline = firstWrittenLabel.get(status.id);
814
- if (baseline === void 0) firstWrittenLabel.set(status.id, status.label);
815
- const onDisk = baseline === void 0 ? void 0 : loadStatus(logDir, status.id);
816
- if (onDisk) {
817
- if (status.label === baseline && onDisk.label !== status.label) status.label = onDisk.label;
818
- if (onDisk.controlsHeld) status.controlsHeld = true;
819
- }
820
- const tmp = statusTmpPath(logDir, status.id);
821
- if (!existsSync(logDir)) mkdirSync(logDir, { recursive: true });
822
- try {
823
- writeFileSync(tmp, JSON.stringify(status), "utf8");
824
- renameSync(tmp, path);
825
- } catch (e) {
826
- try {
827
- rmSync(tmp, { force: true });
828
- } catch {}
829
- throw e;
830
- }
831
- }
832
- /**
833
- * Set a worker's goal (the operator's `--label`), atomically, through the
834
- * same saveStatus path everything else writes with. Used by `pai worker
835
- * goal` and the `--goal` option of `say`: a fresh call in a fresh process, so
836
- * it always carries no baseline yet and always wins over the worker's own
837
- * next periodic write (see saveStatus above).
838
- */
839
- function setWorkerLabel(logDir, id, label) {
840
- const status = loadStatus(logDir, id);
841
- if (!status) throw new Error(`no worker named "${id}"`);
842
- status.label = label;
843
- saveStatus(logDir, status);
844
- return status;
845
- }
846
- /** Load every status file in the logDir, oldest id first, skipping damage. */
847
- function loadStatuses(logDir) {
848
- if (!existsSync(logDir)) return [];
849
- const out = [];
850
- for (const name of readdirSync(logDir).sort()) {
851
- if (!name.endsWith(".status")) continue;
852
- try {
853
- out.push(JSON.parse(readFileSync(join(logDir, name), "utf8")));
854
- } catch {}
855
- }
856
- return out;
857
- }
858
- function loadStatus(logDir, id) {
859
- const path = statusPath(logDir, id);
860
- if (!existsSync(path)) return null;
861
- try {
862
- return JSON.parse(readFileSync(path, "utf8"));
863
- } catch {
864
- return null;
865
- }
866
- }
867
- /**
868
- * Wait for a worker to record its own terminal state (the run's signal
869
- * handler writes killed/rc/secs). Returns that status, or null when it is
870
- * still "running" after `timeoutMs` — the caller then writes the state itself.
871
- */
872
- async function waitForTerminalStatus(logDir, id, timeoutMs = 2e3, stepMs = 50) {
873
- const deadline = Date.now() + timeoutMs;
874
- for (;;) {
875
- const s = loadStatus(logDir, id);
876
- if (s && s.state !== "running") return s;
877
- if (Date.now() >= deadline) return null;
878
- await new Promise((r) => setTimeout(r, stepMs));
879
- }
880
- }
881
- function alive(pid) {
882
- if (!pid || pid <= 0) return false;
883
- try {
884
- process.kill(pid, 0);
885
- return true;
886
- } catch {
887
- return false;
888
- }
889
- }
890
- /**
891
- * Whether `status.pid` still names the process that was started as this
892
- * worker, not a later, unrelated process the OS handed the same pid to after
893
- * the worker exited. `alive()` alone can't tell these apart — a pid observed
894
- * live on 2026-09-19 (worker 20260919-083549-90913) had been reused, and
895
- * `pai worker kill` signalled the wrong, unrelated process. `ps -o lstart=`
896
- * reads the running process's actual start time and compares it against the
897
- * status file's own `started` stamp; a reused pid almost never starts within
898
- * 120s of the original, so a wider drift means "different process".
899
- */
900
- function ownsPid(status) {
901
- if (status.pid <= 0 || !alive(status.pid)) return false;
902
- try {
903
- const out = execFileSync("ps", [
904
- "-o",
905
- "lstart=",
906
- "-p",
907
- String(status.pid)
908
- ], {
909
- encoding: "utf8",
910
- env: {
911
- ...process.env,
912
- LC_ALL: "C"
913
- }
914
- }).trim();
915
- const psStart = Date.parse(out);
916
- const started = Date.parse(status.started.replace(" ", "T"));
917
- if (Number.isNaN(psStart) || Number.isNaN(started)) return alive(status.pid);
918
- return Math.abs(psStart - started) <= 12e4;
919
- } catch {
920
- return alive(status.pid);
921
- }
922
- }
923
- /** Whether a status is both marked "running" and still owns its recorded pid. */
924
- function isLive(status) {
925
- return status.state === "running" && ownsPid(status);
926
- }
927
- /** "42s" under 90s, "7m" above — the coarse age the table and bar show. */
928
- function ageOf(ts, now = /* @__PURE__ */ new Date()) {
929
- const t = Date.parse(ts.replace(" ", "T"));
930
- if (Number.isNaN(t)) return "?";
931
- const s = Math.max(0, Math.floor((now.getTime() - t) / 1e3));
932
- return s < 90 ? `${s}s` : `${Math.floor(s / 60)}m`;
933
- }
934
- /** Precise elapsed time: "45s", "1m 23s", "12m 05s", "1h 02m 05s" — seconds zero-padded after a larger unit. */
935
- function elapsedOf(ts, now = /* @__PURE__ */ new Date()) {
936
- const t = Date.parse(ts.replace(" ", "T"));
937
- if (Number.isNaN(t)) return "?";
938
- const secs = Math.max(0, Math.floor((now.getTime() - t) / 1e3));
939
- const hours = Math.floor(secs / 3600);
940
- const mins = Math.floor(secs % 3600 / 60);
941
- const sec = secs % 60;
942
- if (hours > 0) return `${hours}h ${String(mins).padStart(2, "0")}m ${String(sec).padStart(2, "0")}s`;
943
- if (mins > 0) return `${mins}m ${String(sec).padStart(2, "0")}s`;
944
- return `${sec}s`;
945
- }
946
- /** Shorter sleeps are legitimate polling — not worth a supervision event. */
947
- const SLEEP_FLOOR_SECS = 60;
948
- const SLEEP_RE = /^\s*sleep\s+([0-9]+(?:\.[0-9]+)?)([smhd]?)\s*(?:$|[;&|])/;
949
- /** s/m/h/d suffix to seconds multiplier, shared by every `sleep N<unit>` parse below. */
950
- function sleepUnitMultiplier(unit) {
951
- return unit === "m" ? 60 : unit === "h" ? 3600 : unit === "d" ? 86400 : 1;
952
- }
953
- /**
954
- * Seconds of a `sleep N` (N plain or with an s/m/h/d suffix) that stands alone
955
- * or leads a compound command (`sleep 150; cat f`, `sleep 2m && tail f`,
956
- * `sleep 90 || true`, `sleep 60 &`), or null when no long sleep leads: anchored
957
- * to the start of the command, so a filename containing "sleep" or an
958
- * `echo sleep 500` never trips it, and floored at SLEEP_FLOOR_SECS so ordinary
959
- * polling stays invisible.
960
- */
961
- function parseSleepSecs(command) {
962
- const m = command.match(SLEEP_RE);
963
- if (!m) return null;
964
- const secs = Number(m[1]) * sleepUnitMultiplier(m[2]);
965
- return Number.isFinite(secs) && secs >= SLEEP_FLOOR_SECS ? secs : null;
966
- }
967
- /** One-line description of a tool call, e.g. "Bash: npm test". */
968
- function describeTool(name, inp) {
969
- if (typeof inp !== "object" || inp === null) return name;
970
- const i = inp;
971
- const get = (k) => typeof i[k] === "string" ? i[k] : "";
972
- if (name === "Bash") return `Bash: ${shortText(get("command"), 70)}`;
973
- if (name === "Read" || name === "Edit" || name === "Write" || name === "MultiEdit") return `${name}: ${get("file_path").split("/").pop() ?? ""}`;
974
- if (name === "Grep" || name === "Glob") return `${name}: ${shortText(get("pattern"), 50)}`;
975
- if (name === "WebSearch") return `${name}: ${shortText(get("query"), 50)}`;
976
- if (name === "WebFetch") return `${name}: ${shortText(get("url"), 60)}`;
977
- return name;
978
- }
979
-
980
- //#endregion
981
- //#region src/workers/ledger.ts
982
- /**
983
- * ledger.ts — the routing ledger, one append-only log for every worker event.
984
- *
985
- * Line shapes (whitespace-aligned so `tail` reads as a table):
986
- *
987
- * 2026-09-17 12:00:00 WORKER-START id=<id> provider=<p> mode=headless model=<m> cwd=<cwd> label=<label>
988
- * 2026-09-17 12:01:00 WORKER-END id=<id> provider=<p> mode=headless model=<m> rc=0 secs=60 turns=3 tools=8 label=<label>
989
- * 2026-09-17 12:00:20 WORKER-REROUTE from=<a> to=<b> reason=quota
990
- * 2026-09-17 12:00:00 DENIED-ANTHROPIC-AGENT cwd=<cwd> desc=<desc>
991
- * 2026-09-17 12:00:00 ALLOWED-ANTHROPIC-AGENT cwd=<cwd> desc=<desc>
992
- *
993
- * `pai worker log` (and glm-log before it) counts these; keep the tags stable.
994
- */
995
- function ledgerStamp(d = /* @__PURE__ */ new Date()) {
996
- const p = (n) => String(n).padStart(2, "0");
997
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
998
- }
999
- /** Parse `2026-09-17 12:00:00 TAG key=value …` into its parts. */
1000
- function parseLedgerLine(line) {
1001
- const m = line.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\S+)(?: (.*))?$/);
1002
- if (!m) return null;
1003
- const fields = {};
1004
- for (const part of (m[3] ?? "").split(" ")) {
1005
- if (!part) continue;
1006
- const eq = part.indexOf("=");
1007
- if (eq <= 0) continue;
1008
- fields[part.slice(0, eq)] = part.slice(eq + 1);
1009
- }
1010
- return {
1011
- stamp: m[1],
1012
- event: m[2],
1013
- fields
1014
- };
1015
- }
1016
- /** Append one ledger line. `kv` order is the caller's; values are flattened. */
1017
- function appendLedger(path, event, kv, now = /* @__PURE__ */ new Date()) {
1018
- const parts = [];
1019
- for (const [k, v] of Object.entries(kv)) {
1020
- if (v === void 0 || v === null) continue;
1021
- parts.push(`${k}=${String(v).replace(/\s+/g, " ")}`);
1022
- }
1023
- const dir = dirname(path);
1024
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1025
- const tail = parts.length ? " " + parts.join(" ") : "";
1026
- appendFileSync(path, `${ledgerStamp(now)} ${event}${tail}\n`, "utf8");
1027
- }
1028
- /** The counts `pai worker log` prints, over today's lines or the whole file. */
1029
- function ledgerSummary(path, scope, lastN = 15, now = /* @__PURE__ */ new Date()) {
1030
- if (!existsSync(path)) return null;
1031
- const text = readFileSync(path, "utf8");
1032
- const today = ledgerStamp(now).slice(0, 10);
1033
- const lines = text.split("\n").filter((l) => l.trim());
1034
- const parsed = (scope === "all" ? lines : lines.filter((l) => l.startsWith(today))).map(parseLedgerLine).filter((x) => x !== null);
1035
- const count = (ev) => parsed.filter((p) => p.event === ev).length;
1036
- const ends = parsed.filter((p) => p.event === "WORKER-END");
1037
- const ok = ends.filter((p) => p.fields.rc === "0").length;
1038
- return {
1039
- scope: scope === "all" ? "all time" : `today ${today}`,
1040
- started: count("WORKER-START"),
1041
- endedOk: ok,
1042
- endedFailed: ends.length - ok,
1043
- denied: count("DENIED-ANTHROPIC-AGENT"),
1044
- allowed: count("ALLOWED-ANTHROPIC-AGENT"),
1045
- reroutes: count("WORKER-REROUTE"),
1046
- lastLines: lines.slice(-lastN)
1047
- };
1048
- }
1049
-
1050
- //#endregion
1051
- //#region src/workers/pending.ts
1052
- /**
1053
- * Pending worker results: finished workers whose worktree branch still holds
1054
- * work that never reached the repo (commits not in HEAD, or uncommitted
1055
- * files). Surfaced by `pai worker ps/pending`, the SessionStart hook, the
1056
- * status line and the prepublish gate so an unmerged fix cannot be forgotten.
1057
- */
1058
- /** Stale after this long: `pai worker gc` (archive) instead of merge. */
1059
- const STALE_HOURS = 24;
1060
- function toplevel(dir) {
1061
- try {
1062
- return git(dir, ["rev-parse", "--show-toplevel"]);
1063
- } catch {
1064
- return null;
1065
- }
1066
- }
1067
- function fmtAge(ms) {
1068
- const h = Math.floor(ms / 36e5);
1069
- return h >= 48 ? `${Math.floor(h / 24)}d` : h >= 1 ? `${h}h` : `${Math.floor(ms / 6e4)}m`;
1070
- }
1071
- /** Finished workers with unmerged work; `repoRoot` limits to one repo, else every repo. */
1072
- function pendingResults(logDir, repoRoot, now = Date.now()) {
1073
- const want = repoRoot ? toplevel(repoRoot) : null;
1074
- if (repoRoot && !want) return [];
1075
- const out = [];
1076
- for (const st of loadStatuses(logDir)) {
1077
- if (st.archived || st.merged || isLive(st)) continue;
1078
- if (!st.worktreeDir || !existsSync(st.worktreeDir)) continue;
1079
- const repo = toplevel(st.cwd);
1080
- if (!repo || want && repo !== want) continue;
1081
- let commits = 0;
1082
- let dirty = 0;
1083
- try {
1084
- if (st.branch) commits = git(repo, [
1085
- "cherry",
1086
- "HEAD",
1087
- `refs/heads/${st.branch}`
1088
- ]).split("\n").filter((l) => l.startsWith("+")).length;
1089
- dirty = uncommittedPaths(st.worktreeDir).filter((p) => !/(^|\/)node_modules(\/|$)/.test(p)).length;
1090
- } catch {
1091
- continue;
1092
- }
1093
- if (!commits && !dirty) continue;
1094
- let ageMs = 0;
1095
- try {
1096
- ageMs = Math.max(0, now - statSync(statusPath(logDir, st.id)).mtimeMs);
1097
- } catch {}
1098
- out.push({
1099
- id: st.id,
1100
- label: st.label,
1101
- repo,
1102
- ageMs,
1103
- age: fmtAge(ageMs),
1104
- commits,
1105
- dirty
1106
- });
1107
- }
1108
- return out;
1109
- }
1110
- /** One human line per result, with the exact next command. */
1111
- function formatPending(results, showRepo = false) {
1112
- return results.map((r) => {
1113
- const next = r.ageMs > STALE_HOURS * 36e5 ? "pai worker gc" : `pai worker merge ${r.id}`;
1114
- const repo = showRepo ? ` ${r.repo}` : "";
1115
- return `${r.id} ${r.age} ${r.commits} commit(s), ${r.dirty} dirty ${r.label}${repo} -> ${next}`;
1116
- }).join("\n");
1117
- }
1118
- /**
1119
- * Release gate: exit code and message for `pai worker pending --gate`.
1120
- * PAI_ALLOW_PENDING=1 overrides.
1121
- */
1122
- function pendingGate(results, env = process.env) {
1123
- if (!results.length || env.PAI_ALLOW_PENDING === "1") return {
1124
- code: 0,
1125
- message: ""
1126
- };
1127
- return {
1128
- code: 1,
1129
- message: `${results.length} unmerged worker result(s) in this repo — merge or discard before publishing:\n${formatPending(results)}\nOverride deliberately with PAI_ALLOW_PENDING=1.`
1130
- };
1131
- }
1132
- /** Invalidate pending cache entries for a repo and its subdirectories. */
1133
- function invalidatePendingCache(logDir, repoRoot) {
1134
- const file = join(logDir, "pending-cache.json");
1135
- let cache = {};
1136
- try {
1137
- cache = JSON.parse(readFileSync(file, "utf8"));
1138
- } catch {
1139
- return;
1140
- }
1141
- const resolved = repoRoot.endsWith("/") ? repoRoot : `${repoRoot}/`;
1142
- let changed = false;
1143
- for (const key of Object.keys(cache)) if (key === repoRoot || key.startsWith(resolved)) {
1144
- delete cache[key];
1145
- changed = true;
1146
- }
1147
- if (!changed) return;
1148
- try {
1149
- writeFileSync(file, JSON.stringify(cache));
1150
- } catch {}
1151
- }
1152
-
1153
- //#endregion
1154
- //#region src/workers/worktree.ts
1155
- /**
1156
- * worktree.ts — one git worktree per writing worker.
1157
- *
1158
- * A run whose class edits files (implement, complex, plan) and whose cwd is a
1159
- * git repository gets its own worktree by default: `git worktree add
1160
- * <logDir>/worktrees/<id> -b worker/<id>` from the current HEAD. The worker
1161
- * commits its own work on that branch — the no-commit rule applies to the
1162
- * main branch only — and the parent (or the operator) merges the result back:
1163
- *
1164
- * pai worker merge <id> git merge --no-ff worker/<id> + remove worktree + delete branch
1165
- * pai worker discard <id> remove worktree and branch, keep nothing
1166
- *
1167
- * `ps` marks a worker with an unmerged branch `⎇`. Draft and review run in
1168
- * place; `--no-worktree` opts out, `--worktree` forces one on.
1169
- */
1170
- function worktreesDir(logDir) {
1171
- return join(logDir, "worktrees");
1172
- }
1173
- function worktreeBranch(id) {
1174
- return `worker/${id}`;
1175
- }
1176
- function worktreePath(logDir, id) {
1177
- return join(worktreesDir(logDir), id);
1178
- }
1179
- /** Run git in `cwd` with an optional env override, trimmed stdout, stderr on failure. */
1180
- function runGit(cwd, args, env, timeout = 3e4) {
1181
- try {
1182
- return execFileSync("git", [
1183
- "-C",
1184
- cwd,
1185
- ...args
1186
- ], {
1187
- encoding: "utf8",
1188
- timeout,
1189
- stdio: [
1190
- "ignore",
1191
- "pipe",
1192
- "pipe"
1193
- ],
1194
- ...env ? { env } : {}
1195
- }).trim();
1196
- } catch (e) {
1197
- const err = e;
1198
- const why = (typeof err.stderr === "string" ? err.stderr : err.stderr?.toString("utf8")) || err.message || String(e);
1199
- throw new Error(`git ${args.join(" ")} in ${cwd}: ${why.trim()}`);
1200
- }
1201
- }
1202
- /** Run git in `cwd`, returning trimmed stdout; throws with stderr on failure. */
1203
- function git(cwd, args, timeoutMs) {
1204
- return runGit(cwd, args, void 0, timeoutMs);
1205
- }
1206
- /** Is `cwd` inside a git repository (a .git dir — worktrees: a .git file)? */
1207
- function isGitRepo(cwd) {
1208
- try {
1209
- return git(cwd, ["rev-parse", "--git-dir"]) !== "";
1210
- } catch {
1211
- return false;
1212
- }
1213
- }
1214
- /** Tools that can write to the checkout (Bash can, via the shell). */
1215
- const WRITING_TOOLS = [
1216
- "Edit",
1217
- "Write",
1218
- "MultiEdit",
1219
- "NotebookEdit",
1220
- "Bash"
1221
- ];
1222
- /** Can a run with these --allowedTools write? No restriction at all means yes. */
1223
- function toolsCanWrite(allowedTools) {
1224
- const names = allowedTools.flatMap((e) => e.split(",")).map((s) => s.trim().replace(/\(.*$/, "")).filter(Boolean);
1225
- return !names.length || names.some((n) => WRITING_TOOLS.includes(n));
1226
- }
1227
- /** Should this run get a worktree? Explicit flag first, then: can it write? */
1228
- function worktreeWanted(flag, opts) {
1229
- if (flag !== void 0) return flag;
1230
- return toolsCanWrite(opts.allowedTools) && isGitRepo(opts.cwd);
1231
- }
1232
- /**
1233
- * Commit `cwd`'s current index + working tree (including untracked files) as
1234
- * a floating commit on top of HEAD, without touching the real index, working
1235
- * tree or HEAD: a temporary `GIT_INDEX_FILE` collects the snapshot, `git
1236
- * commit-tree` writes the commit object directly (it updates no ref). The
1237
- * caller then branches a worktree from that commit, so the worktree sees
1238
- * exactly what was on disk, uncommitted or not.
1239
- */
1240
- function snapshotUncommitted(cwd, id, head) {
1241
- const idxDir = mkdtempSync(join(tmpdir(), "pai-worktree-idx-"));
1242
- const idx = join(idxDir, "index");
1243
- try {
1244
- const env = {
1245
- ...process.env,
1246
- GIT_INDEX_FILE: idx
1247
- };
1248
- runGit(cwd, ["read-tree", head], env);
1249
- runGit(cwd, ["add", "-A"], env);
1250
- return runGit(cwd, [
1251
- "commit-tree",
1252
- runGit(cwd, ["write-tree"], env),
1253
- "-p",
1254
- head,
1255
- "-m",
1256
- `worker ${id}: snapshot of uncommitted checkout`
1257
- ]);
1258
- } finally {
1259
- rmSync(idxDir, {
1260
- recursive: true,
1261
- force: true
1262
- });
1263
- }
1264
- }
1265
- /**
1266
- * Create the worktree and branch for `id` from `cwd`'s HEAD — or, when the
1267
- * checkout has uncommitted changes, from a snapshot commit of that dirty
1268
- * state (see `snapshotUncommitted`), so a worktree worker sees the same
1269
- * files the operator sees, not just what was last committed. Throws when git
1270
- * refuses (no commits yet, branch exists, …) — the caller decides whether to
1271
- * degrade to an in-place run.
1272
- */
1273
- function addWorktree(logDir, id, cwd) {
1274
- const dir = worktreePath(logDir, id);
1275
- const branch = worktreeBranch(id);
1276
- const head = git(cwd, ["rev-parse", "HEAD"]);
1277
- const dirty = dirtyPaths(cwd).length > 0;
1278
- const base = dirty ? snapshotUncommitted(cwd, id, head) : head;
1279
- git(cwd, [
1280
- "worktree",
1281
- "add",
1282
- dir,
1283
- "-b",
1284
- branch,
1285
- base
1286
- ]);
1287
- provisionDeps(logDir, id, cwd, dir);
1288
- return {
1289
- dir,
1290
- branch,
1291
- base,
1292
- snapshot: dirty
1293
- };
1294
- }
1295
- /**
1296
- * Give the worktree its own dependencies so the worker never has to improvise
1297
- * (symlinking node_modules to the main checkout, building in a /tmp copy).
1298
- * A real node_modules directory in the main checkout is APFS-cloned
1299
- * (`cp -c`, copy-on-write, near instant); elsewhere the lockfile installs it.
1300
- * Never a symlink. Time-boxed and best effort: a failure is logged, the run
1301
- * goes on.
1302
- */
1303
- function provisionDeps(logDir, id, cwd, wtDir) {
1304
- const note = (n) => appendLedger(ledgerPath(logDir), "WORKER-NOTE", {
1305
- id,
1306
- note: n
1307
- });
1308
- try {
1309
- const main = join(git(cwd, ["rev-parse", "--show-toplevel"]), "node_modules");
1310
- const dest = join(wtDir, "node_modules");
1311
- if (!existsSync(main) || lstatSync(main).isSymbolicLink() || existsSync(dest)) return;
1312
- try {
1313
- git(wtDir, [
1314
- "check-ignore",
1315
- "-q",
1316
- "node_modules"
1317
- ]);
1318
- } catch {
1319
- return;
1320
- }
1321
- const t0 = Date.now();
1322
- const opts = {
1323
- cwd: wtDir,
1324
- stdio: "ignore",
1325
- timeout: 18e4
1326
- };
1327
- if (platform() === "darwin") try {
1328
- execFileSync("cp", [
1329
- "-cR",
1330
- main,
1331
- dest
1332
- ], opts);
1333
- note(`node_modules cloned (apfs) in ${Date.now() - t0}ms`);
1334
- return;
1335
- } catch {
1336
- rmSync(dest, {
1337
- recursive: true,
1338
- force: true
1339
- });
1340
- }
1341
- if (existsSync(join(wtDir, "bun.lock"))) execFileSync("bun", ["install", "--frozen-lockfile"], opts);
1342
- else if (existsSync(join(wtDir, "package-lock.json"))) execFileSync("npm", ["ci"], opts);
1343
- else return;
1344
- note(`node_modules installed from lockfile in ${Date.now() - t0}ms`);
1345
- } catch (e) {
1346
- try {
1347
- note(`node_modules provisioning failed: ${e.message}`);
1348
- } catch {}
1349
- }
1350
- }
1351
- /** Commits the branch collected on top of its base. */
1352
- function commitsSince(dir, base) {
1353
- try {
1354
- return parseInt(git(dir, [
1355
- "rev-list",
1356
- "--count",
1357
- `${base}..HEAD`
1358
- ]), 10) || 0;
1359
- } catch {
1360
- return 0;
1361
- }
1362
- }
1363
- /**
1364
- * Record the worktree result in the status file: branch and commit count on
1365
- * success, the worktree cleaned up on failure. Returns the updated status.
1366
- */
1367
- function recordWorktree(logDir, status, info, ok) {
1368
- const s = { ...status };
1369
- if (ok) {
1370
- s.branch = info.branch;
1371
- s.commits = commitsSince(info.dir, info.base);
1372
- s.worktreeDir = info.dir;
1373
- s.worktreeBase = info.base;
1374
- s.worktreeSnapshot = info.snapshot;
1375
- } else if (safeCommitsSince(info.dir, info.base) > 0) {
1376
- s.branch = info.branch;
1377
- s.commits = commitsSince(info.dir, info.base);
1378
- s.worktreeDir = info.dir;
1379
- s.worktreeBase = info.base;
1380
- s.worktreeSnapshot = info.snapshot;
1381
- } else {
1382
- removeWorktree(s.cwd, info.dir, true);
1383
- try {
1384
- git(s.cwd, [
1385
- "branch",
1386
- "-D",
1387
- info.branch
1388
- ]);
1389
- } catch {}
1390
- s.branch = null;
1391
- s.worktreeDir = null;
1392
- s.worktreeBase = null;
1393
- s.commits = null;
1394
- s.worktreeSnapshot = null;
1395
- }
1396
- saveStatus(logDir, s);
1397
- invalidatePendingCache(logDir, s.cwd);
1398
- return s;
1399
- }
1400
- function safeCommitsSince(dir, base) {
1401
- try {
1402
- return commitsSince(dir, base);
1403
- } catch {
1404
- return 0;
1405
- }
1406
- }
1407
- /**
1408
- * Salvage for an exit path (run finaliser, kill signal): commit whatever the
1409
- * worker left uncommitted, log WORKER-SALVAGE, never throw. Bounded by
1410
- * `timeoutMs` per git call. Returns the committed paths.
1411
- */
1412
- function salvageOnExit(ledger, id, label, wtDir, timeoutMs) {
1413
- try {
1414
- const { committed, skipped } = salvageUncommitted(wtDir, label, timeoutMs);
1415
- if (committed.length) appendLedger(ledger, "WORKER-SALVAGE", {
1416
- id,
1417
- paths: committed.join(","),
1418
- skipped: skipped.length
1419
- });
1420
- if (skipped.length) appendLedger(ledger, "WORKER-NOTE", {
1421
- id,
1422
- note: `salvage skipped: ${skipped.join("; ")}`
1423
- });
1424
- return committed;
1425
- } catch (e) {
1426
- try {
1427
- appendLedger(ledger, "WORKER-NOTE", {
1428
- id,
1429
- note: `salvage failed: ${e.message}`
1430
- });
1431
- } catch {}
1432
- return [];
1433
- }
1434
- }
1435
- /** Remove a worktree directory from git's books and the filesystem. */
1436
- function removeWorktree(cwd, dir, force) {
1437
- try {
1438
- git(cwd, [
1439
- "worktree",
1440
- "remove",
1441
- ...force ? ["--force"] : [],
1442
- dir
1443
- ]);
1444
- return;
1445
- } catch {}
1446
- if (existsSync(dir)) try {
1447
- rmSync(dir, {
1448
- recursive: true,
1449
- force: true
1450
- });
1451
- git(cwd, ["worktree", "prune"]);
1452
- } catch {}
1453
- }
1454
- /**
1455
- * Tracked changes (staged or not) plus untracked files — everything a
1456
- * `git add -A` in `wtDir` would commit. The same two calls the old patch
1457
- * carry used; name-only, not porcelain: a worktree-only change renders as
1458
- * " M path" and the shared git() helper trims that leading space away.
1459
- */
1460
- function uncommittedPaths(wtDir, timeoutMs) {
1461
- const tracked = git(wtDir, [
1462
- "diff",
1463
- "--name-only",
1464
- "HEAD"
1465
- ], timeoutMs).split("\n").filter(Boolean);
1466
- const untracked = git(wtDir, [
1467
- "ls-files",
1468
- "--others",
1469
- "--exclude-standard"
1470
- ], timeoutMs).split("\n").filter(Boolean);
1471
- return [...tracked, ...untracked];
1472
- }
1473
- /**
1474
- * True when `wtDir`/`relPath` is a symlink whose target resolves outside
1475
- * `wtDir` — e.g. a worker's `node_modules -> <main checkout>/node_modules`
1476
- * convenience link. A `.gitignore` using `dir/` (directories only) does not
1477
- * ignore such a link, so it turns up as untracked; staging and merging it
1478
- * lets git replace the real directory on the other side with a symlink to
1479
- * itself. Never a candidate for salvage.
1480
- */
1481
- function symlinkEscapesWorktree(wtDir, relPath) {
1482
- const full = join(wtDir, relPath);
1483
- let stat;
1484
- try {
1485
- stat = lstatSync(full);
1486
- } catch {
1487
- return false;
1488
- }
1489
- if (!stat.isSymbolicLink()) return false;
1490
- const target = readlinkSync(full);
1491
- const resolvedTarget = isAbsolute(target) ? target : resolve(dirname(full), target);
1492
- const realTarget = existsSync(resolvedTarget) ? realpathSync(resolvedTarget) : resolvedTarget;
1493
- const realWtDir = realpathSync(wtDir);
1494
- return realTarget !== realWtDir && !realTarget.startsWith(realWtDir + sep);
1495
- }
1496
- /**
1497
- * Commit a worktree's uncommitted changes to its branch so the merge carries
1498
- * them. `git merge` only moves committed work, so a worker that stopped
1499
- * without committing would lose its edits to `worktree remove` — exactly
1500
- * what happened live on 2026-09-17. Returns the salvaged paths, empty when
1501
- * the worktree is clean. A symlink pointing outside the worktree (see
1502
- * `symlinkEscapesWorktree`) is never staged; it is left on disk and reported
1503
- * as skipped instead. A failed commit throws with the worktree untouched:
1504
- * its edits are still on disk, so nothing is lost.
1505
- */
1506
- function salvageUncommitted(wtDir, label, timeoutMs) {
1507
- const paths = uncommittedPaths(wtDir, timeoutMs);
1508
- if (!paths.length) return {
1509
- committed: [],
1510
- skipped: []
1511
- };
1512
- const skipped = [];
1513
- const missing = new Set(git(wtDir, ["ls-files", "--deleted"], timeoutMs).split("\n").filter(Boolean));
1514
- const toStage = [];
1515
- for (const p of paths) if (missing.has(p)) skipped.push(`${p} (missing, not committed)`);
1516
- else if (symlinkEscapesWorktree(wtDir, p)) skipped.push(`symlink ${p} -> ${readlinkSync(join(wtDir, p))} (points outside the worktree)`);
1517
- else toStage.push(p);
1518
- if (!toStage.length) return {
1519
- committed: [],
1520
- skipped
1521
- };
1522
- try {
1523
- git(wtDir, [
1524
- "add",
1525
- "--ignore-removal",
1526
- "--",
1527
- ".",
1528
- ...paths.filter((p) => !toStage.includes(p)).map((p) => `:(exclude,literal)${p}`)
1529
- ], timeoutMs);
1530
- const deleted = git(wtDir, [
1531
- "diff",
1532
- "--cached",
1533
- "--diff-filter=D",
1534
- "--name-only"
1535
- ], timeoutMs).split("\n").filter(Boolean);
1536
- if (deleted.length > MAX_SALVAGE_DELETES) {
1537
- git(wtDir, ["reset", "-q"], timeoutMs);
1538
- throw new Error(`salvage would delete ${deleted.length} tracked files (${deleted.slice(0, 5).join(", ")}, ...), refused`);
1539
- }
1540
- git(wtDir, [
1541
- "commit",
1542
- "-m",
1543
- `salvaged: ${label}`
1544
- ], timeoutMs);
1545
- } catch (e) {
1546
- throw new Error(`cannot salvage the uncommitted changes in ${wtDir} — ${e.message}; nothing was lost: commit them there by hand, then re-run merge`);
1547
- }
1548
- return {
1549
- committed: toStage,
1550
- skipped
1551
- };
1552
- }
1553
- /** A salvage commit that deletes more tracked files than this is refused. */
1554
- const MAX_SALVAGE_DELETES = 5;
1555
- /**
1556
- * The dirty paths of a checkout, parsed from `git status --porcelain -z`:
1557
- * NUL-separated (a path with a newline in it cannot corrupt the parse),
1558
- * rename entries contribute both sides, and any quoting is stripped.
1559
- */
1560
- function dirtyPaths(cwd) {
1561
- const fields = execFileSync("git", [
1562
- "-C",
1563
- cwd,
1564
- "status",
1565
- "--porcelain",
1566
- "-z"
1567
- ], {
1568
- encoding: "utf8",
1569
- timeout: 3e4,
1570
- stdio: [
1571
- "ignore",
1572
- "pipe",
1573
- "pipe"
1574
- ]
1575
- }).split("\0");
1576
- const strip = (p) => p.startsWith("\"") && p.endsWith("\"") ? p.slice(1, -1) : p;
1577
- const out = [];
1578
- for (let i = 0; i < fields.length; i++) {
1579
- const f = fields[i];
1580
- if (!f || f.length < 4 || f.charAt(2) !== " ") continue;
1581
- out.push(strip(f.slice(3)));
1582
- const xy = f.slice(0, 2);
1583
- if (xy.includes("R") || xy.includes("C")) {
1584
- const orig = fields[i + 1];
1585
- if (orig && orig.charAt(2) !== " ") {
1586
- out.push(strip(orig));
1587
- i += 1;
1588
- }
1589
- }
1590
- }
1591
- return out;
1592
- }
1593
- /**
1594
- * Refuse the merge when the original checkout is dirty in paths the branch
1595
- * touches: the merge would overwrite those edits or fail on them, either way
1596
- * leaving a half-state. No merge is made, the worktree stays.
1597
- */
1598
- function assertNoDirtyOverlap(cwd, incoming, id, branch) {
1599
- const dirty = new Set(dirtyPaths(cwd));
1600
- const overlap = [...new Set(incoming)].filter((p) => dirty.has(p)).sort();
1601
- if (!overlap.length) return;
1602
- throw new Error(`worker ${id}: the checkout ${cwd} has uncommitted changes in paths ${branch} touches: ${overlap.join(", ")}. Commit or stash them in the checkout, then re-run: pai worker merge ${id}. No merge was made; the worktree was kept.`);
1603
- }
1604
- /**
1605
- * Never remove a worktree that still holds uncommitted changes — except a
1606
- * symlink escaping the worktree (see `symlinkEscapesWorktree`): it was
1607
- * deliberately left uncommitted by `salvageUncommitted`, and deleting the
1608
- * link itself touches nothing outside the worktree.
1609
- */
1610
- function assertWorktreeClean(wtDir, id) {
1611
- const leftover = uncommittedPaths(wtDir).filter((p) => !symlinkEscapesWorktree(wtDir, p));
1612
- if (leftover.length) throw new Error(`worker ${id}: the worktree ${wtDir} still holds uncommitted changes (${leftover.join(", ")}) — it was NOT removed; commit or copy them by hand, then re-run merge`);
1613
- }
1614
- /** Blob sha of `path` at `rev` in `cwd`, or null when it does not exist there. */
1615
- function blobAt(cwd, rev, path) {
1616
- try {
1617
- return git(cwd, [
1618
- "rev-parse",
1619
- "--verify",
1620
- "-q",
1621
- `${rev}:${path}`
1622
- ]);
1623
- } catch {
1624
- return null;
1625
- }
1626
- }
1627
- /** Blob sha of `path` as it sits on disk in `cwd`, or null when it is absent. */
1628
- function workingBlob(cwd, path) {
1629
- if (!existsSync(join(cwd, path))) return null;
1630
- try {
1631
- return git(cwd, [
1632
- "hash-object",
1633
- "--",
1634
- path
1635
- ]);
1636
- } catch {
1637
- return null;
1638
- }
1639
- }
1640
- /**
1641
- * Refuse a snapshot merge when the checkout differs from the snapshot the
1642
- * worker branched from, for any path the branch touched: the operator edited
1643
- * it, or it was created/deleted since — applying the branch's diff on top
1644
- * would silently discard that. Absent-in-both counts as equal.
1645
- */
1646
- function assertNoSnapshotDrift(cwd, snapshot, paths, id) {
1647
- const drifted = paths.filter((p) => blobAt(cwd, snapshot, p) !== workingBlob(cwd, p)).sort();
1648
- if (!drifted.length) return;
1649
- throw new Error(`worker ${id}: the checkout ${cwd} has changed since the worktree's snapshot in paths the branch touches: ${drifted.join(", ")}. Resolve by hand, then re-run: pai worker merge ${id}. No merge was made; the worktree was kept.`);
1650
- }
1651
- /**
1652
- * `pai worker merge <id>` for a snapshot-based worktree (see `addWorktree`):
1653
- * git's own merge only moves committed history, and the snapshot commit was
1654
- * never on any branch reachable from `cwd`'s HEAD, so there is nothing to
1655
- * `git merge` here. Instead the worker's own changes — `git diff --binary
1656
- * <snapshot> <branch>` — are applied straight onto the checkout's working
1657
- * tree as uncommitted edits, exactly like the uncommitted state the worker
1658
- * started from. Works even if `cwd`'s HEAD moved since the snapshot: the
1659
- * diff is applied to files, not merged into a tree.
1660
- */
1661
- function mergeSnapshotWorker(logDir, id, st, noCommit = false) {
1662
- const snapshot = st.worktreeBase;
1663
- const branch = st.branch;
1664
- const worktreeDir = st.worktreeDir;
1665
- const salvage = existsSync(worktreeDir) ? salvageUncommitted(worktreeDir, st.label || UNLABELED) : {
1666
- committed: [],
1667
- skipped: []
1668
- };
1669
- if ((parseInt(git(st.cwd, [
1670
- "rev-list",
1671
- "--count",
1672
- `${snapshot}..${branch}`
1673
- ]), 10) || 0) <= 0) throw new Error(`worker ${id}: branch ${branch} has no commits beyond its snapshot to merge. The worktree ${worktreeDir} was NOT removed — uncommitted work there would be destroyed. Commit it yourself, or drop everything with: pai worker discard ${id}`);
1674
- const changedPaths = git(st.cwd, [
1675
- "diff",
1676
- "--name-only",
1677
- snapshot,
1678
- branch
1679
- ]).split("\n").filter(Boolean);
1680
- assertNoSnapshotDrift(st.cwd, snapshot, changedPaths, id);
1681
- const diff = execFileSync("git", [
1682
- "-C",
1683
- st.cwd,
1684
- "diff",
1685
- "--binary",
1686
- snapshot,
1687
- branch
1688
- ], {
1689
- encoding: "utf8",
1690
- timeout: 3e4,
1691
- maxBuffer: 64 * 1024 * 1024
1692
- });
1693
- if (diff.trim()) try {
1694
- execFileSync("git", [
1695
- "-C",
1696
- st.cwd,
1697
- "apply",
1698
- "--binary"
1699
- ], {
1700
- input: diff,
1701
- encoding: "utf8",
1702
- timeout: 3e4,
1703
- stdio: [
1704
- "pipe",
1705
- "pipe",
1706
- "pipe"
1707
- ]
1708
- });
1709
- } catch (e) {
1710
- const err = e;
1711
- const why = (typeof err.stderr === "string" ? err.stderr : err.stderr?.toString("utf8")) || err.message || String(e);
1712
- throw new Error(`worker ${id}: git refused to apply ${branch}'s changes to ${st.cwd} — ${why.trim()}. The worktree ${worktreeDir} was kept: resolve by hand, then re-run merge`);
1713
- }
1714
- if (noCommit) return noCommitNextSteps(id, branch, worktreeDir, changedPaths);
1715
- removeWorktree(st.cwd, worktreeDir, true);
1716
- try {
1717
- git(st.cwd, [
1718
- "branch",
1719
- "-D",
1720
- branch
1721
- ]);
1722
- } catch {}
1723
- saveStatus(logDir, {
1724
- ...st,
1725
- merged: true
1726
- });
1727
- const base = `applied worker ${id}'s changes (branch ${branch}) to ${st.cwd} as uncommitted changes: ${changedPaths.join(", ")} (worktree removed, branch deleted)`;
1728
- const notes = [];
1729
- if (salvage.committed.length) notes.push(`salvaged ${salvage.committed.length} uncommitted change(s) onto the branch first: ${salvage.committed.join(", ")}`);
1730
- if (salvage.skipped.length) notes.push(`skipped ${salvage.skipped.join(", ")}`);
1731
- return notes.length ? `${base}; ${notes.join("; ")}` : base;
1732
- }
1733
- function noCommitNextSteps(id, branch, worktreeDir, paths) {
1734
- return `applied worker ${id}'s changes (branch ${branch}) to the checkout as uncommitted changes: ${paths.join(", ")}. Branch and worktree ${worktreeDir} were kept. Next: review (git diff), commit, then run: pai worker gc`;
1735
- }
1736
- /**
1737
- * `merge --no-commit`: apply base..branch to the checkout with a 3-way
1738
- * `git apply`, leaving the result uncommitted. On conflict the tree is left
1739
- * as is (markers + unmerged index entries) and the conflicted paths are listed.
1740
- */
1741
- function applyNoCommit(cwd, id, branch, worktreeDir, base, paths) {
1742
- const diff = execFileSync("git", [
1743
- "-C",
1744
- cwd,
1745
- "diff",
1746
- "--binary",
1747
- `${base}..${branch}`
1748
- ], {
1749
- encoding: "buffer",
1750
- timeout: 3e4,
1751
- maxBuffer: 64 * 1024 * 1024,
1752
- env: {
1753
- ...process.env,
1754
- LC_ALL: "C"
1755
- }
1756
- });
1757
- try {
1758
- execFileSync("git", [
1759
- "-C",
1760
- cwd,
1761
- "apply",
1762
- "--3way",
1763
- "--binary"
1764
- ], {
1765
- input: diff,
1766
- timeout: 3e4,
1767
- stdio: [
1768
- "pipe",
1769
- "pipe",
1770
- "pipe"
1771
- ],
1772
- env: {
1773
- ...process.env,
1774
- LC_ALL: "C"
1775
- }
1776
- });
1777
- } catch (e) {
1778
- const conflicted = git(cwd, [
1779
- "diff",
1780
- "--name-only",
1781
- "--diff-filter=U"
1782
- ]).split("\n").filter(Boolean);
1783
- const err = e;
1784
- const why = ((typeof err.stderr === "string" ? err.stderr : err.stderr?.toString("utf8")) || err.message || "").trim();
1785
- throw new Error(conflicted.length ? `worker ${id}: applying ${branch} conflicted in ${conflicted.join(", ")}. The tree was left for you: resolve those paths, review, commit; branch and worktree ${worktreeDir} were kept` : `worker ${id}: git refused to apply ${branch} to ${cwd} — ${why}. Nothing was changed; branch and worktree were kept`);
1786
- }
1787
- return noCommitNextSteps(id, branch, worktreeDir, paths);
1788
- }
1789
- /**
1790
- * `pai worker verify <id>`: for every file the worker's branch (or its
1791
- * refs/pai-archive/<id> archive once the branch is gone) changed since its
1792
- * base, compare bytes with the working tree or `--against <ref>`.
1793
- * identical = the target already holds the worker's version (a worker delete
1794
- * counts as identical when the target lacks the file too); differs = other
1795
- * bytes; missing = the worker's file is absent in the target; deleted = the
1796
- * worker deleted it but the target still has it. ok = every file identical.
1797
- */
1798
- function verifyWorker(logDir, id, opts = {}) {
1799
- const st = loadStatus(logDir, id);
1800
- if (!st) throw new Error(`no worker named "${id}"`);
1801
- const env = {
1802
- ...process.env,
1803
- LC_ALL: "C"
1804
- };
1805
- const bytes = (args) => {
1806
- try {
1807
- return execFileSync("git", [
1808
- "-C",
1809
- st.cwd,
1810
- ...args
1811
- ], {
1812
- env,
1813
- timeout: 3e4,
1814
- maxBuffer: 256 * 1024 * 1024,
1815
- stdio: [
1816
- "ignore",
1817
- "pipe",
1818
- "pipe"
1819
- ]
1820
- });
1821
- } catch {
1822
- return null;
1823
- }
1824
- };
1825
- const has = (ref) => bytes([
1826
- "rev-parse",
1827
- "--verify",
1828
- "-q",
1829
- `${ref}^{commit}`
1830
- ]) !== null;
1831
- const ref = [`refs/heads/${worktreeBranch(id)}`, `refs/pai-archive/${id}`].find(has);
1832
- if (!ref) throw new Error(`worker ${id}: neither ${worktreeBranch(id)} nor refs/pai-archive/${id} exists in ${st.cwd}`);
1833
- const base = st.worktreeSnapshot && st.worktreeBase ? st.worktreeBase : git(st.cwd, [
1834
- "merge-base",
1835
- "HEAD",
1836
- ref
1837
- ]);
1838
- const list = (bytes([
1839
- "diff",
1840
- "--name-status",
1841
- "--no-renames",
1842
- "-z",
1843
- `${base}..${ref}`
1844
- ]) ?? Buffer.alloc(0)).toString("utf8").split("\0").filter(Boolean);
1845
- const files = [];
1846
- for (let i = 0; i + 1 < list.length; i += 2) {
1847
- const path = list[i + 1];
1848
- const deleted = list[i] === "D";
1849
- const target = opts.against ? bytes(["show", `${opts.against}:${path}`]) : existsSync(join(st.cwd, path)) ? readFileSync(join(st.cwd, path)) : null;
1850
- let state;
1851
- if (deleted) state = target ? "deleted" : "identical";
1852
- else {
1853
- const mine = bytes(["show", `${ref}:${path}`]);
1854
- state = !target ? "missing" : mine && mine.equals(target) ? "identical" : "differs";
1855
- }
1856
- files.push({
1857
- path,
1858
- state
1859
- });
1860
- }
1861
- return {
1862
- id,
1863
- ref,
1864
- base,
1865
- against: opts.against ?? "working tree",
1866
- files,
1867
- ok: files.every((f) => f.state === "identical")
1868
- };
1869
- }
1870
- /**
1871
- * `pai worker merge <id>`: salvage whatever the worker left uncommitted onto
1872
- * its branch, refuse when the original checkout is dirty in paths the branch
1873
- * touches, merge with --no-ff (the merge commit names the worker), then
1874
- * remove the worktree and delete the branch; the status gains `merged: true`.
1875
- * A branch with nothing to merge is refused loudly — after salvage that
1876
- * genuinely means it holds nothing, and reporting success there would
1877
- * destroy the worktree for no gain.
1878
- */
1879
- function mergeWorker(logDir, id, opts = {}) {
1880
- const st = mustHaveBranch(logDir, id);
1881
- if (st.merged) return `worker ${id}: branch ${st.branch} already merged`;
1882
- if (st.worktreeSnapshot) return mergeSnapshotWorker(logDir, id, st, opts.noCommit);
1883
- const salvage = existsSync(st.worktreeDir) ? salvageUncommitted(st.worktreeDir, st.label || UNLABELED) : {
1884
- committed: [],
1885
- skipped: []
1886
- };
1887
- if ((parseInt(git(st.cwd, [
1888
- "rev-list",
1889
- "--count",
1890
- `HEAD..${st.branch}`
1891
- ]), 10) || 0) <= 0) throw new Error(`worker ${id}: branch ${st.branch} has no commits to merge. The worktree ${st.worktreeDir} was NOT removed — uncommitted work there would be destroyed. Commit it yourself, or drop everything with: pai worker discard ${id}`);
1892
- const mergeBase = git(st.cwd, [
1893
- "merge-base",
1894
- "HEAD",
1895
- st.branch
1896
- ]);
1897
- const incomingPaths = git(st.cwd, [
1898
- "diff",
1899
- "--name-only",
1900
- mergeBase,
1901
- st.branch
1902
- ]).split("\n").filter(Boolean);
1903
- assertNoDirtyOverlap(st.cwd, incomingPaths, id, st.branch);
1904
- if (opts.noCommit) return applyNoCommit(st.cwd, id, st.branch, st.worktreeDir, mergeBase, incomingPaths);
1905
- try {
1906
- git(st.cwd, [
1907
- "merge",
1908
- "--no-ff",
1909
- st.branch,
1910
- "-m",
1911
- `merge worker ${id} (${st.label})`
1912
- ]);
1913
- } catch (e) {
1914
- throw new Error(`worker ${id}: git refused the merge of ${st.branch} — ${e.message}. The worktree ${st.worktreeDir} was kept: resolve the conflict, then re-run merge`);
1915
- }
1916
- if (existsSync(st.worktreeDir)) assertWorktreeClean(st.worktreeDir, id);
1917
- removeWorktree(st.cwd, st.worktreeDir, true);
1918
- let branchGone = true;
1919
- try {
1920
- git(st.cwd, [
1921
- "branch",
1922
- "-d",
1923
- st.branch
1924
- ]);
1925
- } catch {
1926
- branchGone = false;
1927
- }
1928
- saveStatus(logDir, {
1929
- ...st,
1930
- merged: true
1931
- });
1932
- invalidatePendingCache(logDir, st.cwd);
1933
- const base = `merged ${st.branch} into ${st.cwd} (worktree removed${branchGone ? ", branch deleted" : "; branch kept: git refused -d"})`;
1934
- const notes = [];
1935
- if (salvage.committed.length) notes.push(`salvaged ${salvage.committed.length} uncommitted change(s): ${salvage.committed.join(", ")}`);
1936
- if (salvage.skipped.length) notes.push(`skipped ${salvage.skipped.join(", ")}`);
1937
- return notes.length ? `${base}; ${notes.join("; ")}` : base;
1938
- }
1939
- /** `pai worker discard <id>`: drop worktree and branch, keep nothing. */
1940
- function discardWorker(logDir, id) {
1941
- const st = mustHaveBranch(logDir, id);
1942
- removeWorktree(st.cwd, st.worktreeDir, true);
1943
- let branchGone = false;
1944
- try {
1945
- git(st.cwd, [
1946
- "branch",
1947
- "-D",
1948
- st.branch
1949
- ]);
1950
- branchGone = true;
1951
- } catch {
1952
- branchGone = false;
1953
- }
1954
- saveStatus(logDir, {
1955
- ...st,
1956
- branch: null,
1957
- worktreeDir: null,
1958
- worktreeBase: null,
1959
- worktreeSnapshot: null,
1960
- commits: null,
1961
- merged: false
1962
- });
1963
- invalidatePendingCache(logDir, st.cwd);
1964
- return `discarded worker ${id}: worktree removed${branchGone ? `, branch ${st.branch} deleted` : ""}`;
1965
- }
1966
- function mustHaveBranch(logDir, id) {
1967
- const st = loadStatus(logDir, id);
1968
- if (!st) throw new Error(`no worker named "${id}"`);
1969
- if (!st.branch || !st.worktreeDir) throw new Error(`worker ${id} has no worktree branch to ${st.branch ? "clean up" : "merge"} — it ran in place or its branch was already handled`);
1970
- return st;
1971
- }
1972
- /**
1973
- * The paragraph a worktree run's system prompt gains: it may commit on its
1974
- * own branch (the no-commit rule holds for the main branch only), it must not
1975
- * merge or push itself, and the parent or operator merges.
1976
- */
1977
- function worktreeSystemPrompt(id, branch, dir, snapshot = false) {
1978
- return [
1979
- "You are running in your own git worktree:",
1980
- ` ${dir} on branch ${branch} (worker id ${id}).`,
1981
- "Commit your work on that branch as you go (git add / git commit) — committing here is expected;",
1982
- "the no-commit rule applies to the main branch only, and this is not it.",
1983
- "Do not merge, rebase or push; the operator merges your branch back with `pai worker merge`.",
1984
- "Use ONLY relative paths inside the worktree, never absolute worktree paths — absolute paths break after merge and leak machine layout.",
1985
- ...snapshot ? ["This worktree was branched from a snapshot that includes files the parent checkout had uncommitted at spawn time — not just its last commit."] : []
1986
- ].join("\n");
1987
- }
1988
- /**
1989
- * For headless runs WITHOUT a worktree: the worker shares the operator's
1990
- * checkout with other in-flight workers, so a hook blocks git stash (except
1991
- * list/show), reset, clean, checkout/restore of paths, switch, rebase and
1992
- * merge — take baselines from measurements before editing, not from stash.
1993
- */
1994
- function inPlaceSystemPrompt() {
1995
- return [
1996
- "You are running in the operator's shared git checkout, alongside other workers editing it at the same time.",
1997
- "A hook blocks git stash (except list/show), reset, clean, checkout/restore of files, switch, rebase and merge — take baselines from measurements taken before you edit, not from stashing.",
1998
- "Read-only git (status, diff, log, show, stash list) is fine."
1999
- ].join("\n");
2000
- }
2001
- const GC_STAMP = "gc-last";
2002
- /**
2003
- * Archive worktrees of finished workers older than `olderThanHours` and
2004
- * status-less orphan directories: uncommitted state is salvaged onto the
2005
- * branch, the branch is x, the worktree is
2006
- * removed. Nothing is deleted without a salvage first; a failed salvage skips
2007
- * that worktree. Running workers are never touched. `dryRun` reports only.
2008
- */
2009
- function gcWorktrees(logDir, olderThanHours = 24, dryRun = false, now = Date.now()) {
2010
- const cutoff = now - olderThanHours * 36e5;
2011
- const out = [];
2012
- const root = worktreesDir(logDir);
2013
- const known = /* @__PURE__ */ new Set();
2014
- const archive = (id, dir, st) => {
2015
- const target = `refs/pai-archive/${id}`;
2016
- if (dryRun) return void out.push({
2017
- id,
2018
- archive: target
2019
- });
2020
- try {
2021
- let repo;
2022
- try {
2023
- const raw = git(dir, ["rev-parse", "--git-common-dir"]);
2024
- repo = isAbsolute(raw) ? raw : resolve(dir, raw);
2025
- } catch {
2026
- throw new Error("not a git worktree");
2027
- }
2028
- const label = `archive: leftover state of worker ${id}`;
2029
- if (uncommittedPaths(dir).length) {
2030
- const res = salvageUncommitted(dir, label);
2031
- if (res.committed.length) git(dir, [
2032
- "commit",
2033
- "--amend",
2034
- "-q",
2035
- "-m",
2036
- label
2037
- ]);
2038
- if (res.skipped.length && uncommittedPaths(dir).some((p) => !symlinkEscapesWorktree(dir, p))) throw new Error("uncommitted paths remain");
2039
- }
2040
- const src = worktreeBranch(id);
2041
- let hasBranch = true;
2042
- try {
2043
- git(repo, [
2044
- "rev-parse",
2045
- "--verify",
2046
- "-q",
2047
- `refs/heads/${src}`
2048
- ]);
2049
- } catch {
2050
- hasBranch = false;
2051
- }
2052
- const tip = git(dir, ["rev-parse", "HEAD"]);
2053
- if (hasBranch) git(repo, [
2054
- "merge-base",
2055
- "--is-ancestor",
2056
- `refs/heads/${src}`,
2057
- tip
2058
- ]);
2059
- git(repo, [
2060
- "update-ref",
2061
- target,
2062
- tip
2063
- ]);
2064
- git(repo, [
2065
- "worktree",
2066
- "remove",
2067
- "--force",
2068
- dir
2069
- ]);
2070
- if (hasBranch) git(repo, [
2071
- "branch",
2072
- "-D",
2073
- src
2074
- ]);
2075
- if (st) saveStatus(logDir, {
2076
- ...st,
2077
- branch: null,
2078
- worktreeDir: null,
2079
- archived: target
2080
- });
2081
- appendLedger(ledgerPath(logDir), "WORKER-GC", {
2082
- id,
2083
- archive: target
2084
- });
2085
- out.push({
2086
- id,
2087
- archive: target
2088
- });
2089
- } catch (e) {
2090
- out.push({
2091
- id,
2092
- skipped: e.message.split("\n")[0]
2093
- });
2094
- }
2095
- };
2096
- for (const st of loadStatuses(logDir)) {
2097
- known.add(st.id);
2098
- if (!st.worktreeDir || !existsSync(st.worktreeDir) || isLive(st)) continue;
2099
- let end = 0;
2100
- try {
2101
- end = statSync(statusPath(logDir, st.id)).mtimeMs;
2102
- } catch {
2103
- continue;
2104
- }
2105
- if (end > cutoff) continue;
2106
- archive(st.id, st.worktreeDir, st);
2107
- }
2108
- if (existsSync(root)) for (const ent of readdirSync(root, { withFileTypes: true })) {
2109
- if (!ent.isDirectory() || known.has(ent.name) || existsSync(statusPath(logDir, ent.name))) continue;
2110
- const dir = join(root, ent.name);
2111
- try {
2112
- if (statSync(dir).mtimeMs > cutoff) continue;
2113
- } catch {
2114
- continue;
2115
- }
2116
- archive(ent.name, dir, null);
2117
- }
2118
- if (!dryRun) for (const repo of new Set(loadStatuses(logDir).map((s) => s.cwd))) {
2119
- try {
2120
- git(repo, ["worktree", "prune"]);
2121
- } catch {}
2122
- invalidatePendingCache(logDir, repo);
2123
- }
2124
- return out;
2125
- }
2126
- /** Run `gcWorktrees` at most once per `everyMin` minutes (stamp file in the logDir). */
2127
- function gcWorktreesThrottled(logDir, everyMin = 60, now = Date.now()) {
2128
- const stamp = join(logDir, GC_STAMP);
2129
- try {
2130
- if (now - statSync(stamp).mtimeMs < everyMin * 6e4) return null;
2131
- } catch {}
2132
- mkdirSync(logDir, { recursive: true });
2133
- writeFileSync(stamp, String(now), "utf8");
2134
- return gcWorktrees(logDir, 24, false, now);
2135
- }
2136
-
2137
569
  //#endregion
2138
570
  //#region src/workers/scope.ts
2139
571
  /**
@@ -2578,183 +1010,100 @@ const PROFILE_NAME = "pai-worker";
2578
1010
  function dynamicProfilePath() {
2579
1011
  return process.env.PAI_WORKER_PROFILE ?? join(homedir(), "Library", "Application Support", "iTerm2", "DynamicProfiles", "pai-worker.json");
2580
1012
  }
2581
- const WORKER_SPLIT_SCRIPT = `on run(argv)
2582
- set targetID to item 1 of argv
2583
- set candList to item 2 of argv
2584
- set followCmd to item 3 of argv
2585
- set profileName to item 4 of argv
2586
- tell application id "com.googlecode.iterm2"
2587
- if not running then return "notrunning"
2588
- repeat with w in windows
2589
- repeat with t in tabs of w
2590
- repeat with s in sessions of t
2591
- if id of s is targetID then
2592
- -- sizing the new session would grow the whole window:
2593
- -- pin the window's bounds now and restore them after
2594
- -- the split, so the panes share the existing space.
2595
- -- copy, never set: set stores the property
2596
- -- reference lazily, so restoring it would re-read the
2597
- -- post-split bounds instead of these — observed as the
2598
- -- window jumping to the main display
2599
- copy bounds of w to winBounds
2600
- set sessIDs to {}
2601
- repeat with other in sessions of t
2602
- set end of sessIDs to (id of other as text)
2603
- end repeat
2604
- set lived to {}
2605
- set splitS to missing value
2606
- repeat with cid in my splitIds(candList)
2607
- set cidText to (cid as text)
2608
- if sessIDs contains cidText then
2609
- set end of lived to cidText
2610
- if splitS is missing value then
2611
- set splitS to first session of t whose id is cidText
2612
- end if
2613
- end if
2614
- end repeat
2615
- -- the follow command is part of the split itself: the
2616
- -- pane is born already running it, so no text is ever
2617
- -- typed into any session — a typing step raced the
2618
- -- operator's keystrokes and could even land in the
2619
- -- operator's own session
2620
- if profileName is "" then
2621
- if splitS is missing value then
2622
- tell s
2623
- set newS to split vertically with default profile command followCmd
2624
- end tell
2625
- else
2626
- tell splitS
2627
- set newS to split horizontally with default profile command followCmd
2628
- end tell
2629
- end if
2630
- else
2631
- if splitS is missing value then
2632
- tell s
2633
- set newS to split vertically with profile profileName command followCmd
2634
- end tell
2635
- else
2636
- tell splitS
2637
- set newS to split horizontally with profile profileName command followCmd
2638
- end tell
2639
- end if
2640
- end if
2641
- -- a split makes the new session the tab's active one:
2642
- -- re-select the launching session so focus returns to
2643
- -- where the operator was typing, never the new pane
2644
- try
2645
- select s
2646
- end try
2647
- try
2648
- set bounds of w to winBounds
2649
- end try
2650
- set out to ""
2651
- repeat with lid in lived
2652
- set out to out & lid & ","
2653
- end repeat
2654
- return out & "|" & (id of newS as text)
2655
- end if
2656
- end repeat
2657
- end repeat
2658
- end repeat
2659
- end tell
2660
- return "notfound"
2661
- end run
2662
-
2663
- on splitIds(s)
2664
- set out to {}
2665
- if s is "" then return out
2666
- set prevDels to AppleScript's text item delimiters
2667
- set AppleScript's text item delimiters to ","
2668
- repeat with part in text items of s
2669
- set end of out to (part as text)
2670
- end repeat
2671
- set AppleScript's text item delimiters to prevDels
2672
- return out
2673
- end splitIds`;
2674
- const TAB_TTYS_SCRIPT = `on run(argv)
2675
- set targetID to item 1 of argv
2676
- tell application id "com.googlecode.iterm2"
2677
- if not running then return "notrunning"
2678
- repeat with w in windows
2679
- repeat with t in tabs of w
2680
- repeat with s in sessions of t
2681
- if id of s is targetID then
2682
- set ttys to {}
2683
- repeat with other in sessions of t
2684
- copy (tty of other) to end of ttys
2685
- end repeat
2686
- return ttys
2687
- end if
2688
- end repeat
2689
- end repeat
2690
- end repeat
2691
- end tell
2692
- return "notfound"
2693
- end run`;
2694
- const WINDOW_BOUNDS_SCRIPT = `on run(argv)
2695
- set targetID to item 1 of argv
2696
- tell application id "com.googlecode.iterm2"
2697
- if not running then return "notrunning"
2698
- repeat with w in windows
2699
- repeat with t in tabs of w
2700
- repeat with s in sessions of t
2701
- if id of s is targetID then
2702
- copy bounds of w to winBounds
2703
- set prevDels to AppleScript's text item delimiters
2704
- set AppleScript's text item delimiters to ", "
2705
- set out to winBounds as text
2706
- set AppleScript's text item delimiters to prevDels
2707
- return out
2708
- end if
2709
- end repeat
2710
- end repeat
2711
- end repeat
2712
- end tell
2713
- return "notfound"
2714
- end run`;
2715
- const SPLIT_SCRIPT = `on run(argv)
2716
- set targetID to item 1 of argv
2717
- set followCmd to item 2 of argv
2718
- tell application id "com.googlecode.iterm2"
2719
- if not running then return "notrunning"
2720
- repeat with w in windows
2721
- repeat with t in tabs of w
2722
- repeat with s in sessions of t
2723
- if id of s is targetID then
2724
- -- the follow command is part of the split itself (see
2725
- -- WORKER_SPLIT_SCRIPT): nothing is ever typed into a
2726
- -- session afterwards
2727
- tell s
2728
- set newS to split vertically with default profile command followCmd
2729
- end tell
2730
- -- keep the tab's active session where it was (see
2731
- -- WORKER_SPLIT_SCRIPT)
2732
- try
2733
- select s
2734
- end try
2735
- return "opened"
2736
- end if
2737
- end repeat
2738
- end repeat
2739
- end repeat
2740
- end tell
2741
- return "notfound"
2742
- end run`;
2743
- /**
2744
- * True for the transient "every window doesn't understand the count message"
2745
- * (-1708) failure iTerm throws while enumerating windows during a race with
2746
- * window/session churn — seen to succeed on immediate retry. No other error
2747
- * matches: a retry here only re-runs the enumeration, before any split, so it
2748
- * cannot double-create a pane.
2749
- */
2750
- function isRetryableIterm2Error(stderr) {
2751
- return stderr.includes("every window doesn") && stderr.includes("(-1708)");
2752
- }
2753
- const OSASCRIPT_MAX_ATTEMPTS = 6;
2754
- const OSASCRIPT_RETRY_DELAY_MS = 500;
2755
- function runOsascriptOnce(script, args) {
1013
+ const FIND_SESSION = `function findSession(app, id) {
1014
+ var ws = app.windows();
1015
+ for (var i = 0; i < ws.length; i++) {
1016
+ var ts = ws[i].tabs();
1017
+ for (var j = 0; j < ts.length; j++) {
1018
+ var ss = ts[j].sessions();
1019
+ for (var k = 0; k < ss.length; k++) {
1020
+ if (ss[k].id() === id) return { w: ws[i], t: ts[j], s: ss[k], all: ss };
1021
+ }
1022
+ }
1023
+ }
1024
+ return null;
1025
+ }`;
1026
+ const WORKER_SPLIT_SCRIPT = `${FIND_SESSION}
1027
+ function run(argv) {
1028
+ var targetID = argv[0], candList = argv[1], followCmd = argv[2], profileName = argv[3];
1029
+ var app = Application("iTerm2");
1030
+ if (!app.running()) return "notrunning";
1031
+ var f = findSession(app, targetID);
1032
+ if (!f) return "notfound";
1033
+ // sizing the new session would grow the whole window: pin the window's
1034
+ // bounds now and restore them after the split, so the panes share the
1035
+ // existing space
1036
+ var winBounds = f.w.bounds();
1037
+ var sessIDs = f.all.map(function (o) { return o.id(); });
1038
+ var lived = [];
1039
+ var splitS = null;
1040
+ (candList === "" ? [] : candList.split(",")).forEach(function (cid) {
1041
+ var at = sessIDs.indexOf(cid);
1042
+ if (at < 0) return;
1043
+ lived.push(cid);
1044
+ if (!splitS) splitS = f.all[at];
1045
+ });
1046
+ // the follow command is part of the split itself: the pane is born already
1047
+ // running it, so no text is ever typed into any session — a typing step
1048
+ // raced the operator's keystrokes and could even land in the operator's
1049
+ // own session
1050
+ var newS;
1051
+ if (!splitS) {
1052
+ newS = profileName === ""
1053
+ ? f.s.splitVerticallyWithDefaultProfile({ command: followCmd })
1054
+ : f.s.splitVertically({ withProfile: profileName, command: followCmd });
1055
+ } else {
1056
+ newS = profileName === ""
1057
+ ? splitS.splitHorizontallyWithDefaultProfile({ command: followCmd })
1058
+ : splitS.splitHorizontally({ withProfile: profileName, command: followCmd });
1059
+ }
1060
+ // a split makes the new session the tab's active one: re-select the
1061
+ // launching session so focus returns to where the operator was typing,
1062
+ // never the new pane
1063
+ try { f.s.select(); } catch (e) {}
1064
+ try { f.w.bounds = winBounds; } catch (e) {}
1065
+ return lived.map(function (l) { return l + ","; }).join("") + "|" + newS.id();
1066
+ }`;
1067
+ const TAB_TTYS_SCRIPT = `${FIND_SESSION}
1068
+ function run(argv) {
1069
+ var app = Application("iTerm2");
1070
+ if (!app.running()) return "notrunning";
1071
+ var f = findSession(app, argv[0]);
1072
+ if (!f) return "notfound";
1073
+ return f.all.map(function (o) { return o.tty(); }).join(",");
1074
+ }`;
1075
+ const WINDOW_BOUNDS_SCRIPT = `${FIND_SESSION}
1076
+ function run(argv) {
1077
+ var app = Application("iTerm2");
1078
+ if (!app.running()) return "notrunning";
1079
+ var f = findSession(app, argv[0]);
1080
+ if (!f) return "notfound";
1081
+ var b = f.w.bounds();
1082
+ return [b.x, b.y, b.x + b.width, b.y + b.height].join(", ");
1083
+ }`;
1084
+ const SPLIT_SCRIPT = `${FIND_SESSION}
1085
+ function run(argv) {
1086
+ var followCmd = argv[1];
1087
+ var app = Application("iTerm2");
1088
+ if (!app.running()) return "notrunning";
1089
+ var f = findSession(app, argv[0]);
1090
+ if (!f) return "notfound";
1091
+ // the follow command is part of the split itself (see WORKER_SPLIT_SCRIPT):
1092
+ // nothing is ever typed into a session afterwards
1093
+ f.s.splitVerticallyWithDefaultProfile({ command: followCmd });
1094
+ // keep the tab's active session where it was (see WORKER_SPLIT_SCRIPT)
1095
+ try { f.s.select(); } catch (e) {}
1096
+ return "opened";
1097
+ }`;
1098
+ /** Run a JXA script with argv. Rejects when osascript itself cannot run. */
1099
+ function osascript(script, args) {
2756
1100
  return new Promise((resolve, reject) => {
2757
- const proc = spawn("osascript", ["-", ...args], { stdio: [
1101
+ const proc = spawn("osascript", [
1102
+ "-l",
1103
+ "JavaScript",
1104
+ "-",
1105
+ ...args
1106
+ ], { stdio: [
2758
1107
  "pipe",
2759
1108
  "pipe",
2760
1109
  "pipe"
@@ -2772,15 +1121,6 @@ function runOsascriptOnce(script, args) {
2772
1121
  proc.stdin.end();
2773
1122
  });
2774
1123
  }
2775
- /** Run an AppleScript with argv. Rejects when osascript itself cannot run. */
2776
- async function osascript(script, args) {
2777
- let result = await runOsascriptOnce(script, args);
2778
- for (let attempt = 1; attempt < OSASCRIPT_MAX_ATTEMPTS && isRetryableIterm2Error(result.stderr); attempt++) {
2779
- await new Promise((r) => setTimeout(r, OSASCRIPT_RETRY_DELAY_MS));
2780
- result = await runOsascriptOnce(script, args);
2781
- }
2782
- return result;
2783
- }
2784
1124
  function psOutput(format) {
2785
1125
  try {
2786
1126
  return execFileSync("ps", ["-axo", format], { encoding: "utf8" });
@@ -3024,37 +1364,28 @@ function dropEntry(logDir, e) {
3024
1364
  writeFileSync(legacy, JSON.stringify(rest.map(({ scope: _s, ...x }) => x), null, 1), "utf8");
3025
1365
  }
3026
1366
  }
3027
- const LIST_SESSIONS_SCRIPT = `on run(argv)
3028
- set out to ""
3029
- tell application id "com.googlecode.iterm2"
3030
- if not running then return ""
3031
- repeat with w in windows
3032
- repeat with t in tabs of w
3033
- repeat with s in sessions of t
3034
- set out to out & (id of s as text) & (ASCII character 9) & (tty of s as text) & (ASCII character 9) & (name of s as text) & linefeed
3035
- end repeat
3036
- end repeat
3037
- end repeat
3038
- end tell
3039
- return out
3040
- end run`;
3041
- const END_SESSION_SCRIPT = `on run(argv)
3042
- set targetID to item 1 of argv
3043
- tell application id "com.googlecode.iterm2"
3044
- if not running then return "notrunning"
3045
- repeat with w in windows
3046
- repeat with t in tabs of w
3047
- repeat with s in sessions of t
3048
- if id of s is targetID then
3049
- close s
3050
- return "closed"
3051
- end if
3052
- end repeat
3053
- end repeat
3054
- end repeat
3055
- end tell
3056
- return "notfound"
3057
- end run`;
1367
+ const LIST_SESSIONS_SCRIPT = `function run(argv) {
1368
+ var app = Application("iTerm2");
1369
+ if (!app.running()) return "";
1370
+ var out = "";
1371
+ app.windows().forEach(function (w) {
1372
+ w.tabs().forEach(function (t) {
1373
+ t.sessions().forEach(function (s) {
1374
+ out += s.id() + "\t" + s.tty() + "\t" + s.name() + "\n";
1375
+ });
1376
+ });
1377
+ });
1378
+ return out;
1379
+ }`;
1380
+ const END_SESSION_SCRIPT = `${FIND_SESSION}
1381
+ function run(argv) {
1382
+ var app = Application("iTerm2");
1383
+ if (!app.running()) return "notrunning";
1384
+ var f = findSession(app, argv[0]);
1385
+ if (!f) return "notfound";
1386
+ f.s.close();
1387
+ return "closed";
1388
+ }`;
3058
1389
  const realPaneOps = {
3059
1390
  async listIterm() {
3060
1391
  if (process.platform !== "darwin") return [];
@@ -4679,7 +3010,7 @@ async function runWorker(opts) {
4679
3010
  if (gc?.length) process.stderr.write(`pai worker: archived ${gc.length} leftover worktree(s) (pai worker gc)\n`);
4680
3011
  } catch {}
4681
3012
  if (opts.className === "plan" && !opts._planner) {
4682
- const { runPlanner } = await import("./planner-DBoB5GtC.mjs");
3013
+ const { runPlanner } = await import("./planner-CspP59ya.mjs");
4683
3014
  return runPlanner(opts);
4684
3015
  }
4685
3016
  const parent = launchParent(opts.parent);
@@ -5938,5 +4269,5 @@ function resultFromOutput(out) {
5938
4269
  }
5939
4270
 
5940
4271
  //#endregion
5941
- export { saveStatus as $, gcWorktrees as A, UNLABELED as B, itermForClaudeSession as C, sessionTag as D, sessionMapPath as E, formatPending as F, elapsedOf as G, alive as H, pendingGate as I, loadStatus as J, isChatPane as K, pendingResults as L, mergeWorker as M, verifyWorker as N, workerInScope as O, worktreesDir as P, ownsPid as Q, appendLedger as R, currentTabKey as S, resolveSession as T, contextLabel as U, ageOf as V, contextPercent as W, newWorkerId as X, loadStatuses as Y, nowStamp as Z, clickrControlsArgv as _, projectLaunchConfig as _t, deadlineLabel as a, DEFAULT_PROXY_PORT as at, endLabel as b, waitOn as c, clearCooldown as ct, sayToWorker as d, resolveTarget as dt, setWorkerLabel as et, workerDepth as f, ensureNoMcpConfig as ft, openPaneForWorker as g, pinNotices as gt, openFollowPane as h, workersLogDir as ht, usageContextTokens as i, shortText as it, git as j, discardWorker as k, handoffFromInside as l, probeQuota as lt, closeEndedPanes as m, ledgerPath as mt, runWorker as n, longInlinePromptHint as nt, parseWorkerReport as o, ensureProxyRunning as ot, checkPaneForWorker as p, eventsPath as pt, isLive as q, testProvider as r, parseRunnerArgs as rt, renderReport as s, stopProxy as st, printResult as t, waitForTerminalStatus as tt, readInbox as u, quotaSkipThreshold as ut, markControlsHeld as v, describeMcp as vt, itermUuid as w, requestKill as x, callerDescription as y, expandMcpNames as yt, ledgerSummary as z };
5942
- //# sourceMappingURL=run-DPwQkRwh.mjs.map
4272
+ export { ensureProxyRunning as A, itermForClaudeSession as C, sessionTag as D, sessionMapPath as E, resolveTarget as F, pinNotices as I, projectLaunchConfig as L, clearCooldown as M, probeQuota as N, workerInScope as O, quotaSkipThreshold as P, describeMcp as R, currentTabKey as S, resolveSession as T, clickrControlsArgv as _, deadlineLabel as a, endLabel as b, waitOn as c, sayToWorker as d, workerDepth as f, openPaneForWorker as g, openFollowPane as h, usageContextTokens as i, stopProxy as j, DEFAULT_PROXY_PORT as k, handoffFromInside as l, closeEndedPanes as m, runWorker as n, parseWorkerReport as o, checkPaneForWorker as p, testProvider as r, renderReport as s, printResult as t, readInbox as u, markControlsHeld as v, itermUuid as w, requestKill as x, callerDescription as y, expandMcpNames as z };
4273
+ //# sourceMappingURL=run-BZNdpUGQ.mjs.map