frizz-server 0.15.41 → 0.15.43

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 (100) hide show
  1. package/dist/dev-child.js +1417 -477
  2. package/package.json +1 -1
  3. package/runtime/cc-worker/bin/frizzctl.mjs +1 -1
  4. package/runtime/cc-worker/lib/frizz-tools.mjs +307 -7
  5. package/web-dist/assets/{abnfDiagram-VRR7QNED-DZgIn5ff.js → abnfDiagram-VRR7QNED-DZb1taeh.js} +1 -1
  6. package/web-dist/assets/{arc-DwPpA8R3.js → arc-hn35k2HI.js} +1 -1
  7. package/web-dist/assets/architecture-TIHT7OUA-BHGj5CkN.js +1 -0
  8. package/web-dist/assets/{architectureDiagram-ZJ3FMSHR-DbP9lkjM.js → architectureDiagram-ZJ3FMSHR-6QyzD8O3.js} +1 -1
  9. package/web-dist/assets/{blockDiagram-677ZJIJ3-DwQN1M8B.js → blockDiagram-677ZJIJ3-DV1zPeBU.js} +1 -1
  10. package/web-dist/assets/{c4Diagram-LMCZKHZV-BF5QrD37.js → c4Diagram-LMCZKHZV-DovAqz12.js} +1 -1
  11. package/web-dist/assets/channel-DXI8lxvm.js +1 -0
  12. package/web-dist/assets/{chunk-32BRIVSS-CA8c9JxF.js → chunk-32BRIVSS-DvtR4j-C.js} +1 -1
  13. package/web-dist/assets/{chunk-52WLFC77-CdYcy5t0.js → chunk-52WLFC77-DniKgsIc.js} +1 -1
  14. package/web-dist/assets/{chunk-C7G6YPKG-4uxANQmd.js → chunk-C7G6YPKG-BLfDXTkp.js} +1 -1
  15. package/web-dist/assets/{chunk-EX3LRPZG-4wMgoywY.js → chunk-EX3LRPZG-B6AnFQUN.js} +1 -1
  16. package/web-dist/assets/{chunk-FWX5IMBZ-BH3kLM9J.js → chunk-FWX5IMBZ-CucljzDo.js} +2 -2
  17. package/web-dist/assets/{chunk-HOUHSVGY-C6s3cxko.js → chunk-HOUHSVGY-Eii_EemL.js} +1 -1
  18. package/web-dist/assets/{chunk-ICXQ74PX-9fUt4TuP.js → chunk-ICXQ74PX-COVzp5Xd.js} +1 -1
  19. package/web-dist/assets/{chunk-MOJQB5TN-CXZbnRJB.js → chunk-MOJQB5TN-juE3sXKe.js} +1 -1
  20. package/web-dist/assets/{chunk-OGEWGWER-kBUaZg1h.js → chunk-OGEWGWER-Ctnj7hjO.js} +1 -1
  21. package/web-dist/assets/{chunk-PUDLZKDR-T8I9vJeW.js → chunk-PUDLZKDR-DieALR_4.js} +1 -1
  22. package/web-dist/assets/{chunk-Q4XR5HBZ-Bc1e-VQ6.js → chunk-Q4XR5HBZ-CdURCgLS.js} +1 -1
  23. package/web-dist/assets/{chunk-RYQCIY6F-ExoEx5xU.js → chunk-RYQCIY6F-BnZg3wIp.js} +1 -1
  24. package/web-dist/assets/{chunk-V7JOEXUC-BejALgmS.js → chunk-V7JOEXUC-uO2fUZzm.js} +1 -1
  25. package/web-dist/assets/{chunk-VAUOI2AC-DCxTR7U8.js → chunk-VAUOI2AC-CofEt-CQ.js} +1 -1
  26. package/web-dist/assets/{chunk-VR4S4FIN-BukySeYi.js → chunk-VR4S4FIN-9mIXe6Du.js} +1 -1
  27. package/web-dist/assets/{chunk-WYO6CB5R-Bws7hxsV.js → chunk-WYO6CB5R-DX8qax_q.js} +1 -1
  28. package/web-dist/assets/{chunk-XXDRQBXY-DjA78QDQ.js → chunk-XXDRQBXY-C28sBueC.js} +1 -1
  29. package/web-dist/assets/{chunk-ZGVPDNZ5-DKIh9xod.js → chunk-ZGVPDNZ5-BOCPG79n.js} +1 -1
  30. package/web-dist/assets/classDiagram-OUVF2IWQ-D-3vUl4W.js +1 -0
  31. package/web-dist/assets/classDiagram-v2-EOCWNBFH-D-3vUl4W.js +1 -0
  32. package/web-dist/assets/{cose-bilkent-JH36ORCC-C9L1n6fr.js → cose-bilkent-JH36ORCC-CPCiZ8I_.js} +1 -1
  33. package/web-dist/assets/{cynefin-VYW2F7L2-DI26e4Tc.js → cynefin-VYW2F7L2-8xgXFX87.js} +1 -1
  34. package/web-dist/assets/{cynefinDiagram-TSTJHNR4-Cp57PoPj.js → cynefinDiagram-TSTJHNR4-DwVrmsMT.js} +1 -1
  35. package/web-dist/assets/{dagre-VKFMJZFB-DBADVTqD.js → dagre-VKFMJZFB-VfKIjOrh.js} +1 -1
  36. package/web-dist/assets/{diagram-FQU43EPY-0HlOV1mt.js → diagram-FQU43EPY-CfRYwsX4.js} +1 -1
  37. package/web-dist/assets/{diagram-G47NLZAW-DgR5-Pxg.js → diagram-G47NLZAW-LZDctC2c.js} +1 -1
  38. package/web-dist/assets/{diagram-NH7WQ7WH-DoGKoxYE.js → diagram-NH7WQ7WH-B9I9O4q2.js} +1 -1
  39. package/web-dist/assets/{diagram-OA4YK3LP-D5GrLhaq.js → diagram-OA4YK3LP-DyLtLmXq.js} +1 -1
  40. package/web-dist/assets/{diagram-WEI45ONY-DPj7-RdX.js → diagram-WEI45ONY-Cq4XlICY.js} +1 -1
  41. package/web-dist/assets/{dist-Bo2PwwGZ.js → dist-BVACuJBo.js} +1 -1
  42. package/web-dist/assets/{ebnfDiagram-CCIWWBDH-DIXYEkGD.js → ebnfDiagram-CCIWWBDH-CXiLLBrP.js} +1 -1
  43. package/web-dist/assets/{erDiagram-Q63AITRT-Dg3MGwWR.js → erDiagram-Q63AITRT-E4Tq-3uJ.js} +1 -1
  44. package/web-dist/assets/eventmodeling-45OFAUF4-BAy8PeSd.js +1 -0
  45. package/web-dist/assets/flowDiagram-23GEKE2U-D9aeK_Sz.js +1 -0
  46. package/web-dist/assets/{ganttDiagram-NO4QXBWP-BIcCVXZQ.js → ganttDiagram-NO4QXBWP-CV5w3HxN.js} +1 -1
  47. package/web-dist/assets/{gitGraph-TEB2WS4Q-B5RytoFn.js → gitGraph-TEB2WS4Q-Ca8Dwhcu.js} +1 -1
  48. package/web-dist/assets/{gitGraphDiagram-IHSO6WYX-Cb-dT-cW.js → gitGraphDiagram-IHSO6WYX-1S-rnkir.js} +1 -1
  49. package/web-dist/assets/index-BWHvfz4p.css +2 -0
  50. package/web-dist/assets/index-EVfoZw3n.js +377 -0
  51. package/web-dist/assets/{info-DKCQHKI2-GIyDtSFf.js → info-DKCQHKI2-CAprcrba.js} +1 -1
  52. package/web-dist/assets/{infoDiagram-FWYZ7A6U-hajuuFGe.js → infoDiagram-FWYZ7A6U-BVskYXDu.js} +1 -1
  53. package/web-dist/assets/{ishikawaDiagram-FXEZZL3T-DFX-Hnma.js → ishikawaDiagram-FXEZZL3T-GLwxlM0Z.js} +1 -1
  54. package/web-dist/assets/{journeyDiagram-5HDEW3XC-DCAhU4Cx.js → journeyDiagram-5HDEW3XC-CFs0KY4W.js} +1 -1
  55. package/web-dist/assets/{kanban-definition-HUTT4EX6-C3WHlUdK.js → kanban-definition-HUTT4EX6-B1mrGDh-.js} +1 -1
  56. package/web-dist/assets/{line-CSYf7CnT.js → line-CH8_t-Bl.js} +1 -1
  57. package/web-dist/assets/{linear-Di1L0vVF.js → linear-B-zmv10o.js} +1 -1
  58. package/web-dist/assets/{mermaid-parser.core-CudEuGod.js → mermaid-parser.core-C4jXIK12.js} +3 -3
  59. package/web-dist/assets/{mermaid.core-D2s3bQBM.js → mermaid.core-D-5-wAck.js} +3 -3
  60. package/web-dist/assets/{mindmap-definition-LN4V7U3C-yXCjhQFg.js → mindmap-definition-LN4V7U3C-BYpjdopv.js} +1 -1
  61. package/web-dist/assets/{packet-7NZHBO7P-3EcXllio.js → packet-7NZHBO7P-Cjna6hCg.js} +1 -1
  62. package/web-dist/assets/{pegDiagram-2B236MQR-CvS28grz.js → pegDiagram-2B236MQR-DCpSFktT.js} +1 -1
  63. package/web-dist/assets/{pie-RZYD4A2V-CAmA2Snx.js → pie-RZYD4A2V-AOgScQVR.js} +1 -1
  64. package/web-dist/assets/{pieDiagram-ENE6RG2P-BYuB33BI.js → pieDiagram-ENE6RG2P-B3a0v6zL.js} +1 -1
  65. package/web-dist/assets/{quadrantDiagram-ABIIQ3AL-CDnklrlY.js → quadrantDiagram-ABIIQ3AL-CcqK-NK6.js} +1 -1
  66. package/web-dist/assets/{radar-I7S5WNFK-Bz7Vyy1A.js → radar-I7S5WNFK-DtuvXtCm.js} +1 -1
  67. package/web-dist/assets/{railroad-3IZDKUUU-CAUAJCaq.js → railroad-3IZDKUUU-BkqKVzRX.js} +1 -1
  68. package/web-dist/assets/railroad-abnf-AHOZXSZD-CHn7rlun.js +1 -0
  69. package/web-dist/assets/railroad-ebnf-EBAXGLYW-y-9egy8E.js +1 -0
  70. package/web-dist/assets/railroad-peg-LSFZ7HO6-CcjaBCCD.js +1 -0
  71. package/web-dist/assets/{railroadDiagram-RFXS5EU6-DZaYV9Io.js → railroadDiagram-RFXS5EU6-DDHj4uDb.js} +1 -1
  72. package/web-dist/assets/{requirementDiagram-TGXJPOKE-BFlpQunS.js → requirementDiagram-TGXJPOKE-B54HzGZC.js} +1 -1
  73. package/web-dist/assets/{sankeyDiagram-HTMAVEWB-DIOr2M-C.js → sankeyDiagram-HTMAVEWB-3E6dsZaw.js} +1 -1
  74. package/web-dist/assets/{sequenceDiagram-DBY2YBRQ-DpYJiT1u.js → sequenceDiagram-DBY2YBRQ-CVpuzOAQ.js} +1 -1
  75. package/web-dist/assets/{src-BkVLS0R9.js → src-pgycCSL8.js} +1 -1
  76. package/web-dist/assets/{stateDiagram-2N3HPSRC-C4UYGg5g.js → stateDiagram-2N3HPSRC-Cgfbv4Jj.js} +1 -1
  77. package/web-dist/assets/stateDiagram-v2-6OUMAXLB-ROcJdvkR.js +1 -0
  78. package/web-dist/assets/{swimlanes-5IMT3BWC-cJ6KOezW.js → swimlanes-5IMT3BWC-DjH7BeS7.js} +1 -1
  79. package/web-dist/assets/swimlanesDiagram-G3AALYLV-45yhNrvo.js +8 -0
  80. package/web-dist/assets/{timeline-definition-FHXFAJF6-yi-2X9QL.js → timeline-definition-FHXFAJF6-BiHrEvsn.js} +1 -1
  81. package/web-dist/assets/{treeView-QDETBFTQ-Bnlc02cs.js → treeView-QDETBFTQ-BsXOB7X1.js} +1 -1
  82. package/web-dist/assets/{treemap-6X3UGDF4-DUWj2eOS.js → treemap-6X3UGDF4-CEPOvdmd.js} +1 -1
  83. package/web-dist/assets/{vennDiagram-L72KCM5P-jPHNRI-h.js → vennDiagram-L72KCM5P-CmM7sjoE.js} +1 -1
  84. package/web-dist/assets/{wardley-OPB4EBWU-CPbgZ6M1.js → wardley-OPB4EBWU-v6d2b-Ee.js} +1 -1
  85. package/web-dist/assets/{wardleyDiagram-EHGQE667-CrExyaRO.js → wardleyDiagram-EHGQE667-B8zMQrbQ.js} +1 -1
  86. package/web-dist/assets/{xychartDiagram-FW5EYKEG-CN06Wt1I.js → xychartDiagram-FW5EYKEG-BxfsO5vO.js} +1 -1
  87. package/web-dist/index.html +2 -2
  88. package/web-dist/assets/architecture-TIHT7OUA-DaAFvFkn.js +0 -1
  89. package/web-dist/assets/channel-B1iPbzai.js +0 -1
  90. package/web-dist/assets/classDiagram-OUVF2IWQ-DQlurrbL.js +0 -1
  91. package/web-dist/assets/classDiagram-v2-EOCWNBFH-DQlurrbL.js +0 -1
  92. package/web-dist/assets/eventmodeling-45OFAUF4-CeTMJyik.js +0 -1
  93. package/web-dist/assets/flowDiagram-23GEKE2U-QhaJlS-W.js +0 -1
  94. package/web-dist/assets/index-B5PLhSPz.js +0 -375
  95. package/web-dist/assets/index-D_uxez2a.css +0 -2
  96. package/web-dist/assets/railroad-abnf-AHOZXSZD-B9RdcI3r.js +0 -1
  97. package/web-dist/assets/railroad-ebnf-EBAXGLYW-Cimw_4Xu.js +0 -1
  98. package/web-dist/assets/railroad-peg-LSFZ7HO6-DJTpn0sf.js +0 -1
  99. package/web-dist/assets/stateDiagram-v2-6OUMAXLB-CO0mbUgI.js +0 -1
  100. package/web-dist/assets/swimlanesDiagram-G3AALYLV-AkPUIZ-W.js +0 -8
package/dist/dev-child.js CHANGED
@@ -14398,6 +14398,62 @@ function commandWatchCancelledWakeMessage(input) {
14398
14398
  COMMAND_WATCH_CANCELLED_TRAILER
14399
14399
  ].join("\n");
14400
14400
  }
14401
+ function monitorLabel(input) {
14402
+ const described = input.description?.trim().replace(/\s+/g, " ");
14403
+ if (described) return described;
14404
+ const command = input.command.trim().replace(/\s+/g, " ");
14405
+ return command.length > 80 ? `${command.slice(0, 79)}\u2026` : command;
14406
+ }
14407
+ function monitorEventWakeMessage(input) {
14408
+ const shown = input.lines.length;
14409
+ const more = input.more ?? 0;
14410
+ const total = shown + more;
14411
+ return [
14412
+ `\u{1F4DF} Your monitor \`${input.id}\` printed ${total} line${total === 1 ? "" : "s"} (event ${input.event}) \u2014 ${input.label}`,
14413
+ "",
14414
+ codeBlock(input.lines.join("\n")),
14415
+ ...more > 0 ? ["", `\u2026and ${more} more line${more === 1 ? "" : "s"} in the same burst, not shown.`] : [],
14416
+ "",
14417
+ MONITOR_EVENT_TRAILER.replace("<id>", input.id)
14418
+ ].join("\n");
14419
+ }
14420
+ function monitorExitedWakeMessage(input) {
14421
+ const how = input.run.outcome === "exit" ? `exited ${input.run.exitCode ?? "?"}` : input.run.outcome === "error" ? "could not be started" : "was killed by a signal";
14422
+ const output = input.run.output.trim();
14423
+ return [
14424
+ `\u23F9\uFE0F Your monitor \`${input.id}\` ${how} after ${input.events} event${input.events === 1 ? "" : "s"} and is no longer armed \u2014 ${input.label}`,
14425
+ "",
14426
+ codeBlock(input.command, "sh"),
14427
+ "",
14428
+ output ? `Its output ended (stderr included):
14429
+
14430
+ ${codeBlock(output)}` : "It printed nothing more.",
14431
+ "",
14432
+ MONITOR_EXITED_TRAILER
14433
+ ].join("\n");
14434
+ }
14435
+ function monitorExpiredWakeMessage(input) {
14436
+ return [
14437
+ `\u23F0 Your monitor \`${input.id}\` ran out its \`for\` after ${input.events} event${input.events === 1 ? "" : "s"} and was stopped \u2014 ${input.label}`,
14438
+ "",
14439
+ codeBlock(input.command, "sh"),
14440
+ "",
14441
+ MONITOR_EXPIRED_TRAILER
14442
+ ].join("\n");
14443
+ }
14444
+ function monitorCancelledWakeMessage(input) {
14445
+ const events = `${input.events} event${input.events === 1 ? "" : "s"}`;
14446
+ const reason = input.reason.trim();
14447
+ return [
14448
+ input.by === "human" ? `\u{1F6D1} The human stopped your monitor \`${input.id}\` from the board after ${events} \u2014 ${input.label}` : `\u26A0\uFE0F Frizz stopped your monitor \`${input.id}\` after ${events} \u2014 ${input.label}`,
14449
+ "",
14450
+ reason.charAt(0).toUpperCase() + reason.slice(1),
14451
+ "",
14452
+ codeBlock(input.command, "sh"),
14453
+ "",
14454
+ MONITOR_CANCELLED_TRAILER
14455
+ ].join("\n");
14456
+ }
14401
14457
  function questionFencesLive(spawnedAt) {
14402
14458
  if (spawnedAt === void 0 || spawnedAt === null) return true;
14403
14459
  const at2 = typeof spawnedAt === "number" ? spawnedAt : Date.parse(spawnedAt);
@@ -14573,6 +14629,38 @@ function activeBandThreadAt(t, nowMs) {
14573
14629
  if (t.kind !== "session" || t.foreign === true) return false;
14574
14630
  return sectionAt(t, nowMs) === "active" && inActiveBand(t);
14575
14631
  }
14632
+ function displayTitle(t) {
14633
+ if (t.foreign === true && t.title.trim()) return t.title.trim();
14634
+ if (titleIsProvisional(t)) return SPINNING_UP_TITLE;
14635
+ if (t.aiTitle?.trim() && !titleIsHumanOwned(t)) return readableMachineTitle(t.aiTitle);
14636
+ if (t.backend === "codex" && t.titleAuto === true && !t.aiTitle?.trim()) return UNTITLED_THREAD_TITLE;
14637
+ if (t.titleAuto === false && t.title.trim()) return t.title;
14638
+ if (t.title.trim() && !(t.titleAuto === true && t.title.trim() === t.id)) {
14639
+ return t.titleAuto === true ? readableMachineTitle(t.title) : t.title.trim();
14640
+ }
14641
+ return t.titleAuto === true ? UNTITLED_THREAD_TITLE : t.id;
14642
+ }
14643
+ function titleIsHumanOwned(t) {
14644
+ return t.titleLocked ?? t.titleAuto === false;
14645
+ }
14646
+ function readableMachineTitle(raw2) {
14647
+ const title = raw2.trim();
14648
+ if (!/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i.test(title)) return title;
14649
+ const words = title.split(/[-_]+/).filter(Boolean);
14650
+ if (words.length === 0) return title;
14651
+ const joined = words.join(" ").toLowerCase();
14652
+ return joined.charAt(0).toUpperCase() + joined.slice(1);
14653
+ }
14654
+ function titleIsProvisional(t) {
14655
+ if (!t.titleAuto || t.aiTitle) return false;
14656
+ if (t.backend === "codex") {
14657
+ if (t.runtime === "spawning") return true;
14658
+ const spawned2 = Date.parse(t.spawnedAt ?? "");
14659
+ return Number.isFinite(spawned2) && Date.now() - spawned2 < CODEX_TITLE_SIGNAL_GRACE_MS;
14660
+ }
14661
+ const spawned = Date.parse(t.spawnedAt ?? "");
14662
+ return Number.isFinite(spawned) && Date.now() - spawned < SPIN_UP_MS;
14663
+ }
14576
14664
  function hasStandingQuestion(t) {
14577
14665
  return (t.questions ?? []).some((q2) => q2.standing !== false);
14578
14666
  }
@@ -14598,6 +14686,14 @@ function requireEffortOutsideAcp(profile, ctx) {
14598
14686
  ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["effort"], message: `effort is required for a ${profile.backend} profile` });
14599
14687
  }
14600
14688
  }
14689
+ function threadBandAt(t, nowMs) {
14690
+ if (t.kind !== "session" || t.foreign === true) return null;
14691
+ const section = sectionAt(t, nowMs);
14692
+ if (section === "inactive") return "done";
14693
+ if (section === "snoozed") return "snoozed";
14694
+ if (section === "active") return inActiveBand(t) ? "active" : "rested";
14695
+ return null;
14696
+ }
14601
14697
  function formatElapsed(ms) {
14602
14698
  if (!Number.isFinite(ms) || ms < 0) return "an unknown time";
14603
14699
  const s = Math.floor(ms / 1e3);
@@ -14846,7 +14942,7 @@ function parseGithubWakeSteer(text2) {
14846
14942
  function frizzRoute(path3) {
14847
14943
  return `${FRIZZ_ROUTE_PREFIX}${path3.startsWith("/") ? path3 : `/${path3}`}`;
14848
14944
  }
14849
- var import_yaml2, ATTACHMENT_IMAGE_EXTENSIONS, ATTACHMENT_TEXT_EXTENSIONS, ATTACHMENT_OFFICE_EXTENSIONS, ATTACHMENT_DATA_EXTENSIONS, ATTACHMENT_ARCHIVE_EXTENSIONS, ATTACHMENT_DOC_EXTENSIONS, ATTACHMENT_EXTENSIONS, ATTACHMENT_MAX_BASE64_CHARS, ATTACHMENT_MAX_BYTES, ATTACHMENT_EXT_SET, ATTACHMENT_ACCEPT, FrizzStatus, BlockMechanism, RuntimeState, Backend, CodexModel, ClaudeModel, CODEX_MODELS_FALLBACK, AcpAgent, ACP_MODEL_PREFIX, AcpAgentModel, AcpAgentModels, AcpAgentModelsInput, ThreadProfileOption, ThreadAgent, SubAgentView, BgShellView, CompletionHoldOp, CompletionHold, AskOption, AskQuestion, PendingAsk, AwaitingHint, RETIRED_AWAITING_KINDS, RETIRED_LINE_RE, RETIRED_AWAITING_REPLACEMENT, AWAITING_KEY_RE, AWAITING_YAML_KEYS, AWAITING_SEQUENCE_KEYS, AWAITING_HINT_MAX, AWAITING_HINT_VALUE_MAX, AWAITING_SCALAR_KINDS, AWAITING_STEPS_MAX, AWAITING_STEP_VALUE_MAX, AWAITING_QUESTIONS_MAX, AWAITING_TITLE_MAX, FENCE_DELIMITER_RE, AWAITING_STATUSES, AWAITING_ITEM_KINDS, AWAITING_DURATION_RE, DURATION_UNIT_MS, AWAITING_FOR_MAX_MS, SnoozeUntil, SNOOZE_PROMPT_MAX, SnoozePrompt, RECURRING_PROMPT_MAX, RECURRING_MIN_INTERVAL_SECONDS, RECURRING_MAX_INTERVAL_SECONDS, RecurringPromptText, RecurringIntervalSeconds, ThreadRecurringPrompt, INTERRUPT_MARKERS, ALLDONE_SENTINEL, OPT_OUT_NOTE, OVER_QUESTION_NOTE, TIMER_PROMPT_MAX, TIMER_MAX_DELAY_SECONDS, TIMER_MAX_ARMED, TimerPromptText, PR_WATCH_SPENT_TRAILER, PR_WATCH_ARMED_TRAILER, SHELL_DONE_TRAILER, ISSUE_WATCH_SPENT_TRAILER, ISSUE_WATCH_ARMED_TRAILER, LEGACY_PR_WATCH_ARMED_TRAILER, LEGACY_ISSUE_WATCH_ARMED_TRAILER, INTERRUPT_ENDED_LEAD, SIGNOFF_NUDGE_MARKER, SIGNOFF_NUDGE_MESSAGE, SIGNOFF_NUDGE_MESSAGE_NEEDS_INPUT, PARK_CORRECTION_NAMES_LEAD, PARK_CORRECTION_RETIRED_LEAD, PARK_CORRECTION_QUESTION_LEAD, PARK_CORRECTION_NEEDS_INPUT_LEAD, QUESTION_FENCE_CORRECTION_LEAD, DONE_FENCE_CORRECTION_LEAD, ThreadWatchKind, GithubChecksState, GithubMergeState, GithubWatchStatus, GithubIssueStatus, CommandWatchRun, ThreadWatchView, PR_WATCH_FOR_MAX_MS, PR_WATCH_DEFAULT_FOR_MS, PR_WATCH_MAX_ARMED, PrWatchView, AddOwnPrWatchInput, AddOwnPrWatchResult, DropOwnPrWatchInput, DropOwnPrWatchResult, OwnWatchKind, AddOwnWatchInput, OwnWatchView, AddOwnWatchResult, DropOwnWatchInput, DropOwnWatchResult, OWN_WATCH_MAX_ARMED, COMMAND_WATCH_EVERY_MIN_MS, COMMAND_WATCH_EVERY_MAX_MS, COMMAND_WATCH_FOR_MAX_MS, COMMAND_WATCH_MAX_ARMED, COMMAND_WATCH_COMMAND_MAX, COMMAND_WATCH_OUTPUT_MAX_BYTES, COMMAND_WATCH_RUN_TIMEOUT_MS, CommandWatchState, CommandWatchView, AddOwnCommandWatchInput, AddOwnCommandWatchResult, DropOwnCommandWatchInput, DropOwnCommandWatchResult, ListOwnCommandWatchesInput, OwnCommandWatchesResult, COMMAND_WATCH_FALLBACK, COMMAND_WATCH_PASSED_TRAILER, COMMAND_WATCH_EXPIRED_TRAILER, COMMAND_WATCH_CANCELLED_TRAILER, QUESTION_FENCE_RETIRED_AT, NEEDS_INPUT_REQUIRED_AT, AskQuestionKind, ASK_MAX_DEPTH, AskedOptionSchema, AskedQuestionSchema, AskInput, RegisteredQuestionView, QuestionFenceFaultView, ClosedQuestionView, SECRET_ANSWER_PREFIX, SECRET_TTL_MS, AskResult, UnaskInput, UnaskResult, QuestionAnswerSchema, AnswerQuestionsInput, AnswerQuestionsResult, DismissQuestionsInput, DismissQuestionsResult, SettledQuestionView, ThreadSettledQuestionsResult, BURIED_ANSWERS_HEADER, ANSWER_FOLLOW_UP_MARKER, ANSWER_CONTINUATION_INDENT, indentAnswerContinuation, ANSWER_PICK_PREFIX, DISMISSED_ANSWER, ANSWER_ROW_ID_PATTERN, ANSWER_ROW_ID, answerRowId, ANSWERS_NOTE_HEADER, MarkOwnDoneInput, MarkOwnDoneResult, ListOwnPrWatchesInput, OwnPrWatchesResult, ThreadTimerView, ThreadFence, LimitWindow, LimitPause, ProviderError, ThreadLinkView, UpsertOwnLinkInput, UpsertOwnLinkResult, DropOwnLinkInput, DropOwnLinkResult, LiveTool, ThreadView, BoardErrorItem, BoardSnapshot, BoardState, QuotaWindow, ProviderQuota, QuotaSnapshot, ProviderAuth, AccountEmails, AuthSnapshot, AccountBackend, AccountLogoutInput, AccountLogoutResult, PermissionMode, LocalFileOpener, Settings, DispatchProviderPreferences, DispatchPreferences, DispatchProfileSnapshotShape, DispatchProfileSnapshot, SetDispatchPreferenceInput, DispatchInput, ADOPT_THREAD_MESSAGE_MAX_CHARS, AdoptThreadInput, AdoptThreadResult, AdoptSessionInput, FollowUpInput, SteerThreadInput, SteerThreadResult, SpawnThreadInput, SpawnThreadResult, DismissFailedFollowUpInput, DismissFailedFollowUpResult, UnqueueFollowUpInput, UnqueueFollowUpResult, DeliverQueuedNowInput, DeliverQueuedNowResult, CompactThreadInput, SetThreadSnoozeInput, SetThreadPinnedInput, ReorderPinnedThreadsInput, SetThreadConsolePinnedInput, ReorderConsolePinnedThreadsInput, SetThreadRecurringPromptInput, SetOwnThreadRecurringPromptInput, SetOwnThreadRecurringPromptResult, GetOwnThreadRecurringPromptInput, OwnThreadRecurringPromptResult, SetOwnThreadTimerInput, CancelOwnThreadTimerInput, ListOwnThreadTimersInput, OwnThreadTimersResult, ThreadActivityItem, ListOwnThreadActivityInput, OwnThreadActivityResult, SetOwnThreadTimerResult, CancelOwnThreadTimerResult, SetOwnThreadStopHookInput, SetOwnThreadHeartbeatInput, RenameThreadInput, AiRenameThreadInput, AiRenameThreadResult, SetOwnThreadTitleInput, SetOwnThreadTitleResult, SetThreadPermissionInput, SetThreadPermissionResult, ThreadProfileOptionsInput, ThreadProfileOptionsResult, ThreadSkillSource, ThreadSkill, ThreadSkillsInput, ThreadSkillsResult, McpTarget, McpServerState, McpServerReading, McpStatusInput, McpStatusResult, McpSignInInput, McpSignInState, McpSignInResult, McpSignInAttemptInput, McpSignInPollResult, McpSignInFinishInput, SetThreadProfileInput, SetThreadProfileResult, UpgradeThreadModelInput, UpgradeThreadModelResult, DISPATCH_TASK_BANNER, DISPATCH_TASK_BANNER_MARKER, GITHUB_DISPATCH_UI_BOUNDARY, WAKE_TIME_HEADER_TAIL, WAKE_TRAILERS, HUMAN_GAP_FLOOR_MS, HUMAN_GAP_NOTE_TAIL, WAKE_DELIVERY_TOKEN_TAIL, WAKE_DELIVERY_TOKEN_LINE, MERGED_WAKE_LEAD, MERGED_WAKE_HEADING, NOISE_PREFIXES, AGENT_MESSAGE_WRAPPER, CROSS_SESSION_PREAMBLE, CROSS_SESSION_WRAPPER, CROSS_SESSION_GUIDANCE, XML_ATTRIBUTE, THREAD_MESSAGE_OPEN, THREAD_MESSAGE_CLOSE, THREAD_MESSAGE_GUIDANCE, RETRY_FOLLOW_UP, GithubWakeItem, GithubWakeSteer, WAKE_SCOPE, WAKE_REVIEW_LEAD, WAKE_BACKLOG_TAIL, WAKE_REF, WAKE_SINGLE, WAKE_MULTI_HEAD, WAKE_ITEM, WAKE_MORE, PR_WATCH_FINISHED, PR_WATCH_CI_PASSED, PR_WATCH_CI_GATED, PR_WATCH_STATE, PR_WATCH_CI_FAILED, GithubStatus, GithubRefCard, GithubRefPreviewInput, GithubRefPreviewResult, GithubItem, GithubListInput, GithubListResult, GithubBatchInput, GithubBatchResult, BoardMeta, BoardDeltaEvent, ServerEvent, BoardDeltasInput, BoardDeltasResult, TranscriptEdit, TranscriptTodo, TranscriptToolCall, TranscriptPart, TranscriptMessage, TranscriptPageCursor, EditedFile, TranscriptPage, TranscriptEarlierInput, SocketTranscriptSlug, SocketFilePath, SocketTranscriptClientMsg, SocketFileClientMsg, SocketBoardClientMsg, SocketClientMsg, ProjectCard, ProjectRailCounts, PROJECT_ICON_EXTENSIONS, PROJECT_ICON_MAX_BASE64_CHARS, DirectoryPickResult, ThreadLocation, FRIZZ_ROUTE_PREFIX, DEFAULT_PORT, threadIdentityName;
14945
+ var import_yaml2, ATTACHMENT_IMAGE_EXTENSIONS, ATTACHMENT_TEXT_EXTENSIONS, ATTACHMENT_OFFICE_EXTENSIONS, ATTACHMENT_DATA_EXTENSIONS, ATTACHMENT_ARCHIVE_EXTENSIONS, ATTACHMENT_DOC_EXTENSIONS, ATTACHMENT_EXTENSIONS, ATTACHMENT_MAX_BASE64_CHARS, ATTACHMENT_MAX_BYTES, ATTACHMENT_EXT_SET, ATTACHMENT_ACCEPT, FrizzStatus, BlockMechanism, RuntimeState, Backend, CodexModel, ClaudeModel, CODEX_MODELS_FALLBACK, AcpAgent, ACP_MODEL_PREFIX, AcpAgentModel, AcpAgentModels, AcpAgentModelsInput, ThreadProfileOption, ThreadAgent, SubAgentView, BgShellView, CompletionHoldOp, CompletionHold, AskOption, AskQuestion, PendingAsk, AwaitingHint, RETIRED_AWAITING_KINDS, RETIRED_LINE_RE, RETIRED_AWAITING_REPLACEMENT, AWAITING_KEY_RE, AWAITING_YAML_KEYS, AWAITING_SEQUENCE_KEYS, AWAITING_HINT_MAX, AWAITING_HINT_VALUE_MAX, AWAITING_SCALAR_KINDS, AWAITING_STEPS_MAX, AWAITING_STEP_VALUE_MAX, AWAITING_QUESTIONS_MAX, AWAITING_TITLE_MAX, FENCE_DELIMITER_RE, AWAITING_STATUSES, AWAITING_ITEM_KINDS, AWAITING_DURATION_RE, DURATION_UNIT_MS, AWAITING_FOR_MAX_MS, SnoozeUntil, SNOOZE_PROMPT_MAX, SnoozePrompt, RECURRING_PROMPT_MAX, RECURRING_MIN_INTERVAL_SECONDS, RECURRING_MAX_INTERVAL_SECONDS, RecurringPromptText, RecurringIntervalSeconds, ThreadRecurringPrompt, INTERRUPT_MARKERS, ALLDONE_SENTINEL, OPT_OUT_NOTE, OVER_QUESTION_NOTE, TIMER_PROMPT_MAX, TIMER_MAX_DELAY_SECONDS, TIMER_MAX_ARMED, TimerPromptText, PR_WATCH_SPENT_TRAILER, PR_WATCH_ARMED_TRAILER, SHELL_DONE_TRAILER, ISSUE_WATCH_SPENT_TRAILER, ISSUE_WATCH_ARMED_TRAILER, LEGACY_PR_WATCH_ARMED_TRAILER, LEGACY_ISSUE_WATCH_ARMED_TRAILER, INTERRUPT_ENDED_LEAD, SIGNOFF_NUDGE_MARKER, SIGNOFF_NUDGE_MESSAGE, SIGNOFF_NUDGE_MESSAGE_NEEDS_INPUT, PARK_CORRECTION_NAMES_LEAD, PARK_CORRECTION_RETIRED_LEAD, PARK_CORRECTION_QUESTION_LEAD, PARK_CORRECTION_NEEDS_INPUT_LEAD, QUESTION_FENCE_CORRECTION_LEAD, DONE_FENCE_CORRECTION_LEAD, ThreadWatchKind, GithubChecksState, GithubMergeState, GithubWatchStatus, GithubIssueStatus, CommandWatchRun, MonitorStatus, ThreadWatchView, PR_WATCH_FOR_MAX_MS, PR_WATCH_DEFAULT_FOR_MS, PR_WATCH_MAX_ARMED, PrWatchView, AddOwnPrWatchInput, AddOwnPrWatchResult, DropOwnPrWatchInput, DropOwnPrWatchResult, OwnWatchKind, AddOwnWatchInput, OwnWatchView, AddOwnWatchResult, DropOwnWatchInput, DropOwnWatchResult, OWN_WATCH_MAX_ARMED, COMMAND_WATCH_EVERY_MIN_MS, COMMAND_WATCH_EVERY_MAX_MS, COMMAND_WATCH_FOR_MAX_MS, COMMAND_WATCH_MAX_ARMED, COMMAND_WATCH_COMMAND_MAX, COMMAND_WATCH_OUTPUT_MAX_BYTES, COMMAND_WATCH_RUN_TIMEOUT_MS, CommandWatchState, CommandWatchView, AddOwnCommandWatchInput, AddOwnCommandWatchResult, DropOwnCommandWatchInput, DropOwnCommandWatchResult, ListOwnCommandWatchesInput, OwnCommandWatchesResult, COMMAND_WATCH_FALLBACK, COMMAND_WATCH_PASSED_TRAILER, COMMAND_WATCH_EXPIRED_TRAILER, COMMAND_WATCH_CANCELLED_TRAILER, MONITOR_BATCH_MS, MONITOR_LINE_MAX_CHARS, MONITOR_EVENT_MAX_LINES, MONITOR_FLOOD_MAX_EVENTS, MONITOR_FLOOD_WINDOW_MS, MONITOR_REGISTRATION_WINDOW_MS, MONITOR_DESCRIPTION_MAX, MONITOR_SERVER_MAX_RUNNING, AddOwnMonitorInput, AddOwnMonitorResult, MONITOR_FALLBACK, MONITOR_EVENT_TRAILER, MONITOR_EXITED_TRAILER, MONITOR_EXPIRED_TRAILER, MONITOR_CANCELLED_TRAILER, MONITOR_FLOOD_REASON, MONITOR_STOPPED_BY_HUMAN_REASON, QUESTION_FENCE_RETIRED_AT, NEEDS_INPUT_REQUIRED_AT, AskQuestionKind, ASK_MAX_DEPTH, AskedOptionSchema, AskedQuestionSchema, AskInput, RegisteredQuestionView, QuestionFenceFaultView, ClosedQuestionView, SECRET_ANSWER_PREFIX, SECRET_TTL_MS, AskResult, UnaskInput, UnaskResult, QuestionAnswerSchema, AnswerQuestionsInput, AnswerQuestionsResult, DismissQuestionsInput, DismissQuestionsResult, SettledQuestionView, ThreadSettledQuestionsResult, BURIED_ANSWERS_HEADER, ANSWER_FOLLOW_UP_MARKER, ANSWER_CONTINUATION_INDENT, indentAnswerContinuation, ANSWER_PICK_PREFIX, DISMISSED_ANSWER, ANSWER_ROW_ID_PATTERN, ANSWER_ROW_ID, answerRowId, ANSWERS_NOTE_HEADER, MarkOwnDoneInput, MarkOwnDoneResult, ListOwnPrWatchesInput, OwnPrWatchesResult, ThreadTimerView, ThreadFence, LimitWindow, LimitPause, ProviderError, ThreadLinkView, UpsertOwnLinkInput, UpsertOwnLinkResult, DropOwnLinkInput, DropOwnLinkResult, LiveTool, ThreadView, SPINNING_UP_TITLE, UNTITLED_THREAD_TITLE, SPIN_UP_MS, CODEX_TITLE_SIGNAL_GRACE_MS, BoardErrorItem, BoardSnapshot, BoardState, QuotaWindow, ProviderQuota, QuotaSnapshot, ProviderAuth, AccountEmails, AuthSnapshot, AccountBackend, AccountLogoutInput, AccountLogoutResult, PermissionMode, LocalFileOpener, Settings, DispatchProviderPreferences, DispatchPreferences, DispatchProfileSnapshotShape, DispatchProfileSnapshot, SetDispatchPreferenceInput, DispatchInput, ADOPT_THREAD_MESSAGE_MAX_CHARS, AdoptThreadInput, AdoptThreadResult, AdoptSessionInput, FollowUpInput, SteerThreadInput, SteerThreadResult, SpawnThreadInput, SpawnThreadResult, DismissFailedFollowUpInput, DismissFailedFollowUpResult, UnqueueFollowUpInput, UnqueueFollowUpResult, DeliverQueuedNowInput, DeliverQueuedNowResult, CompactThreadInput, SetThreadSnoozeInput, SetThreadPinnedInput, ReorderPinnedThreadsInput, SetThreadConsolePinnedInput, ReorderConsolePinnedThreadsInput, SetThreadRecurringPromptInput, SetOwnThreadRecurringPromptInput, SetOwnThreadRecurringPromptResult, GetOwnThreadRecurringPromptInput, OwnThreadRecurringPromptResult, SetOwnThreadTimerInput, CancelOwnThreadTimerInput, ListOwnThreadTimersInput, OwnThreadTimersResult, ThreadActivityItem, ListOwnThreadActivityInput, OwnThreadActivityResult, ThreadBand, ThreadListing, ListThreadsInput, ListThreadsResult, SetOwnThreadTimerResult, CancelOwnThreadTimerResult, SetOwnThreadStopHookInput, SetOwnThreadHeartbeatInput, RenameThreadInput, AiRenameThreadInput, AiRenameThreadResult, SetOwnThreadTitleInput, SetOwnThreadTitleResult, SetThreadPermissionInput, SetThreadPermissionResult, ThreadProfileOptionsInput, ThreadProfileOptionsResult, ThreadSkillSource, ThreadSkill, ThreadSkillsInput, ThreadSkillsResult, McpTarget, McpServerState, McpServerReading, McpStatusInput, McpStatusResult, McpSignInInput, McpSignInState, McpSignInResult, McpSignInAttemptInput, McpSignInPollResult, McpSignInFinishInput, SetThreadProfileInput, SetThreadProfileResult, UpgradeThreadModelInput, UpgradeThreadModelResult, DISPATCH_TASK_BANNER, DISPATCH_TASK_BANNER_MARKER, GITHUB_DISPATCH_UI_BOUNDARY, WAKE_TIME_HEADER_TAIL, WAKE_TRAILERS, HUMAN_GAP_FLOOR_MS, HUMAN_GAP_NOTE_TAIL, WAKE_DELIVERY_TOKEN_TAIL, WAKE_DELIVERY_TOKEN_LINE, MERGED_WAKE_LEAD, MERGED_WAKE_HEADING, NOISE_PREFIXES, AGENT_MESSAGE_WRAPPER, CROSS_SESSION_PREAMBLE, CROSS_SESSION_WRAPPER, CROSS_SESSION_GUIDANCE, XML_ATTRIBUTE, THREAD_MESSAGE_OPEN, THREAD_MESSAGE_CLOSE, THREAD_MESSAGE_GUIDANCE, RETRY_FOLLOW_UP, GithubWakeItem, GithubWakeSteer, WAKE_SCOPE, WAKE_REVIEW_LEAD, WAKE_BACKLOG_TAIL, WAKE_REF, WAKE_SINGLE, WAKE_MULTI_HEAD, WAKE_ITEM, WAKE_MORE, PR_WATCH_FINISHED, PR_WATCH_CI_PASSED, PR_WATCH_CI_GATED, PR_WATCH_STATE, PR_WATCH_CI_FAILED, GithubStatus, GithubRefCard, GithubRefPreviewInput, GithubRefPreviewResult, GithubItem, GithubListInput, GithubListResult, GithubBatchInput, GithubBatchResult, BoardMeta, BoardDeltaEvent, ServerEvent, BoardDeltasInput, BoardDeltasResult, TranscriptEdit, TranscriptTodo, TranscriptToolCall, TranscriptPart, TranscriptMessage, TranscriptPageCursor, EditedFile, TranscriptPage, TranscriptEarlierInput, SocketTranscriptSlug, SocketFilePath, SocketTranscriptClientMsg, SocketFileClientMsg, SocketBoardClientMsg, SocketClientMsg, ProjectCard, ProjectRailCounts, PROJECT_ICON_EXTENSIONS, PROJECT_ICON_MAX_BASE64_CHARS, DirectoryPickResult, ThreadLocation, FRIZZ_ROUTE_PREFIX, DEFAULT_PORT, threadIdentityName;
14850
14946
  var init_src = __esm({
14851
14947
  "packages/shared/src/index.ts"() {
14852
14948
  "use strict";
@@ -15368,6 +15464,14 @@ var init_src = __esm({
15368
15464
  exitCode: external_exports.number().int().nullable(),
15369
15465
  output: external_exports.string()
15370
15466
  }).strict();
15467
+ MonitorStatus = external_exports.object({
15468
+ /** The worker's own words for what it watches ("errors in deploy.log"), when it gave any. */
15469
+ description: external_exports.string().optional(),
15470
+ /** Events printed so far: each batch of lines that woke (or will wake) the thread is one. */
15471
+ events: external_exports.number().int().nonnegative(),
15472
+ /** The newest event's text, trimmed, and when it was printed. */
15473
+ lastEvent: external_exports.object({ at: external_exports.string(), text: external_exports.string() }).strict().optional()
15474
+ }).strict();
15371
15475
  ThreadWatchView = external_exports.object({
15372
15476
  id: external_exports.string(),
15373
15477
  kind: ThreadWatchKind,
@@ -15400,7 +15504,10 @@ var init_src = __esm({
15400
15504
  every: external_exports.string(),
15401
15505
  expiresAt: external_exports.string(),
15402
15506
  runs: external_exports.number().int().nonnegative(),
15403
- lastRun: CommandWatchRun.optional()
15507
+ lastRun: CommandWatchRun.optional(),
15508
+ /** A MONITOR's own reading (`frizzctl monitor`), and present on nothing else: the row is a running
15509
+ * script, so its status is how many events it has printed, not a cadence. */
15510
+ monitor: MonitorStatus.optional()
15404
15511
  }).strict().optional()
15405
15512
  }).strict();
15406
15513
  PR_WATCH_FOR_MAX_MS = 365 * 24 * 60 * 60 * 1e3;
@@ -15551,7 +15658,11 @@ var init_src = __esm({
15551
15658
  expiresAt: external_exports.string(),
15552
15659
  /** How many checks have run since it was armed, the registration's own first check included. */
15553
15660
  runs: external_exports.number().int().nonnegative(),
15554
- lastRun: CommandWatchRun.optional()
15661
+ lastRun: CommandWatchRun.optional(),
15662
+ /** Present on a MONITOR (`frizzctl monitor`) and nothing else: a script the server keeps RUNNING, whose
15663
+ * every printed line is a wake. A monitor has no cadence and no checks, so `every` reads `0s` and
15664
+ * `runs` 0 on one; read this instead. */
15665
+ monitor: MonitorStatus.optional()
15555
15666
  }).strict();
15556
15667
  AddOwnCommandWatchInput = external_exports.object({
15557
15668
  slug: ThreadSlug,
@@ -15596,6 +15707,49 @@ var init_src = __esm({
15596
15707
  COMMAND_WATCH_PASSED_TRAILER = "The watch is settled and runs no more. Carry on with whatever you were waiting on it for.";
15597
15708
  COMMAND_WATCH_EXPIRED_TRAILER = "If you still mean to wait, find out why it never passed, then register it again with `frizzctl watch-command add` and a fresh `--for`. If you do not, and it was the only thing you were waiting on, end in a proper terminal state instead of parking on it again.";
15598
15709
  COMMAND_WATCH_CANCELLED_TRAILER = "Nothing about it will wake you now. If you still need the wait, run the check in a background shell instead.";
15710
+ MONITOR_BATCH_MS = 200;
15711
+ MONITOR_LINE_MAX_CHARS = 1e3;
15712
+ MONITOR_EVENT_MAX_LINES = 40;
15713
+ MONITOR_FLOOD_MAX_EVENTS = 30;
15714
+ MONITOR_FLOOD_WINDOW_MS = 10 * 6e4;
15715
+ MONITOR_REGISTRATION_WINDOW_MS = 2e3;
15716
+ MONITOR_DESCRIPTION_MAX = 120;
15717
+ MONITOR_SERVER_MAX_RUNNING = 32;
15718
+ AddOwnMonitorInput = external_exports.object({
15719
+ slug: ThreadSlug,
15720
+ /** Run with `/bin/sh -c` in the project root, with the server's environment. Each stdout line is an event. */
15721
+ command: external_exports.string().trim().min(1).max(COMMAND_WATCH_COMMAND_MAX),
15722
+ /** What it watches, in the worker's words — the name on its row and drawer, and the label on every wake.
15723
+ * Required (2026-11-03), as a sub-agent's description is: without one the row could only show the script. */
15724
+ description: external_exports.string().trim().min(1).max(MONITOR_DESCRIPTION_MAX),
15725
+ /** How long to keep it running, as a DURATION. Clamped to COMMAND_WATCH_FOR_MAX_MS and reported. */
15726
+ for: external_exports.string().trim().min(1).max(16)
15727
+ }).strict();
15728
+ AddOwnMonitorResult = external_exports.object({
15729
+ /** Present when the call was REFUSED: the gate, the caps, or a script that could not run here. Nothing
15730
+ * is armed, and the text says why and what to use instead. */
15731
+ refused: external_exports.string().optional(),
15732
+ id: external_exports.string().optional(),
15733
+ /** This exact command already runs as a monitor on this thread; nothing new was registered. */
15734
+ alreadyArmed: external_exports.boolean().default(false),
15735
+ /** Still running when registration stopped watching it (MONITOR_REGISTRATION_WINDOW_MS). */
15736
+ running: external_exports.boolean().default(false),
15737
+ /** The events it printed while registration watched — handed back here rather than woken. */
15738
+ events: external_exports.array(external_exports.string()).default([]),
15739
+ /** It EXITED while registration watched: how, and the end of what it printed. Nothing stays armed. */
15740
+ exited: CommandWatchRun.optional(),
15741
+ expiresAt: external_exports.string().optional(),
15742
+ /** The `for` the worker wrote, present ONLY when it was clamped. */
15743
+ clamped: external_exports.object({ for: external_exports.string() }).strict().optional(),
15744
+ watches: external_exports.array(CommandWatchView)
15745
+ }).strict();
15746
+ MONITOR_FALLBACK = "Run the script with Claude Code's Monitor tool, or in a background shell, instead.";
15747
+ MONITOR_EVENT_TRAILER = "The monitor is still running and wakes you again on its next line. Drop it with `frizzctl monitor drop <id>` once you no longer need it.";
15748
+ MONITOR_EXITED_TRAILER = "Its script ended, so nothing more will come from it. If you still need the watch, find out why it stopped and register it again with `frizzctl monitor add`.";
15749
+ MONITOR_EXPIRED_TRAILER = "If you still need the watch, register it again with `frizzctl monitor add` and a fresh `--for`. If it was the only thing you were waiting on, end in a proper terminal state instead of parking on it again.";
15750
+ MONITOR_CANCELLED_TRAILER = "Nothing about it will wake you now.";
15751
+ MONITOR_FLOOD_REASON = `it printed ${MONITOR_FLOOD_MAX_EVENTS} events inside ${formatElapsed(MONITOR_FLOOD_WINDOW_MS)}, and every event is a turn of yours. Register it again with a tighter filter: print only the lines you would act on (\`grep --line-buffered\`), never raw logs.`;
15752
+ MONITOR_STOPPED_BY_HUMAN_REASON = "register it again only if they ask for it.";
15599
15753
  QUESTION_FENCE_RETIRED_AT = "2026-09-11T17:30:00Z";
15600
15754
  NEEDS_INPUT_REQUIRED_AT = "2026-10-02T00:48:00Z";
15601
15755
  AskQuestionKind = external_exports.enum(["question", "multi"]);
@@ -16127,6 +16281,10 @@ ${ANSWER_CONTINUATION_INDENT}`);
16127
16281
  // `tokens` legitimately DROPS after a compaction — the context really did get smaller.
16128
16282
  context: external_exports.object({ tokens: external_exports.number(), window: external_exports.number() }).optional()
16129
16283
  });
16284
+ SPINNING_UP_TITLE = "Spinning up a thread\u2026";
16285
+ UNTITLED_THREAD_TITLE = "Untitled thread";
16286
+ SPIN_UP_MS = 6e4;
16287
+ CODEX_TITLE_SIGNAL_GRACE_MS = 15e3;
16130
16288
  BoardErrorItem = external_exports.object({
16131
16289
  file: external_exports.string(),
16132
16290
  kind: external_exports.enum(["no-frontmatter", "other"]),
@@ -16618,6 +16776,59 @@ ${ANSWER_CONTINUATION_INDENT}`);
16618
16776
  * agent to read out the current set of watchers and questions?"). */
16619
16777
  questions: external_exports.array(RegisteredQuestionView).default([])
16620
16778
  }).strict();
16779
+ ThreadBand = external_exports.enum(["rested", "active", "snoozed", "done"]);
16780
+ ThreadListing = external_exports.object({
16781
+ slug: ThreadSlug,
16782
+ /** The title the sidebar shows (displayTitle). */
16783
+ title: external_exports.string(),
16784
+ band: ThreadBand,
16785
+ runtime: RuntimeState,
16786
+ backend: Backend.optional(),
16787
+ model: external_exports.string().optional(),
16788
+ /** The human pinned it to the top of this board's sidebar. */
16789
+ pinned: external_exports.literal(true).optional(),
16790
+ /** The caption of the tool call in flight, while a turn is running ("Running the focused tests"). */
16791
+ doing: external_exports.string().optional(),
16792
+ /** The first line of its newest message — the verdict line of a handoff. Capped. */
16793
+ lastLine: external_exports.string().optional(),
16794
+ /** The signal fence its last rest ended on, while the board still reads it. */
16795
+ fence: external_exports.enum(["done", "awaiting"]).optional(),
16796
+ /** Questions standing at its current rest (hasStandingQuestion's rule), plus a native ask or a
16797
+ * permission prompt the human has not answered. */
16798
+ questions: external_exports.number().int(),
16799
+ /** Its own sub-agents still running (direct children only, as the board counts them). */
16800
+ subAgents: external_exports.number().int(),
16801
+ /** Background shells still running. */
16802
+ shells: external_exports.number().int(),
16803
+ /** What its armed watches are on: `owner/repo#N` for a PR or issue, the prompt for a timer, the
16804
+ * command for a command watch. */
16805
+ watches: external_exports.array(external_exports.string()),
16806
+ /** Killed by a usage limit, waiting for the window to reset. */
16807
+ limited: external_exports.literal(true).optional(),
16808
+ /** Its process is gone with the turn unfinished. */
16809
+ crashed: external_exports.literal(true).optional(),
16810
+ spawnedAt: external_exports.string().optional(),
16811
+ /** When its own turn last came to rest (ThreadView.lastAssistantAt). */
16812
+ restedAt: external_exports.string().optional(),
16813
+ lastActivityAt: external_exports.string().optional(),
16814
+ /** A wall-clock snooze still in the future. */
16815
+ snoozedUntil: external_exports.string().optional(),
16816
+ archivedAt: external_exports.string().optional()
16817
+ }).strict();
16818
+ ListThreadsInput = external_exports.object({
16819
+ /** Another project's board — its slug, id or registered name — instead of the one the call lands on. */
16820
+ project: external_exports.string().trim().min(1).optional(),
16821
+ /** Include the Done band (archived threads), which on a long-lived board is nearly every thread. */
16822
+ all: external_exports.boolean().optional()
16823
+ }).strict();
16824
+ ListThreadsResult = external_exports.object({
16825
+ /** The board's project: its URL slug, its registry id, and the name the board shows. */
16826
+ project: external_exports.object({ slug: external_exports.string(), id: external_exports.string(), name: external_exports.string() }).strict(),
16827
+ /** Rested, then active, then snoozed, then done; newest activity first within each. */
16828
+ threads: external_exports.array(ThreadListing),
16829
+ /** Every band's size, the Done band's included when its threads are not listed. */
16830
+ counts: external_exports.object({ rested: external_exports.number().int(), active: external_exports.number().int(), snoozed: external_exports.number().int(), done: external_exports.number().int() }).strict()
16831
+ }).strict();
16621
16832
  SetOwnThreadTimerResult = external_exports.object({
16622
16833
  id: external_exports.string(),
16623
16834
  fireAt: external_exports.string(),
@@ -21365,7 +21576,18 @@ function ensureStorageSchema(db2) {
21365
21576
  } catch {
21366
21577
  }
21367
21578
  }
21368
- for (const [table, column] of [["pr_watch", "kind TEXT NOT NULL DEFAULT 'pull'"], ["thread_question", "delivery_id TEXT"], ["thread_question", "handle TEXT"]]) {
21579
+ for (const [table, column] of [
21580
+ ["pr_watch", "kind TEXT NOT NULL DEFAULT 'pull'"],
21581
+ ["thread_question", "delivery_id TEXT"],
21582
+ ["thread_question", "handle TEXT"],
21583
+ ["command_watch", "kind TEXT NOT NULL DEFAULT 'check'"],
21584
+ ["command_watch", "description TEXT"],
21585
+ ["command_watch", "events INTEGER NOT NULL DEFAULT 0"],
21586
+ ["command_watch", "last_event_at INTEGER"],
21587
+ ["command_watch", "last_event TEXT"],
21588
+ ["command_watch", "pid INTEGER"],
21589
+ ["command_watch", "pid_started_at INTEGER"]
21590
+ ]) {
21369
21591
  try {
21370
21592
  db2.exec(`ALTER TABLE ${table} ADD COLUMN ${column}`);
21371
21593
  } catch {
@@ -21887,6 +22109,25 @@ function createStorage(source, projectId) {
21887
22109
  WHERE project_id = @project_id AND id = ? AND state = 'armed'
21888
22110
  `);
21889
22111
  const delCommandWatches = scope.prepare("DELETE FROM command_watch WHERE project_id = @project_id AND thread_slug = ?");
22112
+ const armMonitorStmt = scope.prepare(`
22113
+ INSERT INTO command_watch (project_id, id, thread_slug, command, every_ms, state, created_at, expires_at, settled_at,
22114
+ runs, kind, description, events)
22115
+ VALUES (@project_id, @id, @slug, @command, 0, 'armed', @createdAtMs, @expiresAtMs, NULL, 0, 'monitor', @description, 0)
22116
+ RETURNING *
22117
+ `);
22118
+ const noteMonitorStartStmt = scope.prepare(`
22119
+ UPDATE command_watch SET runs = runs + 1, pid = ?, pid_started_at = ?
22120
+ WHERE project_id = @project_id AND id = ? AND state = 'armed' AND kind = 'monitor'
22121
+ `);
22122
+ const recordMonitorEventStmt = scope.prepare(`
22123
+ UPDATE command_watch SET events = events + 1, last_event_at = ?, last_event = ?
22124
+ WHERE project_id = @project_id AND id = ? AND state = 'armed' AND kind = 'monitor'
22125
+ RETURNING events
22126
+ `);
22127
+ const recordMonitorExitStmt = scope.prepare(`
22128
+ UPDATE command_watch SET pid = NULL, pid_started_at = NULL, last_run_at = ?, last_outcome = ?, last_exit = ?, last_output = ?
22129
+ WHERE project_id = @project_id AND id = ? AND kind = 'monitor'
22130
+ `);
21890
22131
  const upsertThreadLinkStmt = scope.prepare(`
21891
22132
  INSERT INTO thread_link (project_id, id, thread_slug, kind, label, target, created_at)
21892
22133
  VALUES (@project_id, @id, @slug, @kind, @label, @target, @createdAtMs)
@@ -22535,6 +22776,17 @@ function createStorage(source, projectId) {
22535
22776
  recordCommandWatchRun: (id2, run3) => recordCommandWatchRunStmt.run(run3.atMs, run3.outcome, run3.exitCode, run3.output, id2).changes === 1,
22536
22777
  dropCommandWatch: (slug, id2, settledAtMs) => dropCommandWatchStmt.run(settledAtMs, id2, slug).changes === 1,
22537
22778
  settleCommandWatch: (id2, state, settledAtMs) => settleCommandWatchStmt.run(state, settledAtMs, id2).changes === 1,
22779
+ armMonitor: (monitor) => armMonitorStmt.get({
22780
+ id: monitor.id,
22781
+ slug: monitor.slug,
22782
+ command: monitor.command,
22783
+ description: monitor.description?.trim() || null,
22784
+ createdAtMs: monitor.createdAtMs,
22785
+ expiresAtMs: monitor.expiresAtMs
22786
+ }),
22787
+ noteMonitorStart: (id2, pid, startedAtMs) => noteMonitorStartStmt.run(pid, pid === null ? null : startedAtMs, id2).changes === 1,
22788
+ recordMonitorEvent: (id2, event) => recordMonitorEventStmt.get(event.atMs, event.text, id2)?.events,
22789
+ recordMonitorExit: (id2, run3) => recordMonitorExitStmt.run(run3.atMs, run3.outcome, run3.exitCode, run3.output, id2).changes === 1,
22538
22790
  upsertThreadLink: (link) => upsertThreadLinkStmt.get(link),
22539
22791
  listThreadLinks: (slug) => threadLinksBySlugStmt.all(slug),
22540
22792
  threadLinksBySlug: () => registryBySlug("thread_link", () => groupBySlug(threadLinksStmt.all()), sameRows),
@@ -39867,11 +40119,482 @@ var init_question_fences = __esm({
39867
40119
  }
39868
40120
  });
39869
40121
 
40122
+ // packages/server/src/command-watch.ts
40123
+ import { execFileSync as execFileSync5, spawn as spawn5 } from "node:child_process";
40124
+ import { appendFileSync as appendFileSync4, existsSync as existsSync11, mkdirSync as mkdirSync17, readdirSync as readdirSync9, readFileSync as readFileSync20, rmSync as rmSync10, statSync as statSync15, writeFileSync as writeFileSync13 } from "node:fs";
40125
+ import { homedir as homedir11, userInfo } from "node:os";
40126
+ import { join as join30 } from "node:path";
40127
+ import { StringDecoder as StringDecoder4 } from "node:string_decoder";
40128
+ function killGroup(pid, signal) {
40129
+ if (!pid) return;
40130
+ try {
40131
+ process.kill(-pid, signal);
40132
+ } catch {
40133
+ }
40134
+ }
40135
+ function outputTail(chunks, max = COMMAND_WATCH_OUTPUT_MAX_BYTES) {
40136
+ const all = Buffer.concat(chunks);
40137
+ if (all.length <= max) return all.toString("utf8");
40138
+ let start = all.length - max;
40139
+ while (start < all.length && (all[start] & 192) === 128) start++;
40140
+ return `\u2026${all.subarray(start).toString("utf8")}`;
40141
+ }
40142
+ function runWatchCommand(spec) {
40143
+ const startedAtMs = Date.now();
40144
+ const timeoutMs = spec.timeoutMs ?? COMMAND_WATCH_RUN_TIMEOUT_MS;
40145
+ return new Promise((resolve14) => {
40146
+ const chunks = [];
40147
+ let held = 0;
40148
+ const keep = (chunk2) => {
40149
+ chunks.push(chunk2);
40150
+ held += chunk2.length;
40151
+ while (held - chunks[0].length >= COMMAND_WATCH_OUTPUT_MAX_BYTES && chunks.length > 1) held -= chunks.shift().length;
40152
+ };
40153
+ let settled = false;
40154
+ let timedOut2 = false;
40155
+ let aborted = false;
40156
+ let exit = null;
40157
+ const timers = [];
40158
+ const finish = (result, extra) => {
40159
+ if (settled) return;
40160
+ settled = true;
40161
+ for (const t of timers) clearTimeout(t);
40162
+ spec.signal?.removeEventListener("abort", onAbort);
40163
+ const output = outputTail(extra ? [...chunks, Buffer.from(extra)] : chunks);
40164
+ resolve14({ ...result, output, startedAtMs, finishedAtMs: Date.now() });
40165
+ };
40166
+ let child;
40167
+ try {
40168
+ child = spawn5("/bin/sh", ["-c", spec.command], {
40169
+ cwd: spec.cwd,
40170
+ env: spec.env,
40171
+ stdio: ["ignore", "pipe", "pipe"],
40172
+ detached: true,
40173
+ windowsHide: true
40174
+ });
40175
+ } catch (err) {
40176
+ finish({ outcome: "error", exitCode: null }, `could not start /bin/sh: ${err instanceof Error ? err.message : String(err)}`);
40177
+ return;
40178
+ }
40179
+ const onAbort = () => {
40180
+ aborted = true;
40181
+ killGroup(child.pid, "SIGKILL");
40182
+ };
40183
+ if (spec.signal?.aborted) onAbort();
40184
+ else spec.signal?.addEventListener("abort", onAbort, { once: true });
40185
+ child.stdout?.on("data", keep);
40186
+ child.stderr?.on("data", keep);
40187
+ child.on("error", (err) => {
40188
+ finish({ outcome: "error", exitCode: null }, `could not start /bin/sh: ${err.message}`);
40189
+ });
40190
+ timers.push(setTimeout(() => {
40191
+ timedOut2 = true;
40192
+ killGroup(child.pid, "SIGTERM");
40193
+ timers.push(setTimeout(() => killGroup(child.pid, "SIGKILL"), KILL_GRACE_MS));
40194
+ }, timeoutMs));
40195
+ const conclude = () => {
40196
+ if (!exit) return;
40197
+ if (timedOut2) finish({ outcome: "timeout", exitCode: null });
40198
+ else if (aborted || exit.signal) finish({ outcome: "signal", exitCode: null });
40199
+ else finish({ outcome: "exit", exitCode: exit.code });
40200
+ };
40201
+ child.on("exit", (code, signal) => {
40202
+ exit = { code, signal };
40203
+ killGroup(child.pid, "SIGKILL");
40204
+ timers.push(setTimeout(() => {
40205
+ child.stdout?.destroy();
40206
+ child.stderr?.destroy();
40207
+ conclude();
40208
+ }, DRAIN_AFTER_EXIT_MS));
40209
+ });
40210
+ child.on("close", conclude);
40211
+ });
40212
+ }
40213
+ function createRunLimiter(limit) {
40214
+ let active = 0;
40215
+ const waiting = [];
40216
+ return async (fn) => {
40217
+ if (active < limit) active++;
40218
+ else await new Promise((resolve14) => waiting.push(resolve14));
40219
+ try {
40220
+ return await fn();
40221
+ } finally {
40222
+ const next = waiting.shift();
40223
+ if (next) next();
40224
+ else active--;
40225
+ }
40226
+ };
40227
+ }
40228
+ function claudeManagedPreferencePaths() {
40229
+ let user = "";
40230
+ try {
40231
+ user = userInfo().username;
40232
+ } catch {
40233
+ }
40234
+ return [
40235
+ ...user ? [`/Library/Managed Preferences/${user}/com.anthropic.claudecode.plist`] : [],
40236
+ "/Library/Managed Preferences/com.anthropic.claudecode.plist"
40237
+ ];
40238
+ }
40239
+ function plistAsJson(path3) {
40240
+ return execFileSync5("/usr/bin/plutil", ["-convert", "json", "-o", "-", "--", path3], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
40241
+ }
40242
+ function sandboxInSettings(raw2, file) {
40243
+ let parsed;
40244
+ try {
40245
+ parsed = JSON.parse(raw2);
40246
+ } catch {
40247
+ return `\`${file}\` is not valid JSON, so Frizz cannot tell whether it turns Claude Code's sandbox on for this thread`;
40248
+ }
40249
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
40250
+ const sandbox = parsed.sandbox;
40251
+ if (sandbox === void 0 || sandbox === null || sandbox === false) return void 0;
40252
+ if (typeof sandbox === "object" && !Array.isArray(sandbox)) {
40253
+ const enabled = sandbox.enabled;
40254
+ if (enabled === void 0 || enabled === false) return void 0;
40255
+ }
40256
+ return `Claude Code's sandbox is on for this thread (\`sandbox\` in \`${file}\`), and a command watch would run your command outside it`;
40257
+ }
40258
+ function claudeSettingsFiles(where) {
40259
+ const env = where.env ?? process.env;
40260
+ const configDir = env.CLAUDE_CONFIG_DIR?.trim() ? env.CLAUDE_CONFIG_DIR.trim() : join30(where.home ?? homedir11(), ".claude");
40261
+ return [
40262
+ ...where.managedPaths ?? CLAUDE_MANAGED_SETTINGS_PATHS,
40263
+ join30(where.cwd, ".claude", "settings.local.json"),
40264
+ join30(where.cwd, ".claude", "settings.json"),
40265
+ join30(configDir, "settings.json")
40266
+ ];
40267
+ }
40268
+ function claudeSandboxRefusal(where) {
40269
+ for (const file of claudeSettingsFiles(where)) {
40270
+ let raw2;
40271
+ try {
40272
+ raw2 = readFileSync20(file, "utf8");
40273
+ } catch (err) {
40274
+ if (err?.code === "ENOENT" || err?.code === "ENOTDIR") continue;
40275
+ return `Frizz could not read \`${file}\` to check whether Claude Code's sandbox is on for this thread`;
40276
+ }
40277
+ const refusal = sandboxInSettings(raw2, file);
40278
+ if (refusal) return refusal;
40279
+ }
40280
+ const preferences = where.managedPreferencePaths ?? (process.platform === "darwin" ? claudeManagedPreferencePaths() : []);
40281
+ for (const file of preferences) {
40282
+ if (!existsSync11(file)) continue;
40283
+ let raw2;
40284
+ try {
40285
+ raw2 = (where.readPlistJson ?? plistAsJson)(file);
40286
+ } catch {
40287
+ return `Frizz could not read \`${file}\` to check whether Claude Code's sandbox is on for this thread`;
40288
+ }
40289
+ const refusal = sandboxInSettings(raw2, file);
40290
+ if (refusal) return refusal;
40291
+ }
40292
+ return void 0;
40293
+ }
40294
+ function commandWatchRefusal(row, opts) {
40295
+ const refuse = (reason) => `${reason}. ${COMMAND_WATCH_FALLBACK}`;
40296
+ if ((opts.platform ?? process.platform) === "win32") {
40297
+ return refuse("command watches run under `/bin/sh`, which this machine does not have");
40298
+ }
40299
+ const backend = row.backend ?? "claude";
40300
+ if (backend !== "claude") {
40301
+ return refuse(
40302
+ `command watches are for Claude threads only, and this one runs on ${backend === "codex" ? "Codex" : "an ACP agent"}: Frizz cannot tell whether your thread's own sandbox would have let the command run`
40303
+ );
40304
+ }
40305
+ if (row.permission_mode !== "bypassPermissions") {
40306
+ return refuse(
40307
+ `this thread runs in \`${row.permission_mode ?? "an unrecorded"}\` permission mode, and the server runs a watched command with no permission check at all \u2014 so Frizz runs one only for a thread in \`bypassPermissions\` mode`
40308
+ );
40309
+ }
40310
+ if (row.permission_pending && row.permission_pending !== "bypassPermissions") {
40311
+ return refuse(`this thread's permission mode is being changed to \`${row.permission_pending}\``);
40312
+ }
40313
+ const sandbox = claudeSandboxRefusal({ cwd: opts.cwd, env: opts.env, home: opts.home, managedPaths: opts.managedPaths, managedPreferencePaths: opts.managedPreferencePaths, readPlistJson: opts.readPlistJson });
40314
+ if (sandbox) return refuse(sandbox);
40315
+ return void 0;
40316
+ }
40317
+ function startMonitorProcess(spec) {
40318
+ const startedAtMs = Date.now();
40319
+ const batchMs = spec.batchMs ?? MONITOR_BATCH_MS;
40320
+ const tail = [];
40321
+ let tailHeld = 0;
40322
+ const keepTail = (chunk2) => {
40323
+ tail.push(chunk2);
40324
+ tailHeld += chunk2.length;
40325
+ while (tailHeld - tail[0].length >= COMMAND_WATCH_OUTPUT_MAX_BYTES && tail.length > 1) tailHeld -= tail.shift().length;
40326
+ };
40327
+ let batch = [];
40328
+ let more = 0;
40329
+ let batchTimer = null;
40330
+ const flush = () => {
40331
+ if (batchTimer) clearTimeout(batchTimer);
40332
+ batchTimer = null;
40333
+ if (batch.length === 0 && more === 0) return;
40334
+ const event = { lines: batch, more };
40335
+ batch = [];
40336
+ more = 0;
40337
+ try {
40338
+ spec.onEvent(event);
40339
+ } catch {
40340
+ }
40341
+ };
40342
+ const pushLine = (raw2) => {
40343
+ const line = raw2.replace(/\r$/, "");
40344
+ if (!line.trim()) return;
40345
+ if (batch.length < MONITOR_EVENT_MAX_LINES) {
40346
+ batch.push(line.length > MONITOR_LINE_MAX_CHARS ? `${line.slice(0, MONITOR_LINE_MAX_CHARS)}\u2026` : line);
40347
+ } else {
40348
+ more++;
40349
+ }
40350
+ if (!batchTimer) batchTimer = setTimeout(flush, batchMs);
40351
+ };
40352
+ const decoder = new StringDecoder4("utf8");
40353
+ let partial = "";
40354
+ let overlong = false;
40355
+ const readStdout = (text2) => {
40356
+ let rest = text2;
40357
+ for (; ; ) {
40358
+ const nl2 = rest.indexOf("\n");
40359
+ if (nl2 === -1) break;
40360
+ const piece = rest.slice(0, nl2);
40361
+ rest = rest.slice(nl2 + 1);
40362
+ if (overlong) {
40363
+ overlong = false;
40364
+ pushLine(partial);
40365
+ } else {
40366
+ pushLine(partial + piece);
40367
+ }
40368
+ partial = "";
40369
+ }
40370
+ if (overlong) return;
40371
+ partial += rest;
40372
+ if (partial.length > MONITOR_LINE_MAX_CHARS) {
40373
+ partial = partial.slice(0, MONITOR_LINE_MAX_CHARS + 1);
40374
+ overlong = true;
40375
+ }
40376
+ };
40377
+ let child;
40378
+ let resolveDone;
40379
+ const done = new Promise((resolve14) => {
40380
+ resolveDone = resolve14;
40381
+ });
40382
+ let settled = false;
40383
+ let stopping = false;
40384
+ const timers = [];
40385
+ const finish = (outcome, exitCode, extra) => {
40386
+ if (settled) return;
40387
+ settled = true;
40388
+ for (const t of timers) clearTimeout(t);
40389
+ const last = partial + (overlong ? "" : decoder.end());
40390
+ partial = "";
40391
+ if (last) pushLine(last);
40392
+ flush();
40393
+ if (extra) keepTail(Buffer.from(extra));
40394
+ resolveDone({ outcome, exitCode, output: outputTail(tail), startedAtMs, finishedAtMs: Date.now() });
40395
+ };
40396
+ try {
40397
+ child = spawn5("/bin/sh", ["-c", spec.command], {
40398
+ cwd: spec.cwd,
40399
+ env: spec.env,
40400
+ stdio: ["ignore", "pipe", "pipe"],
40401
+ detached: true,
40402
+ windowsHide: true
40403
+ });
40404
+ } catch (err) {
40405
+ finish("error", null, `could not start /bin/sh: ${err instanceof Error ? err.message : String(err)}`);
40406
+ return { pid: void 0, stop: () => {
40407
+ }, done };
40408
+ }
40409
+ const output = (chunk2) => {
40410
+ try {
40411
+ spec.onOutput?.(chunk2);
40412
+ } catch {
40413
+ }
40414
+ };
40415
+ child.stdout?.on("data", (chunk2) => {
40416
+ keepTail(chunk2);
40417
+ output(chunk2);
40418
+ readStdout(decoder.write(chunk2));
40419
+ });
40420
+ child.stderr?.on("data", (chunk2) => {
40421
+ keepTail(chunk2);
40422
+ output(chunk2);
40423
+ });
40424
+ child.on("error", (err) => finish("error", null, `could not start /bin/sh: ${err.message}`));
40425
+ let exit = null;
40426
+ const conclude = () => {
40427
+ if (!exit) return;
40428
+ if (stopping || exit.signal) finish("signal", null);
40429
+ else finish("exit", exit.code);
40430
+ };
40431
+ child.on("exit", (code, signal) => {
40432
+ exit = { code, signal };
40433
+ killGroup(child.pid, "SIGKILL");
40434
+ timers.push(setTimeout(() => {
40435
+ child.stdout?.destroy();
40436
+ child.stderr?.destroy();
40437
+ conclude();
40438
+ }, DRAIN_AFTER_EXIT_MS));
40439
+ });
40440
+ child.on("close", conclude);
40441
+ return {
40442
+ pid: child.pid,
40443
+ stop() {
40444
+ if (settled || stopping) return;
40445
+ stopping = true;
40446
+ killGroup(child.pid, "SIGTERM");
40447
+ timers.push(setTimeout(() => killGroup(child.pid, "SIGKILL"), KILL_GRACE_MS));
40448
+ },
40449
+ done
40450
+ };
40451
+ }
40452
+ function monitorOutputPath(dir, id2) {
40453
+ return join30(dir, `${id2.replace(/[^A-Za-z0-9_-]/g, "")}.log`);
40454
+ }
40455
+ function monitorOutputSink(path3, maxBytes = MONITOR_OUTPUT_MAX_BYTES, nowIso = () => (/* @__PURE__ */ new Date()).toISOString()) {
40456
+ let size = 0;
40457
+ try {
40458
+ mkdirSync17(join30(path3, ".."), { recursive: true });
40459
+ size = existsSync11(path3) ? statSync15(path3).size : 0;
40460
+ if (size > 0) {
40461
+ const marker = Buffer.from(`
40462
+ [Frizz started the script again at ${nowIso()}]
40463
+ `);
40464
+ appendFileSync4(path3, marker);
40465
+ size += marker.length;
40466
+ } else {
40467
+ writeFileSync13(path3, "");
40468
+ }
40469
+ } catch {
40470
+ }
40471
+ return (chunk2) => {
40472
+ appendFileSync4(path3, chunk2);
40473
+ size += chunk2.length;
40474
+ if (size <= maxBytes) return;
40475
+ const kept = readFileSync20(path3).subarray(-Math.floor(maxBytes / 2));
40476
+ writeFileSync13(path3, kept);
40477
+ size = kept.length;
40478
+ };
40479
+ }
40480
+ function pruneMonitorOutputs(dir, rowOf, nowMs, keepMs = MONITOR_OUTPUT_KEEP_MS) {
40481
+ let names;
40482
+ try {
40483
+ names = readdirSync9(dir);
40484
+ } catch {
40485
+ return [];
40486
+ }
40487
+ return names.flatMap((name) => {
40488
+ const id2 = /^(cmw_[A-Za-z0-9_-]+)\.log$/.exec(name)?.[1];
40489
+ if (!id2) return [];
40490
+ const row = rowOf(id2);
40491
+ if (row && (row.state === "armed" || (row.settled_at ?? nowMs) + keepMs > nowMs)) return [];
40492
+ rmSync10(join30(dir, name), { force: true });
40493
+ return [id2];
40494
+ });
40495
+ }
40496
+ function reapStaleMonitor(pid, startedAtMs, readPs = psLine, nowMs = Date.now()) {
40497
+ if (!Number.isInteger(pid) || pid <= 1 || !Number.isFinite(startedAtMs)) return false;
40498
+ const line = readPs(pid)?.trim();
40499
+ if (!line) return false;
40500
+ const match2 = /^(\d+)\s+(\S+)$/.exec(line);
40501
+ if (!match2 || Number(match2[1]) !== pid) return false;
40502
+ const elapsed = psElapsedMs(match2[2]);
40503
+ if (elapsed === void 0 || Math.abs(nowMs - elapsed - startedAtMs) > MONITOR_START_TOLERANCE_MS) return false;
40504
+ killGroup(pid, "SIGKILL");
40505
+ return true;
40506
+ }
40507
+ function psElapsedMs(etime) {
40508
+ const match2 = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(etime.trim());
40509
+ if (!match2) return void 0;
40510
+ const [, d = "0", h2 = "0", m, s] = match2;
40511
+ return (((Number(d) * 24 + Number(h2)) * 60 + Number(m)) * 60 + Number(s)) * 1e3;
40512
+ }
40513
+ function psLine(pid) {
40514
+ try {
40515
+ return execFileSync5("/bin/ps", ["-o", "pgid=,etime=", "-p", String(pid)], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
40516
+ } catch {
40517
+ return void 0;
40518
+ }
40519
+ }
40520
+ function monitorStatusOf(w) {
40521
+ return {
40522
+ ...w.description ? { description: w.description } : {},
40523
+ events: w.events,
40524
+ ...w.last_event_at !== null && w.last_event !== null ? { lastEvent: { at: new Date(w.last_event_at).toISOString(), text: w.last_event } } : {}
40525
+ };
40526
+ }
40527
+ function monitorEndedLabel(w) {
40528
+ if (w.state === "passed") {
40529
+ if (w.last_outcome === "exit") return `exited ${w.last_exit ?? "?"}`;
40530
+ return w.last_outcome === "signal" ? "killed" : "could not run";
40531
+ }
40532
+ if (w.state === "expired") return "expired";
40533
+ if (w.state === "dropped") return "dropped";
40534
+ return "stopped";
40535
+ }
40536
+ function createCommandWatchService(opts) {
40537
+ const runner = opts.runner ?? runWatchCommand;
40538
+ const limiter = opts.limiter ?? serverRunLimiter;
40539
+ let probesActive = 0;
40540
+ return {
40541
+ refusal: (row) => commandWatchRefusal(row, { cwd: opts.cwd, ...opts.gate }),
40542
+ run: (slug, command, runOpts) => limiter(() => runner({ command, cwd: opts.cwd, env: opts.env(slug), timeoutMs: COMMAND_WATCH_RUN_TIMEOUT_MS, signal: runOpts?.signal })),
40543
+ async probe(slug, command) {
40544
+ if (probesActive >= PROBE_CONCURRENCY) return void 0;
40545
+ probesActive++;
40546
+ try {
40547
+ return await runner({ command, cwd: opts.cwd, env: opts.env(slug), timeoutMs: COMMAND_WATCH_PROBE_TIMEOUT_MS });
40548
+ } finally {
40549
+ probesActive--;
40550
+ }
40551
+ },
40552
+ startMonitor(slug, command, onEvent, id2) {
40553
+ if (monitorsRunning >= MONITOR_SERVER_MAX_RUNNING) return void 0;
40554
+ monitorsRunning++;
40555
+ const onOutput = opts.monitorOutputDir && id2 ? monitorOutputSink(monitorOutputPath(opts.monitorOutputDir, id2)) : void 0;
40556
+ const proc = (opts.startMonitorProcess ?? startMonitorProcess)({ command, cwd: opts.cwd, env: opts.env(slug), onEvent, onOutput, batchMs: opts.monitorBatchMs });
40557
+ void proc.done.finally(() => {
40558
+ monitorsRunning--;
40559
+ });
40560
+ return proc;
40561
+ },
40562
+ monitorsRunning: () => monitorsRunning,
40563
+ reapStaleMonitor: (pid, startedAtMs) => reapStaleMonitor(pid, startedAtMs, opts.readPs),
40564
+ pruneMonitorOutputs: (rowOf, nowMs) => opts.monitorOutputDir ? pruneMonitorOutputs(opts.monitorOutputDir, rowOf, nowMs) : []
40565
+ };
40566
+ }
40567
+ function commandWatchEnvironment(base, frizz) {
40568
+ const { FRIZZ_THREAD: _tag, ...rest } = base;
40569
+ return { ...rest, ...frizz, GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1" };
40570
+ }
40571
+ var KILL_GRACE_MS, DRAIN_AFTER_EXIT_MS, COMMAND_WATCH_SERVER_CONCURRENCY, serverRunLimiter, COMMAND_WATCH_PROBE_TIMEOUT_MS, PROBE_CONCURRENCY, CLAUDE_MANAGED_SETTINGS_PATHS, MONITOR_OUTPUT_MAX_BYTES, MONITOR_OUTPUT_KEEP_MS, monitorsRunning, MONITOR_START_TOLERANCE_MS;
40572
+ var init_command_watch = __esm({
40573
+ "packages/server/src/command-watch.ts"() {
40574
+ "use strict";
40575
+ init_src();
40576
+ KILL_GRACE_MS = 2e3;
40577
+ DRAIN_AFTER_EXIT_MS = 1e3;
40578
+ COMMAND_WATCH_SERVER_CONCURRENCY = 4;
40579
+ serverRunLimiter = createRunLimiter(COMMAND_WATCH_SERVER_CONCURRENCY);
40580
+ COMMAND_WATCH_PROBE_TIMEOUT_MS = 15e3;
40581
+ PROBE_CONCURRENCY = 2;
40582
+ CLAUDE_MANAGED_SETTINGS_PATHS = [
40583
+ "/Library/Application Support/ClaudeCode/managed-settings.json",
40584
+ "/etc/claude-code/managed-settings.json"
40585
+ ];
40586
+ MONITOR_OUTPUT_MAX_BYTES = 1024 * 1024;
40587
+ MONITOR_OUTPUT_KEEP_MS = 24 * 60 * 6e4;
40588
+ monitorsRunning = 0;
40589
+ MONITOR_START_TOLERANCE_MS = 5e3;
40590
+ }
40591
+ });
40592
+
39870
40593
  // packages/server/src/local-file.ts
39871
- import { spawn as spawn5 } from "node:child_process";
39872
- import { closeSync as closeSync13, existsSync as existsSync11, fstatSync as fstatSync2, openSync as openSync14, readFileSync as readFileSync20, readSync as readSync7, realpathSync as realpathSync7, statSync as statSync15 } from "node:fs";
39873
- import { homedir as homedir11 } from "node:os";
39874
- import { basename as basename5, dirname as dirname12, isAbsolute as isAbsolute5, join as join30, resolve as resolve5, sep as sep2 } from "node:path";
40594
+ import { spawn as spawn6 } from "node:child_process";
40595
+ import { closeSync as closeSync13, existsSync as existsSync12, fstatSync as fstatSync2, openSync as openSync14, readFileSync as readFileSync21, readSync as readSync7, realpathSync as realpathSync7, statSync as statSync16 } from "node:fs";
40596
+ import { homedir as homedir12 } from "node:os";
40597
+ import { basename as basename5, dirname as dirname12, isAbsolute as isAbsolute5, join as join31, resolve as resolve5, sep as sep2 } from "node:path";
39875
40598
  function isUnder(real, root) {
39876
40599
  let rootReal;
39877
40600
  try {
@@ -39883,10 +40606,10 @@ function isUnder(real, root) {
39883
40606
  return real === rootReal || real.startsWith(rootReal.endsWith(sep2) ? rootReal : rootReal + sep2);
39884
40607
  }
39885
40608
  try {
39886
- const trusted2 = statSync15(rootReal, { bigint: true });
40609
+ const trusted2 = statSync16(rootReal, { bigint: true });
39887
40610
  if (!trusted2.isDirectory() || trusted2.ino === 0n) return false;
39888
40611
  for (let ancestor = real; ; ) {
39889
- const actual = statSync15(ancestor, { bigint: true });
40612
+ const actual = statSync16(ancestor, { bigint: true });
39890
40613
  if (actual.dev === trusted2.dev && actual.ino === trusted2.ino) return true;
39891
40614
  const parent = dirname12(ancestor);
39892
40615
  if (parent === ancestor) return false;
@@ -39907,17 +40630,17 @@ function resolveLocalFile(rawPath, roots) {
39907
40630
  }
39908
40631
  if (!roots.some((root) => isUnder(real, root))) throw new Error("Local file is outside Frizz's trusted roots");
39909
40632
  try {
39910
- if (!statSync15(real).isFile()) throw new Error("Local path is not a regular file");
40633
+ if (!statSync16(real).isFile()) throw new Error("Local path is not a regular file");
39911
40634
  } catch (error) {
39912
40635
  if (error instanceof Error && error.message === "Local path is not a regular file") throw error;
39913
40636
  throw new Error("Local file was not found");
39914
40637
  }
39915
40638
  return real;
39916
40639
  }
39917
- function resolveOpenableFile(raw2, projectDir, roots, home = homedir11()) {
40640
+ function resolveOpenableFile(raw2, projectDir, roots, home = homedir12()) {
39918
40641
  const trimmed = raw2.trim().replace(/:\d+(?::\d+)?$/, "");
39919
40642
  if (!trimmed) return null;
39920
- const abs = trimmed === "~" ? home : /^~[\/\\]/.test(trimmed) ? join30(home, trimmed.slice(2)) : isAbsolute5(trimmed) ? trimmed : resolve5(projectDir, trimmed);
40643
+ const abs = trimmed === "~" ? home : /^~[\/\\]/.test(trimmed) ? join31(home, trimmed.slice(2)) : isAbsolute5(trimmed) ? trimmed : resolve5(projectDir, trimmed);
39921
40644
  try {
39922
40645
  return resolveLocalFile(abs, roots);
39923
40646
  } catch {
@@ -39965,7 +40688,7 @@ function readLocalTextFile(rawPath, roots) {
39965
40688
  }
39966
40689
  function resolveServedLocalFile(rawPath, roots) {
39967
40690
  const path3 = resolveLocalFile(rawPath, roots);
39968
- return { path: path3, size: statSync15(path3).size, name: basename5(path3), pdf: PDF_FILE_EXT.test(rawPath.trim()) && PDF_FILE_EXT.test(path3) };
40691
+ return { path: path3, size: statSync16(path3).size, name: basename5(path3), pdf: PDF_FILE_EXT.test(rawPath.trim()) && PDF_FILE_EXT.test(path3) };
39969
40692
  }
39970
40693
  function localFileHeaders(file) {
39971
40694
  const name = encodeURIComponent(file.name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
@@ -39983,7 +40706,7 @@ function readLocalMarkdown(rawPath, roots) {
39983
40706
  if (!MARKDOWN_FILE_EXT.test(rawPath.trim())) throw new Error("Local file is not a Markdown file");
39984
40707
  const path3 = resolveLocalFile(rawPath, roots);
39985
40708
  if (!MARKDOWN_FILE_EXT.test(path3)) throw new Error("Local file is not a Markdown file");
39986
- const bytes = readFileSync20(path3);
40709
+ const bytes = readFileSync21(path3);
39987
40710
  if (bytes.length <= MARKDOWN_READ_LIMIT) return { path: path3, markdown: bytes.toString("utf8"), truncated: false };
39988
40711
  const head = bytes.subarray(0, MARKDOWN_READ_LIMIT);
39989
40712
  const lastBreak = head.lastIndexOf(10);
@@ -39997,7 +40720,7 @@ function resolveWatchableLocalFile(rawPath, roots) {
39997
40720
  return path3;
39998
40721
  }
39999
40722
  function defaultSpawn(command, args, options) {
40000
- return spawn5(command, [...args], options);
40723
+ return spawn6(command, [...args], options);
40001
40724
  }
40002
40725
  async function awaitOpenerStart(child, command) {
40003
40726
  child.unref();
@@ -40018,10 +40741,10 @@ function localFileOpenCommand(path3, selected, options = {}) {
40018
40741
  if (selected === "finder") return { command: "explorer.exe", args: [`/select,${path3}`] };
40019
40742
  const editor = WINDOWS_EDITOR_EXE[selected];
40020
40743
  const env = options.env ?? process.env;
40021
- const exists = options.exists ?? existsSync11;
40744
+ const exists = options.exists ?? existsSync12;
40022
40745
  const localAppData = env.LOCALAPPDATA;
40023
40746
  if (localAppData) {
40024
- const exe2 = join30(localAppData, ...editor.exe);
40747
+ const exe2 = join31(localAppData, ...editor.exe);
40025
40748
  if (exists(exe2)) return { command: exe2, args: [path3] };
40026
40749
  }
40027
40750
  if (/["%\r\n]/u.test(path3)) throw new Error(`cannot hand ${path3} to the ${editor.shim} shim through cmd.exe`);
@@ -40033,7 +40756,8 @@ async function openLocalFile(rawPath, opener, roots, options = {}) {
40033
40756
  const path3 = resolveLocalFile(rawPath, roots);
40034
40757
  const chosen = options.forceSystem ? "system" : opener;
40035
40758
  if (chosen === "copy") return { action: "copy", path: path3 };
40036
- const selected = (chosen === "cursor" || chosen === "vscode") && isBinaryLocalFile(path3) ? "system" : chosen;
40759
+ const editor = chosen === "cursor" || chosen === "vscode";
40760
+ const selected = editor && (HTML_FILE_EXT.test(path3) || isBinaryLocalFile(path3)) ? "system" : chosen;
40037
40761
  const spec = localFileOpenCommand(path3, selected, options);
40038
40762
  const child = (options.spawn ?? defaultSpawn)(spec.command, spec.args, {
40039
40763
  detached: true,
@@ -40045,7 +40769,7 @@ async function openLocalFile(rawPath, opener, roots, options = {}) {
40045
40769
  await awaitOpenerStart(child, spec.command);
40046
40770
  return { action: "opened", path: path3 };
40047
40771
  }
40048
- var MARKDOWN_FILE_EXT, MARKDOWN_READ_LIMIT, PDF_FILE_EXT, SNIFF_BYTES, WINDOWS_EDITOR_EXE;
40772
+ var MARKDOWN_FILE_EXT, MARKDOWN_READ_LIMIT, PDF_FILE_EXT, HTML_FILE_EXT, SNIFF_BYTES, WINDOWS_EDITOR_EXE;
40049
40773
  var init_local_file = __esm({
40050
40774
  "packages/server/src/local-file.ts"() {
40051
40775
  "use strict";
@@ -40053,6 +40777,7 @@ var init_local_file = __esm({
40053
40777
  MARKDOWN_FILE_EXT = /\.(?:md|mdx|markdown)$/i;
40054
40778
  MARKDOWN_READ_LIMIT = 1024 * 1024;
40055
40779
  PDF_FILE_EXT = /\.pdf$/i;
40780
+ HTML_FILE_EXT = /\.html?$/i;
40056
40781
  SNIFF_BYTES = 8192;
40057
40782
  WINDOWS_EDITOR_EXE = {
40058
40783
  cursor: { exe: ["Programs", "cursor", "Cursor.exe"], shim: "cursor" },
@@ -40290,7 +41015,7 @@ var init_claude_model_upgrade = __esm({
40290
41015
  // packages/server/src/frizz.ts
40291
41016
  import { execFile as execFile6 } from "node:child_process";
40292
41017
  import { lstatSync as lstatSync3, realpathSync as realpathSync8 } from "node:fs";
40293
- import { basename as basename6, dirname as dirname13, join as join31, resolve as resolve6 } from "node:path";
41018
+ import { basename as basename6, dirname as dirname13, join as join32, resolve as resolve6 } from "node:path";
40294
41019
  import { promisify as promisify5 } from "node:util";
40295
41020
  function frizzScriptsDir() {
40296
41021
  if (process.env.FRIZZ_SCRIPTS_DIR) return process.env.FRIZZ_SCRIPTS_DIR;
@@ -40299,7 +41024,7 @@ function frizzScriptsDir() {
40299
41024
  function directFrizzRoot(projectDir) {
40300
41025
  try {
40301
41026
  const projectRoot = realpathSync8(projectDir);
40302
- const path3 = join31(projectRoot, ".frizz");
41027
+ const path3 = join32(projectRoot, ".frizz");
40303
41028
  const stat2 = lstatSync3(path3);
40304
41029
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) return null;
40305
41030
  const real = realpathSync8(path3);
@@ -40313,7 +41038,7 @@ function frizzDirExists(projectDir) {
40313
41038
  }
40314
41039
  async function readBoard(projectDir, scriptsDir = frizzScriptsDir()) {
40315
41040
  if (!directFrizzRoot(projectDir)) throw new Error("unsafe or missing .frizz directory");
40316
- const { stdout } = await execFileP("node", [join31(scriptsDir, "index.mjs"), "--json"], {
41041
+ const { stdout } = await execFileP("node", [join32(scriptsDir, "index.mjs"), "--json"], {
40317
41042
  cwd: projectDir,
40318
41043
  env: { ...process.env, CLAUDE_PROJECT_DIR: projectDir },
40319
41044
  maxBuffer: 32 * 1024 * 1024
@@ -40338,7 +41063,7 @@ async function readBoard(projectDir, scriptsDir = frizzScriptsDir()) {
40338
41063
  };
40339
41064
  }
40340
41065
  async function runThreadUpdate(projectDir, slug, args, scriptsDir = frizzScriptsDir()) {
40341
- await execFileP("node", [join31(scriptsDir, "thread-update.mjs"), slug, ...args], {
41066
+ await execFileP("node", [join32(scriptsDir, "thread-update.mjs"), slug, ...args], {
40342
41067
  cwd: projectDir,
40343
41068
  env: { ...process.env, CLAUDE_PROJECT_DIR: projectDir }
40344
41069
  });
@@ -40488,12 +41213,12 @@ var init_awaiting = __esm({
40488
41213
  });
40489
41214
 
40490
41215
  // packages/server/src/backend/project-mcp-servers.ts
40491
- import { readFileSync as readFileSync21 } from "node:fs";
40492
- import { homedir as homedir12 } from "node:os";
40493
- import { join as join32 } from "node:path";
41216
+ import { readFileSync as readFileSync22 } from "node:fs";
41217
+ import { homedir as homedir13 } from "node:os";
41218
+ import { join as join33 } from "node:path";
40494
41219
  function readJsonObject(path3) {
40495
41220
  try {
40496
- const parsed = JSON.parse(readFileSync21(path3, "utf8"));
41221
+ const parsed = JSON.parse(readFileSync22(path3, "utf8"));
40497
41222
  return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
40498
41223
  } catch {
40499
41224
  return void 0;
@@ -40596,17 +41321,17 @@ function userScopeRemoteServers(account, cwd, env) {
40596
41321
  }
40597
41322
  function projectMcpServers(cwd, options = {}) {
40598
41323
  const env = options.env ?? process.env;
40599
- const home = options.home ?? homedir12();
41324
+ const home = options.home ?? homedir13();
40600
41325
  const configOverride = options.claudeConfigDir ?? (env.CLAUDE_CONFIG_DIR?.trim() ? env.CLAUDE_CONFIG_DIR.trim() : void 0);
40601
- const accountFile = configOverride ? join32(configOverride, ".claude.json") : join32(home, ".claude.json");
40602
- const userSettingsFile = join32(configOverride ?? join32(home, ".claude"), "settings.json");
41326
+ const accountFile = configOverride ? join33(configOverride, ".claude.json") : join33(home, ".claude.json");
41327
+ const userSettingsFile = join33(configOverride ?? join33(home, ".claude"), "settings.json");
40603
41328
  const account = readJsonObject(accountFile);
40604
41329
  const out = userScopeRemoteServers(account, cwd, env);
40605
- const declared = objectField(readJsonObject(join32(cwd, ".mcp.json")), "mcpServers");
41330
+ const declared = objectField(readJsonObject(join33(cwd, ".mcp.json")), "mcpServers");
40606
41331
  if (!declared) return out;
40607
41332
  const approval = collectApproval([
40608
- readJsonObject(join32(cwd, ".claude", "settings.json")),
40609
- readJsonObject(join32(cwd, ".claude", "settings.local.json")),
41333
+ readJsonObject(join33(cwd, ".claude", "settings.json")),
41334
+ readJsonObject(join33(cwd, ".claude", "settings.local.json")),
40610
41335
  readJsonObject(userSettingsFile),
40611
41336
  objectField(objectField(account, "projects"), cwd)
40612
41337
  ]);
@@ -40630,17 +41355,17 @@ var init_project_mcp_servers = __esm({
40630
41355
  });
40631
41356
 
40632
41357
  // packages/server/src/worker-plugin-dir.ts
40633
- import { existsSync as existsSync12 } from "node:fs";
40634
- import { dirname as dirname14, join as join33 } from "node:path";
41358
+ import { existsSync as existsSync13 } from "node:fs";
41359
+ import { dirname as dirname14, join as join34 } from "node:path";
40635
41360
  import { fileURLToPath as fileURLToPath3 } from "node:url";
40636
41361
  function resolveWorkerPluginDir(moduleUrl = import.meta.url, env = process.env) {
40637
41362
  const override = env.FRIZZ_WORKER_PLUGIN_DIR;
40638
- if (override && existsSync12(join33(override, ".claude-plugin", "plugin.json")))
41363
+ if (override && existsSync13(join34(override, ".claude-plugin", "plugin.json")))
40639
41364
  return override;
40640
41365
  let current = dirname14(fileURLToPath3(moduleUrl));
40641
41366
  for (; ; ) {
40642
- const candidate = join33(current, "cc-worker");
40643
- if (existsSync12(join33(candidate, ".claude-plugin", "plugin.json"))) return candidate;
41367
+ const candidate = join34(current, "cc-worker");
41368
+ if (existsSync13(join34(candidate, ".claude-plugin", "plugin.json"))) return candidate;
40644
41369
  const parent = dirname14(current);
40645
41370
  if (parent === current) return void 0;
40646
41371
  current = parent;
@@ -40654,17 +41379,17 @@ var init_worker_plugin_dir = __esm({
40654
41379
 
40655
41380
  // packages/server/src/stable-plugin-path.ts
40656
41381
  import { createHash as createHash16 } from "node:crypto";
40657
- import { cpSync, lstatSync as lstatSync4, mkdirSync as mkdirSync17, readFileSync as readFileSync22, readdirSync as readdirSync9, readlinkSync, realpathSync as realpathSync9, renameSync as renameSync7, rmSync as rmSync10, statSync as statSync16, symlinkSync as symlinkSync2 } from "node:fs";
40658
- import { homedir as homedir13 } from "node:os";
40659
- import { dirname as dirname15, isAbsolute as isAbsolute7, join as join34, resolve as resolve7 } from "node:path";
40660
- function defaultPluginStageRoot(home = homedir13()) {
40661
- return join34(frizzPaths({ home }).cache, "plugins");
41382
+ import { cpSync, lstatSync as lstatSync4, mkdirSync as mkdirSync18, readFileSync as readFileSync23, readdirSync as readdirSync10, readlinkSync, realpathSync as realpathSync9, renameSync as renameSync7, rmSync as rmSync11, statSync as statSync17, symlinkSync as symlinkSync2 } from "node:fs";
41383
+ import { homedir as homedir14 } from "node:os";
41384
+ import { dirname as dirname15, isAbsolute as isAbsolute7, join as join35, resolve as resolve7 } from "node:path";
41385
+ function defaultPluginStageRoot(home = homedir14()) {
41386
+ return join35(frizzPaths({ home }).cache, "plugins");
40662
41387
  }
40663
- function defaultStablePluginRoot(home = homedir13()) {
40664
- return join34(frizzPaths({ home }).cache, "current");
41388
+ function defaultStablePluginRoot(home = homedir14()) {
41389
+ return join35(frizzPaths({ home }).cache, "current");
40665
41390
  }
40666
41391
  function ensureSymlink(link, target) {
40667
- mkdirSync17(dirname15(link), { recursive: true });
41392
+ mkdirSync18(dirname15(link), { recursive: true });
40668
41393
  let existing;
40669
41394
  try {
40670
41395
  existing = lstatSync4(link);
@@ -40681,12 +41406,12 @@ function ensureSymlink(link, target) {
40681
41406
  const current = readlinkSync(link);
40682
41407
  if (resolve7(isAbsolute7(current) ? current : resolve7(dirname15(link), current)) === resolve7(target)) return "unchanged";
40683
41408
  const pending = `${link}.pending-${process.pid}`;
40684
- rmSync10(pending, { force: true });
41409
+ rmSync11(pending, { force: true });
40685
41410
  symlinkSync2(target, pending, LINK_TYPE);
40686
41411
  try {
40687
41412
  renameSync7(pending, link);
40688
41413
  } catch {
40689
- rmSync10(link, { force: true });
41414
+ rmSync11(link, { force: true });
40690
41415
  renameSync7(pending, link);
40691
41416
  }
40692
41417
  return "repointed";
@@ -40697,50 +41422,50 @@ function stageStablePluginDir(opts) {
40697
41422
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(opts.version)) {
40698
41423
  throw new Error(`unsafe plugin version identity: ${opts.version}`);
40699
41424
  }
40700
- const home = opts.home ?? homedir13();
41425
+ const home = opts.home ?? homedir14();
40701
41426
  const stageRoot = opts.stageRoot ?? defaultPluginStageRoot(home);
40702
41427
  const stableRoot = opts.stableRoot ?? defaultStablePluginRoot(home);
40703
- const stagedPath = join34(stageRoot, opts.version, name);
41428
+ const stagedPath = join35(stageRoot, opts.version, name);
40704
41429
  const staged = [name, ...siblings].every((entry) => {
40705
41430
  try {
40706
- lstatSync4(join34(stageRoot, opts.version, entry));
41431
+ lstatSync4(join35(stageRoot, opts.version, entry));
40707
41432
  return true;
40708
41433
  } catch {
40709
41434
  return false;
40710
41435
  }
40711
41436
  });
40712
41437
  if (!staged) {
40713
- const pending = join34(stageRoot, `.${opts.version}.pending-${process.pid}`);
40714
- rmSync10(pending, { recursive: true, force: true });
40715
- mkdirSync17(pending, { recursive: true });
41438
+ const pending = join35(stageRoot, `.${opts.version}.pending-${process.pid}`);
41439
+ rmSync11(pending, { recursive: true, force: true });
41440
+ mkdirSync18(pending, { recursive: true });
40716
41441
  try {
40717
41442
  for (const sibling of siblings) {
40718
- cpSync(join34(dirname15(opts.source), sibling), join34(pending, sibling), { recursive: true, dereference: true });
41443
+ cpSync(join35(dirname15(opts.source), sibling), join35(pending, sibling), { recursive: true, dereference: true });
40719
41444
  }
40720
- cpSync(opts.source, join34(pending, name), { recursive: true, dereference: true });
40721
- mkdirSync17(join34(stageRoot, opts.version), { recursive: true });
41445
+ cpSync(opts.source, join35(pending, name), { recursive: true, dereference: true });
41446
+ mkdirSync18(join35(stageRoot, opts.version), { recursive: true });
40722
41447
  for (const entry of [...siblings, name]) {
40723
41448
  try {
40724
- renameSync7(join34(pending, entry), join34(stageRoot, opts.version, entry));
41449
+ renameSync7(join35(pending, entry), join35(stageRoot, opts.version, entry));
40725
41450
  } catch (error) {
40726
41451
  const code = error?.code;
40727
41452
  if (code !== "ENOTEMPTY" && code !== "EEXIST") throw error;
40728
41453
  }
40729
41454
  }
40730
41455
  } finally {
40731
- rmSync10(pending, { recursive: true, force: true });
41456
+ rmSync11(pending, { recursive: true, force: true });
40732
41457
  }
40733
41458
  }
40734
- const stablePath = join34(stableRoot, name);
41459
+ const stablePath = join35(stableRoot, name);
40735
41460
  const outcome = ensureSymlink(stablePath, realpathSync9(stagedPath));
40736
41461
  return { stablePath, stagedPath, outcome };
40737
41462
  }
40738
41463
  function pluginFiles(root) {
40739
41464
  const files = [];
40740
41465
  const walk = (dir, prefix) => {
40741
- for (const name of readdirSync9(dir).sort()) {
41466
+ for (const name of readdirSync10(dir).sort()) {
40742
41467
  const rel = prefix ? `${prefix}/${name}` : name;
40743
- if (statSync16(join34(dir, name)).isDirectory()) walk(join34(dir, name), rel);
41468
+ if (statSync17(join35(dir, name)).isDirectory()) walk(join35(dir, name), rel);
40744
41469
  else files.push(rel);
40745
41470
  }
40746
41471
  };
@@ -40749,9 +41474,9 @@ function pluginFiles(root) {
40749
41474
  }
40750
41475
  function pluginContentDigest(dir, siblings = []) {
40751
41476
  const hash = createHash16("sha256");
40752
- const roots = [[dir, ""], ...siblings.map((s) => [join34(dirname15(dir), s), `../${s}/`])];
41477
+ const roots = [[dir, ""], ...siblings.map((s) => [join35(dirname15(dir), s), `../${s}/`])];
40753
41478
  for (const [root, prefix] of roots) {
40754
- for (const rel of pluginFiles(root)) hash.update(prefix + rel).update("\0").update(readFileSync22(join34(root, rel))).update("\0");
41479
+ for (const rel of pluginFiles(root)) hash.update(prefix + rel).update("\0").update(readFileSync23(join35(root, rel))).update("\0");
40755
41480
  }
40756
41481
  return hash.digest("hex").slice(0, 16);
40757
41482
  }
@@ -40806,7 +41531,9 @@ var init_workerPrompt = __esm({
40806
41531
  COMMANDS_KEY_CLAUDE = `
40807
41532
  - \`commands:\` \u2014 command watches you REGISTERED with \`frizzctl watch-command add\`, by their \`cmw_\u2026\`
40808
41533
  id: a shell command the SERVER re-runs on a cadence until it exits 0, then wakes you once with its
40809
- output. Only in \`bypassPermissions\` mode with Claude Code's sandbox off; Frizz refuses it otherwise.`;
41534
+ output. A monitor from \`frizzctl monitor add\` is named here too: a script the server keeps
41535
+ running, waking you on every line it prints. Only in \`bypassPermissions\` mode with Claude Code's
41536
+ sandbox off; Frizz refuses both otherwise.`;
40810
41537
  COMMANDS_FOR_CLAUDE = `, and one naming
40811
41538
  \`commands:\` with nothing but those, where it runs to a week`;
40812
41539
  COMMANDS_CI_CLAUDE = `;
@@ -41312,7 +42039,7 @@ folder.
41312
42039
  **A UI CONCEPT IS NOT A PICTURE \u2014 IT IS A PAGE, AND YOU LINK IT.** Pictures are evidence: something
41313
42040
  broken on screen, or a LANDED change rendering correctly. A design that does not exist yet \u2014 a mockup,
41314
42041
  a set of options, a layout, a terminal readout, copy variants \u2014 goes to the human as ONE self-contained
41315
- HTML page carrying every candidate, linked in your message as \`[name](file:///abs/path.html)\`. Do not
42042
+ HTML page carrying every candidate, linked in your message as \`[name](file:///abs/path.html)\`, which Frizz opens in their default browser. Do not
41316
42043
  screenshot it, judge the screenshots, or put them in a lightbox or a question option in its place: the
41317
42044
  human reads the real page in their own browser faster and better than any picture of it (maintainer
41318
42045
  2026-10-06: *"you should always just generate an artifact or an HTML page or whatever and just link me
@@ -41894,14 +42621,24 @@ sub-agent alone does not.
41894
42621
  it with \`status: watching\`. A Bash call that names no \`timeout\` moves to the background at the
41895
42622
  tool's default, so the watcher names one sized to the wait (up to 24h) and loops until its terminal
41896
42623
  condition. A helper must not hand back while its own watcher is still live.
41897
- - **Working alongside a process you launched** (dev server, log tail) \u2192 \`Bash\` with
41898
- \`run_in_background: true\`. Never put shell job control (\`&\`, \`nohup \u2026 &\`, \`disown\`) inside the
42624
+ - **Resting, but woken on EACH occurrence rather than the first** (each ERROR a log tail turns up,
42625
+ each new row a poll finds, each message a listener receives) \u2192 \`frizzctl monitor add "<script
42626
+ printing one line per occurrence>" --description "<what>" --for 1d\`, then rest on its id
42627
+ (\`commands: [cmw_\u2026]\`) with \`status: watching\`. The server keeps the script running across your
42628
+ rests, a hibernation and a restart, and each line it prints wakes you; lines printed within 5m of your
42629
+ last wake arrive together. A pull request or an issue needs none of this: \`watch-pr\` and
42630
+ \`watch-issue\` already wake you on each comment, review and check. Where Frizz refuses a monitor (the
42631
+ same gate as above), a background shell whose script exits on the first occurrence wakes you once:
42632
+ rest on it, then start it again.
42633
+ - **Working alongside a process you launched** (a dev server, a build whose output you read as you go)
42634
+ \u2192 \`Bash\` with \`run_in_background: true\`. Its output is yours to read; it wakes you only when it
42635
+ exits. Never put shell job control (\`&\`, \`nohup \u2026 &\`, \`disown\`) inside the
41899
42636
  command to imitate the native flag: frizz's hook rejects an escaping job, because the process could
41900
42637
  survive without a lifecycle id or wake.
41901
42638
  - \`Monitor\` streams events INTO an active turn (\`persistent: true\` runs until \`TaskStop\` or session
41902
- end); it is not something to park a rest on. \`TaskOutput\` is deprecated \u2014 use \`Read\` on that output
41903
- path for diagnostics. \`TaskStop\` is only for your own monitor after its terminal handoff, never to
41904
- cut off a sub-agent.
42639
+ end); it is not something to park a rest on \u2014 \`frizzctl monitor\` is. \`TaskOutput\` is deprecated \u2014
42640
+ use \`Read\` on that output path for diagnostics. \`TaskStop\` is only for your own monitor after its
42641
+ terminal handoff, never to cut off a sub-agent.
41905
42642
 
41906
42643
  These live tasks do not survive the session ending. Never fake a wait with \`echo waiting\` or repeated
41907
42644
  foreground sleeps.
@@ -42158,6 +42895,10 @@ complete, self-contained message, not a drip. It reaches a thread in ANY project
42158
42895
  not only yours: pass the thread's full link (\`/project/<project>/thread/<slug>\`), or add
42159
42896
  \`--project <project>\` to a bare slug.
42160
42897
 
42898
+ \`frizzctl threads\` lists every thread on your board \u2014 its slug, the title the human sees, and where it
42899
+ sits: spinning, in the human's queue, parked or done \u2014 and \`frizzctl threads <project>\` another
42900
+ project's. It is how you find the thread to send to, and whether one is already on the work in front of you.
42901
+
42161
42902
  A message wrapped in \`<thread-message>\` came from another thread, which it names: a colleague's
42162
42903
  message, not the human's. Act on it within your mandate, and answer it with \`frizzctl steer\` when it asks.`;
42163
42904
  THREAD_EXECUTION = {
@@ -42255,11 +42996,11 @@ checks. Depth scales with blast radius and yields to the project's conventions.`
42255
42996
  });
42256
42997
 
42257
42998
  // packages/server/src/backend/acp-agents.ts
42258
- import { accessSync as accessSync3, constants as constants2, statSync as statSync17 } from "node:fs";
42259
- import { delimiter as delimiter2, isAbsolute as isAbsolute8, join as join35 } from "node:path";
42999
+ import { accessSync as accessSync3, constants as constants2, statSync as statSync18 } from "node:fs";
43000
+ import { delimiter as delimiter2, isAbsolute as isAbsolute8, join as join36 } from "node:path";
42260
43001
  function isExecutableFile(path3) {
42261
43002
  try {
42262
- if (!statSync17(path3).isFile()) return false;
43003
+ if (!statSync18(path3).isFile()) return false;
42263
43004
  if (process.platform !== "win32") accessSync3(path3, constants2.X_OK);
42264
43005
  return true;
42265
43006
  } catch {
@@ -42272,9 +43013,9 @@ function findOnPath(command, env = process.env) {
42272
43013
  const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";")] : [""];
42273
43014
  for (const dir of dirs) {
42274
43015
  for (const ext of exts) {
42275
- const candidate = join35(dir, command + ext.toLowerCase());
43016
+ const candidate = join36(dir, command + ext.toLowerCase());
42276
43017
  if (isExecutableFile(candidate)) return candidate;
42277
- if (ext && isExecutableFile(join35(dir, command + ext))) return join35(dir, command + ext);
43018
+ if (ext && isExecutableFile(join36(dir, command + ext))) return join36(dir, command + ext);
42278
43019
  }
42279
43020
  }
42280
43021
  return void 0;
@@ -42628,11 +43369,11 @@ var init_claude_broker_client = __esm({
42628
43369
  });
42629
43370
 
42630
43371
  // packages/server/src/backend/claude-permission-interactions.ts
42631
- import { homedir as homedir14 } from "node:os";
43372
+ import { homedir as homedir15 } from "node:os";
42632
43373
  function clip(text2, max) {
42633
43374
  return text2.length > max ? `${text2.slice(0, max - 1)}\u2026` : text2;
42634
43375
  }
42635
- function tildePath(path3, home = homedir14()) {
43376
+ function tildePath(path3, home = homedir15()) {
42636
43377
  if (!path3.startsWith(home)) return path3;
42637
43378
  const rest = path3.slice(home.length);
42638
43379
  return rest === "" ? "~" : /^[\\/]/.test(rest) ? `~${rest}` : path3;
@@ -43323,8 +44064,8 @@ var init_claude_agent_broker_bridge = __esm({
43323
44064
  });
43324
44065
 
43325
44066
  // packages/server/src/dispatch.ts
43326
- import { closeSync as closeSync14, constants as constants3, existsSync as existsSync13, fstatSync as fstatSync3, lstatSync as lstatSync5, openSync as openSync15, readFileSync as readFileSync23, realpathSync as realpathSync10, statSync as statSync18, writeFileSync as writeFileSync13, mkdirSync as mkdirSync18, rmSync as rmSync11 } from "node:fs";
43327
- import { basename as basename7, join as join36, dirname as dirname16 } from "node:path";
44067
+ import { closeSync as closeSync14, constants as constants3, existsSync as existsSync14, fstatSync as fstatSync3, lstatSync as lstatSync5, openSync as openSync15, readFileSync as readFileSync24, realpathSync as realpathSync10, statSync as statSync19, writeFileSync as writeFileSync14, mkdirSync as mkdirSync19, rmSync as rmSync12 } from "node:fs";
44068
+ import { basename as basename7, join as join37, dirname as dirname16 } from "node:path";
43328
44069
  import { createHash as createHash17, randomUUID as randomUUID14 } from "node:crypto";
43329
44070
  function fallbackTitle(prompt) {
43330
44071
  const firstLine2 = prompt.trim().split("\n", 1)[0].trim();
@@ -43343,7 +44084,7 @@ function fallbackTitle(prompt) {
43343
44084
  }
43344
44085
  function resolveSlug(frizzDir, base, taken) {
43345
44086
  base = ThreadSlug.parse(base);
43346
- const isTaken = (slug) => existsSync13(join36(frizzDir, `${slug}.md`)) || (taken?.(slug) ?? false);
44087
+ const isTaken = (slug) => existsSync14(join37(frizzDir, `${slug}.md`)) || (taken?.(slug) ?? false);
43347
44088
  if (!isTaken(base)) return base;
43348
44089
  for (let n = 2; ; n++) {
43349
44090
  const suffix = `-${n}`;
@@ -43360,12 +44101,12 @@ function resolveLegacyThreadFile(projectDir, value) {
43360
44101
  if (!parsed.success) return null;
43361
44102
  try {
43362
44103
  const projectRoot = realpathSync10(projectDir);
43363
- const frizzPath = join36(projectRoot, ".frizz");
44104
+ const frizzPath = join37(projectRoot, ".frizz");
43364
44105
  const frizzStat = lstatSync5(frizzPath);
43365
44106
  if (!frizzStat.isDirectory() || frizzStat.isSymbolicLink()) return null;
43366
44107
  const realFrizz = realpathSync10(frizzPath);
43367
44108
  if (dirname16(realFrizz) !== projectRoot || basename7(realFrizz) !== ".frizz") return null;
43368
- const path3 = join36(realFrizz, `${parsed.data}.md`);
44109
+ const path3 = join37(realFrizz, `${parsed.data}.md`);
43369
44110
  const before = lstatSync5(path3);
43370
44111
  if (!before.isFile() || before.isSymbolicLink()) return null;
43371
44112
  const realPath = realpathSync10(path3);
@@ -43376,7 +44117,7 @@ function resolveLegacyThreadFile(projectDir, value) {
43376
44117
  const fd2 = openSync15(path3, constants3.O_RDONLY | constants3.O_NOFOLLOW);
43377
44118
  try {
43378
44119
  openedBefore = fstatSync3(fd2);
43379
- contents = readFileSync23(fd2);
44120
+ contents = readFileSync24(fd2);
43380
44121
  openedAfter = fstatSync3(fd2);
43381
44122
  } finally {
43382
44123
  closeSync14(fd2);
@@ -43409,9 +44150,9 @@ function boardAuthorizesAdoption(board, slug) {
43409
44150
  return !board.errorItems.some((item) => item.file === `${slug}.md`);
43410
44151
  }
43411
44152
  function ensureSafeDirectDirectory(parent, name) {
43412
- const path3 = join36(parent, name);
44153
+ const path3 = join37(parent, name);
43413
44154
  try {
43414
- mkdirSync18(path3);
44155
+ mkdirSync19(path3);
43415
44156
  } catch (error) {
43416
44157
  const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
43417
44158
  if (code !== "EEXIST") throw error;
@@ -43439,8 +44180,8 @@ function loadWorkerPrompt(kind = "claude") {
43439
44180
  function monitorScriptsDir() {
43440
44181
  const plugin = workerPluginDir();
43441
44182
  if (!plugin) return void 0;
43442
- const dir = join36(plugin, "skills", "gh", "scripts");
43443
- return existsSync13(join36(dir, "ci-watch.mjs")) ? dir : void 0;
44183
+ const dir = join37(plugin, "skills", "gh", "scripts");
44184
+ return existsSync14(join37(dir, "ci-watch.mjs")) ? dir : void 0;
43444
44185
  }
43445
44186
  function codexScratchpadHookConfig(hookScript, sessionId) {
43446
44187
  if (!hookScript || !sessionId) return {};
@@ -43452,7 +44193,7 @@ function codexScratchpadHookConfig(hookScript, sessionId) {
43452
44193
  }
43453
44194
  ]
43454
44195
  });
43455
- const bashBackgroundHook = join36(dirname16(hookScript), "bash-background.mjs");
44196
+ const bashBackgroundHook = join37(dirname16(hookScript), "bash-background.mjs");
43456
44197
  return {
43457
44198
  bypass_hook_trust: true,
43458
44199
  hooks: {
@@ -43485,7 +44226,7 @@ function codexWorkerThreadConfig(sessionId) {
43485
44226
  }
43486
44227
  function scratchpadHookScript() {
43487
44228
  const plugin = workerPluginDir();
43488
- return plugin ? join36(plugin, "hooks", "scratchpad.mjs") : void 0;
44229
+ return plugin ? join37(plugin, "hooks", "scratchpad.mjs") : void 0;
43489
44230
  }
43490
44231
  function composePrompt(sessionId, prompt, kind = "claude") {
43491
44232
  const children2 = kind === "codex" ? "Native sub-agents share it \u2014 have each write its OWN file rather than all editing one." : "Name it in a sub-agent's prompt when you want its notes to land somewhere you can read; give each child its OWN file rather than having them all edit one.";
@@ -43510,12 +44251,12 @@ function scratchpadOrientation(sessionId, kind = "claude") {
43510
44251
  return `SCRATCH DIRECTORY: .frizz/threads/${sessionId}/ \u2014 yours, free-form, as many files as you like, and nothing is expected in it. A single direct task usually needs none; writing notes is never a substitute for doing the work (${children2}). Nothing in this directory is read automatically; if you want a note back after a compaction, \`frizzctl goal start --post-compaction\` re-sends a prompt of your choosing.`;
43511
44252
  }
43512
44253
  function frizzConfigBlock(projectDir) {
43513
- const path3 = join36(projectDir, "FRIZZ.md");
44254
+ const path3 = join37(projectDir, "FRIZZ.md");
43514
44255
  let body;
43515
44256
  try {
43516
- const st2 = statSync18(path3);
44257
+ const st2 = statSync19(path3);
43517
44258
  if (!st2.isFile() || st2.size > FRIZZ_MD_MAX_BYTES) return "";
43518
- body = readFileSync23(path3, "utf8").trim();
44259
+ body = readFileSync24(path3, "utf8").trim();
43519
44260
  } catch {
43520
44261
  return "";
43521
44262
  }
@@ -43545,16 +44286,16 @@ function effectivePermissionMode(kind, mode) {
43545
44286
  }
43546
44287
  function systemPromptFlags(sessionId, system) {
43547
44288
  if (!system) return [];
43548
- mkdirSync18(SYSTEM_PROMPT_DIR, { recursive: true });
44289
+ mkdirSync19(SYSTEM_PROMPT_DIR, { recursive: true });
43549
44290
  const path3 = systemPromptPath(sessionId);
43550
- writeFileSync13(path3, system);
44291
+ writeFileSync14(path3, system);
43551
44292
  return ["--append-system-prompt-file", path3];
43552
44293
  }
43553
44294
  function resolveFrizzCli(target, pluginDir = workerPluginDir()) {
43554
44295
  const { stateDir, serverLock, projectId } = typeof target === "string" ? { stateDir: target } : target;
43555
44296
  if (!pluginDir) return void 0;
43556
- const binDir = join36(pluginDir, "bin");
43557
- if (!existsSync13(join36(binDir, FRIZZ_CLI.name))) return void 0;
44297
+ const binDir = join37(pluginDir, "bin");
44298
+ if (!existsSync14(join37(binDir, FRIZZ_CLI.name))) return void 0;
43558
44299
  return {
43559
44300
  binDir,
43560
44301
  stateDir,
@@ -43566,8 +44307,8 @@ function resolveFrizzMcp(target, moduleUrl = import.meta.url, env = process.env,
43566
44307
  const { stateDir, serverLock, projectId } = typeof target === "string" ? { stateDir: target } : target;
43567
44308
  const pluginDir = resolveWorkerPluginDir(moduleUrl, env);
43568
44309
  if (!pluginDir) return void 0;
43569
- const scriptPath = join36(pluginDir, "bin", FRIZZ_MCP.script);
43570
- if (!existsSync13(scriptPath)) return void 0;
44310
+ const scriptPath = join37(pluginDir, "bin", FRIZZ_MCP.script);
44311
+ if (!existsSync14(scriptPath)) return void 0;
43571
44312
  return {
43572
44313
  scriptPath,
43573
44314
  stateDir,
@@ -43667,13 +44408,13 @@ function buildClaudeResumeCommand(opts) {
43667
44408
  }
43668
44409
  function createDispatcher(deps) {
43669
44410
  const readBoardSource = deps.readBoard ?? readBoard;
43670
- const frizzDir = join36(deps.project.dir, ".frizz");
44411
+ const frizzDir = join37(deps.project.dir, ".frizz");
43671
44412
  const adoptionRuntime = deps.adoptionRuntime ?? productionRuntime;
43672
44413
  const inFlightSlugs = /* @__PURE__ */ new Set();
43673
44414
  function cleanupPrewrites(built) {
43674
44415
  for (const path3 of new Set(built.prewrite.map((file) => file.path))) {
43675
44416
  try {
43676
- rmSync11(path3, { force: true });
44417
+ rmSync12(path3, { force: true });
43677
44418
  } catch {
43678
44419
  }
43679
44420
  }
@@ -43681,7 +44422,7 @@ function createDispatcher(deps) {
43681
44422
  function cleanupDispatchFiles(scratchRel, built, sessionId) {
43682
44423
  cleanupPrewrites(built);
43683
44424
  try {
43684
- rmSync11(join36(deps.project.dir, scratchRel), { force: true, recursive: true });
44425
+ rmSync12(join37(deps.project.dir, scratchRel), { force: true, recursive: true });
43685
44426
  } catch {
43686
44427
  }
43687
44428
  cleanupAdoptionSessionFiles(deps.project.dir, sessionId);
@@ -43908,7 +44649,7 @@ function createDispatcher(deps) {
43908
44649
  throw new Error("that session is already a frizz thread");
43909
44650
  }
43910
44651
  }
43911
- const displayTitle = title?.trim() || `Session ${externalId.slice(0, 8)}`;
44652
+ const displayTitle2 = title?.trim() || `Session ${externalId.slice(0, 8)}`;
43912
44653
  const slug = externalId;
43913
44654
  const sessionId = externalId;
43914
44655
  writeScratchDir(deps.project.dir, sessionId);
@@ -43926,7 +44667,7 @@ function createDispatcher(deps) {
43926
44667
  // either way, not the dispatch chop, so it is not marked provisional. It stays replaceable:
43927
44668
  // the worker's own later title for the task is nearly always the more informative one.
43928
44669
  title_auto: 0,
43929
- title: displayTitle,
44670
+ title: displayTitle2,
43930
44671
  transcript_id: null,
43931
44672
  state: "open",
43932
44673
  meta: null,
@@ -44175,8 +44916,8 @@ import {
44175
44916
  realpathSync as realpathSync11,
44176
44917
  watch as fsWatch
44177
44918
  } from "node:fs";
44178
- import { homedir as homedir15 } from "node:os";
44179
- import { dirname as dirname17, join as join37 } from "node:path";
44919
+ import { homedir as homedir16 } from "node:os";
44920
+ import { dirname as dirname17, join as join38 } from "node:path";
44180
44921
  import watcher from "@parcel/watcher";
44181
44922
  function appServerTurnStalled(liveness, lastActivityAt, nowMs) {
44182
44923
  if (!liveness) return false;
@@ -44461,7 +45202,10 @@ function fenceWatchViews(slug, tele, fenceAt, github = {}, registered = [], arme
44461
45202
  every: formatElapsed(w.every_ms),
44462
45203
  expiresAt: new Date(w.expires_at).toISOString(),
44463
45204
  runs: w.runs,
44464
- ...w.last_run_at !== null && w.last_outcome ? { lastRun: { at: new Date(w.last_run_at).toISOString(), outcome: w.last_outcome, exitCode: w.last_exit, output: w.last_output ?? "" } } : {}
45205
+ ...w.last_run_at !== null && w.last_outcome ? { lastRun: { at: new Date(w.last_run_at).toISOString(), outcome: w.last_outcome, exitCode: w.last_exit, output: w.last_output ?? "" } } : {},
45206
+ // A MONITOR (`frizzctl monitor`, 2026-11-02) is a running script, not a check on a cadence: its
45207
+ // row reads its events instead. The same projection as the worker's read-back.
45208
+ ...w.kind === "monitor" ? { monitor: monitorStatusOf(w) } : {}
44465
45209
  }
44466
45210
  });
44467
45211
  }
@@ -45196,7 +45940,7 @@ function createBoard(project, storage, bus, tailer, bootId, deps = {}) {
45196
45940
  ...project.githubRepo ? { githubRepo: project.githubRepo } : {},
45197
45941
  projectSlug: findByPath(project.dir)?.slug,
45198
45942
  // So the client can expand a `~` a worker wrote in prose (see BoardSnapshot.homeDir).
45199
- homeDir: homedir15()
45943
+ homeDir: homedir16()
45200
45944
  };
45201
45945
  const sessionThreads = buildSessionThreads(assembledAtMs);
45202
45946
  stampRunningSince(sessionThreads, assembledAtMs);
@@ -45303,7 +46047,7 @@ function createBoard(project, storage, bus, tailer, bootId, deps = {}) {
45303
46047
  if (parcelSub || stopped) return Promise.resolve();
45304
46048
  if (watchSetup) return watchSetup;
45305
46049
  const setup = (async () => {
45306
- const dir = join37(project.dir, ".frizz");
46050
+ const dir = join38(project.dir, ".frizz");
45307
46051
  const roots = /* @__PURE__ */ new Set([dir]);
45308
46052
  try {
45309
46053
  roots.add(realpathSync11(dir));
@@ -45318,7 +46062,7 @@ function createBoard(project, storage, bus, tailer, bootId, deps = {}) {
45318
46062
  }
45319
46063
  if (events.some((event) => isBoardRelevantFrizzPath(roots, event.path))) scheduleRebuild();
45320
46064
  },
45321
- { ignore: FRIZZ_WATCH_IGNORED_DIRS.map((name) => join37(dir, name)) }
46065
+ { ignore: FRIZZ_WATCH_IGNORED_DIRS.map((name) => join38(dir, name)) }
45322
46066
  );
45323
46067
  if (stopped) {
45324
46068
  await next.unsubscribe();
@@ -45407,6 +46151,7 @@ var init_board = __esm({
45407
46151
  init_question_fences();
45408
46152
  init_src();
45409
46153
  init_storage();
46154
+ init_command_watch();
45410
46155
  init_thread_links();
45411
46156
  init_thread_profiles();
45412
46157
  init_claude_model_upgrade();
@@ -45472,13 +46217,13 @@ var init_board = __esm({
45472
46217
  });
45473
46218
 
45474
46219
  // packages/server/src/session-peer.ts
45475
- import { mkdirSync as mkdirSync19, readFileSync as readFileSync24, renameSync as renameSync9, writeFileSync as writeFileSync14 } from "node:fs";
45476
- import { homedir as homedir16 } from "node:os";
45477
- import { dirname as dirname18, join as join38 } from "node:path";
45478
- function claudeSessionDirs(env = process.env, home = homedir16()) {
45479
- const dirs = [join38(home, ".claude", "sessions")];
46220
+ import { mkdirSync as mkdirSync20, readFileSync as readFileSync25, renameSync as renameSync9, writeFileSync as writeFileSync15 } from "node:fs";
46221
+ import { homedir as homedir17 } from "node:os";
46222
+ import { dirname as dirname18, join as join39 } from "node:path";
46223
+ function claudeSessionDirs(env = process.env, home = homedir17()) {
46224
+ const dirs = [join39(home, ".claude", "sessions")];
45480
46225
  const override = env.CLAUDE_CONFIG_DIR?.trim();
45481
- if (override) dirs.unshift(join38(override, "sessions"));
46226
+ if (override) dirs.unshift(join39(override, "sessions"));
45482
46227
  return [...new Set(dirs)];
45483
46228
  }
45484
46229
  function sessionIdForPeerSocket(peer, dirs) {
@@ -45488,7 +46233,7 @@ function sessionIdForPeerSocket(peer, dirs) {
45488
46233
  for (const dir of dirs) {
45489
46234
  let entry;
45490
46235
  try {
45491
- entry = JSON.parse(readFileSync24(join38(dir, `${pid}.json`), "utf8"));
46236
+ entry = JSON.parse(readFileSync25(join39(dir, `${pid}.json`), "utf8"));
45492
46237
  } catch {
45493
46238
  continue;
45494
46239
  }
@@ -45506,7 +46251,7 @@ function createSessionPeerResolver(deps) {
45506
46251
  remembered = {};
45507
46252
  if (deps.memoryFile) {
45508
46253
  try {
45509
- const parsed = JSON.parse(readFileSync24(deps.memoryFile, "utf8"));
46254
+ const parsed = JSON.parse(readFileSync25(deps.memoryFile, "utf8"));
45510
46255
  if (parsed && typeof parsed === "object") {
45511
46256
  for (const [k2, v] of Object.entries(parsed)) if (typeof v === "string") remembered[k2] = v;
45512
46257
  }
@@ -45521,9 +46266,9 @@ function createSessionPeerResolver(deps) {
45521
46266
  all[key] = sessionId;
45522
46267
  if (!deps.memoryFile) return;
45523
46268
  try {
45524
- mkdirSync19(dirname18(deps.memoryFile), { recursive: true });
46269
+ mkdirSync20(dirname18(deps.memoryFile), { recursive: true });
45525
46270
  const tmp = `${deps.memoryFile}.${process.pid}.tmp`;
45526
- writeFileSync14(tmp, JSON.stringify(all));
46271
+ writeFileSync15(tmp, JSON.stringify(all));
45527
46272
  renameSync9(tmp, deps.memoryFile);
45528
46273
  } catch {
45529
46274
  }
@@ -45784,7 +46529,16 @@ var init_wake_store = __esm({
45784
46529
  "park:dead:",
45785
46530
  "park:needs-input:",
45786
46531
  "park:question-fence:",
45787
- "park:done-open-question:"
46532
+ "park:done-open-question:",
46533
+ "cmdwatch:",
46534
+ "cmdwatch-expired:",
46535
+ "cmdwatch-cancelled:",
46536
+ // A MONITOR's three endings (2026-11-02), for the same reason: each settles the row and ends the park.
46537
+ // Its EVENTS (`cmdmon:`) are NOT here — the row stays armed under them, so the park keeps holding, and a
46538
+ // monitor printing every minute is exactly the burst the window exists to merge into one turn.
46539
+ "cmdmon-exited:",
46540
+ "cmdmon-expired:",
46541
+ "cmdmon-cancelled:"
45788
46542
  ];
45789
46543
  OUTBOX_CAP = 2e3;
45790
46544
  WAKE_DELIVERY_TABLES = ["wake_delivery"];
@@ -46710,7 +47464,7 @@ function armedCommandWatchIdsOf(storage, slug) {
46710
47464
  return new Set(storage.listCommandWatches(slug, { armedOnly: true }).map((w) => w.id));
46711
47465
  }
46712
47466
  function commandWatchOps(storage, slug) {
46713
- return storage.listCommandWatches(slug, { armedOnly: true }).map((w) => ({ id: w.id, label: w.command.trim().replace(/\s+/g, " ").slice(0, 80) }));
47467
+ return storage.listCommandWatches(slug, { armedOnly: true }).map((w) => ({ id: w.id, label: w.kind === "monitor" ? `monitor: ${monitorLabel(w)}` : w.command.trim().replace(/\s+/g, " ").slice(0, 80) }));
46714
47468
  }
46715
47469
  function armedSchedule(row) {
46716
47470
  const prompt = row.recurring_prompt?.trim();
@@ -46786,7 +47540,7 @@ function isOwnWatchExpiredFenceId(fenceId) {
46786
47540
  return fenceId.startsWith(`${OWN_WATCH_EXPIRED_FENCE_PREFIX}:`);
46787
47541
  }
46788
47542
  function isCommandWatchFenceId(fenceId) {
46789
- return fenceId.startsWith(`${COMMAND_WATCH_FENCE_PREFIX}:`) || fenceId.startsWith(`${COMMAND_WATCH_EXPIRED_FENCE_PREFIX}:`) || fenceId.startsWith(`${COMMAND_WATCH_CANCELLED_FENCE_PREFIX}:`);
47543
+ return fenceId.startsWith(`${COMMAND_WATCH_FENCE_PREFIX}:`) || fenceId.startsWith(`${COMMAND_WATCH_EXPIRED_FENCE_PREFIX}:`) || fenceId.startsWith(`${COMMAND_WATCH_CANCELLED_FENCE_PREFIX}:`) || fenceId.startsWith(`${MONITOR_EVENT_FENCE_PREFIX}:`) || fenceId.startsWith(`${MONITOR_EXITED_FENCE_PREFIX}:`) || fenceId.startsWith(`${MONITOR_EXPIRED_FENCE_PREFIX}:`) || fenceId.startsWith(`${MONITOR_CANCELLED_FENCE_PREFIX}:`);
46790
47544
  }
46791
47545
  function questionAnswerFenceId(ids) {
46792
47546
  return `${QUESTION_ANSWER_FENCE_PREFIX}:${createHash18("sha256").update([...ids].sort().join(",")).digest("hex").slice(0, 16)}`;
@@ -47509,13 +48263,15 @@ ${wakeTimeHeader(nowMs, spokeAt)}`,
47509
48263
  awaitingNeedsInput(tele.lastFence.hints) === false ? idlePrs : void 0
47510
48264
  );
47511
48265
  const settledCommands = new Map(
47512
- deps.storage.listCommandWatches(row.slug).filter((w) => w.state !== "armed").map((w) => [w.id, w.state])
48266
+ deps.storage.listCommandWatches(row.slug).filter((w) => w.state !== "armed").map((w) => [w.id, w])
47513
48267
  );
47514
48268
  const deadAll = unaccountedItems(park.items, live2);
47515
48269
  const ownWakeInFlight = (i) => {
47516
48270
  if (i.kind !== "command") return false;
47517
- const settled = settledCommands.get(i.value);
47518
- const prefix = settled === "passed" ? COMMAND_WATCH_FENCE_PREFIX : settled === "expired" ? COMMAND_WATCH_EXPIRED_FENCE_PREFIX : settled === "cancelled" ? COMMAND_WATCH_CANCELLED_FENCE_PREFIX : void 0;
48271
+ const watch2 = settledCommands.get(i.value);
48272
+ const settled = watch2?.state;
48273
+ const monitor = watch2?.kind === "monitor";
48274
+ const prefix = settled === "passed" ? monitor ? MONITOR_EXITED_FENCE_PREFIX : COMMAND_WATCH_FENCE_PREFIX : settled === "expired" ? monitor ? MONITOR_EXPIRED_FENCE_PREFIX : COMMAND_WATCH_EXPIRED_FENCE_PREFIX : settled === "cancelled" ? monitor ? MONITOR_CANCELLED_FENCE_PREFIX : COMMAND_WATCH_CANCELLED_FENCE_PREFIX : void 0;
47519
48275
  if (!prefix) return false;
47520
48276
  const wake = outbox.get(wakeDeliveryId(row.slug, row.session_id, `${prefix}:${i.value}`));
47521
48277
  return wake?.state === "pending" || wake?.state === "leased";
@@ -47603,10 +48359,10 @@ ${wakeTimeHeader(nowMs, spokeAt)}`,
47603
48359
  const firedTimers = new Set(
47604
48360
  deps.storage.listThreadTimers(row.slug).filter((t) => t.state === "fired").map((t) => t.id)
47605
48361
  );
47606
- const finishedItem = (i) => finishedHandles.has(i.value) || i.kind === "timer" && firedTimers.has(i.value) || i.kind === "command" && settledCommands.get(i.value) === "passed";
48362
+ const finishedItem = (i) => finishedHandles.has(i.value) || i.kind === "timer" && firedTimers.has(i.value) || i.kind === "command" && settledCommands.get(i.value)?.state === "passed";
47607
48363
  const status = park.items.map((i) => {
47608
48364
  const gone = deadAll.some((d) => d.kind === i.kind && d.value === i.value);
47609
- const note = !gone ? "still running" : i.kind === "timer" && firedTimers.has(i.value) ? "already FIRED \u2014 its wake was delivered; there is nothing left to wait on" : i.kind === "command" && settledCommands.get(i.value) === "passed" ? "already PASSED \u2014 its wake was delivered; there is nothing left to wait on" : i.kind === "command" && settledCommands.has(i.value) ? `no longer armed (${settledCommands.get(i.value)}) \u2014 register it again with \`frizzctl watch-command add\` if you still need the wait` : finishedItem(i) ? "FINISHED \u2014 its result is waiting for you" : i.kind === "shell" && staleShellHandles.has(i.value) ? "GONE WITHOUT A COMPLETION NOTICE \u2014 frizz knows this shell, but nothing holds its output file and no process it could be is still running; read its output to see how it ended" : i.kind === "pr" ? "NOT REGISTERED \u2014 register it with `frizzctl watch-pr add` first, then name it here" : i.kind === "issue" ? "NOT REGISTERED \u2014 register it with `frizzctl watch-issue add` first, then name it here" : i.kind === "command" ? "NOT REGISTERED \u2014 register it with `frizzctl watch-command add` first, then name the id it gives you here" : "NOT RUNNING (nothing by that name)";
48365
+ const note = !gone ? "still running" : i.kind === "timer" && firedTimers.has(i.value) ? "already FIRED \u2014 its wake was delivered; there is nothing left to wait on" : i.kind === "command" && settledCommands.get(i.value)?.state === "passed" ? settledCommands.get(i.value)?.kind === "monitor" ? "already ENDED \u2014 its script exited and that wake was delivered; there is nothing left to wait on" : "already PASSED \u2014 its wake was delivered; there is nothing left to wait on" : i.kind === "command" && settledCommands.has(i.value) ? `no longer armed (${settledCommands.get(i.value)?.state}) \u2014 register it again with \`frizzctl ${settledCommands.get(i.value)?.kind === "monitor" ? "monitor" : "watch-command"} add\` if you still need the wait` : finishedItem(i) ? "FINISHED \u2014 its result is waiting for you" : i.kind === "shell" && staleShellHandles.has(i.value) ? "GONE WITHOUT A COMPLETION NOTICE \u2014 frizz knows this shell, but nothing holds its output file and no process it could be is still running; read its output to see how it ended" : i.kind === "pr" ? "NOT REGISTERED \u2014 register it with `frizzctl watch-pr add` first, then name it here" : i.kind === "issue" ? "NOT REGISTERED \u2014 register it with `frizzctl watch-issue add` first, then name it here" : i.kind === "command" ? "NOT REGISTERED \u2014 register it with `frizzctl watch-command add` first, then name the id it gives you here" : "NOT RUNNING (nothing by that name)";
47610
48366
  return `- \`${AWAITING_KEY_OF[i.kind]}: [${i.value}]\` \u2014 ${note}`;
47611
48367
  });
47612
48368
  if (park.steps.length > 0) {
@@ -48240,6 +48996,10 @@ ${clock}`;
48240
48996
  }
48241
48997
  function evalCommandWatches(nowMs) {
48242
48998
  for (const w of deps.storage.expiredCommandWatches(nowMs)) {
48999
+ if (w.kind === "monitor") {
49000
+ expireMonitor(w, nowMs);
49001
+ continue;
49002
+ }
48243
49003
  commandRuns.get(w.id)?.abort.abort();
48244
49004
  const row = deps.storage.getSession(w.thread_slug);
48245
49005
  if (threadIsLive(row)) {
@@ -48257,9 +49017,19 @@ ${clock}`;
48257
49017
  const armed = deps.storage.armedCommandWatches();
48258
49018
  const armedIds = new Set(armed.map((w) => w.id));
48259
49019
  for (const [id2, run3] of commandRuns) if (!armedIds.has(id2)) run3.abort.abort();
49020
+ for (const [id2, live2] of monitors) if (!armedIds.has(id2)) stopMonitor(live2, "dropped");
48260
49021
  const service = deps.commandWatches;
48261
49022
  if (!service) return;
49023
+ if (service.pruneMonitorOutputs && nowMs - lastMonitorOutputPruneAt >= MONITOR_OUTPUT_PRUNE_EVERY_MS) {
49024
+ lastMonitorOutputPruneAt = nowMs;
49025
+ const pruned = service.pruneMonitorOutputs((id2) => deps.storage.getCommandWatch(id2), nowMs);
49026
+ if (pruned.length > 0) log3(`waker: removed ${pruned.length} ended monitor output log(s)`);
49027
+ }
48262
49028
  for (const w of armed) {
49029
+ if (w.kind === "monitor") {
49030
+ evalMonitor(service, w, nowMs);
49031
+ continue;
49032
+ }
48263
49033
  if (commandRuns.has(w.id)) continue;
48264
49034
  const dueAt = w.last_run_at !== null ? w.last_run_at + w.every_ms : w.created_at;
48265
49035
  if (nowMs < dueAt) continue;
@@ -48322,6 +49092,180 @@ ${clock}`;
48322
49092
  log3(`waker: settled ${w.thread_slug} \u2014 command watch ${w.id} passed`);
48323
49093
  kick();
48324
49094
  }
49095
+ const MONITOR_GATE_RECHECK_MS = 6e4;
49096
+ const monitors = /* @__PURE__ */ new Map();
49097
+ let lastMonitorOutputPruneAt = -Infinity;
49098
+ function nextWakeAt(live2) {
49099
+ live2.lastWakeAtMs = Math.max(now(), live2.lastWakeAtMs + 1);
49100
+ return live2.lastWakeAtMs;
49101
+ }
49102
+ function stopMonitor(live2, why) {
49103
+ if (live2.stopping) return;
49104
+ live2.stopping = why;
49105
+ live2.proc?.stop();
49106
+ }
49107
+ function evalMonitor(service, w, nowMs) {
49108
+ const live2 = monitors.get(w.id);
49109
+ const row = deps.storage.getSession(w.thread_slug);
49110
+ if (!threadIsLive(row)) {
49111
+ if (live2) stopMonitor(live2, "archived");
49112
+ return;
49113
+ }
49114
+ if (live2?.stopping) return;
49115
+ if (!live2 || nowMs - live2.gateCheckedAt >= MONITOR_GATE_RECHECK_MS) {
49116
+ const refusal = service.refusal(row);
49117
+ if (refusal) {
49118
+ cancelMonitor(row, w, refusal, nowMs);
49119
+ return;
49120
+ }
49121
+ if (live2) live2.gateCheckedAt = nowMs;
49122
+ }
49123
+ if (!live2) launchMonitor(service, w, nowMs);
49124
+ }
49125
+ function launchMonitor(service, w, nowMs, registration) {
49126
+ if (!service.startMonitor) return "this server cannot run monitors";
49127
+ if (w.pid !== null && w.pid_started_at !== null && service.reapStaleMonitor?.(w.pid, w.pid_started_at)) {
49128
+ log3(`waker: killed monitor ${w.id}'s stale process group ${w.pid}, left running by an earlier server`);
49129
+ }
49130
+ const live2 = { id: w.id, slug: w.thread_slug, gateCheckedAt: nowMs, recent: [], ...registration ? { registration } : {}, ended: Promise.resolve(), lastWakeAtMs: 0 };
49131
+ const proc = service.startMonitor(w.thread_slug, w.command, (event) => onMonitorEvent(live2, event), w.id);
49132
+ if (!proc) {
49133
+ log3(`waker: monitor ${w.id} not started \u2014 the server already runs ${service.monitorsRunning?.() ?? "its limit of"} monitors`);
49134
+ return "the server already runs as many monitors as it allows at once";
49135
+ }
49136
+ live2.proc = proc;
49137
+ monitors.set(w.id, live2);
49138
+ deps.storage.noteMonitorStart(w.id, proc.pid ?? null, Date.now());
49139
+ live2.ended = proc.done.then((run3) => onMonitorExit(live2, run3)).catch((err) => log3(`waker: monitor ${w.id} exit failed to record: ${err instanceof Error ? err.message : String(err)}`)).finally(() => {
49140
+ if (monitors.get(w.id) === live2) monitors.delete(w.id);
49141
+ });
49142
+ log3(`waker: started monitor ${w.id} for ${w.thread_slug} (pid ${proc.pid ?? "?"})`);
49143
+ return live2;
49144
+ }
49145
+ function onMonitorEvent(live2, event) {
49146
+ if (stopped || live2.stopping) return;
49147
+ const atMs = nextWakeAt(live2);
49148
+ const text2 = event.lines.join("\n");
49149
+ const n = deps.storage.recordMonitorEvent(live2.id, { atMs, text: text2.slice(0, 500) });
49150
+ if (n === void 0) {
49151
+ stopMonitor(live2, "dropped");
49152
+ return;
49153
+ }
49154
+ if (live2.registration) {
49155
+ live2.registration.events.push(event.more > 0 ? `${text2}
49156
+ \u2026and ${event.more} more line${event.more === 1 ? "" : "s"}` : text2);
49157
+ return;
49158
+ }
49159
+ const w = deps.storage.getCommandWatch(live2.id);
49160
+ const row = deps.storage.getSession(live2.slug);
49161
+ if (!w || !threadIsLive(row)) return;
49162
+ enqueueCommandWatchWake(
49163
+ row,
49164
+ `${MONITOR_EVENT_FENCE_PREFIX}:${live2.id}:${n}`,
49165
+ monitorEventWakeMessage({ id: live2.id, label: monitorLabel(w), lines: event.lines, more: event.more, event: n }),
49166
+ `monitor ${live2.id} event ${n}`,
49167
+ atMs
49168
+ );
49169
+ live2.recent = live2.recent.filter((t) => atMs - t < MONITOR_FLOOD_WINDOW_MS);
49170
+ live2.recent.push(atMs);
49171
+ if (live2.recent.length >= MONITOR_FLOOD_MAX_EVENTS) cancelMonitor(row, deps.storage.getCommandWatch(live2.id) ?? w, MONITOR_FLOOD_REASON, atMs);
49172
+ kick();
49173
+ }
49174
+ function onMonitorExit(live2, run3) {
49175
+ const atMs = nextWakeAt(live2);
49176
+ deps.storage.recordMonitorExit(live2.id, { atMs, outcome: run3.outcome, exitCode: run3.exitCode, output: run3.output });
49177
+ if (live2.stopping || stopped) return;
49178
+ const w = deps.storage.getCommandWatch(live2.id);
49179
+ if (!w || w.state !== "armed") return;
49180
+ if (live2.registration) {
49181
+ live2.registration.exited = { at: new Date(run3.finishedAtMs).toISOString(), outcome: run3.outcome, exitCode: run3.exitCode, output: run3.output };
49182
+ deps.storage.settleCommandWatch(live2.id, "passed", atMs);
49183
+ return;
49184
+ }
49185
+ const row = deps.storage.getSession(live2.slug);
49186
+ if (threadIsLive(row)) {
49187
+ enqueueCommandWatchWake(
49188
+ row,
49189
+ `${MONITOR_EXITED_FENCE_PREFIX}:${live2.id}`,
49190
+ monitorExitedWakeMessage({ id: live2.id, label: monitorLabel(w), command: w.command, events: w.events, run: run3 }),
49191
+ `monitor ${live2.id} ended (${run3.outcome === "exit" ? `exit ${run3.exitCode}` : run3.outcome}) after ${w.events} event(s)`,
49192
+ atMs
49193
+ );
49194
+ }
49195
+ deps.storage.settleCommandWatch(live2.id, "passed", atMs);
49196
+ log3(`waker: settled ${live2.slug} \u2014 monitor ${live2.id} ended on its own`);
49197
+ kick();
49198
+ }
49199
+ function expireMonitor(w, at2) {
49200
+ const live2 = monitors.get(w.id);
49201
+ if (live2) stopMonitor(live2, "expired");
49202
+ const nowMs = live2 ? Math.max(at2, nextWakeAt(live2)) : at2;
49203
+ const row = deps.storage.getSession(w.thread_slug);
49204
+ if (threadIsLive(row)) {
49205
+ enqueueCommandWatchWake(
49206
+ row,
49207
+ `${MONITOR_EXPIRED_FENCE_PREFIX}:${w.id}`,
49208
+ monitorExpiredWakeMessage({ id: w.id, label: monitorLabel(w), command: w.command, events: w.events }),
49209
+ `monitor ${w.id} expired after ${w.events} event(s)`,
49210
+ nowMs
49211
+ );
49212
+ }
49213
+ deps.storage.settleCommandWatch(w.id, "expired", nowMs);
49214
+ log3(`waker: settled ${w.thread_slug} \u2014 monitor ${w.id} expired`);
49215
+ }
49216
+ function cancelMonitor(row, w, reason, at2, by = "frizz") {
49217
+ const live2 = monitors.get(w.id);
49218
+ if (live2) stopMonitor(live2, "cancelled");
49219
+ const nowMs = live2 ? Math.max(at2, nextWakeAt(live2)) : at2;
49220
+ enqueueCommandWatchWake(
49221
+ row,
49222
+ `${MONITOR_CANCELLED_FENCE_PREFIX}:${w.id}`,
49223
+ monitorCancelledWakeMessage({ id: w.id, label: monitorLabel(w), command: w.command, events: w.events, reason, by }),
49224
+ by === "human" ? `monitor ${w.id} stopped by the human` : `monitor ${w.id} cancelled: ${reason}`,
49225
+ nowMs
49226
+ );
49227
+ deps.storage.settleCommandWatch(w.id, "cancelled", nowMs);
49228
+ log3(`waker: settled ${w.thread_slug} \u2014 monitor ${w.id} cancelled: ${reason}`);
49229
+ }
49230
+ async function startMonitor(id2, windowMs = MONITOR_REGISTRATION_WINDOW_MS) {
49231
+ const w = deps.storage.getCommandWatch(id2);
49232
+ if (!w || w.state !== "armed" || w.kind !== "monitor") return { running: false, events: [], refused: `no armed monitor ${id2}` };
49233
+ if (monitors.has(id2)) return { running: true, events: [] };
49234
+ const service = deps.commandWatches;
49235
+ if (!service) return { running: false, events: [], refused: "this server cannot run monitors" };
49236
+ const live2 = launchMonitor(service, w, now(), { events: [] });
49237
+ if (typeof live2 === "string") return { running: false, events: [], refused: live2 };
49238
+ let timer2;
49239
+ await Promise.race([live2.ended, new Promise((resolve14) => {
49240
+ timer2 = setTimeout(resolve14, windowMs);
49241
+ })]);
49242
+ if (timer2) clearTimeout(timer2);
49243
+ const seen = live2.registration ?? { events: [] };
49244
+ delete live2.registration;
49245
+ if (seen.exited) return { running: false, events: seen.events, exited: seen.exited };
49246
+ return { running: true, events: seen.events };
49247
+ }
49248
+ async function stopMonitorByHuman(slug, id2) {
49249
+ const w = deps.storage.getCommandWatch(id2);
49250
+ if (!w || w.kind !== "monitor" || w.state !== "armed" || w.thread_slug !== slug) return false;
49251
+ const row = deps.storage.getSession(slug);
49252
+ const live2 = monitors.get(id2);
49253
+ if (row && threadIsLive(row)) cancelMonitor(row, w, MONITOR_STOPPED_BY_HUMAN_REASON, now(), "human");
49254
+ else {
49255
+ if (live2) stopMonitor(live2, "cancelled");
49256
+ deps.storage.settleCommandWatch(id2, "cancelled", now());
49257
+ }
49258
+ await live2?.ended;
49259
+ return true;
49260
+ }
49261
+ async function releaseMonitor(id2) {
49262
+ const live2 = monitors.get(id2);
49263
+ if (!live2) return;
49264
+ const w = deps.storage.getCommandWatch(id2);
49265
+ if (w && w.state === "armed") return;
49266
+ stopMonitor(live2, "dropped");
49267
+ await live2.ended;
49268
+ }
48325
49269
  function evalQuestionAnswers(nowMs) {
48326
49270
  const bySlug = /* @__PURE__ */ new Map();
48327
49271
  for (const q2 of deps.storage.undeliveredSettlements()) {
@@ -48891,13 +49835,19 @@ ${wakeTimeHeader(now(), spokeAt)}`;
48891
49835
  if (draining) await draining;
48892
49836
  for (const run3 of commandRuns.values()) run3.abort.abort();
48893
49837
  await commandRunsIdle();
49838
+ const ending = [...monitors.values()];
49839
+ for (const live2 of ending) stopMonitor(live2, "server");
49840
+ await Promise.all(ending.map((live2) => live2.ended));
48894
49841
  },
48895
49842
  tick,
48896
49843
  kick,
48897
- commandRunsIdle
49844
+ commandRunsIdle,
49845
+ startMonitor,
49846
+ releaseMonitor,
49847
+ stopMonitorByHuman
48898
49848
  };
48899
49849
  }
48900
- var execFileAsync5, PR_REF_RE2, OFF_MERGE_PATHS, MERGING_PERMISSIONS, LIMIT_FENCE_PREFIX, LIMIT_HINT_PREFIX, LIMIT_RESUME_GRACE_MS, LIMIT_RESUME_HEADROOM_PERCENT, LIMIT_HEADROOM_MIN_FAULT_AGE_MS, REPORT_FENCE_PREFIX, REPORT_HINT_PREFIX, SNOOZE_FENCE_PREFIX, SNOOZE_HINT_PREFIX, HEARTBEAT_FENCE_PREFIX, HEARTBEAT_HINT_PREFIX, STOP_HOOK_FENCE_PREFIX, STOP_HOOK_HINT_KEY, COMPACT_FENCE_PREFIX, COMPACT_HINT_KEY, TIMER_FENCE_PREFIX, TIMER_HINT_PREFIX, SHELL_FENCE_PREFIX, INTERRUPT_ENDED_FENCE_PREFIX, PR_WATCH_FENCE_PREFIX, PR_WATCH_EXPIRED_FENCE_PREFIX, OWN_WATCH_EXPIRED_FENCE_PREFIX, COMMAND_WATCH_FENCE_PREFIX, COMMAND_WATCH_EXPIRED_FENCE_PREFIX, COMMAND_WATCH_CANCELLED_FENCE_PREFIX, QUESTION_ANSWER_FENCE_PREFIX, ANSWER_REOFFER_BACKOFF_MS, CONTEXT_SUPERSEDED, PR_WATCH_POLL_MS, PR_WATCH_GONE_MS, PR_STATUS_FALLBACK_LIMIT, SIGNOFF_FENCE_PREFIX, SIGNOFF_HINT_KEY, SIGNOFF_NUDGE_MAX, PARK_BUMP_MAX, SIGNOFF_NUDGE_SETTING, PARK_FENCE_PREFIX, QUESTION_FENCE_CAUSE, DONE_OVER_QUESTION_CAUSE, DONE_GATE_FROM_MS, FAULTS_OUTLIVE_HUMAN_FROM_MS, GITHUB_STATUS_CAP, REVIEW_SEEN_CAP, REVIEW_STEER_CAP, AWAITING_KEY_OF, MID_TURN_HOLD_MAX_MS, WAKE_HOLD_DEFERRAL;
49850
+ var execFileAsync5, PR_REF_RE2, OFF_MERGE_PATHS, MERGING_PERMISSIONS, LIMIT_FENCE_PREFIX, LIMIT_HINT_PREFIX, LIMIT_RESUME_GRACE_MS, LIMIT_RESUME_HEADROOM_PERCENT, LIMIT_HEADROOM_MIN_FAULT_AGE_MS, REPORT_FENCE_PREFIX, REPORT_HINT_PREFIX, SNOOZE_FENCE_PREFIX, SNOOZE_HINT_PREFIX, HEARTBEAT_FENCE_PREFIX, HEARTBEAT_HINT_PREFIX, STOP_HOOK_FENCE_PREFIX, STOP_HOOK_HINT_KEY, COMPACT_FENCE_PREFIX, COMPACT_HINT_KEY, TIMER_FENCE_PREFIX, TIMER_HINT_PREFIX, SHELL_FENCE_PREFIX, INTERRUPT_ENDED_FENCE_PREFIX, PR_WATCH_FENCE_PREFIX, PR_WATCH_EXPIRED_FENCE_PREFIX, OWN_WATCH_EXPIRED_FENCE_PREFIX, COMMAND_WATCH_FENCE_PREFIX, COMMAND_WATCH_EXPIRED_FENCE_PREFIX, COMMAND_WATCH_CANCELLED_FENCE_PREFIX, MONITOR_EVENT_FENCE_PREFIX, MONITOR_EXITED_FENCE_PREFIX, MONITOR_EXPIRED_FENCE_PREFIX, MONITOR_CANCELLED_FENCE_PREFIX, MONITOR_OUTPUT_PRUNE_EVERY_MS, QUESTION_ANSWER_FENCE_PREFIX, ANSWER_REOFFER_BACKOFF_MS, CONTEXT_SUPERSEDED, PR_WATCH_POLL_MS, PR_WATCH_GONE_MS, PR_STATUS_FALLBACK_LIMIT, SIGNOFF_FENCE_PREFIX, SIGNOFF_HINT_KEY, SIGNOFF_NUDGE_MAX, PARK_BUMP_MAX, SIGNOFF_NUDGE_SETTING, PARK_FENCE_PREFIX, QUESTION_FENCE_CAUSE, DONE_OVER_QUESTION_CAUSE, DONE_GATE_FROM_MS, FAULTS_OUTLIVE_HUMAN_FROM_MS, GITHUB_STATUS_CAP, REVIEW_SEEN_CAP, REVIEW_STEER_CAP, AWAITING_KEY_OF, MID_TURN_HOLD_MAX_MS, WAKE_HOLD_DEFERRAL;
48901
49851
  var init_scheduler = __esm({
48902
49852
  "packages/server/src/scheduler.ts"() {
48903
49853
  "use strict";
@@ -48944,6 +49894,11 @@ var init_scheduler = __esm({
48944
49894
  COMMAND_WATCH_FENCE_PREFIX = "cmdwatch";
48945
49895
  COMMAND_WATCH_EXPIRED_FENCE_PREFIX = "cmdwatch-expired";
48946
49896
  COMMAND_WATCH_CANCELLED_FENCE_PREFIX = "cmdwatch-cancelled";
49897
+ MONITOR_EVENT_FENCE_PREFIX = "cmdmon";
49898
+ MONITOR_EXITED_FENCE_PREFIX = "cmdmon-exited";
49899
+ MONITOR_EXPIRED_FENCE_PREFIX = "cmdmon-expired";
49900
+ MONITOR_CANCELLED_FENCE_PREFIX = "cmdmon-cancelled";
49901
+ MONITOR_OUTPUT_PRUNE_EVERY_MS = 60 * 6e4;
48947
49902
  QUESTION_ANSWER_FENCE_PREFIX = "answers";
48948
49903
  ANSWER_REOFFER_BACKOFF_MS = 30 * 6e4;
48949
49904
  CONTEXT_SUPERSEDED = "the exact awaiting fence or session was superseded";
@@ -49052,7 +50007,7 @@ var init_resume = __esm({
49052
50007
  });
49053
50008
 
49054
50009
  // packages/server/src/backend/claude.ts
49055
- import { join as join39 } from "node:path";
50010
+ import { join as join40 } from "node:path";
49056
50011
  function toolResultText2(content) {
49057
50012
  if (typeof content === "string") return content;
49058
50013
  if (!Array.isArray(content)) return "";
@@ -49143,7 +50098,7 @@ function createClaudeBackend(opts) {
49143
50098
  return { argv, env: claudeWorkerEnvironment(), prewrite: [] };
49144
50099
  },
49145
50100
  transcriptPath(sessionId) {
49146
- return join39(opts.logDir, `${sessionId}.jsonl`);
50101
+ return join40(opts.logDir, `${sessionId}.jsonl`);
49147
50102
  },
49148
50103
  parseLine(line) {
49149
50104
  return parseClaudeLine(line);
@@ -49168,10 +50123,10 @@ var init_claude = __esm({
49168
50123
  });
49169
50124
 
49170
50125
  // packages/server/src/backend/acp-transcript.ts
49171
- import { appendFileSync as appendFileSync4, existsSync as existsSync15, mkdirSync as mkdirSync20, readFileSync as readFileSync25 } from "node:fs";
49172
- import { dirname as dirname19, join as join40 } from "node:path";
50126
+ import { appendFileSync as appendFileSync5, existsSync as existsSync16, mkdirSync as mkdirSync21, readFileSync as readFileSync26 } from "node:fs";
50127
+ import { dirname as dirname19, join as join41 } from "node:path";
49173
50128
  function acpTranscriptPath(stateDir, sessionId) {
49174
- return join40(stateDir, ACP_TRANSCRIPT_DIR, `${sessionId}.jsonl`);
50129
+ return join41(stateDir, ACP_TRANSCRIPT_DIR, `${sessionId}.jsonl`);
49175
50130
  }
49176
50131
  function parseAcpRecord(line) {
49177
50132
  if (!line.trim()) return void 0;
@@ -49195,7 +50150,7 @@ function parseAcpLine(line) {
49195
50150
  function acpContractOwed(path3) {
49196
50151
  let text2;
49197
50152
  try {
49198
- text2 = readFileSync25(path3, "utf8");
50153
+ text2 = readFileSync26(path3, "utf8");
49199
50154
  } catch {
49200
50155
  return false;
49201
50156
  }
@@ -49403,11 +50358,11 @@ var init_acp_transcript = __esm({
49403
50358
  AcpTranscriptWriter = class {
49404
50359
  constructor(path3) {
49405
50360
  this.path = path3;
49406
- mkdirSync20(dirname19(path3), { recursive: true });
49407
- if (!existsSync15(path3)) appendFileSync4(path3, "");
50361
+ mkdirSync21(dirname19(path3), { recursive: true });
50362
+ if (!existsSync16(path3)) appendFileSync5(path3, "");
49408
50363
  }
49409
50364
  append(record) {
49410
- appendFileSync4(this.path, JSON.stringify(record) + "\n");
50365
+ appendFileSync5(this.path, JSON.stringify(record) + "\n");
49411
50366
  }
49412
50367
  };
49413
50368
  TOOL_TEXT_MAX = 12e3;
@@ -49566,14 +50521,14 @@ var init_acp_types = __esm({
49566
50521
  });
49567
50522
 
49568
50523
  // packages/server/src/backend/acp-rpc.ts
49569
- import { spawn as spawn6 } from "node:child_process";
49570
- import { StringDecoder as StringDecoder4 } from "node:string_decoder";
50524
+ import { spawn as spawn7 } from "node:child_process";
50525
+ import { StringDecoder as StringDecoder5 } from "node:string_decoder";
49571
50526
  var spawnAcpChild, AcpRequestError, AcpRemoteError, AcpConnectionClosed, AcpRequestTimeout, DEFAULT_TIMEOUT_MS, DEFAULT_MAX_LINE_BYTES, AcpConnection;
49572
50527
  var init_acp_rpc = __esm({
49573
50528
  "packages/server/src/backend/acp-rpc.ts"() {
49574
50529
  "use strict";
49575
50530
  init_acp_types();
49576
- spawnAcpChild = ({ command, args, cwd, env }) => spawn6(command, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
50531
+ spawnAcpChild = ({ command, args, cwd, env }) => spawn7(command, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
49577
50532
  AcpRequestError = class extends Error {
49578
50533
  constructor(code, message, data) {
49579
50534
  super(message);
@@ -49650,7 +50605,7 @@ var init_acp_rpc = __esm({
49650
50605
  }
49651
50606
  nextId = 1;
49652
50607
  pending = /* @__PURE__ */ new Map();
49653
- decoder = new StringDecoder4("utf8");
50608
+ decoder = new StringDecoder5("utf8");
49654
50609
  buffer = "";
49655
50610
  overflowing = false;
49656
50611
  closedReason;
@@ -49791,18 +50746,18 @@ var init_acp_rpc = __esm({
49791
50746
  });
49792
50747
 
49793
50748
  // packages/server/src/backend/acp-host.ts
49794
- import { spawn as spawn7 } from "node:child_process";
50749
+ import { spawn as spawn8 } from "node:child_process";
49795
50750
  import { createConnection as createConnection2 } from "node:net";
49796
50751
  import { createHash as createHash19, randomUUID as randomUUID16 } from "node:crypto";
49797
- import { existsSync as existsSync16, mkdirSync as mkdirSync21, readFileSync as readFileSync26, readdirSync as readdirSync10, unlinkSync as unlinkSync4 } from "node:fs";
49798
- import { join as join41 } from "node:path";
50752
+ import { existsSync as existsSync17, mkdirSync as mkdirSync22, readFileSync as readFileSync27, readdirSync as readdirSync11, unlinkSync as unlinkSync4 } from "node:fs";
50753
+ import { join as join42 } from "node:path";
49799
50754
  import { PassThrough as PassThrough3, Writable as Writable3 } from "node:stream";
49800
- import { StringDecoder as StringDecoder5 } from "node:string_decoder";
50755
+ import { StringDecoder as StringDecoder6 } from "node:string_decoder";
49801
50756
  function daemonDir2(stateDir) {
49802
- return join41(stateDir, "acp-daemon");
50757
+ return join42(stateDir, "acp-daemon");
49803
50758
  }
49804
50759
  function acpDaemonRecordPath(stateDir, sessionId) {
49805
- return join41(daemonDir2(stateDir), `${sessionId}.json`);
50760
+ return join42(daemonDir2(stateDir), `${sessionId}.json`);
49806
50761
  }
49807
50762
  function acpDaemonSocketPath(stateDir, sessionId) {
49808
50763
  const key = createHash19("sha256").update(stateDir).update("\0").update(sessionId).digest("hex").slice(0, 16);
@@ -49818,7 +50773,7 @@ function pidAlive4(pid) {
49818
50773
  }
49819
50774
  function readAcpDaemonRecord(stateDir, sessionId) {
49820
50775
  try {
49821
- const value = JSON.parse(readFileSync26(acpDaemonRecordPath(stateDir, sessionId), "utf8"));
50776
+ const value = JSON.parse(readFileSync27(acpDaemonRecordPath(stateDir, sessionId), "utf8"));
49822
50777
  if (typeof value.daemonPid !== "number" || typeof value.socketPath !== "string" || typeof value.generation !== "string") return null;
49823
50778
  return {
49824
50779
  threadSlug: typeof value.threadSlug === "string" ? value.threadSlug : "",
@@ -49864,7 +50819,7 @@ async function stopAcpDaemon(stateDir, sessionId, timeoutMs = 1e4) {
49864
50819
  }
49865
50820
  function forkDaemon2(options) {
49866
50821
  const { stateDir, sessionId } = options;
49867
- mkdirSync21(daemonDir2(stateDir), { recursive: true });
50822
+ mkdirSync22(daemonDir2(stateDir), { recursive: true });
49868
50823
  const record = acpDaemonRecordPath(stateDir, sessionId);
49869
50824
  try {
49870
50825
  unlinkSync4(record);
@@ -49887,7 +50842,7 @@ function forkDaemon2(options) {
49887
50842
  ...options.reachabilityCheckMs === void 0 ? {} : { reachabilityCheckMs: options.reachabilityCheckMs },
49888
50843
  ...options.idleExitMs === void 0 ? {} : { idleExitMs: options.idleExitMs }
49889
50844
  });
49890
- const child = spawn7(process.execPath, [options.daemonEntry ?? daemonEntry2()], {
50845
+ const child = spawn8(process.execPath, [options.daemonEntry ?? daemonEntry2()], {
49891
50846
  cwd: options.cwd,
49892
50847
  // The daemon's OWN environment only needs the handoff; the agent's environment travels in the
49893
50848
  // payload and is applied by the daemon, keeping the audited env allowlist authoritative.
@@ -49974,7 +50929,7 @@ function attach3(record, timeoutMs) {
49974
50929
  } catch {
49975
50930
  }
49976
50931
  };
49977
- const decoder = new StringDecoder5("utf8");
50932
+ const decoder = new StringDecoder6("utf8");
49978
50933
  let buffer = "";
49979
50934
  socket.on("data", (chunk2) => {
49980
50935
  buffer += decoder.write(chunk2);
@@ -50060,7 +51015,7 @@ var init_acp_host = __esm({
50060
51015
  }
50061
51016
  if (process.platform !== "win32") {
50062
51017
  const stale = acpDaemonSocketPath(stateDir, sessionId);
50063
- if (existsSync16(stale) && !liveAcpDaemonRecord(stateDir, sessionId)) {
51018
+ if (existsSync17(stale) && !liveAcpDaemonRecord(stateDir, sessionId)) {
50064
51019
  try {
50065
51020
  unlinkSync4(stale);
50066
51021
  } catch {
@@ -78476,7 +79431,7 @@ var init_claude_context_window = __esm({
78476
79431
  });
78477
79432
 
78478
79433
  // packages/server/src/backend/claude-agent-sdk.ts
78479
- import { accessSync as accessSync4, constants as fsConstants3, rmSync as rmSync13 } from "node:fs";
79434
+ import { accessSync as accessSync4, constants as fsConstants3, rmSync as rmSync14 } from "node:fs";
78480
79435
  import { delimiter as delimiter3, isAbsolute as isAbsolute10 } from "node:path";
78481
79436
  function stillQueuedIds(raw2) {
78482
79437
  return boundedStringArray(raw2, "interrupt.stillQueued", 256, 512).map((id2, index) => boundedId(id2, `interrupt.stillQueued[${index}]`));
@@ -78616,7 +79571,7 @@ function startClaudeQuery(executablePath, options) {
78616
79571
  if (mcpConfigFile) {
78617
79572
  const drop = () => {
78618
79573
  try {
78619
- rmSync13(mcpConfigFile, { force: true });
79574
+ rmSync14(mcpConfigFile, { force: true });
78620
79575
  } catch {
78621
79576
  }
78622
79577
  };
@@ -80035,240 +80990,6 @@ var init_claude_agent_sdk = __esm({
80035
80990
  }
80036
80991
  });
80037
80992
 
80038
- // packages/server/src/command-watch.ts
80039
- import { execFileSync as execFileSync5, spawn as spawn8 } from "node:child_process";
80040
- import { existsSync as existsSync18, readFileSync as readFileSync28 } from "node:fs";
80041
- import { homedir as homedir17, userInfo } from "node:os";
80042
- import { join as join43 } from "node:path";
80043
- function killGroup(pid, signal) {
80044
- if (!pid) return;
80045
- try {
80046
- process.kill(-pid, signal);
80047
- } catch {
80048
- }
80049
- }
80050
- function outputTail(chunks, max = COMMAND_WATCH_OUTPUT_MAX_BYTES) {
80051
- const all = Buffer.concat(chunks);
80052
- if (all.length <= max) return all.toString("utf8");
80053
- let start = all.length - max;
80054
- while (start < all.length && (all[start] & 192) === 128) start++;
80055
- return `\u2026${all.subarray(start).toString("utf8")}`;
80056
- }
80057
- function runWatchCommand(spec) {
80058
- const startedAtMs = Date.now();
80059
- const timeoutMs = spec.timeoutMs ?? COMMAND_WATCH_RUN_TIMEOUT_MS;
80060
- return new Promise((resolve14) => {
80061
- const chunks = [];
80062
- let held = 0;
80063
- const keep = (chunk2) => {
80064
- chunks.push(chunk2);
80065
- held += chunk2.length;
80066
- while (held - chunks[0].length >= COMMAND_WATCH_OUTPUT_MAX_BYTES && chunks.length > 1) held -= chunks.shift().length;
80067
- };
80068
- let settled = false;
80069
- let timedOut2 = false;
80070
- let aborted = false;
80071
- let exit = null;
80072
- const timers = [];
80073
- const finish = (result, extra) => {
80074
- if (settled) return;
80075
- settled = true;
80076
- for (const t of timers) clearTimeout(t);
80077
- spec.signal?.removeEventListener("abort", onAbort);
80078
- const output = outputTail(extra ? [...chunks, Buffer.from(extra)] : chunks);
80079
- resolve14({ ...result, output, startedAtMs, finishedAtMs: Date.now() });
80080
- };
80081
- let child;
80082
- try {
80083
- child = spawn8("/bin/sh", ["-c", spec.command], {
80084
- cwd: spec.cwd,
80085
- env: spec.env,
80086
- stdio: ["ignore", "pipe", "pipe"],
80087
- detached: true,
80088
- windowsHide: true
80089
- });
80090
- } catch (err) {
80091
- finish({ outcome: "error", exitCode: null }, `could not start /bin/sh: ${err instanceof Error ? err.message : String(err)}`);
80092
- return;
80093
- }
80094
- const onAbort = () => {
80095
- aborted = true;
80096
- killGroup(child.pid, "SIGKILL");
80097
- };
80098
- if (spec.signal?.aborted) onAbort();
80099
- else spec.signal?.addEventListener("abort", onAbort, { once: true });
80100
- child.stdout?.on("data", keep);
80101
- child.stderr?.on("data", keep);
80102
- child.on("error", (err) => {
80103
- finish({ outcome: "error", exitCode: null }, `could not start /bin/sh: ${err.message}`);
80104
- });
80105
- timers.push(setTimeout(() => {
80106
- timedOut2 = true;
80107
- killGroup(child.pid, "SIGTERM");
80108
- timers.push(setTimeout(() => killGroup(child.pid, "SIGKILL"), KILL_GRACE_MS));
80109
- }, timeoutMs));
80110
- const conclude = () => {
80111
- if (!exit) return;
80112
- if (timedOut2) finish({ outcome: "timeout", exitCode: null });
80113
- else if (aborted || exit.signal) finish({ outcome: "signal", exitCode: null });
80114
- else finish({ outcome: "exit", exitCode: exit.code });
80115
- };
80116
- child.on("exit", (code, signal) => {
80117
- exit = { code, signal };
80118
- killGroup(child.pid, "SIGKILL");
80119
- timers.push(setTimeout(() => {
80120
- child.stdout?.destroy();
80121
- child.stderr?.destroy();
80122
- conclude();
80123
- }, DRAIN_AFTER_EXIT_MS));
80124
- });
80125
- child.on("close", conclude);
80126
- });
80127
- }
80128
- function createRunLimiter(limit) {
80129
- let active = 0;
80130
- const waiting = [];
80131
- return async (fn) => {
80132
- if (active < limit) active++;
80133
- else await new Promise((resolve14) => waiting.push(resolve14));
80134
- try {
80135
- return await fn();
80136
- } finally {
80137
- const next = waiting.shift();
80138
- if (next) next();
80139
- else active--;
80140
- }
80141
- };
80142
- }
80143
- function claudeManagedPreferencePaths() {
80144
- let user = "";
80145
- try {
80146
- user = userInfo().username;
80147
- } catch {
80148
- }
80149
- return [
80150
- ...user ? [`/Library/Managed Preferences/${user}/com.anthropic.claudecode.plist`] : [],
80151
- "/Library/Managed Preferences/com.anthropic.claudecode.plist"
80152
- ];
80153
- }
80154
- function plistAsJson(path3) {
80155
- return execFileSync5("/usr/bin/plutil", ["-convert", "json", "-o", "-", "--", path3], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
80156
- }
80157
- function sandboxInSettings(raw2, file) {
80158
- let parsed;
80159
- try {
80160
- parsed = JSON.parse(raw2);
80161
- } catch {
80162
- return `\`${file}\` is not valid JSON, so Frizz cannot tell whether it turns Claude Code's sandbox on for this thread`;
80163
- }
80164
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
80165
- const sandbox = parsed.sandbox;
80166
- if (sandbox === void 0 || sandbox === null || sandbox === false) return void 0;
80167
- if (typeof sandbox === "object" && !Array.isArray(sandbox)) {
80168
- const enabled = sandbox.enabled;
80169
- if (enabled === void 0 || enabled === false) return void 0;
80170
- }
80171
- return `Claude Code's sandbox is on for this thread (\`sandbox\` in \`${file}\`), and a command watch would run your command outside it`;
80172
- }
80173
- function claudeSettingsFiles(where) {
80174
- const env = where.env ?? process.env;
80175
- const configDir = env.CLAUDE_CONFIG_DIR?.trim() ? env.CLAUDE_CONFIG_DIR.trim() : join43(where.home ?? homedir17(), ".claude");
80176
- return [
80177
- ...where.managedPaths ?? CLAUDE_MANAGED_SETTINGS_PATHS,
80178
- join43(where.cwd, ".claude", "settings.local.json"),
80179
- join43(where.cwd, ".claude", "settings.json"),
80180
- join43(configDir, "settings.json")
80181
- ];
80182
- }
80183
- function claudeSandboxRefusal(where) {
80184
- for (const file of claudeSettingsFiles(where)) {
80185
- let raw2;
80186
- try {
80187
- raw2 = readFileSync28(file, "utf8");
80188
- } catch (err) {
80189
- if (err?.code === "ENOENT" || err?.code === "ENOTDIR") continue;
80190
- return `Frizz could not read \`${file}\` to check whether Claude Code's sandbox is on for this thread`;
80191
- }
80192
- const refusal = sandboxInSettings(raw2, file);
80193
- if (refusal) return refusal;
80194
- }
80195
- const preferences = where.managedPreferencePaths ?? (process.platform === "darwin" ? claudeManagedPreferencePaths() : []);
80196
- for (const file of preferences) {
80197
- if (!existsSync18(file)) continue;
80198
- let raw2;
80199
- try {
80200
- raw2 = (where.readPlistJson ?? plistAsJson)(file);
80201
- } catch {
80202
- return `Frizz could not read \`${file}\` to check whether Claude Code's sandbox is on for this thread`;
80203
- }
80204
- const refusal = sandboxInSettings(raw2, file);
80205
- if (refusal) return refusal;
80206
- }
80207
- return void 0;
80208
- }
80209
- function commandWatchRefusal(row, opts) {
80210
- const refuse = (reason) => `${reason}. ${COMMAND_WATCH_FALLBACK}`;
80211
- if ((opts.platform ?? process.platform) === "win32") {
80212
- return refuse("command watches run under `/bin/sh`, which this machine does not have");
80213
- }
80214
- const backend = row.backend ?? "claude";
80215
- if (backend !== "claude") {
80216
- return refuse(
80217
- `command watches are for Claude threads only, and this one runs on ${backend === "codex" ? "Codex" : "an ACP agent"}: Frizz cannot tell whether your thread's own sandbox would have let the command run`
80218
- );
80219
- }
80220
- if (row.permission_mode !== "bypassPermissions") {
80221
- return refuse(
80222
- `this thread runs in \`${row.permission_mode ?? "an unrecorded"}\` permission mode, and the server runs a watched command with no permission check at all \u2014 so Frizz runs one only for a thread in \`bypassPermissions\` mode`
80223
- );
80224
- }
80225
- if (row.permission_pending && row.permission_pending !== "bypassPermissions") {
80226
- return refuse(`this thread's permission mode is being changed to \`${row.permission_pending}\``);
80227
- }
80228
- const sandbox = claudeSandboxRefusal({ cwd: opts.cwd, env: opts.env, home: opts.home, managedPaths: opts.managedPaths, managedPreferencePaths: opts.managedPreferencePaths, readPlistJson: opts.readPlistJson });
80229
- if (sandbox) return refuse(sandbox);
80230
- return void 0;
80231
- }
80232
- function createCommandWatchService(opts) {
80233
- const runner = opts.runner ?? runWatchCommand;
80234
- const limiter = opts.limiter ?? serverRunLimiter;
80235
- let probesActive = 0;
80236
- return {
80237
- refusal: (row) => commandWatchRefusal(row, { cwd: opts.cwd, ...opts.gate }),
80238
- run: (slug, command, runOpts) => limiter(() => runner({ command, cwd: opts.cwd, env: opts.env(slug), timeoutMs: COMMAND_WATCH_RUN_TIMEOUT_MS, signal: runOpts?.signal })),
80239
- async probe(slug, command) {
80240
- if (probesActive >= PROBE_CONCURRENCY) return void 0;
80241
- probesActive++;
80242
- try {
80243
- return await runner({ command, cwd: opts.cwd, env: opts.env(slug), timeoutMs: COMMAND_WATCH_PROBE_TIMEOUT_MS });
80244
- } finally {
80245
- probesActive--;
80246
- }
80247
- }
80248
- };
80249
- }
80250
- function commandWatchEnvironment(base, frizz) {
80251
- const { FRIZZ_THREAD: _tag, ...rest } = base;
80252
- return { ...rest, ...frizz, GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1" };
80253
- }
80254
- var KILL_GRACE_MS, DRAIN_AFTER_EXIT_MS, COMMAND_WATCH_SERVER_CONCURRENCY, serverRunLimiter, COMMAND_WATCH_PROBE_TIMEOUT_MS, PROBE_CONCURRENCY, CLAUDE_MANAGED_SETTINGS_PATHS;
80255
- var init_command_watch = __esm({
80256
- "packages/server/src/command-watch.ts"() {
80257
- "use strict";
80258
- init_src();
80259
- KILL_GRACE_MS = 2e3;
80260
- DRAIN_AFTER_EXIT_MS = 1e3;
80261
- COMMAND_WATCH_SERVER_CONCURRENCY = 4;
80262
- serverRunLimiter = createRunLimiter(COMMAND_WATCH_SERVER_CONCURRENCY);
80263
- COMMAND_WATCH_PROBE_TIMEOUT_MS = 15e3;
80264
- PROBE_CONCURRENCY = 2;
80265
- CLAUDE_MANAGED_SETTINGS_PATHS = [
80266
- "/Library/Application Support/ClaudeCode/managed-settings.json",
80267
- "/etc/claude-code/managed-settings.json"
80268
- ];
80269
- }
80270
- });
80271
-
80272
80993
  // packages/server/src/backend/claude-models.ts
80273
80994
  function resolveClaudeModels(rows) {
80274
80995
  const byAlias = /* @__PURE__ */ new Map();
@@ -80377,7 +81098,7 @@ var init_claude_models = __esm({
80377
81098
  });
80378
81099
 
80379
81100
  // packages/server/src/backend/codex-app-server-diagnostics.ts
80380
- import { appendFileSync as appendFileSync6, mkdirSync as mkdirSync23, renameSync as renameSync11, statSync as statSync20 } from "node:fs";
81101
+ import { appendFileSync as appendFileSync7, mkdirSync as mkdirSync24, renameSync as renameSync11, statSync as statSync21 } from "node:fs";
80381
81102
  import { join as join44 } from "node:path";
80382
81103
  function codexDiagnosticLogPath(stateDir, projectId) {
80383
81104
  return join44(stateDir, "codex-app-server", `${projectId}.diagnostics.log`);
@@ -80390,14 +81111,14 @@ function createCodexDiagnosticSink(stateDir, projectId, now = () => /* @__PURE__
80390
81111
  if (event.event === "stderr") return;
80391
81112
  try {
80392
81113
  if (!ensured) {
80393
- mkdirSync23(dir, { recursive: true });
81114
+ mkdirSync24(dir, { recursive: true });
80394
81115
  ensured = true;
80395
81116
  }
80396
81117
  try {
80397
- if (statSync20(path3).size > MAX_BYTES2) renameSync11(path3, `${path3}.1`);
81118
+ if (statSync21(path3).size > MAX_BYTES2) renameSync11(path3, `${path3}.1`);
80398
81119
  } catch {
80399
81120
  }
80400
- appendFileSync6(path3, `${JSON.stringify({ at: now().toISOString(), ...event })}
81121
+ appendFileSync7(path3, `${JSON.stringify({ at: now().toISOString(), ...event })}
80401
81122
  `);
80402
81123
  } catch {
80403
81124
  }
@@ -80413,7 +81134,7 @@ var init_codex_app_server_diagnostics = __esm({
80413
81134
 
80414
81135
  // packages/server/src/backend/stale-socket-sweep.ts
80415
81136
  import { execFile as execFile9 } from "node:child_process";
80416
- import { readdirSync as readdirSync12, unlinkSync as unlinkSync6 } from "node:fs";
81137
+ import { readdirSync as readdirSync13, unlinkSync as unlinkSync6 } from "node:fs";
80417
81138
  import { connect as connectSocket } from "node:net";
80418
81139
  import { join as join45 } from "node:path";
80419
81140
  function parseLsofSocketNames(stdout) {
@@ -80432,7 +81153,7 @@ function sweepStaleSockets(options, deps = {}) {
80432
81153
  const keep = new Set(options.keep ?? []);
80433
81154
  let candidates;
80434
81155
  try {
80435
- candidates = (deps.readdir ?? readdirSync12)(options.dir).filter((name) => name.startsWith(options.prefix) && name.endsWith(".sock")).map((name) => join45(options.dir, name)).filter((path3) => !keep.has(path3));
81156
+ candidates = (deps.readdir ?? readdirSync13)(options.dir).filter((name) => name.startsWith(options.prefix) && name.endsWith(".sock")).map((name) => join45(options.dir, name)).filter((path3) => !keep.has(path3));
80436
81157
  } catch {
80437
81158
  return;
80438
81159
  }
@@ -80810,7 +81531,7 @@ var init_orphan_reaper = __esm({
80810
81531
 
80811
81532
  // packages/server/src/backend/lazy-mcp-host.ts
80812
81533
  import { createHash as createHash20, randomBytes as randomBytes2 } from "node:crypto";
80813
- import { mkdirSync as mkdirSync24, readFileSync as readFileSync30, renameSync as renameSync12, writeFileSync as writeFileSync15 } from "node:fs";
81534
+ import { mkdirSync as mkdirSync25, readFileSync as readFileSync30, renameSync as renameSync12, writeFileSync as writeFileSync16 } from "node:fs";
80814
81535
  import { join as join46 } from "node:path";
80815
81536
  function lazyMcpCacheKey(server, cwd) {
80816
81537
  const identity = JSON.stringify({ command: server.command, args: server.args ?? [], env: server.env ?? {}, cwd });
@@ -81687,6 +82408,7 @@ function createContextUnchecked(opts, resources) {
81687
82408
  });
81688
82409
  const commandWatches = createCommandWatchService({
81689
82410
  cwd: project.dir,
82411
+ monitorOutputDir: join47(project.stateDir, "monitors"),
81690
82412
  env: (slug) => {
81691
82413
  const base = sanitizeProviderChildEnvironment(process.env);
81692
82414
  const cli = resolveFrizzCli(frizzMcpTarget);
@@ -84568,7 +85290,7 @@ var init_server = __esm({
84568
85290
  });
84569
85291
 
84570
85292
  // packages/server/src/repair.ts
84571
- import { existsSync as existsSync19, readFileSync as readFileSync31, writeFileSync as writeFileSync16 } from "node:fs";
85293
+ import { existsSync as existsSync19, readFileSync as readFileSync31, writeFileSync as writeFileSync17 } from "node:fs";
84572
85294
  import { basename as basename8, dirname as dirname22, resolve as resolve10 } from "node:path";
84573
85295
  function quoteValue(v) {
84574
85296
  if (/^[\w./#:+-]+$/.test(v)) return v;
@@ -84599,7 +85321,7 @@ function repairThreadFile(frizzDir, file) {
84599
85321
  "---",
84600
85322
  ""
84601
85323
  ].join("\n");
84602
- writeFileSync16(abs, frontmatter + content);
85324
+ writeFileSync17(abs, frontmatter + content);
84603
85325
  return { slug };
84604
85326
  }
84605
85327
  var RepairError, REPAIR_STATUS_TEXT;
@@ -85023,9 +85745,9 @@ var init_bash_background = __esm({
85023
85745
  });
85024
85746
 
85025
85747
  // packages/server/src/transcript.ts
85026
- import { closeSync as closeSync16, existsSync as existsSync20, fstatSync as fstatSync4, mkdirSync as mkdirSync25, openSync as openSync17, readdirSync as readdirSync13, readFileSync as readFileSync33, readSync as readSync9, renameSync as renameSync13, statSync as statSync21, unlinkSync as unlinkSync7, writeFileSync as writeFileSync17 } from "node:fs";
85748
+ import { closeSync as closeSync16, existsSync as existsSync20, fstatSync as fstatSync4, mkdirSync as mkdirSync26, openSync as openSync17, readdirSync as readdirSync14, readFileSync as readFileSync33, readSync as readSync9, renameSync as renameSync13, statSync as statSync22, unlinkSync as unlinkSync7, writeFileSync as writeFileSync18 } from "node:fs";
85027
85749
  import { createHash as createHash21 } from "node:crypto";
85028
- import { StringDecoder as StringDecoder6 } from "node:string_decoder";
85750
+ import { StringDecoder as StringDecoder7 } from "node:string_decoder";
85029
85751
  import { join as join48 } from "node:path";
85030
85752
  import { homedir as homedir19 } from "node:os";
85031
85753
  function compactionMessage(sourceId, at2) {
@@ -85675,11 +86397,11 @@ function looksLikeImage(buf, ext) {
85675
86397
  }
85676
86398
  function pruneScreenshotCache() {
85677
86399
  try {
85678
- const entries2 = readdirSync13(SCREENSHOT_CACHE_DIR).filter((n) => !n.startsWith("."));
86400
+ const entries2 = readdirSync14(SCREENSHOT_CACHE_DIR).filter((n) => !n.startsWith("."));
85679
86401
  if (entries2.length <= SCREENSHOT_CACHE_MAX) return;
85680
86402
  const byMtime = entries2.map((n) => {
85681
86403
  try {
85682
- return { n, m: statSync21(join48(SCREENSHOT_CACHE_DIR, n)).mtimeMs };
86404
+ return { n, m: statSync22(join48(SCREENSHOT_CACHE_DIR, n)).mtimeMs };
85683
86405
  } catch {
85684
86406
  return { n, m: 0 };
85685
86407
  }
@@ -85722,9 +86444,9 @@ function persistBase64Image(mediaType, data, idKey) {
85722
86444
  if (data.length > SCREENSHOT_MAX_BASE64) return void 0;
85723
86445
  const buf = Buffer.from(data, "base64");
85724
86446
  if (buf.length === 0 || !looksLikeImage(buf, ext)) return void 0;
85725
- mkdirSync25(SCREENSHOT_CACHE_DIR, { recursive: true });
86447
+ mkdirSync26(SCREENSHOT_CACHE_DIR, { recursive: true });
85726
86448
  const tmp = join48(SCREENSHOT_CACHE_DIR, `.${name}.${process.pid}.${screenshotTmpSeq++}.tmp`);
85727
- writeFileSync17(tmp, buf);
86449
+ writeFileSync18(tmp, buf);
85728
86450
  renameSync13(tmp, path3);
85729
86451
  pruneScreenshotCache();
85730
86452
  return path3;
@@ -85740,13 +86462,13 @@ function persistSentFile(srcPath, idKey) {
85740
86462
  const name = createHash21("sha256").update(idKey).digest("hex").slice(0, 32);
85741
86463
  const dest = join48(SCREENSHOT_CACHE_DIR, `${name}.${outExt}`);
85742
86464
  if (existsSync20(dest)) return dest;
85743
- const size = statSync21(srcPath).size;
86465
+ const size = statSync22(srcPath).size;
85744
86466
  if (size === 0 || size > SENT_IMAGE_MAX_BYTES) return void 0;
85745
86467
  const buf = readFileSync33(srcPath);
85746
86468
  if (!looksLikeImage(buf, outExt)) return void 0;
85747
- mkdirSync25(SCREENSHOT_CACHE_DIR, { recursive: true });
86469
+ mkdirSync26(SCREENSHOT_CACHE_DIR, { recursive: true });
85748
86470
  const tmp = join48(SCREENSHOT_CACHE_DIR, `.${name}.${process.pid}.${screenshotTmpSeq++}.tmp`);
85749
- writeFileSync17(tmp, buf);
86471
+ writeFileSync18(tmp, buf);
85750
86472
  renameSync13(tmp, dest);
85751
86473
  pruneScreenshotCache();
85752
86474
  return dest;
@@ -86152,7 +86874,7 @@ function retainedFoldEntry(path3, identityPrefix, fileId, size) {
86152
86874
  }
86153
86875
  const hit = entry !== void 0;
86154
86876
  if (!entry) {
86155
- entry = { identityPrefix, fold: createTranscriptFold(identityPrefix), bytesRead: 0, decoder: new StringDecoder6("utf8"), fileId };
86877
+ entry = { identityPrefix, fold: createTranscriptFold(identityPrefix), bytesRead: 0, decoder: new StringDecoder7("utf8"), fileId };
86156
86878
  } else {
86157
86879
  transcriptCache.delete(path3);
86158
86880
  }
@@ -86213,7 +86935,7 @@ function logDirOf(project) {
86213
86935
  function resolveTranscriptPath(project, sessionId) {
86214
86936
  const path3 = join48(logDirOf(project), `${sessionId}.jsonl`);
86215
86937
  try {
86216
- if (statSync21(path3).size > 0) return path3;
86938
+ if (statSync22(path3).size > 0) return path3;
86217
86939
  } catch {
86218
86940
  }
86219
86941
  const stranded = discoverTranscriptDir(logDirOf(project), sessionId);
@@ -87709,7 +88431,7 @@ var init_transcript = __esm({
87709
88431
  });
87710
88432
 
87711
88433
  // packages/server/src/subagent-facts.ts
87712
- import { readFileSync as readFileSync34, statSync as statSync22 } from "node:fs";
88434
+ import { readFileSync as readFileSync34, statSync as statSync23 } from "node:fs";
87713
88435
  function readSubAgentContextUsage(absPath, format) {
87714
88436
  let text2;
87715
88437
  try {
@@ -87721,7 +88443,7 @@ function readSubAgentContextUsage(absPath, format) {
87721
88443
  }
87722
88444
  function readSubAgentLastActivityAt(absPath) {
87723
88445
  try {
87724
- return statSync22(absPath).mtime.toISOString();
88446
+ return statSync23(absPath).mtime.toISOString();
87725
88447
  } catch {
87726
88448
  return void 0;
87727
88449
  }
@@ -87819,6 +88541,72 @@ var init_open_external = __esm({
87819
88541
  }
87820
88542
  });
87821
88543
 
88544
+ // packages/server/src/thread-listing.ts
88545
+ function threadListing(t, nowMs) {
88546
+ const band = threadBandAt(t, nowMs);
88547
+ if (!band) return null;
88548
+ const inFlight2 = t.runtime === "running" || t.runtime === "spawning";
88549
+ const asked = (t.questions ?? []).filter((q2) => q2.standing !== false).length;
88550
+ const unregistered = (t.pendingAsk ? 1 : 0) + (t.pendingQuestion && !hasStandingQuestion(t) ? 1 : 0) + (t.runtime === "perm-prompt" ? 1 : 0);
88551
+ const lastLine = t.lastAssistantLine?.trim();
88552
+ const snoozedUntil = futureSnoozedUntil(t, nowMs);
88553
+ return {
88554
+ slug: t.id,
88555
+ title: displayTitle(t),
88556
+ band,
88557
+ runtime: t.runtime,
88558
+ ...t.backend ? { backend: t.backend } : {},
88559
+ ...t.model ? { model: t.model } : {},
88560
+ ...t.pinnedAt ? { pinned: true } : {},
88561
+ ...inFlight2 && t.liveTool ? { doing: t.liveTool.desc?.trim() || t.liveTool.name } : {},
88562
+ ...lastLine ? { lastLine: lastLine.length > LAST_LINE_MAX ? `${lastLine.slice(0, LAST_LINE_MAX - 1)}\u2026` : lastLine } : {},
88563
+ ...t.lastFence ? { fence: t.lastFence.kind } : {},
88564
+ questions: asked + unregistered,
88565
+ subAgents: (t.subAgents ?? []).filter((a) => isDirectSubAgent(a) && a.state === "running").length,
88566
+ shells: (t.bgShells ?? []).filter((s) => s.state === "running").length,
88567
+ watches: (t.watches ?? []).filter((w) => w.state === "armed" && w.kind !== "shell").map(watchLabel),
88568
+ ...t.limitPause ? { limited: true } : {},
88569
+ ...t.crashed ? { crashed: true } : {},
88570
+ ...t.spawnedAt ? { spawnedAt: t.spawnedAt } : {},
88571
+ ...t.lastAssistantAt ? { restedAt: t.lastAssistantAt } : {},
88572
+ ...t.lastActivityAt ? { lastActivityAt: t.lastActivityAt } : {},
88573
+ ...snoozedUntil ? { snoozedUntil } : {},
88574
+ ...t.archivedAt ? { archivedAt: t.archivedAt } : {}
88575
+ };
88576
+ }
88577
+ function watchLabel(w) {
88578
+ if (w.kind === "timer" && w.timer) return `timer at ${w.timer.fireAt}`;
88579
+ return w.target;
88580
+ }
88581
+ function recency(row) {
88582
+ const at2 = row.band === "done" ? row.archivedAt ?? row.lastActivityAt : row.lastActivityAt ?? row.restedAt ?? row.spawnedAt;
88583
+ const ms = Date.parse(at2 ?? "");
88584
+ return Number.isFinite(ms) ? ms : 0;
88585
+ }
88586
+ function listBoardThreads(threads, project, opts = {}) {
88587
+ const nowMs = opts.nowMs ?? Date.now();
88588
+ const counts = { rested: 0, active: 0, snoozed: 0, done: 0 };
88589
+ const rows = [];
88590
+ for (const t of threads) {
88591
+ const row = threadListing(t, nowMs);
88592
+ if (!row) continue;
88593
+ counts[row.band] += 1;
88594
+ if (row.band === "done" && !opts.all) continue;
88595
+ rows.push(row);
88596
+ }
88597
+ rows.sort((a, b) => BAND_ORDER.indexOf(a.band) - BAND_ORDER.indexOf(b.band) || recency(b) - recency(a) || a.slug.localeCompare(b.slug));
88598
+ return { project, threads: rows, counts };
88599
+ }
88600
+ var BAND_ORDER, LAST_LINE_MAX;
88601
+ var init_thread_listing = __esm({
88602
+ "packages/server/src/thread-listing.ts"() {
88603
+ "use strict";
88604
+ init_src();
88605
+ BAND_ORDER = ["rested", "active", "snoozed", "done"];
88606
+ LAST_LINE_MAX = 200;
88607
+ }
88608
+ });
88609
+
87822
88610
  // packages/server/src/github-hovercard.ts
87823
88611
  function parseRef(ref) {
87824
88612
  const match2 = REF_PATTERN.exec(ref);
@@ -88248,12 +89036,12 @@ var init_background_shell_output = __esm({
88248
89036
  });
88249
89037
 
88250
89038
  // packages/server/src/image-header.ts
88251
- import { closeSync as closeSync18, openSync as openSync19, readSync as readSync11, statSync as statSync23 } from "node:fs";
89039
+ import { closeSync as closeSync18, openSync as openSync19, readSync as readSync11, statSync as statSync24 } from "node:fs";
88252
89040
  import { extname as extname2 } from "node:path";
88253
89041
  function readHead4(path3, budget) {
88254
89042
  let fd2;
88255
89043
  try {
88256
- const size = statSync23(path3).size;
89044
+ const size = statSync24(path3).size;
88257
89045
  if (size === 0) return void 0;
88258
89046
  const buffer = Buffer.alloc(Math.min(size, budget));
88259
89047
  fd2 = openSync19(path3, "r");
@@ -88766,7 +89554,7 @@ var init_raster = __esm({
88766
89554
  });
88767
89555
 
88768
89556
  // packages/server/src/icon-renditions.ts
88769
- import { mkdirSync as mkdirSync26, readdirSync as readdirSync14, readFileSync as readFileSync35, renameSync as renameSync14, rmSync as rmSync14, writeFileSync as writeFileSync18 } from "node:fs";
89557
+ import { mkdirSync as mkdirSync27, readdirSync as readdirSync15, readFileSync as readFileSync35, renameSync as renameSync14, rmSync as rmSync15, writeFileSync as writeFileSync19 } from "node:fs";
88770
89558
  import { homedir as homedir20 } from "node:os";
88771
89559
  import { join as join49 } from "node:path";
88772
89560
  function iconRenditionDir(id2, home = homedir20()) {
@@ -88799,10 +89587,10 @@ function projectIconRendition(id2, bytes, hash, size, options = {}) {
88799
89587
  if (!master) return void 0;
88800
89588
  const png2 = encodePng(resizeToFit(master, size));
88801
89589
  try {
88802
- mkdirSync26(dir, { recursive: true });
88803
- for (const name of readdirSync14(dir)) if (!name.startsWith(`${hash}-`)) rmSync14(join49(dir, name), { force: true });
89590
+ mkdirSync27(dir, { recursive: true });
89591
+ for (const name of readdirSync15(dir)) if (!name.startsWith(`${hash}-`)) rmSync15(join49(dir, name), { force: true });
88804
89592
  const partial = `${file}.${process.pid}.tmp`;
88805
- writeFileSync18(partial, png2);
89593
+ writeFileSync19(partial, png2);
88806
89594
  renameSync14(partial, file);
88807
89595
  } catch {
88808
89596
  }
@@ -88823,7 +89611,7 @@ var init_icon_renditions = __esm({
88823
89611
  });
88824
89612
 
88825
89613
  // packages/server/src/project-icon.ts
88826
- import { readFileSync as readFileSync36, readdirSync as readdirSync15, realpathSync as realpathSync15, statSync as statSync24 } from "node:fs";
89614
+ import { readFileSync as readFileSync36, readdirSync as readdirSync16, realpathSync as realpathSync15, statSync as statSync25 } from "node:fs";
88827
89615
  import { homedir as homedir21 } from "node:os";
88828
89616
  import { basename as basename10, dirname as dirname23, extname as extname3, join as join50, relative as relative2, sep as sep4 } from "node:path";
88829
89617
  function normalizeStem(stem) {
@@ -88850,7 +89638,7 @@ function under(root, relativeDirectory) {
88850
89638
  }
88851
89639
  function listFiles(directory) {
88852
89640
  try {
88853
- return readdirSync15(directory, { withFileTypes: true }).filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => entry.name);
89641
+ return readdirSync16(directory, { withFileTypes: true }).filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => entry.name);
88854
89642
  } catch {
88855
89643
  return [];
88856
89644
  }
@@ -88859,7 +89647,7 @@ function iconDirectories(root) {
88859
89647
  let children2;
88860
89648
  try {
88861
89649
  children2 = new Set(
88862
- readdirSync15(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name)
89650
+ readdirSync16(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name)
88863
89651
  );
88864
89652
  } catch {
88865
89653
  return [root];
@@ -88875,7 +89663,7 @@ function iconDirectories(root) {
88875
89663
  if (!children2.has(container)) continue;
88876
89664
  let members;
88877
89665
  try {
88878
- members = readdirSync15(join50(root, container), { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
89666
+ members = readdirSync16(join50(root, container), { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
88879
89667
  } catch {
88880
89668
  continue;
88881
89669
  }
@@ -88977,7 +89765,7 @@ function resolveProjectIconResponse(id2, options = {}) {
88977
89765
  let real;
88978
89766
  try {
88979
89767
  real = realpathSync15(path3);
88980
- if (!statSync24(real).isFile()) return { status: 404 };
89768
+ if (!statSync25(real).isFile()) return { status: 404 };
88981
89769
  } catch {
88982
89770
  return { status: 404 };
88983
89771
  }
@@ -89356,11 +90144,11 @@ function run(argv) {
89356
90144
  });
89357
90145
 
89358
90146
  // packages/server/src/router.ts
89359
- import { readFileSync as readFileSync37, statSync as statSync25 } from "node:fs";
90147
+ import { readFileSync as readFileSync37, statSync as statSync26 } from "node:fs";
89360
90148
  import { join as join51, resolve as resolve11 } from "node:path";
89361
90149
  import { randomUUID as randomUUID20 } from "node:crypto";
89362
90150
  import { basename as basename11, dirname as dirname24 } from "node:path";
89363
- import { existsSync as existsSync21, mkdirSync as mkdirSync27, rmSync as rmSync15, writeFileSync as writeFileSync19 } from "node:fs";
90151
+ import { existsSync as existsSync21, mkdirSync as mkdirSync28, rmSync as rmSync16, writeFileSync as writeFileSync20 } from "node:fs";
89364
90152
  import { homedir as homedir22 } from "node:os";
89365
90153
  function validateGithubDispatchProfile(input, codexModels) {
89366
90154
  if (input.backend === "acp") return;
@@ -89541,7 +90329,7 @@ function addProjectAtPath(input, home = homedir22()) {
89541
90329
  const absolute = resolve11(expanded);
89542
90330
  let stats;
89543
90331
  try {
89544
- stats = statSync25(absolute);
90332
+ stats = statSync26(absolute);
89545
90333
  } catch {
89546
90334
  throw new Error(`No folder at ${absolute}`);
89547
90335
  }
@@ -89569,15 +90357,15 @@ function storeProjectIcon(id2, name, bytes) {
89569
90357
  if (!entry) throw new Error("No such project.");
89570
90358
  if (bytes.length === 0) throw new Error("That file is empty.");
89571
90359
  const path3 = customIconPath(id2, `.${extension2}`);
89572
- mkdirSync27(dirname24(path3), { recursive: true });
89573
- writeFileSync19(path3, bytes);
90360
+ mkdirSync28(dirname24(path3), { recursive: true });
90361
+ writeFileSync20(path3, bytes);
89574
90362
  if (!imageDimensions(path3)) {
89575
- rmSync15(path3, { force: true });
90363
+ rmSync16(path3, { force: true });
89576
90364
  throw new Error("That file does not look like an image Frizz can draw.");
89577
90365
  }
89578
90366
  for (const stale of PROJECT_ICON_EXTENSIONS) {
89579
90367
  const other = customIconPath(id2, `.${stale}`);
89580
- if (other !== path3) rmSync15(other, { force: true });
90368
+ if (other !== path3) rmSync16(other, { force: true });
89581
90369
  }
89582
90370
  const updated = setProjectIcon(id2, path3);
89583
90371
  if (!updated) throw new Error("No such project.");
@@ -90066,7 +90854,8 @@ ${gapNote}` : input.message;
90066
90854
  createdAt: new Date(w.created_at).toISOString(),
90067
90855
  expiresAt: new Date(w.expires_at).toISOString(),
90068
90856
  runs: w.runs,
90069
- ...w.last_run_at !== null && w.last_outcome ? { lastRun: { at: new Date(w.last_run_at).toISOString(), outcome: w.last_outcome, exitCode: w.last_exit, output: w.last_output ?? "" } } : {}
90857
+ ...w.last_run_at !== null && w.last_outcome ? { lastRun: { at: new Date(w.last_run_at).toISOString(), outcome: w.last_outcome, exitCode: w.last_exit, output: w.last_output ?? "" } } : {},
90858
+ ...w.kind === "monitor" ? { monitor: monitorStatusOf(w) } : {}
90070
90859
  };
90071
90860
  }
90072
90861
  function armedCommandWatchViews(slug) {
@@ -91528,6 +92317,23 @@ ${gapNote}` : input.message;
91528
92317
  return { activity, questions: openQuestionViews(input.slug), links: ctx.storage.listThreadLinks(input.slug).map(threadLinkView) };
91529
92318
  }
91530
92319
  }),
92320
+ // `frizzctl threads`: every thread on a board — this project's, or another one this Frizz serves — by
92321
+ // slug, shown title and band (thread-listing.ts), so a worker can see who else is working where
92322
+ // without the multi-megabyte board snapshot. A READ, so it verifies no caller: anything that can reach
92323
+ // this surface can already read the whole board through `board`. A mutation only because a worker's
92324
+ // command line POSTs every call (frizz-tools.mjs callRpc), as listOwnThreadActivity is. A project
92325
+ // that is registered but not open here is refused with openProjectNamed's reason rather than opened:
92326
+ // a read has no business starting another project's tailer and scheduler.
92327
+ listThreads: mutation({
92328
+ input: ListThreadsInput,
92329
+ output: ListThreadsResult,
92330
+ handler: async ({ input }) => {
92331
+ const open = input.project ? openProjectNamed(input.project, "its threads cannot be listed from here") : void 0;
92332
+ const project = open?.project ?? ctx.project;
92333
+ const { threads } = await (open?.board ?? ctx.board).snapshot();
92334
+ return listBoardThreads(threads, { slug: projectSlugOf(project.id), id: project.id, name: project.name }, { all: input.all });
92335
+ }
92336
+ }),
91531
92337
  // THE WATCHER REGISTRY WAS DELETED ON 2026-08-14 AND CAME BACK ON 2026-08-26, under two narrow verbs
91532
92338
  // rather than the four it had. It was removed because a wait had become a `watch:` line in the
91533
92339
  // worker's own ```awaiting fence, which was BOTH the park and the wake — leaving nothing to register.
@@ -91718,9 +92524,141 @@ ${gapNote}` : input.message;
91718
92524
  handler: async ({ input }) => {
91719
92525
  const dropped = ctx.storage.dropCommandWatch(input.slug, input.id, Date.now());
91720
92526
  if (dropped) ctx.board.refresh();
92527
+ if (dropped) await ctx.scheduler?.releaseMonitor?.(input.id);
91721
92528
  return { dropped, watches: armedCommandWatchViews(input.slug) };
91722
92529
  }
91723
92530
  }),
92531
+ // ---- THE WORKER'S MONITORS (`frizzctl monitor add`, 2026-11-02) --------------------------------
92532
+ // A script the server keeps RUNNING, each stdout line a wake (scheduler SOURCE 13, command-watch.ts).
92533
+ // A command watch row of kind `monitor`, so `drop` and `list` are the command watch's own RPCs above.
92534
+ // Same gate first, for the same reason; then the caps; then the row is armed and the script started,
92535
+ // and registration watches it for a moment so a script that cannot run is reported here.
92536
+ // A MONITOR'S DRAWER (2026-11-03): its script and everything it printed, the way a background shell's
92537
+ // drawer reads its output file. The log is written by the monitor's own process (command-watch.ts
92538
+ // monitorOutputSink); `ended` says how a monitor that is no longer running stopped.
92539
+ monitorOutput: query({
92540
+ input: external_exports.object({ slug: ThreadSlug, id: external_exports.string() }).strict(),
92541
+ output: external_exports.object({
92542
+ command: external_exports.string().nullable(),
92543
+ description: external_exports.string().nullable(),
92544
+ output: external_exports.string(),
92545
+ truncated: external_exports.boolean(),
92546
+ state: external_exports.enum(["running", "ended", "gone"]),
92547
+ ended: external_exports.string().nullable(),
92548
+ events: external_exports.number(),
92549
+ startedAt: external_exports.string().nullable(),
92550
+ stoppable: external_exports.boolean()
92551
+ }),
92552
+ handler: async ({ input }) => {
92553
+ const w = ctx.storage.getCommandWatch(input.id);
92554
+ if (!w || w.kind !== "monitor" || w.thread_slug !== input.slug) {
92555
+ return { command: null, description: null, output: "", truncated: false, state: "gone", ended: null, events: 0, startedAt: null, stoppable: false };
92556
+ }
92557
+ const content = readBackgroundShellOutput(monitorOutputPath(join51(ctx.project.stateDir, "monitors"), w.id));
92558
+ const running = w.state === "armed";
92559
+ return {
92560
+ command: w.command,
92561
+ description: w.description,
92562
+ ...content,
92563
+ state: running ? "running" : "ended",
92564
+ ended: running ? null : monitorEndedLabel(w),
92565
+ events: w.events,
92566
+ startedAt: new Date(w.created_at).toISOString(),
92567
+ stoppable: running
92568
+ };
92569
+ }
92570
+ }),
92571
+ // The HUMAN's stop, from the monitor's drawer. Unlike the worker's own drop, it wakes the worker: the
92572
+ // monitor ended under it, and its park names a monitor that is gone.
92573
+ stopMonitor: mutation({
92574
+ input: external_exports.object({ slug: ThreadSlug, id: external_exports.string() }).strict(),
92575
+ output: external_exports.object({ stopped: external_exports.boolean() }),
92576
+ handler: async ({ input }) => {
92577
+ const stopped = await ctx.scheduler?.stopMonitorByHuman?.(input.slug, input.id);
92578
+ if (stopped === void 0) {
92579
+ const w = ctx.storage.getCommandWatch(input.id);
92580
+ if (!w || w.kind !== "monitor" || w.state !== "armed" || w.thread_slug !== input.slug) return { stopped: false };
92581
+ ctx.storage.settleCommandWatch(input.id, "cancelled", Date.now());
92582
+ return { stopped: true };
92583
+ }
92584
+ return { stopped };
92585
+ }
92586
+ }),
92587
+ addOwnMonitor: mutation({
92588
+ input: AddOwnMonitorInput,
92589
+ output: AddOwnMonitorResult,
92590
+ handler: async ({ input }) => {
92591
+ const row = ctx.storage.getSession(input.slug);
92592
+ if (!row) throw new Error(`thread ${input.slug} is not registered`);
92593
+ if (row.state === "archived" || row.archived === 1) {
92594
+ throw new Error("Reopen this thread before registering a monitor on it");
92595
+ }
92596
+ const refuse = (refused) => ({ refused, alreadyArmed: false, running: false, events: [], watches: armedCommandWatchViews(input.slug) });
92597
+ const service = ctx.commandWatches;
92598
+ const gate = service ? service.refusal(row) : `this server cannot run monitors. ${MONITOR_FALLBACK}`;
92599
+ if (gate) return refuse(`Frizz will not run a monitor for this thread: ${gate.replace(COMMAND_WATCH_FALLBACK, MONITOR_FALLBACK)}`);
92600
+ if (!service?.startMonitor || !ctx.scheduler?.startMonitor) return refuse(`Frizz will not run a monitor for this thread: this server cannot run monitors. ${MONITOR_FALLBACK}`);
92601
+ const command = input.command.trim();
92602
+ const description = input.description?.trim().replace(/\s+/g, " ") || void 0;
92603
+ const armed = ctx.storage.listCommandWatches(input.slug, { armedOnly: true });
92604
+ const existing = armed.find((w) => w.kind === "monitor" && w.command === command);
92605
+ if (existing) {
92606
+ return {
92607
+ id: existing.id,
92608
+ alreadyArmed: true,
92609
+ running: true,
92610
+ events: [],
92611
+ expiresAt: new Date(existing.expires_at).toISOString(),
92612
+ watches: armedCommandWatchViews(input.slug)
92613
+ };
92614
+ }
92615
+ if (armed.length >= COMMAND_WATCH_MAX_ARMED) {
92616
+ throw new Error(`this thread already has ${armed.length} command watches and monitors armed (the limit is ${COMMAND_WATCH_MAX_ARMED}) \u2014 drop one first`);
92617
+ }
92618
+ if ((service.monitorsRunning?.() ?? 0) >= MONITOR_SERVER_MAX_RUNNING) {
92619
+ return refuse(`Frizz already runs ${MONITOR_SERVER_MAX_RUNNING} monitors across every project, its limit. ${MONITOR_FALLBACK}`);
92620
+ }
92621
+ const forAsked = parseAwaitingDurationRaw(input.for);
92622
+ if (forAsked === null) throw new Error(`\`--for ${input.for}\` is not a duration \u2014 give one like \`2h\` or \`3d\` (max 7d)`);
92623
+ const forMs = Math.min(forAsked, COMMAND_WATCH_FOR_MAX_MS);
92624
+ const now = Date.now();
92625
+ const id2 = `cmw_${randomUUID20().replace(/-/g, "").slice(0, 12)}`;
92626
+ ctx.storage.clearThreadDone(input.slug);
92627
+ ctx.storage.armMonitor({ id: id2, slug: input.slug, command, description, createdAtMs: now, expiresAtMs: now + forMs });
92628
+ const started = await ctx.scheduler.startMonitor(id2);
92629
+ ctx.board.refresh();
92630
+ const clamped = forMs !== forAsked ? { clamped: { for: input.for } } : {};
92631
+ if (started.refused) {
92632
+ ctx.storage.settleCommandWatch(id2, "cancelled", Date.now());
92633
+ ctx.board.refresh();
92634
+ return refuse(`Frizz could not start your monitor: ${started.refused}. ${MONITOR_FALLBACK}`);
92635
+ }
92636
+ if (started.exited) {
92637
+ const notHere = started.exited.outcome === "error" || started.exited.outcome === "exit" && (started.exited.exitCode === 126 || started.exited.exitCode === 127);
92638
+ return {
92639
+ id: id2,
92640
+ alreadyArmed: false,
92641
+ running: false,
92642
+ events: started.events,
92643
+ exited: started.exited,
92644
+ ...notHere ? {
92645
+ refused: `Your script could not run here (${started.exited.outcome === "error" ? "the shell did not start" : `\`/bin/sh\` exited ${started.exited.exitCode}`}). The server runs it with \`/bin/sh -c\` in ${ctx.project.dir}, with the server's own PATH, not your shell's: use absolute paths, or ${MONITOR_FALLBACK.charAt(0).toLowerCase()}${MONITOR_FALLBACK.slice(1)}`
92646
+ } : {},
92647
+ ...clamped,
92648
+ watches: armedCommandWatchViews(input.slug)
92649
+ };
92650
+ }
92651
+ return {
92652
+ id: id2,
92653
+ alreadyArmed: false,
92654
+ running: true,
92655
+ events: started.events,
92656
+ expiresAt: new Date(now + forMs).toISOString(),
92657
+ ...clamped,
92658
+ watches: armedCommandWatchViews(input.slug)
92659
+ };
92660
+ }
92661
+ }),
91724
92662
  listOwnCommandWatches: mutation({
91725
92663
  input: ListOwnCommandWatchesInput,
91726
92664
  output: OwnCommandWatchesResult,
@@ -92442,7 +93380,7 @@ Say which way you went and why in your write-up, so the human can course-correct
92442
93380
  output: ProjectCard,
92443
93381
  handler: async ({ input }) => {
92444
93382
  for (const extension2 of PROJECT_ICON_EXTENSIONS) {
92445
- rmSync15(customIconPath(input.id, `.${extension2}`), { force: true });
93383
+ rmSync16(customIconPath(input.id, `.${extension2}`), { force: true });
92446
93384
  }
92447
93385
  if (!clearProjectIcon(input.id)) throw new Error("No such project.");
92448
93386
  resolveProjectIcon(input.id, (root) => detectProjectIcon(root)?.path);
@@ -92685,6 +93623,7 @@ var init_router5 = __esm({
92685
93623
  init_src();
92686
93624
  init_context();
92687
93625
  init_secret_files();
93626
+ init_command_watch();
92688
93627
  init_acp_agents();
92689
93628
  init_storage();
92690
93629
  init_usage_limit();
@@ -92700,6 +93639,7 @@ var init_router5 = __esm({
92700
93639
  init_local_file();
92701
93640
  init_project();
92702
93641
  init_thread_links();
93642
+ init_thread_listing();
92703
93643
  init_github();
92704
93644
  init_github_hovercard();
92705
93645
  init_dispatch();
@@ -92792,11 +93732,11 @@ var init_compression = __esm({
92792
93732
  });
92793
93733
 
92794
93734
  // packages/server/src/local-visualization.ts
92795
- import { readdirSync as readdirSync16, readFileSync as readFileSync38, realpathSync as realpathSync16, statSync as statSync26 } from "node:fs";
93735
+ import { readdirSync as readdirSync17, readFileSync as readFileSync38, realpathSync as realpathSync16, statSync as statSync27 } from "node:fs";
92796
93736
  import { join as join52, sep as sep5 } from "node:path";
92797
93737
  function children(path3, pattern) {
92798
93738
  try {
92799
- return readdirSync16(path3, { withFileTypes: true }).filter((entry) => entry.isDirectory() && pattern.test(entry.name)).map((entry) => entry.name).sort().reverse();
93739
+ return readdirSync17(path3, { withFileTypes: true }).filter((entry) => entry.isDirectory() && pattern.test(entry.name)).map((entry) => entry.name).sort().reverse();
92800
93740
  } catch {
92801
93741
  return [];
92802
93742
  }
@@ -92824,7 +93764,7 @@ function resolveFragment(projectDir, sessionId, file) {
92824
93764
  const candidate = join52(monthDir, day, sessionId, file);
92825
93765
  try {
92826
93766
  const real = realpathSync16(candidate);
92827
- if (isUnder2(real, sessionRoot) && statSync26(real).isFile()) return real;
93767
+ if (isUnder2(real, sessionRoot) && statSync27(real).isFile()) return real;
92828
93768
  } catch {
92829
93769
  }
92830
93770
  }
@@ -92909,7 +93849,7 @@ function resolveLocalVisualization(projectDir, sessionId, file) {
92909
93849
  if (!path3) return { status: 404 };
92910
93850
  let fragment;
92911
93851
  try {
92912
- const size = statSync26(path3).size;
93852
+ const size = statSync27(path3).size;
92913
93853
  if (size > MAX_FRAGMENT_BYTES) return { status: 413 };
92914
93854
  fragment = readFileSync38(path3, "utf8");
92915
93855
  } catch {
@@ -93003,7 +93943,7 @@ var init_launch_routing = __esm({
93003
93943
  });
93004
93944
 
93005
93945
  // packages/server/src/project-serving.ts
93006
- import { readFileSync as readFileSync39, renameSync as renameSync15, writeFileSync as writeFileSync20 } from "node:fs";
93946
+ import { readFileSync as readFileSync39, renameSync as renameSync15, writeFileSync as writeFileSync21 } from "node:fs";
93007
93947
  import { isAbsolute as isAbsolute12, join as join53 } from "node:path";
93008
93948
  function parse3(value) {
93009
93949
  if (!value || typeof value !== "object") return null;
@@ -93030,7 +93970,7 @@ function readProjectServing(stateDir) {
93030
93970
  function writeRecord(stateDir, record) {
93031
93971
  const path3 = join53(stateDir, PROJECT_SERVING_FILE);
93032
93972
  const partial = `${path3}.${process.pid}.tmp`;
93033
- writeFileSync20(partial, `${JSON.stringify(record)}
93973
+ writeFileSync21(partial, `${JSON.stringify(record)}
93034
93974
  `, { mode: 384 });
93035
93975
  renameSync15(partial, path3);
93036
93976
  }
@@ -93100,7 +94040,7 @@ var init_project_serving = __esm({
93100
94040
  });
93101
94041
 
93102
94042
  // packages/server/src/app.ts
93103
- import { createReadStream as createReadStream2, mkdirSync as mkdirSync28, writeFileSync as writeFileSync21 } from "node:fs";
94043
+ import { createReadStream as createReadStream2, mkdirSync as mkdirSync29, writeFileSync as writeFileSync22 } from "node:fs";
93104
94044
  import { Readable } from "node:stream";
93105
94045
  import { join as join54 } from "node:path";
93106
94046
  import { randomUUID as randomUUID21 } from "node:crypto";
@@ -93269,9 +94209,9 @@ function createApp(ctx, options = {}) {
93269
94209
  if (typeof body.data !== "string" || body.data.length > ATTACHMENT_MAX_BASE64_CHARS) return c.json({ error: "bad payload" }, 400);
93270
94210
  const buf = Buffer.from(body.data, "base64");
93271
94211
  const dir = join54(ctx.project.stateDir, "attachments", `${Date.now()}-${randomUUID21().slice(0, 8)}`);
93272
- mkdirSync28(dir, { recursive: true });
94212
+ mkdirSync29(dir, { recursive: true });
93273
94213
  const path3 = join54(dir, attachmentFileName(name));
93274
- writeFileSync21(path3, buf);
94214
+ writeFileSync22(path3, buf);
93275
94215
  return c.json({ path: path3 });
93276
94216
  });
93277
94217
  app.get(
@@ -94209,11 +95149,11 @@ var init_app_socket = __esm({
94209
95149
  });
94210
95150
 
94211
95151
  // packages/server/src/local-file-watch.ts
94212
- import { statSync as statSync27, watch } from "node:fs";
95152
+ import { statSync as statSync28, watch } from "node:fs";
94213
95153
  import { basename as basename12, dirname as dirname25 } from "node:path";
94214
95154
  function stampOf(path3) {
94215
95155
  try {
94216
- const s = statSync27(path3, { bigint: true });
95156
+ const s = statSync28(path3, { bigint: true });
94217
95157
  return `${s.ino}:${s.size}:${s.mtimeNs}`;
94218
95158
  } catch {
94219
95159
  return "gone";
@@ -94269,7 +95209,7 @@ var init_local_file_watch = __esm({
94269
95209
  });
94270
95210
 
94271
95211
  // packages/server/src/boot-progress.ts
94272
- import { mkdirSync as mkdirSync29, readFileSync as readFileSync40, renameSync as renameSync16, rmSync as rmSync16, writeFileSync as writeFileSync22 } from "node:fs";
95212
+ import { mkdirSync as mkdirSync30, readFileSync as readFileSync40, renameSync as renameSync16, rmSync as rmSync17, writeFileSync as writeFileSync23 } from "node:fs";
94273
95213
  import { basename as basename13, dirname as dirname26, join as join55 } from "node:path";
94274
95214
  function bootProgressPath(stateDir) {
94275
95215
  return join55(stateDir, BOOT_PROGRESS_NAME);
@@ -94292,9 +95232,9 @@ function createBootProgressPublisher(stateDir, minIntervalMs = 200) {
94292
95232
  lastAt = now;
94293
95233
  step++;
94294
95234
  try {
94295
- mkdirSync29(dirname26(path3), { recursive: true, mode: 448 });
95235
+ mkdirSync30(dirname26(path3), { recursive: true, mode: 448 });
94296
95236
  const temp = join55(dirname26(path3), `.${basename13(path3)}.${process.pid}.tmp`);
94297
- writeFileSync22(temp, `${JSON.stringify({ pid: process.pid, step, phase, at: new Date(now).toISOString() })}
95237
+ writeFileSync23(temp, `${JSON.stringify({ pid: process.pid, step, phase, at: new Date(now).toISOString() })}
94298
95238
  `, "utf8");
94299
95239
  renameSync16(temp, path3);
94300
95240
  } catch {
@@ -94303,7 +95243,7 @@ function createBootProgressPublisher(stateDir, minIntervalMs = 200) {
94303
95243
  return Object.assign(write, {
94304
95244
  done: () => {
94305
95245
  try {
94306
- rmSync16(path3, { force: true });
95246
+ rmSync17(path3, { force: true });
94307
95247
  } catch {
94308
95248
  }
94309
95249
  }
@@ -94319,7 +95259,7 @@ var init_boot_progress = __esm({
94319
95259
  });
94320
95260
 
94321
95261
  // packages/server/src/runtime-lease.ts
94322
- import { existsSync as existsSync22, mkdirSync as mkdirSync30, readdirSync as readdirSync17, readFileSync as readFileSync41, unlinkSync as unlinkSync8, writeFileSync as writeFileSync23 } from "node:fs";
95262
+ import { existsSync as existsSync22, mkdirSync as mkdirSync31, readdirSync as readdirSync18, readFileSync as readFileSync41, unlinkSync as unlinkSync8, writeFileSync as writeFileSync24 } from "node:fs";
94323
95263
  import { dirname as dirname27, join as join56 } from "node:path";
94324
95264
  function runtimeVersionDir(bin) {
94325
95265
  let dir = dirname27(bin);
@@ -94345,9 +95285,9 @@ function leaseRuntime(bin, role) {
94345
95285
  };
94346
95286
  const path3 = join56(versionDir, LEASES_DIR, `${process.pid}.json`);
94347
95287
  try {
94348
- mkdirSync30(dirname27(path3), { recursive: true });
95288
+ mkdirSync31(dirname27(path3), { recursive: true });
94349
95289
  const lease = { pid: process.pid, role, bin, at: (/* @__PURE__ */ new Date()).toISOString() };
94350
- writeFileSync23(path3, JSON.stringify(lease));
95290
+ writeFileSync24(path3, JSON.stringify(lease));
94351
95291
  } catch {
94352
95292
  return () => {
94353
95293
  };
@@ -94363,7 +95303,7 @@ function liveRuntimeLeases(versionDir) {
94363
95303
  const dir = join56(versionDir, LEASES_DIR);
94364
95304
  let names;
94365
95305
  try {
94366
- names = readdirSync17(dir);
95306
+ names = readdirSync18(dir);
94367
95307
  } catch {
94368
95308
  return [];
94369
95309
  }
@@ -94405,14 +95345,14 @@ import {
94405
95345
  chmodSync as chmodSync5,
94406
95346
  closeSync as closeSync19,
94407
95347
  existsSync as existsSync23,
94408
- mkdirSync as mkdirSync31,
95348
+ mkdirSync as mkdirSync32,
94409
95349
  openSync as openSync20,
94410
95350
  readFileSync as readFileSync42,
94411
- readdirSync as readdirSync18,
95351
+ readdirSync as readdirSync19,
94412
95352
  renameSync as renameSync17,
94413
- rmSync as rmSync17,
94414
- statSync as statSync28,
94415
- writeFileSync as writeFileSync24,
95353
+ rmSync as rmSync18,
95354
+ statSync as statSync29,
95355
+ writeFileSync as writeFileSync25,
94416
95356
  writeSync as writeSync3
94417
95357
  } from "node:fs";
94418
95358
  import { dirname as dirname28, isAbsolute as isAbsolute13, join as join57, normalize, relative as relative3, sep as sep6 } from "node:path";
@@ -94475,7 +95415,7 @@ function locateBinary(dir, backend, binary) {
94475
95415
  const vendor = join57(dir, "vendor");
94476
95416
  let triples;
94477
95417
  try {
94478
- triples = readdirSync18(vendor);
95418
+ triples = readdirSync19(vendor);
94479
95419
  } catch {
94480
95420
  return void 0;
94481
95421
  }
@@ -94499,9 +95439,9 @@ async function provisionRuntime(backend, options) {
94499
95439
  const backendDir = join57(root, backend);
94500
95440
  const finalDir = join57(backendDir, coordinates.label);
94501
95441
  const partial = join57(backendDir, `.partial-${coordinates.label}-${process.pid}`);
94502
- mkdirSync31(backendDir, { recursive: true });
94503
- rmSync17(partial, { recursive: true, force: true });
94504
- mkdirSync31(partial);
95442
+ mkdirSync32(backendDir, { recursive: true });
95443
+ rmSync18(partial, { recursive: true, force: true });
95444
+ mkdirSync32(partial);
94505
95445
  try {
94506
95446
  const manifestUrl = `${registry}/${coordinates.pkg.replace("/", "%2F")}/${coordinates.packageVersion}`;
94507
95447
  progress(`resolving ${coordinates.pkg}@${coordinates.packageVersion}`);
@@ -94545,7 +95485,7 @@ async function provisionRuntime(backend, options) {
94545
95485
  binary: relative3(partial, bin),
94546
95486
  at: (/* @__PURE__ */ new Date()).toISOString()
94547
95487
  };
94548
- writeFileSync24(join57(partial, MARKER), `${JSON.stringify(marker, null, 2)}
95488
+ writeFileSync25(join57(partial, MARKER), `${JSON.stringify(marker, null, 2)}
94549
95489
  `, "utf8");
94550
95490
  const rename3 = options.rename ?? renameSync17;
94551
95491
  try {
@@ -94561,13 +95501,13 @@ async function provisionRuntime(backend, options) {
94561
95501
  } catch (err) {
94562
95502
  const theirs = provisionedBinary(backend, root, coordinates.label);
94563
95503
  if (!theirs) throw err;
94564
- rmSync17(partial, { recursive: true, force: true });
95504
+ rmSync18(partial, { recursive: true, force: true });
94565
95505
  return { bin: theirs, label: coordinates.label, fetched: false };
94566
95506
  }
94567
95507
  progress("ready");
94568
95508
  return { bin: join57(finalDir, marker.binary), label: coordinates.label, fetched: true };
94569
95509
  } catch (err) {
94570
- rmSync17(partial, { recursive: true, force: true });
95510
+ rmSync18(partial, { recursive: true, force: true });
94571
95511
  throw err;
94572
95512
  }
94573
95513
  }
@@ -94576,7 +95516,7 @@ function sweepRuntimes(backend, root, keepLabel, now = Date.now(), deps = {}) {
94576
95516
  const backendDir = join57(root, backend);
94577
95517
  let entries2;
94578
95518
  try {
94579
- entries2 = readdirSync18(backendDir);
95519
+ entries2 = readdirSync19(backendDir);
94580
95520
  } catch {
94581
95521
  return { removed: [], kept: [] };
94582
95522
  }
@@ -94586,7 +95526,7 @@ function sweepRuntimes(backend, root, keepLabel, now = Date.now(), deps = {}) {
94586
95526
  const full = join57(backendDir, entry);
94587
95527
  if (entry.startsWith(".partial-")) {
94588
95528
  try {
94589
- if (now - statSync28(full).mtimeMs < 24 * 60 * 60 * 1e3) continue;
95529
+ if (now - statSync29(full).mtimeMs < 24 * 60 * 60 * 1e3) continue;
94590
95530
  } catch {
94591
95531
  continue;
94592
95532
  }
@@ -94766,7 +95706,7 @@ var init_runtimes = __esm({
94766
95706
  return;
94767
95707
  case "5": {
94768
95708
  const dir = safeEntryPath(this.dest, name);
94769
- if (dir) mkdirSync31(dir, { recursive: true });
95709
+ if (dir) mkdirSync32(dir, { recursive: true });
94770
95710
  return;
94771
95711
  }
94772
95712
  case "0":
@@ -94774,7 +95714,7 @@ var init_runtimes = __esm({
94774
95714
  case "7": {
94775
95715
  const file = safeEntryPath(this.dest, name);
94776
95716
  if (!file) return;
94777
- mkdirSync31(dirname28(file), { recursive: true });
95717
+ mkdirSync32(dirname28(file), { recursive: true });
94778
95718
  this.fd = openSync20(file, "w", octal(header, 100, 8) & 511 || 420);
94779
95719
  this.written.push(file);
94780
95720
  return;
@@ -94818,7 +95758,7 @@ var init_runtimes = __esm({
94818
95758
  RENAME_RETRY_DELAY_MS = 200;
94819
95759
  TRANSIENT_HANDLE_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"]);
94820
95760
  errorCode4 = (err) => err?.code;
94821
- defaultSweepRm = (path3) => rmSync17(path3, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
95761
+ defaultSweepRm = (path3) => rmSync18(path3, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
94822
95762
  }
94823
95763
  });
94824
95764
 
@@ -95361,7 +96301,7 @@ var init_legacy_project_db = __esm({
95361
96301
  });
95362
96302
 
95363
96303
  // packages/server/src/frizz-db.ts
95364
- import { existsSync as existsSync24, mkdirSync as mkdirSync32, readdirSync as readdirSync19, renameSync as renameSync18, statSync as statSync29 } from "node:fs";
96304
+ import { existsSync as existsSync24, mkdirSync as mkdirSync33, readdirSync as readdirSync20, renameSync as renameSync18, statSync as statSync30 } from "node:fs";
95365
96305
  import { basename as basename14, dirname as dirname29, join as join58 } from "node:path";
95366
96306
  function frizzDatabaseLocation(options) {
95367
96307
  if (options.stateDir !== void 0) {
@@ -95391,7 +96331,7 @@ function ensureFrizzSchema(db2) {
95391
96331
  }
95392
96332
  function openFrizzDatabase(options = {}) {
95393
96333
  const { path: path3, projectsDir } = frizzDatabaseLocation(options);
95394
- mkdirSync32(dirname29(path3), { recursive: true });
96334
+ mkdirSync33(dirname29(path3), { recursive: true });
95395
96335
  const db2 = new sqlite_default(path3);
95396
96336
  db2.pragma("busy_timeout = 5000");
95397
96337
  db2.pragma("journal_mode = WAL");
@@ -95447,9 +96387,9 @@ function openFrizzDatabase(options = {}) {
95447
96387
  }
95448
96388
  function projectIdsWithFile(projectsDir, file) {
95449
96389
  if (!existsSync24(projectsDir)) return [];
95450
- return readdirSync19(projectsDir).filter((name) => {
96390
+ return readdirSync20(projectsDir).filter((name) => {
95451
96391
  try {
95452
- return statSync29(join58(projectsDir, name, file)).isFile();
96392
+ return statSync30(join58(projectsDir, name, file)).isFile();
95453
96393
  } catch {
95454
96394
  return false;
95455
96395
  }
@@ -95638,7 +96578,7 @@ var init_projects_changed = __esm({
95638
96578
  });
95639
96579
 
95640
96580
  // packages/server/src/project-teardown.ts
95641
- import { rmSync as rmSync18 } from "node:fs";
96581
+ import { rmSync as rmSync19 } from "node:fs";
95642
96582
  import { homedir as homedir24 } from "node:os";
95643
96583
  import { dirname as dirname30, resolve as resolve12 } from "node:path";
95644
96584
  async function stopProjectWorkers(ctx) {
@@ -95663,7 +96603,7 @@ function deleteProjectState(projectId, home = homedir24()) {
95663
96603
  if (dirname30(resolve12(target)) !== resolve12(dirname30(projectStateDir("x", home)))) {
95664
96604
  throw new Error(`Refusing to delete ${target} \u2014 it is not a project state directory`);
95665
96605
  }
95666
- rmSync18(target, { recursive: true, force: true });
96606
+ rmSync19(target, { recursive: true, force: true });
95667
96607
  }
95668
96608
  var init_project_teardown = __esm({
95669
96609
  "packages/server/src/project-teardown.ts"() {
@@ -95689,7 +96629,7 @@ __export(index_exports, {
95689
96629
  unknownProjectPage: () => unknownProjectPage
95690
96630
  });
95691
96631
  import { createServer } from "node:http";
95692
- import { readFileSync as readFileSync43, existsSync as existsSync25, statSync as statSync30 } from "node:fs";
96632
+ import { readFileSync as readFileSync43, existsSync as existsSync25, statSync as statSync31 } from "node:fs";
95693
96633
  import { dirname as dirname31, join as join59, resolve as resolve13, extname as extname4, posix as posix2, sep as sep7 } from "node:path";
95694
96634
  function readServerAddressHolder(path3) {
95695
96635
  try {
@@ -95825,7 +96765,7 @@ function serveStatic(distDir, req, res) {
95825
96765
  if (!file.startsWith(distDir + sep7)) file = join59(distDir, "index.html");
95826
96766
  if (!existsSync25(file)) file = join59(distDir, "index.html");
95827
96767
  try {
95828
- const stats = statSync30(file);
96768
+ const stats = statSync31(file);
95829
96769
  const cacheControl = file.startsWith(join59(distDir, "assets") + sep7) ? STATIC_CACHE_IMMUTABLE : STATIC_CACHE_REVALIDATE;
95830
96770
  const etag = `"${stats.size.toString(16)}-${Math.trunc(stats.mtimeMs).toString(16)}"`;
95831
96771
  const headers = {