frizz-server 0.15.33 → 0.15.35

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 (97) hide show
  1. package/dist/dev-child.js +959 -330
  2. package/package.json +1 -1
  3. package/web-dist/assets/{abnfDiagram-VRR7QNED-BrVXb__x.js → abnfDiagram-VRR7QNED-D129srQj.js} +1 -1
  4. package/web-dist/assets/{arc-BoUaeqZC.js → arc-lZudOQfd.js} +1 -1
  5. package/web-dist/assets/architecture-TIHT7OUA-CA5ec0Gm.js +1 -0
  6. package/web-dist/assets/{architectureDiagram-ZJ3FMSHR-DGWVwhQr.js → architectureDiagram-ZJ3FMSHR-CrtK2py-.js} +1 -1
  7. package/web-dist/assets/{blockDiagram-677ZJIJ3-C0I_trEX.js → blockDiagram-677ZJIJ3-Cr7MSTZQ.js} +1 -1
  8. package/web-dist/assets/{c4Diagram-LMCZKHZV-jhJjAmkd.js → c4Diagram-LMCZKHZV-CNCtP_VP.js} +1 -1
  9. package/web-dist/assets/channel-BVTiuco4.js +1 -0
  10. package/web-dist/assets/{chunk-32BRIVSS-CHaer5BL.js → chunk-32BRIVSS-DUIgVT9q.js} +1 -1
  11. package/web-dist/assets/{chunk-52WLFC77-DDuJk3Ke.js → chunk-52WLFC77-ll0wxrGo.js} +1 -1
  12. package/web-dist/assets/{chunk-C7G6YPKG-7ukYWIW5.js → chunk-C7G6YPKG-C7nZQ7PD.js} +1 -1
  13. package/web-dist/assets/{chunk-EX3LRPZG-CqcBwy5d.js → chunk-EX3LRPZG-H1Md81EP.js} +1 -1
  14. package/web-dist/assets/{chunk-FWX5IMBZ-3XEQ0xZ2.js → chunk-FWX5IMBZ-Dp2I8ck_.js} +2 -2
  15. package/web-dist/assets/{chunk-HOUHSVGY-BT7cImMb.js → chunk-HOUHSVGY-D26eCze_.js} +1 -1
  16. package/web-dist/assets/{chunk-ICXQ74PX-BsAT5XY-.js → chunk-ICXQ74PX-Da4scpSO.js} +1 -1
  17. package/web-dist/assets/{chunk-MOJQB5TN-DGVKPHff.js → chunk-MOJQB5TN-DkPSKSSy.js} +1 -1
  18. package/web-dist/assets/{chunk-OGEWGWER-Sewb945r.js → chunk-OGEWGWER-B6i3Jran.js} +1 -1
  19. package/web-dist/assets/{chunk-PUDLZKDR-DuGLsVUp.js → chunk-PUDLZKDR-v-Plka6E.js} +1 -1
  20. package/web-dist/assets/{chunk-Q4XR5HBZ-CiwsrkUy.js → chunk-Q4XR5HBZ-6_YVJ7i9.js} +1 -1
  21. package/web-dist/assets/{chunk-RYQCIY6F-BjVGpf6s.js → chunk-RYQCIY6F-D0ZjBw8D.js} +1 -1
  22. package/web-dist/assets/{chunk-V7JOEXUC-q_lp6OxX.js → chunk-V7JOEXUC-CCy2fibM.js} +1 -1
  23. package/web-dist/assets/{chunk-VAUOI2AC-BN6F7b33.js → chunk-VAUOI2AC-DtsKL0xS.js} +1 -1
  24. package/web-dist/assets/{chunk-VR4S4FIN-C-8jG7rN.js → chunk-VR4S4FIN-BZFI-yXe.js} +1 -1
  25. package/web-dist/assets/{chunk-WYO6CB5R-DZ67MmXf.js → chunk-WYO6CB5R-BvJbL3sv.js} +1 -1
  26. package/web-dist/assets/{chunk-XXDRQBXY-8yDwwa_d.js → chunk-XXDRQBXY-C_M3xhvd.js} +1 -1
  27. package/web-dist/assets/{chunk-ZGVPDNZ5-C9rgKaOT.js → chunk-ZGVPDNZ5-C8RyBdFb.js} +1 -1
  28. package/web-dist/assets/classDiagram-OUVF2IWQ-9CrZWFBB.js +1 -0
  29. package/web-dist/assets/classDiagram-v2-EOCWNBFH-9CrZWFBB.js +1 -0
  30. package/web-dist/assets/{cose-bilkent-JH36ORCC-Bm-Cd5yO.js → cose-bilkent-JH36ORCC-DGSLJpi2.js} +1 -1
  31. package/web-dist/assets/{cynefin-VYW2F7L2-BfRkzvLb.js → cynefin-VYW2F7L2-B0dqUUva.js} +1 -1
  32. package/web-dist/assets/{cynefinDiagram-TSTJHNR4-DghzY6TM.js → cynefinDiagram-TSTJHNR4-C6-pVgHN.js} +1 -1
  33. package/web-dist/assets/{dagre-VKFMJZFB-C6_eZ1bq.js → dagre-VKFMJZFB-BPhBZDn_.js} +1 -1
  34. package/web-dist/assets/{diagram-FQU43EPY-Dx7LVMsJ.js → diagram-FQU43EPY-Dx0GRxRd.js} +1 -1
  35. package/web-dist/assets/{diagram-G47NLZAW-Bwzvto-6.js → diagram-G47NLZAW-tRnsp5NZ.js} +1 -1
  36. package/web-dist/assets/{diagram-NH7WQ7WH-DFhGj2ep.js → diagram-NH7WQ7WH-brRG4YP3.js} +1 -1
  37. package/web-dist/assets/{diagram-OA4YK3LP-bn7FXN3O.js → diagram-OA4YK3LP-HPCPq5vN.js} +1 -1
  38. package/web-dist/assets/{diagram-WEI45ONY-DMVSEHfp.js → diagram-WEI45ONY-DBIDlkOn.js} +1 -1
  39. package/web-dist/assets/{dist-CmaVLdB8.js → dist-QrxGAEfI.js} +1 -1
  40. package/web-dist/assets/{ebnfDiagram-CCIWWBDH-BUE8xIGA.js → ebnfDiagram-CCIWWBDH-DPpG2nEr.js} +1 -1
  41. package/web-dist/assets/{erDiagram-Q63AITRT-DR9ix-xX.js → erDiagram-Q63AITRT-B03KTREu.js} +1 -1
  42. package/web-dist/assets/eventmodeling-45OFAUF4-D4WnFJFn.js +1 -0
  43. package/web-dist/assets/flowDiagram-23GEKE2U-Db_Yi3kp.js +1 -0
  44. package/web-dist/assets/{ganttDiagram-NO4QXBWP-Ipxt_uSG.js → ganttDiagram-NO4QXBWP-IHjbBNTs.js} +1 -1
  45. package/web-dist/assets/{gitGraph-TEB2WS4Q-XmmiScF4.js → gitGraph-TEB2WS4Q-BJwmP2d4.js} +1 -1
  46. package/web-dist/assets/{gitGraphDiagram-IHSO6WYX-C6jROnBu.js → gitGraphDiagram-IHSO6WYX-C8pGIJ9F.js} +1 -1
  47. package/web-dist/assets/{index-D0Ssk83M.js → index-6SDsPnCe.js} +117 -117
  48. package/web-dist/assets/index-BbpuV6k_.css +2 -0
  49. package/web-dist/assets/{info-DKCQHKI2-1_wtxke4.js → info-DKCQHKI2-BVcPA0uT.js} +1 -1
  50. package/web-dist/assets/{infoDiagram-FWYZ7A6U-BJOvR8xI.js → infoDiagram-FWYZ7A6U-DvqztdKA.js} +1 -1
  51. package/web-dist/assets/{ishikawaDiagram-FXEZZL3T-DkIZViQd.js → ishikawaDiagram-FXEZZL3T-DyhVzZBU.js} +1 -1
  52. package/web-dist/assets/{journeyDiagram-5HDEW3XC-DaorCHw-.js → journeyDiagram-5HDEW3XC-ZEKauv5n.js} +1 -1
  53. package/web-dist/assets/{kanban-definition-HUTT4EX6-Ch2xLVxk.js → kanban-definition-HUTT4EX6-CepyK851.js} +1 -1
  54. package/web-dist/assets/{line-C6UvMvEa.js → line-wQ98gODj.js} +1 -1
  55. package/web-dist/assets/{linear-DvNKY7RD.js → linear-C2rtjUR9.js} +1 -1
  56. package/web-dist/assets/{mermaid-parser.core-ByygzUll.js → mermaid-parser.core-Ci-cUDXV.js} +3 -3
  57. package/web-dist/assets/{mermaid.core-B4Kz8RNJ.js → mermaid.core-D26PB2uv.js} +3 -3
  58. package/web-dist/assets/{mindmap-definition-LN4V7U3C-DCYo533N.js → mindmap-definition-LN4V7U3C-pQ423WTQ.js} +1 -1
  59. package/web-dist/assets/{packet-7NZHBO7P-D4EtiplI.js → packet-7NZHBO7P-m5EZAdVa.js} +1 -1
  60. package/web-dist/assets/{pegDiagram-2B236MQR-CYeavBZi.js → pegDiagram-2B236MQR-CmQauXMc.js} +1 -1
  61. package/web-dist/assets/{pie-RZYD4A2V-GbGqezva.js → pie-RZYD4A2V-DsCjC6Aw.js} +1 -1
  62. package/web-dist/assets/{pieDiagram-ENE6RG2P-I4bzOJ_0.js → pieDiagram-ENE6RG2P-DAnWnktJ.js} +1 -1
  63. package/web-dist/assets/{quadrantDiagram-ABIIQ3AL-k0pqbavI.js → quadrantDiagram-ABIIQ3AL-yV-55X6h.js} +1 -1
  64. package/web-dist/assets/{radar-I7S5WNFK-oBkUe6as.js → radar-I7S5WNFK-DmYrhbGZ.js} +1 -1
  65. package/web-dist/assets/{railroad-3IZDKUUU-B3kub48g.js → railroad-3IZDKUUU-1Af5LHVH.js} +1 -1
  66. package/web-dist/assets/railroad-abnf-AHOZXSZD-q1VO-5_s.js +1 -0
  67. package/web-dist/assets/railroad-ebnf-EBAXGLYW-H0RP0IGY.js +1 -0
  68. package/web-dist/assets/railroad-peg-LSFZ7HO6-P2_YWa6e.js +1 -0
  69. package/web-dist/assets/{railroadDiagram-RFXS5EU6-PwB5kN0Y.js → railroadDiagram-RFXS5EU6-CL490ICY.js} +1 -1
  70. package/web-dist/assets/{requirementDiagram-TGXJPOKE-CHUTqcm7.js → requirementDiagram-TGXJPOKE-D4V2V4M4.js} +1 -1
  71. package/web-dist/assets/{sankeyDiagram-HTMAVEWB-CenSHY2N.js → sankeyDiagram-HTMAVEWB-DboOdoog.js} +1 -1
  72. package/web-dist/assets/{sequenceDiagram-DBY2YBRQ-SPVT29Vk.js → sequenceDiagram-DBY2YBRQ-B9imFSyN.js} +1 -1
  73. package/web-dist/assets/{src-D80-5Mjy.js → src-bXz5F_73.js} +1 -1
  74. package/web-dist/assets/{stateDiagram-2N3HPSRC-BsHYII7A.js → stateDiagram-2N3HPSRC-9fBbVPbS.js} +1 -1
  75. package/web-dist/assets/stateDiagram-v2-6OUMAXLB-D3NihPE7.js +1 -0
  76. package/web-dist/assets/{swimlanes-5IMT3BWC-ecWgHNfO.js → swimlanes-5IMT3BWC-NuoWaLoT.js} +1 -1
  77. package/web-dist/assets/swimlanesDiagram-G3AALYLV-i7_yBzZ9.js +8 -0
  78. package/web-dist/assets/{timeline-definition-FHXFAJF6-XPw0PlGY.js → timeline-definition-FHXFAJF6-CFTpt9PD.js} +1 -1
  79. package/web-dist/assets/{treeView-QDETBFTQ-CBvTj7YK.js → treeView-QDETBFTQ-DMVW9992.js} +1 -1
  80. package/web-dist/assets/{treemap-6X3UGDF4-B0bvmGfT.js → treemap-6X3UGDF4-DnVjneTc.js} +1 -1
  81. package/web-dist/assets/{vennDiagram-L72KCM5P-CZMSLELl.js → vennDiagram-L72KCM5P-CRxeJqHm.js} +1 -1
  82. package/web-dist/assets/{wardley-OPB4EBWU-BCT4pKef.js → wardley-OPB4EBWU-j2g5ErAe.js} +1 -1
  83. package/web-dist/assets/{wardleyDiagram-EHGQE667-cDuR7lnO.js → wardleyDiagram-EHGQE667-Cwy2dkRh.js} +1 -1
  84. package/web-dist/assets/{xychartDiagram-FW5EYKEG-BbSTRu2S.js → xychartDiagram-FW5EYKEG-D0talZt6.js} +1 -1
  85. package/web-dist/index.html +2 -2
  86. package/web-dist/assets/architecture-TIHT7OUA-C1qSqZXr.js +0 -1
  87. package/web-dist/assets/channel-C-BjOH0x.js +0 -1
  88. package/web-dist/assets/classDiagram-OUVF2IWQ-BoBKdAfq.js +0 -1
  89. package/web-dist/assets/classDiagram-v2-EOCWNBFH-BoBKdAfq.js +0 -1
  90. package/web-dist/assets/eventmodeling-45OFAUF4-GIR56vYX.js +0 -1
  91. package/web-dist/assets/flowDiagram-23GEKE2U-DWCtfKi1.js +0 -1
  92. package/web-dist/assets/index-IvdpjBO_.css +0 -2
  93. package/web-dist/assets/railroad-abnf-AHOZXSZD-ClQREIyY.js +0 -1
  94. package/web-dist/assets/railroad-ebnf-EBAXGLYW-OejkFuAL.js +0 -1
  95. package/web-dist/assets/railroad-peg-LSFZ7HO6-DwamBKJg.js +0 -1
  96. package/web-dist/assets/stateDiagram-v2-6OUMAXLB-CIppfyrw.js +0 -1
  97. package/web-dist/assets/swimlanesDiagram-G3AALYLV-Cc45jWM2.js +0 -8
package/dist/dev-child.js CHANGED
@@ -8717,14 +8717,14 @@ function isValidJWT(jwt, alg) {
8717
8717
  if (!header)
8718
8718
  return false;
8719
8719
  const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
8720
- const decoded = JSON.parse(atob(base64));
8721
- if (typeof decoded !== "object" || decoded === null)
8720
+ const decoded2 = JSON.parse(atob(base64));
8721
+ if (typeof decoded2 !== "object" || decoded2 === null)
8722
8722
  return false;
8723
- if ("typ" in decoded && decoded?.typ !== "JWT")
8723
+ if ("typ" in decoded2 && decoded2?.typ !== "JWT")
8724
8724
  return false;
8725
- if (!decoded.alg)
8725
+ if (!decoded2.alg)
8726
8726
  return false;
8727
- if (alg && decoded.alg !== alg)
8727
+ if (alg && decoded2.alg !== alg)
8728
8728
  return false;
8729
8729
  return true;
8730
8730
  } catch {
@@ -14293,6 +14293,7 @@ function timerPromptMessage(prompt, fireAt) {
14293
14293
  }
14294
14294
  function limitResumeSteer(window) {
14295
14295
  const which = window === "weekly" ? "weekly usage limit" : window === "session" ? "session usage limit" : window === "model" ? "model usage limit" : "usage limit";
14296
+ if (window === "unknown") return "\u23F3 Capacity is available again after the usage limit that interrupted you. Continue exactly where you left off.";
14296
14297
  return `\u23F3 The ${which} that interrupted you has reset. Continue exactly where you left off.`;
14297
14298
  }
14298
14299
  function limitModelSwitchSteer(capped, to) {
@@ -16144,8 +16145,20 @@ ${ANSWER_CONTINUATION_INDENT}`);
16144
16145
  planType: external_exports.string().optional(),
16145
16146
  // "pro" / "max" / etc. when the source reports it
16146
16147
  windows: external_exports.array(QuotaWindow),
16147
- detail: external_exports.string().optional()
16148
+ detail: external_exports.string().optional(),
16148
16149
  // why unavailable, or an extra note
16150
+ // Recovery evidence from a LIVE Codex read only. Rollout quota has no account identity or freshness
16151
+ // guarantee and must never wake a failed thread. accountKey is a hash, not a credential/account id.
16152
+ codexRecovery: external_exports.object({
16153
+ observedAt: external_exports.number(),
16154
+ // request start, unix milliseconds (not the later cache/read time)
16155
+ accountKey: external_exports.string().optional(),
16156
+ creditsAvailable: external_exports.boolean().optional(),
16157
+ ordinaryUsageAllowed: external_exports.boolean().nullable().optional(),
16158
+ // null is explicitly unavailable
16159
+ blocked: external_exports.boolean().optional()
16160
+ // explicit workspace/spend-control denial beats apparent headroom
16161
+ }).optional()
16149
16162
  });
16150
16163
  QuotaSnapshot = external_exports.object({
16151
16164
  claude: ProviderQuota,
@@ -16350,8 +16363,10 @@ ${ANSWER_CONTINUATION_INDENT}`);
16350
16363
  // human wrote it, and as fast as a steer does.
16351
16364
  answers: external_exports.array(QuestionAnswerSchema).optional(),
16352
16365
  // SEND TO THE QUEUE: while the agent is mid-turn, Frizz keeps this message and delivers it when the
16353
- // thread comes to rest, so it opens the next turn instead of steering this one. At rest it is an
16354
- // ordinary send — there is nothing to wait for. See `held` in the server's delivery-ledger.ts.
16366
+ // thread comes to rest, so it opens the next turn instead of steering this one. The queue goes out ONE
16367
+ // message per turn (2026-10-20), so a message also waits, even at rest, behind one already held or one
16368
+ // whose turn has not ended. With nothing ahead of it, it is an ordinary send. See `held` and
16369
+ // nextHeldRelease in the server's delivery-ledger.ts.
16355
16370
  hold: external_exports.boolean().optional(),
16356
16371
  // Generated once before the optimistic clear so a transport replay can be idempotent.
16357
16372
  deliveryId: external_exports.string().min(1).max(200).optional(),
@@ -17265,12 +17280,15 @@ ${DISPATCH_TASK_BANNER}
17265
17280
  /** The directory is gone — moved or deleted. The card stays so it can be reopened or forgotten. */
17266
17281
  stale: external_exports.boolean(),
17267
17282
  /**
17268
- * When this project's icon was last established, or absent if it never has been.
17283
+ * A hash of the icon's bytes; for a project with no icon, when it was last scanned. Absent if it
17284
+ * never has been.
17269
17285
  *
17270
17286
  * Carried purely so the client can hang it off the `/_frizz/project-icon` URL: the icon bytes are
17271
17287
  * cached hard (a rail of forty squares is forty requests, and none of them should recur), which
17272
17288
  * means a newly uploaded icon would otherwise stay invisible behind the cached old one. A changed
17273
17289
  * version is a changed URL, so the swap is immediate without weakening the caching for everyone.
17290
+ * It is the HASH, not the scan time, because a rescan restamps the time every ten minutes whether
17291
+ * or not the picture changed, and every restamp was a fresh download of every icon.
17274
17292
  *
17275
17293
  * Deliberately NOT "does this project have an icon". Answering that for a project nobody has
17276
17294
  * scanned yet would mean scanning it, and this list is one file read on purpose.
@@ -17317,6 +17335,7 @@ ${DISPATCH_TASK_BANNER}
17317
17335
  });
17318
17336
 
17319
17337
  // packages/server/src/project-registry.ts
17338
+ import { createHash as createHash4 } from "node:crypto";
17320
17339
  import { closeSync as closeSync3, existsSync as existsSync3, fsyncSync as fsyncSync3, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync4, readdirSync, realpathSync as realpathSync3, renameSync as renameSync3, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs";
17321
17340
  import { homedir as homedir4 } from "node:os";
17322
17341
  import { basename, dirname as dirname4, join as join5 } from "node:path";
@@ -17548,10 +17567,30 @@ function updateEntry(id, apply, home) {
17548
17567
  return entry;
17549
17568
  }
17550
17569
  function setProjectIcon(id, path3, home = homedir4()) {
17570
+ const hash = iconFileHash(path3);
17551
17571
  return updateEntry(id, (entry) => {
17552
17572
  entry.icon = path3;
17553
17573
  entry.iconSource = "custom";
17554
17574
  entry.iconScannedAt = (/* @__PURE__ */ new Date()).toISOString();
17575
+ if (hash) entry.iconHash = hash;
17576
+ else delete entry.iconHash;
17577
+ }, home);
17578
+ }
17579
+ function iconContentHash(bytes) {
17580
+ return createHash4("sha256").update(bytes).digest("hex").slice(0, 16);
17581
+ }
17582
+ function iconFileHash(path3) {
17583
+ try {
17584
+ return iconContentHash(readFileSync4(path3));
17585
+ } catch {
17586
+ return void 0;
17587
+ }
17588
+ }
17589
+ function recordProjectIconHash(id, path3, hash, home = homedir4()) {
17590
+ const entry = readRegistry(home).projects.find((p) => p.id === id);
17591
+ if (!entry || entry.icon !== path3 || entry.iconHash === hash) return;
17592
+ updateEntry(id, (target) => {
17593
+ target.iconHash = hash;
17555
17594
  }, home);
17556
17595
  }
17557
17596
  function clearProjectIcon(id, home = homedir4()) {
@@ -17559,6 +17598,7 @@ function clearProjectIcon(id, home = homedir4()) {
17559
17598
  delete entry.icon;
17560
17599
  delete entry.iconSource;
17561
17600
  delete entry.iconScannedAt;
17601
+ delete entry.iconHash;
17562
17602
  }, home);
17563
17603
  }
17564
17604
  function resolveProjectIcon(id, detect, options = {}) {
@@ -17576,6 +17616,7 @@ function resolveProjectIcon(id, detect, options = {}) {
17576
17616
  }
17577
17617
  if (!existsSync3(entry.path)) return void 0;
17578
17618
  const found = detect(entry.path);
17619
+ const hash = found ? iconFileHash(found) : void 0;
17579
17620
  updateEntry(id, (target) => {
17580
17621
  if (found) {
17581
17622
  target.icon = found;
@@ -17584,6 +17625,8 @@ function resolveProjectIcon(id, detect, options = {}) {
17584
17625
  delete target.icon;
17585
17626
  delete target.iconSource;
17586
17627
  }
17628
+ if (hash) target.iconHash = hash;
17629
+ else delete target.iconHash;
17587
17630
  target.iconScannedAt = new Date(now()).toISOString();
17588
17631
  target.iconScanVersion = version;
17589
17632
  }, home);
@@ -17897,9 +17940,9 @@ async function attachLinkedPrs(repo, items) {
17897
17940
  const chunks = [];
17898
17941
  for (let i = 0; i < numbers.length; i += LINKED_PR_CHUNK) chunks.push(numbers.slice(i, i + LINKED_PR_CHUNK));
17899
17942
  const results = await Promise.all(
17900
- chunks.map(async (chunk) => {
17943
+ chunks.map(async (chunk2) => {
17901
17944
  try {
17902
- return parseLinkedPrJson(await gh(["api", "graphql", "-f", `query=${linkedPrQuery(chunk)}`, "-F", `owner=${owner}`, "-F", `name=${name}`]));
17945
+ return parseLinkedPrJson(await gh(["api", "graphql", "-f", `query=${linkedPrQuery(chunk2)}`, "-F", `owner=${owner}`, "-F", `name=${name}`]));
17903
17946
  } catch {
17904
17947
  return /* @__PURE__ */ new Map();
17905
17948
  }
@@ -18235,7 +18278,7 @@ var init_project = __esm({
18235
18278
  });
18236
18279
 
18237
18280
  // packages/server/src/project-launch.ts
18238
- import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
18281
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
18239
18282
  import {
18240
18283
  closeSync as closeSync4,
18241
18284
  fsyncSync as fsyncSync4,
@@ -18443,7 +18486,7 @@ function sameProjectIdentity(record, target) {
18443
18486
  }
18444
18487
  function projectLaunchTokenProof(target, token) {
18445
18488
  if (!UUID_RE.test(token)) throw new Error("invalid Frizz project launch owner token");
18446
- return createHash4("sha256").update("frizz-project-launch-v2\0").update(target.projectId).update("\0").update(target.projectDir).update("\0").update(token).digest("hex");
18489
+ return createHash5("sha256").update("frizz-project-launch-v2\0").update(target.projectId).update("\0").update(target.projectDir).update("\0").update(token).digest("hex");
18447
18490
  }
18448
18491
  function removeStatusesForToken(stateDir, token) {
18449
18492
  for (const name of ["dev-supervisor.lock", "server.lock"]) {
@@ -19404,7 +19447,7 @@ var init_local_image = __esm({
19404
19447
 
19405
19448
  // packages/server/src/audit.ts
19406
19449
  import { AsyncLocalStorage } from "node:async_hooks";
19407
- import { createHash as createHash5 } from "node:crypto";
19450
+ import { createHash as createHash6 } from "node:crypto";
19408
19451
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, mkdirSync as mkdirSync8 } from "node:fs";
19409
19452
  import { dirname as dirname7, join as join10 } from "node:path";
19410
19453
  function bounded(value) {
@@ -19441,7 +19484,7 @@ function currentRequestOrigin() {
19441
19484
  return requestOrigin.getStore() ?? { via: "internal" };
19442
19485
  }
19443
19486
  function textDigest(text2) {
19444
- return { chars: text2.length, sha256: createHash5("sha256").update(text2).digest("hex") };
19487
+ return { chars: text2.length, sha256: createHash6("sha256").update(text2).digest("hex") };
19445
19488
  }
19446
19489
  function auditLogPathForStateDir(stateDir) {
19447
19490
  return join10(dirname7(serverAddressPathForStateDir(stateDir)), "logs", "audit.jsonl");
@@ -24680,6 +24723,33 @@ var init_usage_limit = __esm({
24680
24723
  }
24681
24724
  });
24682
24725
 
24726
+ // packages/server/src/backend/codex-usage-limit.ts
24727
+ function codexLimitFault(error, at2) {
24728
+ if (error.retrying || !at2 || !Number.isFinite(Date.parse(at2))) return void 0;
24729
+ if (error.code !== "usage_limit_exceeded" && error.code !== "rate_limit_exceeded") return void 0;
24730
+ return {
24731
+ window: "unknown",
24732
+ at: at2,
24733
+ codex: /\bworkspace is out of credits\b/i.test(error.message) ? "credits" : "usage"
24734
+ };
24735
+ }
24736
+ function codexLimitRecovery(fault, quota, nowMs) {
24737
+ const live2 = quota?.codexRecovery;
24738
+ const faultAt = Date.parse(fault.at);
24739
+ if (!fault.codex || !Number.isFinite(faultAt) || quota?.status !== "ok" || !live2 || !Number.isFinite(live2.observedAt) || live2.observedAt <= faultAt || live2.observedAt > nowMs || nowMs - live2.observedAt > 6e4) return void 0;
24740
+ if (live2.blocked) return "blocked";
24741
+ const credits = live2.creditsAvailable === true;
24742
+ const headroom = quota.windows.length > 0 && quota.windows.every((w) => Number.isFinite(w.usedPercent) && w.usedPercent >= 0 && w.usedPercent <= 85);
24743
+ const included = live2.ordinaryUsageAllowed === true || fault.codex !== "credits" && live2.ordinaryUsageAllowed === void 0 && headroom;
24744
+ if (!credits && !included) return "blocked";
24745
+ return { key: live2.accountKey ?? "unidentified-codex-account" };
24746
+ }
24747
+ var init_codex_usage_limit = __esm({
24748
+ "packages/server/src/backend/codex-usage-limit.ts"() {
24749
+ "use strict";
24750
+ }
24751
+ });
24752
+
24683
24753
  // packages/server/src/backend/claude-agent-sdk-protocol.ts
24684
24754
  function hasUndeliverableInputText(value) {
24685
24755
  for (const character of value) {
@@ -24995,7 +25065,7 @@ var init_ipc_path = __esm({
24995
25065
 
24996
25066
  // packages/server/src/backend/claude-broker-host.ts
24997
25067
  import { spawn } from "node:child_process";
24998
- import { createHash as createHash6, randomUUID as randomUUID8 } from "node:crypto";
25068
+ import { createHash as createHash7, randomUUID as randomUUID8 } from "node:crypto";
24999
25069
  import { accessSync, constants as fsConstants, mkdirSync as mkdirSync13, readFileSync as readFileSync12, readdirSync as readdirSync5, statSync as statSync8, unlinkSync, writeFileSync as writeFileSync10 } from "node:fs";
25000
25070
  import { delimiter, dirname as dirname11, isAbsolute as isAbsolute4, join as join20 } from "node:path";
25001
25071
  function windowsShimTarget(shimPath) {
@@ -25048,7 +25118,7 @@ function resolveClaudeExecutableAbsolute(bin, env = process.env) {
25048
25118
  throw new Error(`Claude session broker: could not resolve '${candidate}' to an absolute executable path on PATH (the SDK requires one)`);
25049
25119
  }
25050
25120
  function claudeBrokerSocketPath(stateDir, sessionId) {
25051
- const key = createHash6("sha256").update(stateDir).update("\0").update(sessionId).digest("hex").slice(0, 16);
25121
+ const key = createHash7("sha256").update(stateDir).update("\0").update(sessionId).digest("hex").slice(0, 16);
25052
25122
  return frizzIpcPath(`frizz-claude-${key}`);
25053
25123
  }
25054
25124
  function claudeBrokerRecordPath(stateDir, sessionId) {
@@ -25057,7 +25127,7 @@ function claudeBrokerRecordPath(stateDir, sessionId) {
25057
25127
  function claudeBrokerRecordName(sessionId) {
25058
25128
  let name = recordNames.get(sessionId);
25059
25129
  if (name === void 0) {
25060
- name = `${createHash6("sha256").update(sessionId).digest("hex").slice(0, 16)}.json`;
25130
+ name = `${createHash7("sha256").update(sessionId).digest("hex").slice(0, 16)}.json`;
25061
25131
  recordNames.set(sessionId, name);
25062
25132
  }
25063
25133
  return name;
@@ -25098,7 +25168,7 @@ function brokerLivenessSnapshot(stateDir) {
25098
25168
  });
25099
25169
  }
25100
25170
  function claudeBrokerRetirementPath(stateDir, sessionId) {
25101
- const key = createHash6("sha256").update(sessionId).digest("hex").slice(0, 16);
25171
+ const key = createHash7("sha256").update(sessionId).digest("hex").slice(0, 16);
25102
25172
  return join20(stateDir, "claude-broker", `${key}.retired`);
25103
25173
  }
25104
25174
  function markBrokerRetired(stateDir, sessionId, reason, generation) {
@@ -25484,6 +25554,15 @@ function heldDeliveries(storage, slug) {
25484
25554
  if (!row?.delivery_ledger) return [];
25485
25555
  return parseDeliveryLedger(row.delivery_ledger).filter((item) => item.state === "held");
25486
25556
  }
25557
+ function nextHeldRelease(items, opts = {}) {
25558
+ const head = items.find((item) => item.state === "held");
25559
+ if (!head) return null;
25560
+ if (!opts.force && items.some((item) => OUTSTANDING.has(item.state))) return null;
25561
+ return head;
25562
+ }
25563
+ function heldSendMustWait(items) {
25564
+ return items.some((item) => item.state === "held" || OUTSTANDING.has(item.state));
25565
+ }
25487
25566
  function dropHeldDelivery(storage, slug, id) {
25488
25567
  const row = storage.getSession(slug);
25489
25568
  if (!row) return null;
@@ -25822,7 +25901,7 @@ function projectDeliveryLedger(messages, items) {
25822
25901
  }
25823
25902
  return messages;
25824
25903
  }
25825
- var PENDING_TIMEOUT_MS, UNCONFIRMED_DROP_MS, MAX_LEDGER_ITEMS, MAX_CANCELLED_ITEMS, MAX_FAILED_ITEMS, SENDING_STALL_MS, RETRYABLE_SEND_GRACE_MS, SENDING_STALL_ERROR, DELIVERY_STATES, canon, DELIVERY_ERROR_MAX_CHARS, COMPOSED_ANCHOR_MIN, renderMatchKey, CANCEL_MATCH_SLACK_MS;
25904
+ var PENDING_TIMEOUT_MS, UNCONFIRMED_DROP_MS, MAX_LEDGER_ITEMS, MAX_CANCELLED_ITEMS, MAX_FAILED_ITEMS, SENDING_STALL_MS, RETRYABLE_SEND_GRACE_MS, SENDING_STALL_ERROR, DELIVERY_STATES, canon, DELIVERY_ERROR_MAX_CHARS, OUTSTANDING, COMPOSED_ANCHOR_MIN, renderMatchKey, CANCEL_MATCH_SLACK_MS;
25826
25905
  var init_delivery_ledger = __esm({
25827
25906
  "packages/server/src/delivery-ledger.ts"() {
25828
25907
  "use strict";
@@ -25839,6 +25918,7 @@ var init_delivery_ledger = __esm({
25839
25918
  DELIVERY_STATES = ["sending", "pending", "enqueued", "delivered", "unconfirmed", "failed", "cancelled", "held"];
25840
25919
  canon = (s) => s.replace(/\s+/g, " ").trim();
25841
25920
  DELIVERY_ERROR_MAX_CHARS = 300;
25921
+ OUTSTANDING = /* @__PURE__ */ new Set(["sending", "pending", "enqueued", "delivered"]);
25842
25922
  COMPOSED_ANCHOR_MIN = 24;
25843
25923
  renderMatchKey = (s) => canon(stripHumanGapNote(stripWakeDeliveryToken(stripDeliveryMarkers(s))));
25844
25924
  CANCEL_MATCH_SLACK_MS = 5e3;
@@ -26179,12 +26259,12 @@ var init_completion_relay = __esm({
26179
26259
  });
26180
26260
 
26181
26261
  // packages/server/src/tail-cache.ts
26182
- import { createHash as createHash7 } from "node:crypto";
26262
+ import { createHash as createHash8 } from "node:crypto";
26183
26263
  import { closeSync as closeSync9, openSync as openSync10, readFileSync as readFileSync13, readSync as readSync3, statSync as statSync10 } from "node:fs";
26184
26264
  import { join as join21 } from "node:path";
26185
26265
  function foldSchemaDigest(dir = import.meta.dirname) {
26186
26266
  if (foldSchemaMemo) return foldSchemaMemo;
26187
- const hash = createHash7("sha256").update("frizz-tail-state-v1\0");
26267
+ const hash = createHash8("sha256").update("frizz-tail-state-v1\0");
26188
26268
  let read = 0;
26189
26269
  for (const name of FOLD_SOURCES) {
26190
26270
  try {
@@ -26227,7 +26307,7 @@ function measureFence(path3, offset) {
26227
26307
  const tail = Buffer.allocUnsafe(window);
26228
26308
  const tailRead = readSync3(fd, tail, 0, window, offset - window);
26229
26309
  if (headRead !== window || tailRead !== window) return null;
26230
- const contentDigest = createHash7("sha256").update(String(offset)).update("\0").update(head).update("\0").update(tail).digest("hex").slice(0, 32);
26310
+ const contentDigest = createHash8("sha256").update(String(offset)).update("\0").update(head).update("\0").update(tail).digest("hex").slice(0, 32);
26231
26311
  return {
26232
26312
  offset,
26233
26313
  size: stat2.size,
@@ -26438,7 +26518,7 @@ var init_json_value = __esm({
26438
26518
  // packages/server/src/tailer.ts
26439
26519
  import { statSync as statSync11, openSync as openSync11, readSync as readSync4, closeSync as closeSync10, readdirSync as readdirSync6, realpathSync as realpathSync6, mkdirSync as mkdirSync14, writeFileSync as writeFileSync11, readFileSync as readFileSync14, existsSync as existsSync7 } from "node:fs";
26440
26520
  import { execFile as execFile2 } from "node:child_process";
26441
- import { createHash as createHash8 } from "node:crypto";
26521
+ import { createHash as createHash9 } from "node:crypto";
26442
26522
  import { promisify as promisify2 } from "node:util";
26443
26523
  import { basename as basename4, join as join22, win32 } from "node:path";
26444
26524
  import { homedir as homedir7 } from "node:os";
@@ -27197,7 +27277,7 @@ function trackCompletions(state, rec) {
27197
27277
  const monitorTimedOut = isMonitorTimeoutEvent(block);
27198
27278
  const terminal = status === "completed" || status === "failed" || status === "killed" ? status : status === "stopped" || monitorTimedOut ? "killed" : void 0;
27199
27279
  if (!terminal) continue;
27200
- const fingerprint = createHash8("sha1").update(block).digest("hex").slice(0, 16);
27280
+ const fingerprint = createHash9("sha1").update(block).digest("hex").slice(0, 16);
27201
27281
  const repeatOf = /* @__PURE__ */ new Set();
27202
27282
  for (const id of blockTaskIds(block)) {
27203
27283
  if (state.foldedTerminals?.get(id) === fingerprint) repeatOf.add(id);
@@ -27463,6 +27543,7 @@ function applyEvent(state, ev2) {
27463
27543
  state.turn = "idle";
27464
27544
  state.apiFault = true;
27465
27545
  state.providerError = ev2.error;
27546
+ state.limitFault = codexLimitFault(ev2.error, ev2.at);
27466
27547
  state.lastAssistant = ev2.error.message;
27467
27548
  state.lastAssistantLine = firstTextLine(ev2.error.message);
27468
27549
  state.lastFence = void 0;
@@ -27481,6 +27562,7 @@ function applyEvent(state, ev2) {
27481
27562
  if (ev2.finalText !== void 0 || ev2.successful) {
27482
27563
  state.apiFault = void 0;
27483
27564
  state.providerError = void 0;
27565
+ state.limitFault = void 0;
27484
27566
  }
27485
27567
  if (ev2.finalText !== void 0) {
27486
27568
  applyFinalText(state, ev2.finalText);
@@ -27492,6 +27574,7 @@ function applyEvent(state, ev2) {
27492
27574
  state.sawRecords = true;
27493
27575
  state.apiFault = void 0;
27494
27576
  state.providerError = void 0;
27577
+ state.limitFault = void 0;
27495
27578
  if (ev2.final) {
27496
27579
  if (typeof ev2.at === "string") state.lastAssistantAt = ev2.at;
27497
27580
  applyFinalText(state, ev2.text);
@@ -27507,6 +27590,7 @@ function applyEvent(state, ev2) {
27507
27590
  break;
27508
27591
  case "user-message":
27509
27592
  state.sawRecords = true;
27593
+ state.limitFault = void 0;
27510
27594
  state.turn = "in-flight";
27511
27595
  state.lastAssistantAllDone = false;
27512
27596
  state.lastFence = void 0;
@@ -28434,16 +28518,16 @@ ${ask}`;
28434
28518
  if (row?.backend === "codex") return false;
28435
28519
  const current = measureFence(entry.path, entry.offset);
28436
28520
  if (!current || !fenceMatches(entry, current)) return false;
28437
- const decoded = decodeTailState(entry.state);
28438
- if (!decoded) return false;
28439
- if (decoded.offset !== entry.offset || typeof decoded.partial !== "string") return false;
28521
+ const decoded2 = decodeTailState(entry.state);
28522
+ if (!decoded2) return false;
28523
+ if (decoded2.offset !== entry.offset || typeof decoded2.partial !== "string") return false;
28440
28524
  for (const field2 of ["subAgents", "retiredSubAgents", "queuedReports", "retiredShells"]) {
28441
- if (!(decoded[field2] instanceof Map)) return false;
28525
+ if (!(decoded2[field2] instanceof Map)) return false;
28442
28526
  }
28443
- if (!(decoded.deliveredReports instanceof Set)) return false;
28444
- if (!(decoded.ownedToolUseIds instanceof Set)) return false;
28527
+ if (!(decoded2.deliveredReports instanceof Set)) return false;
28528
+ if (!(decoded2.ownedToolUseIds instanceof Set)) return false;
28445
28529
  const target = state;
28446
- for (const [key2, value] of Object.entries(decoded)) {
28530
+ for (const [key2, value] of Object.entries(decoded2)) {
28447
28531
  if (UNRESTORED_TAIL_FIELDS.has(key2)) continue;
28448
28532
  target[key2] = value;
28449
28533
  }
@@ -29181,6 +29265,7 @@ var init_tailer = __esm({
29181
29265
  init_subagent_profile();
29182
29266
  init_claude_runtime_ingest();
29183
29267
  init_usage_limit();
29268
+ init_codex_usage_limit();
29184
29269
  init_claude_broker_diagnostics();
29185
29270
  init_claude_broker_host();
29186
29271
  init_delivery_ledger();
@@ -29997,19 +30082,19 @@ function searchPath2(env) {
29997
30082
  function vendoredNativeBeside(launcherJs, arch, access) {
29998
30083
  const triple = WINDOWS_TRIPLE[arch];
29999
30084
  if (!triple) return void 0;
30000
- const { dirname: dirname32, join: join60 } = win322;
30085
+ const { dirname: dirname32, join: join61 } = win322;
30001
30086
  const pkgRoot = dirname32(dirname32(launcherJs));
30002
30087
  const platformPkg = `codex-win32-${arch}`;
30003
30088
  const vendorRoots = [
30004
- join60(pkgRoot, "node_modules", "@openai", platformPkg, "vendor"),
30089
+ join61(pkgRoot, "node_modules", "@openai", platformPkg, "vendor"),
30005
30090
  // nested under the package
30006
- join60(dirname32(pkgRoot), platformPkg, "vendor"),
30091
+ join61(dirname32(pkgRoot), platformPkg, "vendor"),
30007
30092
  // hoisted beside it: <prefix>\node_modules\@openai\<pkg>
30008
- join60(pkgRoot, "vendor")
30093
+ join61(pkgRoot, "vendor")
30009
30094
  // the pre-platform-package layout, binaries inside @openai/codex itself
30010
30095
  ];
30011
30096
  for (const root of vendorRoots) {
30012
- const exe2 = join60(root, triple, "bin", "codex.exe");
30097
+ const exe2 = join61(root, triple, "bin", "codex.exe");
30013
30098
  if (access(exe2, "exists")) return exe2;
30014
30099
  }
30015
30100
  return void 0;
@@ -30066,14 +30151,14 @@ var init_codex_executable = __esm({
30066
30151
  });
30067
30152
 
30068
30153
  // packages/server/src/backend/claude-quota-observed.ts
30069
- import { createHash as createHash9 } from "node:crypto";
30154
+ import { createHash as createHash10 } from "node:crypto";
30070
30155
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
30071
30156
  import { join as join24 } from "node:path";
30072
30157
  function finite(value) {
30073
30158
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
30074
30159
  }
30075
30160
  function observedQuotaPath(cacheDir, configDir) {
30076
- const profile = createHash9("sha256").update(configDir).digest("hex").slice(0, 12);
30161
+ const profile = createHash10("sha256").update(configDir).digest("hex").slice(0, 12);
30077
30162
  return join24(cacheDir, `claude-observed-${profile}.json`);
30078
30163
  }
30079
30164
  function live(window, now) {
@@ -30114,7 +30199,7 @@ var init_claude_quota_observed = __esm({
30114
30199
  // packages/server/src/backend/claude-quota.ts
30115
30200
  import { join as join25 } from "node:path";
30116
30201
  import { homedir as homedir9, platform } from "node:os";
30117
- import { createHash as createHash10 } from "node:crypto";
30202
+ import { createHash as createHash11 } from "node:crypto";
30118
30203
  import { mkdir as mkdir2, readFile as readFile2, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
30119
30204
  import { execFile as execFile3 } from "node:child_process";
30120
30205
  import { promisify as promisify3 } from "node:util";
@@ -30263,11 +30348,11 @@ async function resolveConfiguredRoute(configDir, env = process.env) {
30263
30348
  return {
30264
30349
  url,
30265
30350
  headers: credential,
30266
- fingerprint: createHash10("sha256").update(JSON.stringify([url, credential])).digest("hex").slice(0, 16)
30351
+ fingerprint: createHash11("sha256").update(JSON.stringify([url, credential])).digest("hex").slice(0, 16)
30267
30352
  };
30268
30353
  }
30269
30354
  function cachePaths(cacheDir, configDir) {
30270
- const profile = createHash10("sha256").update(configDir).digest("hex").slice(0, 12);
30355
+ const profile = createHash11("sha256").update(configDir).digest("hex").slice(0, 12);
30271
30356
  return {
30272
30357
  data: join25(cacheDir, `claude-${profile}.json`),
30273
30358
  lock: join25(cacheDir, `claude-${profile}.lock`)
@@ -31488,14 +31573,14 @@ var require_permessage_deflate = __commonJS({
31488
31573
  }
31489
31574
  };
31490
31575
  module.exports = PerMessageDeflate2;
31491
- function deflateOnData(chunk) {
31492
- this[kBuffers].push(chunk);
31493
- this[kTotalLength] += chunk.length;
31576
+ function deflateOnData(chunk2) {
31577
+ this[kBuffers].push(chunk2);
31578
+ this[kTotalLength] += chunk2.length;
31494
31579
  }
31495
- function inflateOnData(chunk) {
31496
- this[kTotalLength] += chunk.length;
31580
+ function inflateOnData(chunk2) {
31581
+ this[kTotalLength] += chunk2.length;
31497
31582
  if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
31498
- this[kBuffers].push(chunk);
31583
+ this[kBuffers].push(chunk2);
31499
31584
  return;
31500
31585
  }
31501
31586
  this[kError] = new RangeError("Max payload size exceeded");
@@ -31795,7 +31880,7 @@ var require_receiver = __commonJS({
31795
31880
  * @param {Function} cb Callback
31796
31881
  * @private
31797
31882
  */
31798
- _write(chunk, encoding, cb) {
31883
+ _write(chunk2, encoding, cb) {
31799
31884
  if (this._opcode === 8 && this._state == GET_INFO) return cb();
31800
31885
  if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
31801
31886
  cb(
@@ -31809,8 +31894,8 @@ var require_receiver = __commonJS({
31809
31894
  );
31810
31895
  return;
31811
31896
  }
31812
- this._bufferedBytes += chunk.length;
31813
- this._buffers.push(chunk);
31897
+ this._bufferedBytes += chunk2.length;
31898
+ this._buffers.push(chunk2);
31814
31899
  this.startLoop(cb);
31815
31900
  }
31816
31901
  /**
@@ -33233,7 +33318,7 @@ var require_websocket = __commonJS({
33233
33318
  var http = __require("http");
33234
33319
  var net2 = __require("net");
33235
33320
  var tls = __require("tls");
33236
- var { randomBytes: randomBytes3, createHash: createHash22 } = __require("crypto");
33321
+ var { randomBytes: randomBytes3, createHash: createHash24 } = __require("crypto");
33237
33322
  var { Duplex, Readable: Readable3 } = __require("stream");
33238
33323
  var { URL: URL2 } = __require("url");
33239
33324
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -33901,7 +33986,7 @@ var require_websocket = __commonJS({
33901
33986
  abortHandshake(websocket, socket, "Invalid Upgrade header");
33902
33987
  return;
33903
33988
  }
33904
- const digest = createHash22("sha1").update(key + GUID).digest("base64");
33989
+ const digest = createHash24("sha1").update(key + GUID).digest("base64");
33905
33990
  if (res.headers["sec-websocket-accept"] !== digest) {
33906
33991
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
33907
33992
  return;
@@ -34084,8 +34169,8 @@ var require_websocket = __commonJS({
34084
34169
  this.removeListener("end", socketOnEnd);
34085
34170
  websocket._readyState = WebSocket3.CLOSING;
34086
34171
  if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
34087
- const chunk = this.read(this._readableState.length);
34088
- websocket._receiver.write(chunk);
34172
+ const chunk2 = this.read(this._readableState.length);
34173
+ websocket._receiver.write(chunk2);
34089
34174
  }
34090
34175
  websocket._receiver.end();
34091
34176
  this[kWebSocket] = void 0;
@@ -34097,8 +34182,8 @@ var require_websocket = __commonJS({
34097
34182
  websocket._receiver.on("finish", receiverOnFinish);
34098
34183
  }
34099
34184
  }
34100
- function socketOnData(chunk) {
34101
- if (!this[kWebSocket]._receiver.write(chunk)) {
34185
+ function socketOnData(chunk2) {
34186
+ if (!this[kWebSocket]._receiver.write(chunk2)) {
34102
34187
  this.pause();
34103
34188
  }
34104
34189
  }
@@ -34201,14 +34286,14 @@ var require_stream = __commonJS({
34201
34286
  duplex._read = function() {
34202
34287
  if (ws2.isPaused) ws2.resume();
34203
34288
  };
34204
- duplex._write = function(chunk, encoding, callback) {
34289
+ duplex._write = function(chunk2, encoding, callback) {
34205
34290
  if (ws2.readyState === ws2.CONNECTING) {
34206
34291
  ws2.once("open", function open() {
34207
- duplex._write(chunk, encoding, callback);
34292
+ duplex._write(chunk2, encoding, callback);
34208
34293
  });
34209
34294
  return;
34210
34295
  }
34211
- ws2.send(chunk, callback);
34296
+ ws2.send(chunk2, callback);
34212
34297
  };
34213
34298
  duplex.on("end", duplexOnEnd);
34214
34299
  duplex.on("error", duplexOnError);
@@ -34270,7 +34355,7 @@ var require_websocket_server = __commonJS({
34270
34355
  var EventEmitter = __require("events");
34271
34356
  var http = __require("http");
34272
34357
  var { Duplex } = __require("stream");
34273
- var { createHash: createHash22 } = __require("crypto");
34358
+ var { createHash: createHash24 } = __require("crypto");
34274
34359
  var extension2 = require_extension();
34275
34360
  var PerMessageDeflate2 = require_permessage_deflate();
34276
34361
  var subprotocol2 = require_subprotocol();
@@ -34577,7 +34662,7 @@ var require_websocket_server = __commonJS({
34577
34662
  );
34578
34663
  }
34579
34664
  if (this._state > RUNNING) return abortHandshake(socket, 503);
34580
- const digest = createHash22("sha1").update(key + GUID).digest("base64");
34665
+ const digest = createHash24("sha1").update(key + GUID).digest("base64");
34581
34666
  const headers = [
34582
34667
  "HTTP/1.1 101 Switching Protocols",
34583
34668
  "Upgrade: websocket",
@@ -34746,7 +34831,7 @@ var init_codex_mcp = __esm({
34746
34831
  import { spawn as spawn2 } from "node:child_process";
34747
34832
  import { connect } from "node:net";
34748
34833
  import { Agent as HttpAgent } from "node:http";
34749
- import { createHash as createHash11, randomUUID as randomUUID9 } from "node:crypto";
34834
+ import { createHash as createHash12, randomUUID as randomUUID9 } from "node:crypto";
34750
34835
  import { existsSync as existsSync8, mkdirSync as mkdirSync15, readFileSync as readFileSync18, unlinkSync as unlinkSync2, writeFileSync as writeFileSync12 } from "node:fs";
34751
34836
  import { join as join27 } from "node:path";
34752
34837
  import { PassThrough, Writable } from "node:stream";
@@ -34758,7 +34843,7 @@ function nativeRecordPath(stateDir, projectId) {
34758
34843
  return join27(nativeDir(stateDir), `${projectId}.json`);
34759
34844
  }
34760
34845
  function nativeListenSocketPath(stateDir, projectId) {
34761
- const key = createHash11("sha256").update(stateDir).update("\0").update(projectId).digest("hex").slice(0, 16);
34846
+ const key = createHash12("sha256").update(stateDir).update("\0").update(projectId).digest("hex").slice(0, 16);
34762
34847
  return frizzIpcPath(`frizz-codex-native-${key}`);
34763
34848
  }
34764
34849
  function pidAlive2(pid) {
@@ -34864,8 +34949,8 @@ function attach(record, timeoutMs) {
34864
34949
  const decoder = new StringDecoder("utf8");
34865
34950
  let outbound = "";
34866
34951
  const stdin = new Writable({
34867
- write(chunk, _encoding, callback) {
34868
- outbound += decoder.write(chunk);
34952
+ write(chunk2, _encoding, callback) {
34953
+ outbound += decoder.write(chunk2);
34869
34954
  for (; ; ) {
34870
34955
  const index = outbound.indexOf("\n");
34871
34956
  if (index < 0) break;
@@ -35026,7 +35111,7 @@ var init_codex_app_server_native = __esm({
35026
35111
  // packages/server/src/backend/codex-app-server-host.ts
35027
35112
  import { spawn as spawn3 } from "node:child_process";
35028
35113
  import { createConnection } from "node:net";
35029
- import { createHash as createHash12, randomUUID as randomUUID10 } from "node:crypto";
35114
+ import { createHash as createHash13, randomUUID as randomUUID10 } from "node:crypto";
35030
35115
  import { existsSync as existsSync9, mkdirSync as mkdirSync16, readFileSync as readFileSync19, unlinkSync as unlinkSync3 } from "node:fs";
35031
35116
  import { join as join28 } from "node:path";
35032
35117
  import { PassThrough as PassThrough2, Writable as Writable2 } from "node:stream";
@@ -35038,7 +35123,7 @@ function recordPath(stateDir, projectId) {
35038
35123
  return join28(daemonDir(stateDir), `${projectId}.json`);
35039
35124
  }
35040
35125
  function codexAppServerSocketPath(stateDir, projectId) {
35041
- const key = createHash12("sha256").update(stateDir).update("\0").update(projectId).digest("hex").slice(0, 16);
35126
+ const key = createHash13("sha256").update(stateDir).update("\0").update(projectId).digest("hex").slice(0, 16);
35042
35127
  return frizzIpcPath(`frizz-codex-${key}`);
35043
35128
  }
35044
35129
  function pidAlive3(pid) {
@@ -35195,8 +35280,8 @@ function attach2(record, timeoutMs) {
35195
35280
  }, timeoutMs);
35196
35281
  timer.unref?.();
35197
35282
  const stdin = new Writable2({
35198
- write(chunk, _encoding, callback) {
35199
- socket.write(chunk, (error) => callback(error ?? null));
35283
+ write(chunk2, _encoding, callback) {
35284
+ socket.write(chunk2, (error) => callback(error ?? null));
35200
35285
  }
35201
35286
  });
35202
35287
  const handle = {
@@ -35217,8 +35302,8 @@ function attach2(record, timeoutMs) {
35217
35302
  };
35218
35303
  const decoder = new StringDecoder2("utf8");
35219
35304
  let buffer = "";
35220
- socket.on("data", (chunk) => {
35221
- buffer += decoder.write(chunk);
35305
+ socket.on("data", (chunk2) => {
35306
+ buffer += decoder.write(chunk2);
35222
35307
  for (; ; ) {
35223
35308
  const index = buffer.indexOf("\n");
35224
35309
  if (index < 0) break;
@@ -35407,7 +35492,7 @@ var init_codex_execution_health = __esm({
35407
35492
  });
35408
35493
 
35409
35494
  // packages/server/src/backend/codex-app-server.ts
35410
- import { createHash as createHash13, randomUUID as randomUUID11 } from "node:crypto";
35495
+ import { createHash as createHash14, randomUUID as randomUUID11 } from "node:crypto";
35411
35496
  import { existsSync as existsSync10 } from "node:fs";
35412
35497
  import { StringDecoder as StringDecoder3 } from "node:string_decoder";
35413
35498
  function selectCodexHostKind(flagValue, platform3, hasSpawn) {
@@ -35755,7 +35840,7 @@ function canonicalJson2(value) {
35755
35840
  return JSON.stringify(normalize2(value));
35756
35841
  }
35757
35842
  function logicalRequestId(method, parts) {
35758
- const digest = createHash13("sha256").update(JSON.stringify([method, ...parts])).digest("hex");
35843
+ const digest = createHash14("sha256").update(JSON.stringify([method, ...parts])).digest("hex");
35759
35844
  return `codex-${digest}`;
35760
35845
  }
35761
35846
  function requestFingerprint(value) {
@@ -35765,7 +35850,7 @@ function requestFingerprint(value) {
35765
35850
  delete record.startedAtMs;
35766
35851
  delete record.autoResolutionMs;
35767
35852
  }
35768
- return createHash13("sha256").update(canonicalJson2(normalized)).digest("hex");
35853
+ return createHash14("sha256").update(canonicalJson2(normalized)).digest("hex");
35769
35854
  }
35770
35855
  function decision(id, semantic, label) {
35771
35856
  return { id, semantic, label };
@@ -36350,12 +36435,12 @@ var init_codex_app_server = __esm({
36350
36435
  this.onNotification = onNotification;
36351
36436
  this.onClosed = onClosed;
36352
36437
  this.diagnostic = diagnostic;
36353
- child.stdout.on("data", (chunk) => this.consume(chunk));
36438
+ child.stdout.on("data", (chunk2) => this.consume(chunk2));
36354
36439
  child.stdout.on("end", () => this.fail("protocol", new Error("Codex app-server stdout ended")));
36355
36440
  child.stdout.on("error", () => this.fail("protocol", new Error("Codex app-server stdout failed")));
36356
36441
  child.stdin.on("error", () => this.fail("error", new Error("Codex app-server stdin failed")));
36357
- child.stderr.on("data", (chunk) => {
36358
- const size = Buffer.byteLength(chunk);
36442
+ child.stderr.on("data", (chunk2) => {
36443
+ const size = Buffer.byteLength(chunk2);
36359
36444
  this.stderrBytes = Math.min(MAX_STDERR_BYTES + 1, this.stderrBytes + size);
36360
36445
  if (!this.stderrReported) {
36361
36446
  this.stderrReported = true;
@@ -36418,9 +36503,9 @@ var init_codex_app_server = __esm({
36418
36503
  if (!this.draining) return Promise.resolve();
36419
36504
  return new Promise((resolve14) => this.idleWaiters.add(resolve14));
36420
36505
  }
36421
- consume(chunk) {
36506
+ consume(chunk2) {
36422
36507
  if (this.closed) return;
36423
- this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
36508
+ this.buffer += typeof chunk2 === "string" ? chunk2 : this.decoder.write(chunk2);
36424
36509
  while (true) {
36425
36510
  const newline = this.buffer.indexOf("\n");
36426
36511
  if (newline < 0) {
@@ -38928,6 +39013,7 @@ var init_codex_app_server = __esm({
38928
39013
  import { join as join29 } from "node:path";
38929
39014
  import { readdirSync as readdirSync8, statSync as statSync14, openSync as openSync13, readSync as readSync6, fstatSync, closeSync as closeSync12 } from "node:fs";
38930
39015
  import { spawn as spawn4 } from "node:child_process";
39016
+ import { createHash as createHash15 } from "node:crypto";
38931
39017
  function sessionsDir2(codexHome) {
38932
39018
  return join29(codexHome, "sessions");
38933
39019
  }
@@ -39041,18 +39127,32 @@ function toLiveWindow(raw2) {
39041
39127
  const w = raw2;
39042
39128
  return makeWindow(num(w.usedPercent), num(w.windowDurationMins), num(w.resetsAt));
39043
39129
  }
39044
- function parseCodexQuotaFromRateLimits(result) {
39130
+ function parseCodexQuotaFromRateLimits(result, observedAt = Date.now()) {
39045
39131
  if (!result || typeof result !== "object") return void 0;
39046
39132
  const rl2 = result.rateLimits;
39047
39133
  if (!rl2 || typeof rl2 !== "object") return void 0;
39048
39134
  const r = rl2;
39135
+ const allowed = result.ordinaryUsageAllowed;
39136
+ const ordinaryUsageAllowed = !("ordinaryUsageAllowed" in result) ? void 0 : typeof allowed === "boolean" ? allowed : null;
39049
39137
  const windows = [toLiveWindow(r.primary), toLiveWindow(r.secondary)].filter((x4) => x4 !== void 0);
39050
- if (windows.length === 0) return void 0;
39138
+ const credits = r.credits && typeof r.credits === "object" ? r.credits : void 0;
39139
+ const creditsAvailable = credits?.unlimited === true || credits?.hasCredits === true ? true : credits?.unlimited === false && credits?.hasCredits === false ? false : void 0;
39140
+ const reached = r.rateLimitReachedType;
39141
+ const individual = r.individualLimit && typeof r.individualLimit === "object" ? r.individualLimit : void 0;
39142
+ const blocked = r.spendControlReached === true || typeof reached === "string" && reached !== "rate_limit_reached" || typeof individual?.remainingPercent === "number" && individual.remainingPercent <= 0;
39143
+ if (windows.length === 0 && creditsAvailable === void 0 && ordinaryUsageAllowed !== true) return void 0;
39051
39144
  const planType = typeof r.planType === "string" ? r.planType : void 0;
39052
- return { status: "ok", planType, windows };
39145
+ return { status: "ok", planType, windows, codexRecovery: {
39146
+ observedAt,
39147
+ creditsAvailable,
39148
+ ...ordinaryUsageAllowed !== void 0 ? { ordinaryUsageAllowed } : {},
39149
+ ...blocked ? { blocked: true } : {}
39150
+ } };
39053
39151
  }
39054
39152
  function queryCodexRateLimits(codexHome = defaultCodexHome(), codexBin = "codex", timeoutMs = 12e3) {
39055
39153
  return new Promise((resolve14) => {
39154
+ const observedAt = Date.now();
39155
+ const accountId = readCodexAccountId(codexHome);
39056
39156
  let child;
39057
39157
  try {
39058
39158
  const codex = resolveCodexExecutable(codexBin);
@@ -39089,8 +39189,8 @@ function queryCodexRateLimits(codexHome = defaultCodexHome(), codexBin = "codex"
39089
39189
  child.on("exit", () => finish(void 0));
39090
39190
  child.stdin?.on("error", () => finish(void 0));
39091
39191
  let buf = "";
39092
- child.stdout?.on("data", (chunk) => {
39093
- buf += chunk.toString("utf8");
39192
+ child.stdout?.on("data", (chunk2) => {
39193
+ buf += chunk2.toString("utf8");
39094
39194
  if (buf.length > 4 * 1024 * 1024) buf = buf.slice(-64 * 1024);
39095
39195
  let nl2;
39096
39196
  while ((nl2 = buf.indexOf("\n")) >= 0) {
@@ -39107,7 +39207,13 @@ function queryCodexRateLimits(codexHome = defaultCodexHome(), codexBin = "codex"
39107
39207
  send({ jsonrpc: "2.0", method: "initialized" });
39108
39208
  send({ jsonrpc: "2.0", id: 2, method: "account/rateLimits/read", params: {} });
39109
39209
  } else if (msg.id === 2) {
39110
- finish(parseCodexQuotaFromRateLimits(msg.result));
39210
+ const quota = parseCodexQuotaFromRateLimits(msg.result, observedAt);
39211
+ if (quota) {
39212
+ const reported = msg.result && typeof msg.result === "object" ? msg.result.accountId : void 0;
39213
+ if (readCodexAccountId(codexHome) !== accountId || accountId && typeof reported === "string" && reported !== accountId) delete quota.codexRecovery;
39214
+ else if (accountId) quota.codexRecovery.accountKey = createHash15("sha256").update(accountId).digest("hex");
39215
+ }
39216
+ finish(quota);
39111
39217
  }
39112
39218
  }
39113
39219
  });
@@ -39525,7 +39631,7 @@ function readQuestionFences(storage, input) {
39525
39631
  for (const id of assembled.refs) {
39526
39632
  const row = index.get(id);
39527
39633
  if (!row) {
39528
- fault(id, `\`id: ${id}\` alone references a question, and no question of yours uses that id \u2014 to ask a new one, give the fence a \`kind:\` and a \`question:\``);
39634
+ fault(id, `\`id: ${id}\` alone references a question, and no question of yours uses that id, so the human was never asked it and no answer is coming \u2014 \`frizzctl activity\` lists the questions you have open; to ask this one, write the whole fence, with a \`kind:\` and a \`question:\``);
39529
39635
  } else if (!settledBefore(row)) ref(row);
39530
39636
  else if (row.state === "answered") continue;
39531
39637
  else if (row.state === "withdrawn") {
@@ -39569,7 +39675,7 @@ ${b.read.id.toLowerCase()}`)) continue;
39569
39675
  return open.filter((q5) => q5.asked_at > restFrom || named.has(q5.id));
39570
39676
  }
39571
39677
  function questionFenceCorrection(faults, opts = {}) {
39572
- const asks = faults.some((f) => f.faults.some((x4) => !/alone references|nothing left to reference/.test(x4)));
39678
+ const asks = faults.some((f) => f.faults.some((x4) => !/nothing left to reference/.test(x4)));
39573
39679
  const lines = [
39574
39680
  `${QUESTION_FENCE_CORRECTION_LEAD}could not register, so ${asks ? "the human has NOT been asked" : "it placed nothing"}:`,
39575
39681
  "",
@@ -39581,6 +39687,7 @@ function questionFenceCorrection(faults, opts = {}) {
39581
39687
  "`description:`, `recommended: true` and an indented `detail: |` block. Anything else the human needs",
39582
39688
  "goes below a `---` line as markdown. A fence with `id:` alone references a question you already asked."
39583
39689
  ];
39690
+ if (opts.typedPast) lines.push("", QUESTION_FENCE_TYPED_PAST_HINT);
39584
39691
  if (opts.closedOnDone) lines.push("", QUESTION_FENCE_UNDER_DONE_HINT);
39585
39692
  return lines.join("\n");
39586
39693
  }
@@ -39635,13 +39742,14 @@ function createQuestionRegistrar(deps) {
39635
39742
  }
39636
39743
  };
39637
39744
  }
39638
- var QUESTION_FENCES_REGISTER_FROM, REGISTER_FROM_MS, bare, SETTLED_WORD, QUESTION_FENCE_UNDER_DONE_HINT;
39745
+ var QUESTION_FENCES_REGISTER_FROM, REGISTER_FROM_MS, QUESTION_FAULTS_OUTLIVE_HUMAN_FROM, bare, SETTLED_WORD, QUESTION_FENCE_TYPED_PAST_HINT, QUESTION_FENCE_UNDER_DONE_HINT;
39639
39746
  var init_question_fences = __esm({
39640
39747
  "packages/server/src/question-fences.ts"() {
39641
39748
  "use strict";
39642
39749
  init_src();
39643
39750
  QUESTION_FENCES_REGISTER_FROM = "2026-10-13T20:00:00Z";
39644
39751
  REGISTER_FROM_MS = Date.parse(QUESTION_FENCES_REGISTER_FROM);
39752
+ QUESTION_FAULTS_OUTLIVE_HUMAN_FROM = "2026-10-21T22:00:00Z";
39645
39753
  bare = (q5) => JSON.stringify({ ...q5, options: q5.options?.map(({ followUps: _followUps, ...o }) => o) });
39646
39754
  SETTLED_WORD = {
39647
39755
  open: "open",
@@ -39649,6 +39757,7 @@ var init_question_fences = __esm({
39649
39757
  withdrawn: "withdrawn",
39650
39758
  dismissed: "dismissed by the human"
39651
39759
  };
39760
+ QUESTION_FENCE_TYPED_PAST_HINT = "The human has written to you since the message that carried this fence; if what they wrote already settles it, there is nothing to ask again.";
39652
39761
  QUESTION_FENCE_UNDER_DONE_HINT = "This rest also closed on a ```done fence, and a done fence cannot stand beside a question once it registers: the message that carries the fixed fence carries no ```done fence, and the sign-off as done comes once the question is answered.";
39653
39762
  }
39654
39763
  });
@@ -40426,7 +40535,7 @@ var init_worker_plugin_dir = __esm({
40426
40535
  });
40427
40536
 
40428
40537
  // packages/server/src/stable-plugin-path.ts
40429
- import { createHash as createHash14 } from "node:crypto";
40538
+ import { createHash as createHash16 } from "node:crypto";
40430
40539
  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";
40431
40540
  import { homedir as homedir13 } from "node:os";
40432
40541
  import { dirname as dirname15, isAbsolute as isAbsolute7, join as join34, resolve as resolve7 } from "node:path";
@@ -40521,7 +40630,7 @@ function pluginFiles(root) {
40521
40630
  return files;
40522
40631
  }
40523
40632
  function pluginContentDigest(dir, siblings = []) {
40524
- const hash = createHash14("sha256");
40633
+ const hash = createHash16("sha256");
40525
40634
  const roots = [[dir, ""], ...siblings.map((s) => [join34(dirname15(dir), s), `../${s}/`])];
40526
40635
  for (const [root, prefix] of roots) {
40527
40636
  for (const rel of pluginFiles(root)) hash.update(prefix + rel).update("\0").update(readFileSync22(join34(root, rel))).update("\0");
@@ -41081,7 +41190,17 @@ HTML page carrying every candidate, linked in your message as \`[name](file:///a
41081
41190
  screenshot it, judge the screenshots, or put them in a lightbox or a question option in its place: the
41082
41191
  human reads the real page in their own browser faster and better than any picture of it (maintainer
41083
41192
  2026-10-06: *"you should always just generate an artifact or an HTML page or whatever and just link me
41084
- to it. You don't need to take screenshots; that just made it harder for me to gauge"*).`;
41193
+ to it. You don't need to take screenshots; that just made it harder for me to gauge"*).
41194
+
41195
+ **SELF-CONTAINED MEANS THE ONE FILE, AND NOTHING BESIDE IT.** Every image, stylesheet, font and
41196
+ script the page uses goes INSIDE it: a screenshot as a \`data:\` URI, never a relative \`src\` to a
41197
+ file in the same folder. The browser that opens the link may be allowed that one file and nothing
41198
+ else. On macOS a browser denied the folder the page sits in (Documents, Desktop and Downloads each
41199
+ need the human's permission) is still handed the page it was asked to open, and refused every file
41200
+ beside it, so each image draws as a broken icon. Your own headless browser cannot catch this, since
41201
+ it inherits your terminal's folder access: check the page COPIED ALONE into an empty directory
41202
+ before you link it (maintainer 2026-10-21, after galleries of screenshots reached them as broken
41203
+ images: *"You keep making this mistake"*).`;
41085
41204
  MARKDOWN_COMPONENTS = `## Markdown that Frizz draws as more than text
41086
41205
 
41087
41206
  Each of these is drawn wherever your Markdown is: a message, the body of \`frizzctl done\`, a
@@ -42057,8 +42176,8 @@ function connectClaudeBroker(socketPath, handlers, options = {}) {
42057
42176
  }
42058
42177
  pendingInputs.clear();
42059
42178
  };
42060
- const onData = (chunk) => {
42061
- buf += chunk;
42179
+ const onData = (chunk2) => {
42180
+ buf += chunk2;
42062
42181
  for (let nl2 = buf.indexOf("\n"); nl2 >= 0; nl2 = buf.indexOf("\n")) {
42063
42182
  const line = buf.slice(0, nl2);
42064
42183
  buf = buf.slice(nl2 + 1);
@@ -43030,7 +43149,7 @@ var init_claude_agent_broker_bridge = __esm({
43030
43149
  // packages/server/src/dispatch.ts
43031
43150
  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";
43032
43151
  import { basename as basename7, join as join36, dirname as dirname16 } from "node:path";
43033
- import { createHash as createHash15, randomUUID as randomUUID14 } from "node:crypto";
43152
+ import { createHash as createHash17, randomUUID as randomUUID14 } from "node:crypto";
43034
43153
  function fallbackTitle(prompt) {
43035
43154
  const firstLine2 = prompt.trim().split("\n", 1)[0].trim();
43036
43155
  let allWords = firstLine2.split(/\s+/).filter(Boolean);
@@ -43099,7 +43218,7 @@ function resolveLegacyThreadFile(projectDir, value) {
43099
43218
  size: after.size,
43100
43219
  mtimeMs: after.mtimeMs,
43101
43220
  ctimeMs: after.ctimeMs,
43102
- digest: createHash15("sha256").update(contents).digest("hex")
43221
+ digest: createHash17("sha256").update(contents).digest("hex")
43103
43222
  };
43104
43223
  } catch {
43105
43224
  return null;
@@ -44222,6 +44341,7 @@ function deriveNeedsYou(row, tele, runtime, hasActionableInteraction = false, no
44222
44341
  if (tele?.pendingQuestion) return true;
44223
44342
  if (openQuestions > 0) return true;
44224
44343
  if (limitPause) return true;
44344
+ if (tele?.lastFence?.kind === "done") return true;
44225
44345
  const answered = tele?.lastFence?.kind === "awaiting" && awaitingNeedsInput(tele.lastFence.hints) !== null;
44226
44346
  if (answered || needsInputRequired(row.spawned_at)) {
44227
44347
  return needsInputQueues(row, tele, runtime, nowMs, excuseLiveOwnWork, registeredPrWatches, armedTimerIds);
@@ -44230,8 +44350,7 @@ function deriveNeedsYou(row, tele, runtime, hasActionableInteraction = false, no
44230
44350
  if (excuseLiveOwnWork && runtime !== "exited" && hasLiveBackgroundWork(tele) && !tele?.lastFence) return false;
44231
44351
  if (excuseLiveOwnWork && runtime !== "exited" && (hasDeclaredBackgroundPark(tele, nowMs) || hasRegisteredBackgroundPark(tele, armedWatches, nowMs))) return false;
44232
44352
  if (excuseLiveOwnWork && runtime !== "exited" && heldByRunningChecks(github, registeredPrWatches)) return false;
44233
- if (runtime !== "exited" && (hasLiveOwnWork(tele, registeredPrWatches) || hasParkedTimerWatch(tele, armedTimerIds)) && tele?.lastFence?.kind !== "done") return !bgSnoozeArmed(row);
44234
- if (tele?.lastFence?.kind === "done") return true;
44353
+ if (runtime !== "exited" && (hasLiveOwnWork(tele, registeredPrWatches) || hasParkedTimerWatch(tele, armedTimerIds))) return !bgSnoozeArmed(row);
44235
44354
  return true;
44236
44355
  }
44237
44356
  function needsInputQueues(row, tele, runtime, nowMs, excuseLiveOwnWork, registeredPrWatches, armedTimerIds) {
@@ -44336,6 +44455,7 @@ function resolveRecurringPrompt(row) {
44336
44455
  function resolveLimitPause(row, tele, nowMs) {
44337
44456
  const fault = tele?.limitFault;
44338
44457
  if (!fault) return void 0;
44458
+ if (fault.codex) return void 0;
44339
44459
  const at2 = Date.parse(fault.at);
44340
44460
  const stale = limitPauseIsStale(fault.window, at2, nowMs);
44341
44461
  const resumesAtMs = fault.resetClock && Number.isFinite(at2) ? textResetInstant({ window: fault.window, resetClock: fault.resetClock }, at2) : void 0;
@@ -45956,16 +46076,16 @@ function createGithubReviewFetcher(deps = {}) {
45956
46076
  }
45957
46077
  const entries2 = [...batch.values()];
45958
46078
  for (let offset = 0; offset < entries2.length; offset += MAX_REFS_PER_REQUEST) {
45959
- const chunk = entries2.slice(offset, offset + MAX_REFS_PER_REQUEST);
46079
+ const chunk2 = entries2.slice(offset, offset + MAX_REFS_PER_REQUEST);
45960
46080
  if (offset > 0 && now() < rateLimitBlockedUntilMs) {
45961
- for (const entry of chunk) for (const resolve14 of entry.resolve) resolve14({ status: "deferred" });
46081
+ for (const entry of chunk2) for (const resolve14 of entry.resolve) resolve14({ status: "deferred" });
45962
46082
  continue;
45963
46083
  }
45964
46084
  let results;
45965
46085
  try {
45966
- results = await fetchChunk(chunk.map((entry) => entry.ref));
46086
+ results = await fetchChunk(chunk2.map((entry) => entry.ref));
45967
46087
  } catch (error) {
45968
- results = new Map(chunk.map((entry) => [
46088
+ results = new Map(chunk2.map((entry) => [
45969
46089
  refKey(entry.ref),
45970
46090
  {
45971
46091
  status: "error",
@@ -45973,7 +46093,7 @@ function createGithubReviewFetcher(deps = {}) {
45973
46093
  }
45974
46094
  ]));
45975
46095
  }
45976
- for (const entry of chunk) {
46096
+ for (const entry of chunk2) {
45977
46097
  const result = results.get(refKey(entry.ref)) ?? {
45978
46098
  status: "error",
45979
46099
  failure: { kind: "shape", message: `No GitHub result for ${refKey(entry.ref)}` }
@@ -46144,7 +46264,7 @@ var init_pr_watch_noise = __esm({
46144
46264
  // packages/server/src/scheduler.ts
46145
46265
  import { execFile as execFile8 } from "node:child_process";
46146
46266
  import { promisify as promisify7 } from "node:util";
46147
- import { createHash as createHash16, randomUUID as randomUUID15 } from "node:crypto";
46267
+ import { createHash as createHash18, randomUUID as randomUUID15 } from "node:crypto";
46148
46268
  function failureSignature(rollup) {
46149
46269
  const ids = [];
46150
46270
  for (const c of Array.isArray(rollup) ? rollup : []) {
@@ -46154,7 +46274,7 @@ function failureSignature(rollup) {
46154
46274
  ids.push(`${label}@${c.detailsUrl ?? c.targetUrl ?? c.completedAt ?? ""}`);
46155
46275
  }
46156
46276
  if (ids.length === 0) return "";
46157
- return createHash16("sha1").update(ids.sort().join("\n")).digest("hex").slice(0, 12);
46277
+ return createHash18("sha1").update(ids.sort().join("\n")).digest("hex").slice(0, 12);
46158
46278
  }
46159
46279
  function ghPrViewArgs(ref) {
46160
46280
  return ["pr", "view", String(ref.number), "--repo", `${ref.owner}/${ref.repo}`, "--json", "state,mergedAt,statusCheckRollup,headRefOid,mergeable,reviewDecision"];
@@ -46266,7 +46386,7 @@ function githubWatchStatus(pr, polledAt) {
46266
46386
  };
46267
46387
  }
46268
46388
  function wakeDeliveryId(slug, sessionId, fenceId) {
46269
- return createHash16("sha256").update(slug).update("\0").update(sessionId).update("\0").update(fenceId).digest("hex");
46389
+ return createHash18("sha256").update(slug).update("\0").update(sessionId).update("\0").update(fenceId).digest("hex");
46270
46390
  }
46271
46391
  function limitFenceId(fault) {
46272
46392
  return `${LIMIT_FENCE_PREFIX}${fault.at}`;
@@ -46281,7 +46401,7 @@ function isReportFenceId(fenceId) {
46281
46401
  return fenceId.startsWith(`${REPORT_FENCE_PREFIX}:`);
46282
46402
  }
46283
46403
  function snoozeFenceId(until, prompt) {
46284
- const digest = createHash16("sha256").update(prompt).digest("hex").slice(0, 16);
46404
+ const digest = createHash18("sha256").update(prompt).digest("hex").slice(0, 16);
46285
46405
  return `${SNOOZE_FENCE_PREFIX}:${until}:${digest}`;
46286
46406
  }
46287
46407
  function isSnoozeFenceId(fenceId) {
@@ -46421,7 +46541,7 @@ function isCommandWatchFenceId(fenceId) {
46421
46541
  return fenceId.startsWith(`${COMMAND_WATCH_FENCE_PREFIX}:`) || fenceId.startsWith(`${COMMAND_WATCH_EXPIRED_FENCE_PREFIX}:`) || fenceId.startsWith(`${COMMAND_WATCH_CANCELLED_FENCE_PREFIX}:`);
46422
46542
  }
46423
46543
  function questionAnswerFenceId(ids) {
46424
- return `${QUESTION_ANSWER_FENCE_PREFIX}:${createHash16("sha256").update([...ids].sort().join(",")).digest("hex").slice(0, 16)}`;
46544
+ return `${QUESTION_ANSWER_FENCE_PREFIX}:${createHash18("sha256").update([...ids].sort().join(",")).digest("hex").slice(0, 16)}`;
46425
46545
  }
46426
46546
  function isQuestionAnswerFenceId(fenceId) {
46427
46547
  return fenceId.startsWith(`${QUESTION_ANSWER_FENCE_PREFIX}:`);
@@ -46595,11 +46715,29 @@ function createScheduler(deps) {
46595
46715
  function retryDelay(attempts) {
46596
46716
  return Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, Math.min(30, attempts - 1)));
46597
46717
  }
46718
+ function limitTelemetry(row) {
46719
+ const tele = deps.tailer.get(row.slug);
46720
+ const live2 = row.backend === "codex" ? deps.codexTurnLiveness?.(row.slug, row.session_id) : void 0;
46721
+ if (live2?.bridgeTurn) return tele ? { ...tele, turn: "in-flight" } : void 0;
46722
+ const error = live2?.providerError;
46723
+ if (!error || error.retrying || !error.at || tele?.lastActivityAt && error.at < tele.lastActivityAt) return tele;
46724
+ const same2 = tele?.providerError?.message === error.message && tele?.providerError?.code === error.code;
46725
+ const at2 = same2 ? tele?.providerError?.at ?? error.at : error.at;
46726
+ return {
46727
+ subAgents: [],
46728
+ bgShells: [],
46729
+ ...tele,
46730
+ turn: "idle",
46731
+ permPrompt: false,
46732
+ pendingQuestion: false,
46733
+ limitFault: codexLimitFault(error, at2)
46734
+ };
46735
+ }
46598
46736
  function deliveryContext(item) {
46599
46737
  const row = deps.storage.getSession(item.slug);
46600
46738
  if (!row || row.session_id !== item.sessionId) return "superseded";
46601
46739
  if (row.state === "archived" || row.archived === 1) return "superseded";
46602
- const tele = deps.tailer.get(item.slug);
46740
+ const tele = isLimitFenceId(item.fenceId) ? limitTelemetry(row) : deps.tailer.get(item.slug);
46603
46741
  if (!tele) return "unknown";
46604
46742
  if (tele.lastUserText?.includes(wakeDeliveryToken(item.id))) return "confirmed";
46605
46743
  if (isLimitFenceId(item.fenceId)) {
@@ -46742,10 +46880,14 @@ function createScheduler(deps) {
46742
46880
  const out = [];
46743
46881
  for (const row of deps.storage.allSessions()) {
46744
46882
  if (row.state === "archived" || row.archived === 1) continue;
46745
- const tele = deps.tailer.get(row.slug);
46883
+ const tele = limitTelemetry(row);
46746
46884
  const fault = tele?.limitFault;
46885
+ const spent = spentCodexResume.get(row.slug);
46886
+ if (!fault && spent && !tele?.apiFault && Date.parse(tele?.lastAssistantAt ?? "") > spent.at) {
46887
+ spentCodexResume.delete(row.slug);
46888
+ }
46747
46889
  if (!fault || tele?.turn !== "idle") continue;
46748
- if (limitPauseIsStale(fault.window, Date.parse(fault.at), nowMs)) continue;
46890
+ if (limitPauseIsStale(fault.codex ? "weekly" : fault.window, Date.parse(fault.at), nowMs)) continue;
46749
46891
  out.push({
46750
46892
  slug: row.slug,
46751
46893
  sessionId: row.session_id,
@@ -46756,9 +46898,21 @@ function createScheduler(deps) {
46756
46898
  return out;
46757
46899
  }
46758
46900
  const spentEarlyResume = /* @__PURE__ */ new Map();
46901
+ const spentCodexResume = /* @__PURE__ */ new Map();
46759
46902
  function limitRecovered(c, quota, nowMs) {
46760
46903
  const faultAtMs = Date.parse(c.fault.at);
46761
46904
  const provider = quota?.[c.backend];
46905
+ if (c.backend === "codex") {
46906
+ if (!Number.isFinite(faultAtMs) || nowMs - faultAtMs < LIMIT_HEADROOM_MIN_FAULT_AGE_MS) return void 0;
46907
+ const recovery = codexLimitRecovery(c.fault, provider, nowMs);
46908
+ if (recovery === "blocked") {
46909
+ spentCodexResume.delete(c.slug);
46910
+ return false;
46911
+ }
46912
+ if (!recovery || spentCodexResume.get(c.slug)?.key === recovery.key) return void 0;
46913
+ spentCodexResume.set(c.slug, { key: recovery.key, at: nowMs });
46914
+ return true;
46915
+ }
46762
46916
  if (provider?.status === "ok" && Number.isFinite(faultAtMs) && nowMs - faultAtMs >= LIMIT_HEADROOM_MIN_FAULT_AGE_MS) {
46763
46917
  const key = quotaWindowKeyFor(c.fault.window);
46764
46918
  const w = key ? provider.windows.find((x4) => x4.key === key) : c.fault.window === "model" ? scopedQuotaWindow(provider.windows, c.fault.model) : void 0;
@@ -46812,7 +46966,7 @@ function createScheduler(deps) {
46812
46966
  const deliveryId = wakeDeliveryId(c.slug, c.sessionId, fenceId);
46813
46967
  if (outbox.get(deliveryId)) continue;
46814
46968
  const fallback = modelFallbackFor(c);
46815
- if (!fallback && limitRecovered(c, quota, nowMs) !== true) continue;
46969
+ if (!fallback && limitRecovered(c, quota, now()) !== true) continue;
46816
46970
  if (fallback) deps.storage.setProfile(c.slug, fallback.model, fallback.effort);
46817
46971
  const item = outbox.enqueue({
46818
46972
  id: deliveryId,
@@ -46821,7 +46975,7 @@ function createScheduler(deps) {
46821
46975
  fenceId,
46822
46976
  hintKey: fallback ? `${LIMIT_HINT_PREFIX}model-switch` : `${LIMIT_HINT_PREFIX}${c.fault.window}`,
46823
46977
  message: fallback ? limitModelSwitchSteer(fallback.capped, fallback.label) : limitResumeSteer(c.fault.window),
46824
- reason: fallback ? `${fallback.capped} limit \u2014 restarting on ${fallback.label} (interrupted ${c.fault.at})` : `${c.fault.window} usage limit reset (interrupted ${c.fault.at})`
46978
+ reason: fallback ? `${fallback.capped} limit \u2014 restarting on ${fallback.label} (interrupted ${c.fault.at})` : c.backend === "codex" ? `Codex capacity recovered (interrupted ${c.fault.at})` : `${c.fault.window} usage limit reset (interrupted ${c.fault.at})`
46825
46979
  }, nowMs).delivery;
46826
46980
  log3(`waker: queued ${c.slug} \u2014 ${item.reason}`);
46827
46981
  checkpoint("after-enqueue", item);
@@ -46963,7 +47117,12 @@ ${wakeTimeHeader(now(), spokeAt)}`;
46963
47117
  if (tele.lastUserAt && Date.parse(spokeAt) <= Date.parse(tele.lastUserAt)) continue;
46964
47118
  if (tele.authFault || tele.apiFault) continue;
46965
47119
  const instant2 = (at2) => at2 ? Date.parse(at2) : Number.NEGATIVE_INFINITY;
46966
- const restFrom = Math.max(instant2(tele.restFromAt ?? tele.lastUserAt), instant2(tele.questionCorrectedAt));
47120
+ const humanAt = instant2(tele.restFromAt ?? tele.lastUserAt);
47121
+ const correctedAt = instant2(tele.questionCorrectedAt);
47122
+ const untold = (at2) => {
47123
+ const atMs = Date.parse(at2);
47124
+ return atMs > correctedAt && (atMs >= FAULTS_OUTLIVE_HUMAN_FROM_MS || atMs > humanAt);
47125
+ };
46967
47126
  const rows = deps.storage.listThreadQuestions(row.slug);
46968
47127
  const fixedAfter = (id, at2) => {
46969
47128
  if (!id) return false;
@@ -46972,8 +47131,9 @@ ${wakeTimeHeader(now(), spokeAt)}`;
46972
47131
  const fixedByRef = sync.refs.some((r) => Date.parse(r.at) > atMs && rows.some((q5) => q5.id === r.rowId && q5.handle === id));
46973
47132
  return fixedByRow || fixedByRef;
46974
47133
  };
46975
- const faults = sync.faults.filter((f) => Date.parse(f.at) > restFrom && !fixedAfter(f.id, f.at));
47134
+ const faults = sync.faults.filter((f) => untold(f.at) && !fixedAfter(f.id, f.at));
46976
47135
  if (faults.length === 0) continue;
47136
+ const typedPast = faults.some((f) => Date.parse(f.at) < humanAt);
46977
47137
  if (faults.some((f) => Date.parse(f.at) > instant2(tele.lastUserAt))) questionFaultRests.set(row.slug, spokeAt);
46978
47138
  if (parkCapSpent(row, spokeAt) || !correctionAllowedSinceHuman(row.slug, QUESTION_FENCE_CAUSE, tele)) continue;
46979
47139
  const fenceId = parkFenceId(QUESTION_FENCE_CAUSE, spokeAt);
@@ -46981,9 +47141,9 @@ ${wakeTimeHeader(now(), spokeAt)}`;
46981
47141
  if (outbox.get(deliveryId)) continue;
46982
47142
  const underDone = correctionAllowedSinceHuman(row.slug, DONE_OVER_QUESTION_CAUSE, tele) ? questionsUnderDoneFence(row, tele, rows) : [];
46983
47143
  const closedOnDone = underDone.length === 0 && tele.lastFence?.kind === "done";
46984
- const correction = underDone.length > 0 ? `${questionFenceCorrection(faults)}
47144
+ const correction = underDone.length > 0 ? `${questionFenceCorrection(faults, { typedPast })}
46985
47145
 
46986
- Separately, your \`\`\`done fence ${doneOverOpenQuestionsBody(underDone)}` : questionFenceCorrection(faults, { closedOnDone });
47146
+ Separately, your \`\`\`done fence ${doneOverOpenQuestionsBody(underDone)}` : questionFenceCorrection(faults, { closedOnDone, typedPast });
46987
47147
  const item = outbox.enqueue({
46988
47148
  id: deliveryId,
46989
47149
  slug: row.slug,
@@ -48187,6 +48347,7 @@ ${clock}`;
48187
48347
  const adopted = [];
48188
48348
  for (const sibling of outbox.pendingFor(carrier.slug, carrier.sessionId)) {
48189
48349
  if (sibling.id === carrier.id || isQuestionAnswerFenceId(sibling.fenceId)) continue;
48350
+ if (isLimitFenceId(sibling.fenceId) && deps.storage.getSession(sibling.slug)?.backend === "codex") continue;
48190
48351
  const context = deliveryContext(sibling);
48191
48352
  if (context === "confirmed") {
48192
48353
  outbox.confirm(sibling.id, now());
@@ -48237,7 +48398,18 @@ ${wakeTimeHeader(now(), spokeAt)}`;
48237
48398
  settleSnooze(item);
48238
48399
  continue;
48239
48400
  }
48240
- if (!isDeliverableNow(item, context, claimedAt)) {
48401
+ let codexCapacity = true;
48402
+ const row = deps.storage.getSession(item.slug);
48403
+ if (isLimitFenceId(item.fenceId) && row?.backend === "codex") {
48404
+ const fault = limitTelemetry(row)?.limitFault;
48405
+ try {
48406
+ const recovery = fault && codexLimitRecovery(fault, (await deps.readQuota?.())?.codex, now());
48407
+ codexCapacity = !!recovery && recovery !== "blocked";
48408
+ } catch {
48409
+ codexCapacity = false;
48410
+ }
48411
+ }
48412
+ if (!codexCapacity || !isDeliverableNow(item, deliveryContext(item), claimedAt)) {
48241
48413
  const deferredAt = now();
48242
48414
  outbox.deferFailure(
48243
48415
  item.id,
@@ -48433,13 +48605,14 @@ ${wakeTimeHeader(now(), spokeAt)}`;
48433
48605
  commandRunsIdle
48434
48606
  };
48435
48607
  }
48436
- var execFileAsync5, OFF_MERGE_PATHS, 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, GITHUB_STATUS_CAP, REVIEW_SEEN_CAP, REVIEW_STEER_CAP, AWAITING_KEY_OF, MID_TURN_HOLD_MAX_MS, WAKE_HOLD_DEFERRAL;
48608
+ var execFileAsync5, OFF_MERGE_PATHS, 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;
48437
48609
  var init_scheduler = __esm({
48438
48610
  "packages/server/src/scheduler.ts"() {
48439
48611
  "use strict";
48440
48612
  init_src();
48441
48613
  init_question_fences();
48442
48614
  init_awaiting();
48615
+ init_codex_usage_limit();
48443
48616
  init_usage_limit();
48444
48617
  init_thread_profiles();
48445
48618
  init_wake_store();
@@ -48492,6 +48665,7 @@ var init_scheduler = __esm({
48492
48665
  QUESTION_FENCE_CAUSE = "question-fence";
48493
48666
  DONE_OVER_QUESTION_CAUSE = "done-open-question";
48494
48667
  DONE_GATE_FROM_MS = Date.parse(QUESTION_FENCES_REGISTER_FROM);
48668
+ FAULTS_OUTLIVE_HUMAN_FROM_MS = Date.parse(QUESTION_FAULTS_OUTLIVE_HUMAN_FROM);
48495
48669
  GITHUB_STATUS_CAP = 200;
48496
48670
  REVIEW_SEEN_CAP = 300;
48497
48671
  REVIEW_STEER_CAP = 10;
@@ -49152,8 +49326,8 @@ var init_acp_rpc = __esm({
49152
49326
  });
49153
49327
  });
49154
49328
  process2.stdin?.on("error", (err) => this.settleClosed(`stdin: ${err.message}`));
49155
- process2.stdout?.on("data", (chunk) => {
49156
- this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
49329
+ process2.stdout?.on("data", (chunk2) => {
49330
+ this.buffer += typeof chunk2 === "string" ? chunk2 : this.decoder.write(chunk2);
49157
49331
  let nl2;
49158
49332
  while ((nl2 = this.buffer.indexOf("\n")) >= 0) {
49159
49333
  const line = this.buffer.slice(0, nl2);
@@ -49170,8 +49344,8 @@ var init_acp_rpc = __esm({
49170
49344
  this.overflowing = true;
49171
49345
  }
49172
49346
  });
49173
- process2.stderr?.on("data", (chunk) => {
49174
- const text2 = String(chunk);
49347
+ process2.stderr?.on("data", (chunk2) => {
49348
+ const text2 = String(chunk2);
49175
49349
  for (const line of text2.split("\n")) {
49176
49350
  if (!line.trim()) continue;
49177
49351
  this.stderrTail.push(line.slice(0, 2e3));
@@ -49325,7 +49499,7 @@ var init_acp_rpc = __esm({
49325
49499
  // packages/server/src/backend/acp-host.ts
49326
49500
  import { spawn as spawn7 } from "node:child_process";
49327
49501
  import { createConnection as createConnection2 } from "node:net";
49328
- import { createHash as createHash17, randomUUID as randomUUID16 } from "node:crypto";
49502
+ import { createHash as createHash19, randomUUID as randomUUID16 } from "node:crypto";
49329
49503
  import { existsSync as existsSync16, mkdirSync as mkdirSync21, readFileSync as readFileSync26, readdirSync as readdirSync10, unlinkSync as unlinkSync4 } from "node:fs";
49330
49504
  import { join as join41 } from "node:path";
49331
49505
  import { PassThrough as PassThrough3, Writable as Writable3 } from "node:stream";
@@ -49337,7 +49511,7 @@ function acpDaemonRecordPath(stateDir, sessionId) {
49337
49511
  return join41(daemonDir2(stateDir), `${sessionId}.json`);
49338
49512
  }
49339
49513
  function acpDaemonSocketPath(stateDir, sessionId) {
49340
- const key = createHash17("sha256").update(stateDir).update("\0").update(sessionId).digest("hex").slice(0, 16);
49514
+ const key = createHash19("sha256").update(stateDir).update("\0").update(sessionId).digest("hex").slice(0, 16);
49341
49515
  return frizzIpcPath(`frizz-acp-${key}`);
49342
49516
  }
49343
49517
  function pidAlive4(pid) {
@@ -49473,8 +49647,8 @@ function attach3(record, timeoutMs) {
49473
49647
  }, timeoutMs);
49474
49648
  timer.unref?.();
49475
49649
  const stdin = new Writable3({
49476
- write(chunk, _encoding, callback) {
49477
- socket.write(chunk, (error) => callback(error ?? null));
49650
+ write(chunk2, _encoding, callback) {
49651
+ socket.write(chunk2, (error) => callback(error ?? null));
49478
49652
  },
49479
49653
  // The bridge's `close()` ends stdin as the protocol's teardown. On a daemon attachment that is a
49480
49654
  // DETACH: the socket closes, the agent keeps running.
@@ -49508,8 +49682,8 @@ function attach3(record, timeoutMs) {
49508
49682
  };
49509
49683
  const decoder = new StringDecoder5("utf8");
49510
49684
  let buffer = "";
49511
- socket.on("data", (chunk) => {
49512
- buffer += decoder.write(chunk);
49685
+ socket.on("data", (chunk2) => {
49686
+ buffer += decoder.write(chunk2);
49513
49687
  for (; ; ) {
49514
49688
  const index = buffer.indexOf("\n");
49515
49689
  if (index < 0) break;
@@ -79079,9 +79253,9 @@ function runWatchCommand(spec) {
79079
79253
  return new Promise((resolve14) => {
79080
79254
  const chunks = [];
79081
79255
  let held = 0;
79082
- const keep = (chunk) => {
79083
- chunks.push(chunk);
79084
- held += chunk.length;
79256
+ const keep = (chunk2) => {
79257
+ chunks.push(chunk2);
79258
+ held += chunk2.length;
79085
79259
  while (held - chunks[0].length >= COMMAND_WATCH_OUTPUT_MAX_BYTES && chunks.length > 1) held -= chunks.shift().length;
79086
79260
  };
79087
79261
  let settled = false;
@@ -79641,13 +79815,13 @@ async function enumerateProcs(exec = defaultExec, opts = {}) {
79641
79815
  return rows;
79642
79816
  }
79643
79817
  const records = [];
79644
- for (const chunk of text2.split(/\n(?=[ \t]*\d+ )/)) {
79645
- const record = chunk.replace(/^[ \t]+/, "");
79818
+ for (const chunk2 of text2.split(/\n(?=[ \t]*\d+ )/)) {
79819
+ const record = chunk2.replace(/^[ \t]+/, "");
79646
79820
  const pid = Number(record.match(/^(\d+) /)?.[1]);
79647
79821
  const argv = byPid.get(pid)?.command;
79648
79822
  if (argv !== void 0 && record.startsWith(`${pid} ${argv}`)) records.push(record);
79649
79823
  else if (records.length) records[records.length - 1] += `
79650
- ${chunk}`;
79824
+ ${chunk2}`;
79651
79825
  }
79652
79826
  for (const rec of records) {
79653
79827
  const pid = Number(rec.slice(0, rec.indexOf(" ")));
@@ -79828,12 +80002,12 @@ var init_orphan_reaper = __esm({
79828
80002
  });
79829
80003
 
79830
80004
  // packages/server/src/backend/lazy-mcp-host.ts
79831
- import { createHash as createHash18, randomBytes as randomBytes2 } from "node:crypto";
80005
+ import { createHash as createHash20, randomBytes as randomBytes2 } from "node:crypto";
79832
80006
  import { mkdirSync as mkdirSync24, readFileSync as readFileSync30, renameSync as renameSync12, writeFileSync as writeFileSync15 } from "node:fs";
79833
80007
  import { join as join46 } from "node:path";
79834
80008
  function lazyMcpCacheKey(server, cwd) {
79835
80009
  const identity = JSON.stringify({ command: server.command, args: server.args ?? [], env: server.env ?? {}, cwd });
79836
- return createHash18("sha256").update(identity).digest("hex").slice(0, 32);
80010
+ return createHash20("sha256").update(identity).digest("hex").slice(0, 32);
79837
80011
  }
79838
80012
  function lazyMcpCachedToolCount(server, cwd, cacheDir) {
79839
80013
  try {
@@ -80733,6 +80907,7 @@ function createContextUnchecked(opts, resources) {
80733
80907
  // so consulting it per tick costs a live request only every few minutes. Read through the resolved
80734
80908
  // runtimes, as the quota RPC does: a bare call would start whatever `codex` is first on PATH.
80735
80909
  readQuota: () => readQuota({ claudeBin: opts.claudeBin, codexBin: opts.codexBin }),
80910
+ codexTurnLiveness: (slug, sessionId) => codexAppServer?.turnLiveness(slug, sessionId),
80736
80911
  // The only runtime that can answer is the broker: its daemon record is on disk while the daemon
80737
80912
  // lives and is unlinked when it dies (liveBrokerRecords checks the pid), so "did the process that
80738
80913
  // took this wake survive" is one directory read. Codex and any row whose session moved on answer
@@ -81353,15 +81528,15 @@ var init_request = __esm({
81353
81528
  return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
81354
81529
  }
81355
81530
  #getAllDecodedParams() {
81356
- const decoded = {};
81531
+ const decoded2 = {};
81357
81532
  const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
81358
81533
  for (const key of keys) {
81359
81534
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
81360
81535
  if (value !== void 0) {
81361
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
81536
+ decoded2[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
81362
81537
  }
81363
81538
  }
81364
- return decoded;
81539
+ return decoded2;
81365
81540
  }
81366
81541
  #getParamValue(paramKey) {
81367
81542
  return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
@@ -84041,7 +84216,7 @@ var init_bash_background = __esm({
84041
84216
 
84042
84217
  // packages/server/src/transcript.ts
84043
84218
  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";
84044
- import { createHash as createHash19 } from "node:crypto";
84219
+ import { createHash as createHash21 } from "node:crypto";
84045
84220
  import { StringDecoder as StringDecoder6 } from "node:string_decoder";
84046
84221
  import { join as join48 } from "node:path";
84047
84222
  import { homedir as homedir19 } from "node:os";
@@ -84572,9 +84747,9 @@ ${block.text}` : block.text;
84572
84747
  processLine(text2, at2);
84573
84748
  return true;
84574
84749
  }
84575
- function ingest(chunk) {
84576
- if (!chunk) return;
84577
- const data = buffer + chunk;
84750
+ function ingest(chunk2) {
84751
+ if (!chunk2) return;
84752
+ const data = buffer + chunk2;
84578
84753
  buffer = "";
84579
84754
  let pos = offset;
84580
84755
  const lastNl = data.lastIndexOf("\n");
@@ -84729,7 +84904,7 @@ function persistDataUrlImage(dataUrl, idKey) {
84729
84904
  function persistBase64Image(mediaType, data, idKey) {
84730
84905
  const ext = IMAGE_MEDIA_EXT[typeof mediaType === "string" ? mediaType.toLowerCase() : ""];
84731
84906
  if (!ext || !data) return void 0;
84732
- const name = createHash19("sha256").update(idKey).digest("hex").slice(0, 32);
84907
+ const name = createHash21("sha256").update(idKey).digest("hex").slice(0, 32);
84733
84908
  const path3 = join48(SCREENSHOT_CACHE_DIR, `${name}.${ext}`);
84734
84909
  try {
84735
84910
  if (existsSync20(path3)) return path3;
@@ -84751,7 +84926,7 @@ function persistSentFile(srcPath, idKey) {
84751
84926
  if (!ATTACHMENT_IMAGE_EXTENSIONS.includes(ext)) return void 0;
84752
84927
  const outExt = ext === "jpeg" ? "jpg" : ext;
84753
84928
  try {
84754
- const name = createHash19("sha256").update(idKey).digest("hex").slice(0, 32);
84929
+ const name = createHash21("sha256").update(idKey).digest("hex").slice(0, 32);
84755
84930
  const dest = join48(SCREENSHOT_CACHE_DIR, `${name}.${outExt}`);
84756
84931
  if (existsSync20(dest)) return dest;
84757
84932
  const size = statSync21(srcPath).size;
@@ -85143,9 +85318,9 @@ function ingestBounded(entry, to, read) {
85143
85318
  while (entry.bytesRead < to) {
85144
85319
  const buf = read(entry.bytesRead, Math.min(TRANSCRIPT_DECODE_WINDOW, to - entry.bytesRead));
85145
85320
  if (buf.length === 0) break;
85146
- const chunk = entry.decoder.write(buf);
85321
+ const chunk2 = entry.decoder.write(buf);
85147
85322
  entry.bytesRead += buf.length;
85148
- if (chunk) entry.fold.ingest(chunk);
85323
+ if (chunk2) entry.fold.ingest(chunk2);
85149
85324
  }
85150
85325
  }
85151
85326
  function readAppendedBytes(fd, from, to) {
@@ -85557,7 +85732,7 @@ function latestTranscriptWindow(messages, start = latestWindowStart(messages)) {
85557
85732
  );
85558
85733
  if (tools.length === 0) continue;
85559
85734
  pinned.push({
85560
- sourceId: `pinned-bg:${createHash19("sha256").update(message.sourceId).digest("base64url").slice(0, 24)}`,
85735
+ sourceId: `pinned-bg:${createHash21("sha256").update(message.sourceId).digest("base64url").slice(0, 24)}`,
85561
85736
  pinnedFromSourceId: message.sourceId,
85562
85737
  role: "assistant",
85563
85738
  text: "",
@@ -86353,7 +86528,7 @@ function fixedSnapshot(source) {
86353
86528
  };
86354
86529
  let allBytes;
86355
86530
  const fileKey = `${before.dev}:${before.ino}:${Math.trunc(before.birthtimeMs)}`;
86356
- const transcriptKey = createHash19("sha256").update(`${source.slug}\0${source.sessionId}\0${source.nativeId}\0${source.backend}\0${source.runtimeGeneration}\0${fileKey}`).digest("base64url").slice(0, 32);
86531
+ const transcriptKey = createHash21("sha256").update(`${source.slug}\0${source.sessionId}\0${source.nativeId}\0${source.backend}\0${source.runtimeGeneration}\0${fileKey}`).digest("base64url").slice(0, 32);
86357
86532
  let rawText;
86358
86533
  return {
86359
86534
  ...source,
@@ -86386,7 +86561,7 @@ function projectSnapshot(snapshot) {
86386
86561
  return retireStaleQueuedBubbles([...entry.fold.allMessages()]);
86387
86562
  }
86388
86563
  function digestPrefix(snapshot, length) {
86389
- const hash = createHash19("sha256");
86564
+ const hash = createHash21("sha256");
86390
86565
  hashRange(hash, snapshot, 0, length);
86391
86566
  return hash.digest("base64url");
86392
86567
  }
@@ -86408,7 +86583,7 @@ function fullDigest(snapshot) {
86408
86583
  fullDigestCache.set(key, entry);
86409
86584
  return entry.digest;
86410
86585
  }
86411
- if (!entry || entry.bytes > snapshot.size) entry = { hash: createHash19("sha256"), bytes: 0, digest: "" };
86586
+ if (!entry || entry.bytes > snapshot.size) entry = { hash: createHash21("sha256"), bytes: 0, digest: "" };
86412
86587
  entry.bytes = hashRange(entry.hash, snapshot, entry.bytes, snapshot.size);
86413
86588
  entry.digest = entry.hash.copy().digest("base64url");
86414
86589
  fullDigestCache.set(key, entry);
@@ -86486,7 +86661,7 @@ function emptyTranscriptPage(source) {
86486
86661
  beforeCursor: null,
86487
86662
  hasEarlier: false,
86488
86663
  reachedTurnBoundary: true,
86489
- transcriptKey: createHash19("sha256").update(keySeed).digest("base64url").slice(0, 32),
86664
+ transcriptKey: createHash21("sha256").update(keySeed).digest("base64url").slice(0, 32),
86490
86665
  editedFiles: []
86491
86666
  };
86492
86667
  }
@@ -86633,7 +86808,7 @@ function projectTranscriptPageAgentLifecycles(page, lookup, peerLookup, sessionP
86633
86808
  }
86634
86809
  function readTranscriptFile(absPath) {
86635
86810
  try {
86636
- const pathKey = createHash19("sha256").update(absPath).digest("base64url").slice(0, 16);
86811
+ const pathKey = createHash21("sha256").update(absPath).digest("base64url").slice(0, 16);
86637
86812
  return parseTranscript(readFileSync33(absPath, "utf8"), `claude-file:${pathKey}`);
86638
86813
  } catch {
86639
86814
  return [];
@@ -87055,11 +87230,11 @@ function createGithubHovercardService(deps = {}) {
87055
87230
  if (wanted.length > 0) {
87056
87231
  const chunks = [];
87057
87232
  for (let i = 0; i < wanted.length; i += MAX_REFS_PER_QUERY) chunks.push(wanted.slice(i, i + MAX_REFS_PER_QUERY));
87058
- const runs = chunks.map((chunk) => {
87059
- const run3 = fetchChunk(chunk);
87060
- for (const ref of chunk) inflight.set(ref.key, run3);
87233
+ const runs = chunks.map((chunk2) => {
87234
+ const run3 = fetchChunk(chunk2);
87235
+ for (const ref of chunk2) inflight.set(ref.key, run3);
87061
87236
  return run3.finally(() => {
87062
- for (const ref of chunk) if (inflight.get(ref.key) === run3) inflight.delete(ref.key);
87237
+ for (const ref of chunk2) if (inflight.get(ref.key) === run3) inflight.delete(ref.key);
87063
87238
  });
87064
87239
  });
87065
87240
  const settled = await Promise.allSettled([...runs, ...joins]);
@@ -87298,15 +87473,15 @@ function gif(head) {
87298
87473
  function webp(head) {
87299
87474
  if (head.length < 30) return void 0;
87300
87475
  if (head.toString("ascii", 0, 4) !== "RIFF" || head.toString("ascii", 8, 12) !== "WEBP") return void 0;
87301
- const chunk = head.toString("ascii", 12, 16);
87302
- if (chunk === "VP8 ") {
87476
+ const chunk2 = head.toString("ascii", 12, 16);
87477
+ if (chunk2 === "VP8 ") {
87303
87478
  return { width: head.readUInt16LE(26) & 16383, height: head.readUInt16LE(28) & 16383, scalable: false };
87304
87479
  }
87305
- if (chunk === "VP8L") {
87480
+ if (chunk2 === "VP8L") {
87306
87481
  const bits = head.readUInt32LE(21);
87307
87482
  return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1, scalable: false };
87308
87483
  }
87309
- if (chunk === "VP8X") {
87484
+ if (chunk2 === "VP8X") {
87310
87485
  const read24 = (at2) => head[at2] | head[at2 + 1] << 8 | head[at2 + 2] << 16;
87311
87486
  return { width: read24(24) + 1, height: read24(27) + 1, scalable: false };
87312
87487
  }
@@ -87403,10 +87578,443 @@ var init_image_header = __esm({
87403
87578
  }
87404
87579
  });
87405
87580
 
87406
- // packages/server/src/project-icon.ts
87407
- import { readFileSync as readFileSync35, readdirSync as readdirSync14, realpathSync as realpathSync15, statSync as statSync24 } from "node:fs";
87581
+ // packages/server/src/raster.ts
87582
+ import { deflateSync, inflateSync } from "node:zlib";
87583
+ function decodeRaster(bytes) {
87584
+ try {
87585
+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
87586
+ if (buffer.subarray(0, 8).equals(PNG_SIGNATURE)) return decodePng(buffer);
87587
+ if (buffer.length >= 6 && buffer.readUInt16LE(0) === 0 && buffer.readUInt16LE(2) === 1) return decodeIco(buffer);
87588
+ return void 0;
87589
+ } catch {
87590
+ return void 0;
87591
+ }
87592
+ }
87593
+ function rasterDimensions(bytes) {
87594
+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
87595
+ if (buffer.length >= 24 && buffer.subarray(0, 8).equals(PNG_SIGNATURE)) {
87596
+ return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
87597
+ }
87598
+ if (buffer.length < 22 || buffer.readUInt16LE(0) !== 0 || buffer.readUInt16LE(2) !== 1) return void 0;
87599
+ let best;
87600
+ for (let i = 0; i < buffer.readUInt16LE(4) && 6 + i * 16 + 16 <= buffer.length; i++) {
87601
+ const width = buffer[6 + i * 16] || 256;
87602
+ const height = buffer[7 + i * 16] || 256;
87603
+ if (!best || width * height > best.width * best.height) best = { width, height };
87604
+ }
87605
+ return best;
87606
+ }
87607
+ function decodePng(buffer) {
87608
+ let at2 = 8;
87609
+ let width = 0;
87610
+ let height = 0;
87611
+ let depth = 0;
87612
+ let colorType = 0;
87613
+ let interlace = 0;
87614
+ let palette;
87615
+ let transparency;
87616
+ const data = [];
87617
+ while (at2 + 8 <= buffer.length) {
87618
+ const length = buffer.readUInt32BE(at2);
87619
+ const type = buffer.toString("latin1", at2 + 4, at2 + 8);
87620
+ const body = buffer.subarray(at2 + 8, at2 + 8 + length);
87621
+ if (body.length !== length) return void 0;
87622
+ if (type === "IHDR") {
87623
+ width = body.readUInt32BE(0);
87624
+ height = body.readUInt32BE(4);
87625
+ depth = body[8];
87626
+ colorType = body[9];
87627
+ interlace = body[12];
87628
+ } else if (type === "PLTE") palette = body;
87629
+ else if (type === "tRNS") transparency = body;
87630
+ else if (type === "IDAT") data.push(body);
87631
+ else if (type === "IEND") break;
87632
+ at2 += 12 + length;
87633
+ }
87634
+ const channels = CHANNELS[colorType];
87635
+ if (!channels || width === 0 || height === 0 || width * height > MAX_DECODE_PIXELS || data.length === 0) return void 0;
87636
+ if (colorType === 3 && !palette) return void 0;
87637
+ const raw2 = inflateSync(Buffer.concat(data));
87638
+ const rgba = new Uint8Array(width * height * 4);
87639
+ const bitsPerPixel = channels * depth;
87640
+ const filterStride = Math.max(1, bitsPerPixel >> 3);
87641
+ let offset = 0;
87642
+ const passes = interlace === 1 ? ADAM7 : [[0, 0, 1, 1]];
87643
+ for (const [x02, y02, dx2, dy2] of passes) {
87644
+ const passWidth = Math.ceil((width - x02) / dx2);
87645
+ const passHeight = Math.ceil((height - y02) / dy2);
87646
+ if (passWidth <= 0 || passHeight <= 0) continue;
87647
+ const rowBytes = Math.ceil(passWidth * bitsPerPixel / 8);
87648
+ let previous = new Uint8Array(rowBytes);
87649
+ for (let row = 0; row < passHeight; row++) {
87650
+ const filter = raw2[offset];
87651
+ const line = raw2.subarray(offset + 1, offset + 1 + rowBytes);
87652
+ if (filter === void 0 || line.length !== rowBytes) return void 0;
87653
+ const current = new Uint8Array(line);
87654
+ unfilter(filter, current, previous, filterStride);
87655
+ offset += 1 + rowBytes;
87656
+ for (let column = 0; column < passWidth; column++) {
87657
+ const target = ((y02 + row * dy2) * width + x02 + column * dx2) * 4;
87658
+ writePixel(rgba, target, current, column, colorType, depth, palette, transparency);
87659
+ }
87660
+ previous = current;
87661
+ }
87662
+ }
87663
+ return { width, height, rgba };
87664
+ }
87665
+ function unfilter(filter, line, above, stride) {
87666
+ const n = line.length;
87667
+ switch (filter) {
87668
+ case 0:
87669
+ return;
87670
+ case 1:
87671
+ for (let i = stride; i < n; i++) line[i] = line[i] + line[i - stride] & 255;
87672
+ return;
87673
+ case 2:
87674
+ for (let i = 0; i < n; i++) line[i] = line[i] + above[i] & 255;
87675
+ return;
87676
+ case 3:
87677
+ for (let i = 0; i < n; i++) line[i] = line[i] + ((i >= stride ? line[i - stride] : 0) + above[i] >> 1) & 255;
87678
+ return;
87679
+ case 4:
87680
+ for (let i = 0; i < n; i++) {
87681
+ const left = i >= stride ? line[i - stride] : 0;
87682
+ const upperLeft = i >= stride ? above[i - stride] : 0;
87683
+ line[i] = line[i] + paeth(left, above[i], upperLeft) & 255;
87684
+ }
87685
+ return;
87686
+ default:
87687
+ throw new Error(`unknown PNG filter ${filter}`);
87688
+ }
87689
+ }
87690
+ function paeth(a, b, c) {
87691
+ const p = a + b - c;
87692
+ const pa2 = Math.abs(p - a);
87693
+ const pb = Math.abs(p - b);
87694
+ const pc2 = Math.abs(p - c);
87695
+ return pa2 <= pb && pa2 <= pc2 ? a : pb <= pc2 ? b : c;
87696
+ }
87697
+ function sample(line, index, depth) {
87698
+ if (depth === 8) return line[index];
87699
+ if (depth === 16) return line[index * 2] << 8 | line[index * 2 + 1];
87700
+ const perByte = 8 / depth;
87701
+ const byte = line[Math.floor(index / perByte)];
87702
+ const shift = 8 - depth * (index % perByte + 1);
87703
+ return byte >> shift & (1 << depth) - 1;
87704
+ }
87705
+ function writePixel(out, at2, line, column, colorType, depth, palette, transparency) {
87706
+ const max = (1 << depth) - 1;
87707
+ const to8 = (value) => depth === 16 ? value >> 8 : depth === 8 ? value : Math.round(value * 255 / max);
87708
+ if (colorType === 3) {
87709
+ const index = sample(line, column, depth);
87710
+ out[at2] = palette[index * 3] ?? 0;
87711
+ out[at2 + 1] = palette[index * 3 + 1] ?? 0;
87712
+ out[at2 + 2] = palette[index * 3 + 2] ?? 0;
87713
+ out[at2 + 3] = transparency && index < transparency.length ? transparency[index] : 255;
87714
+ return;
87715
+ }
87716
+ if (colorType === 0 || colorType === 4) {
87717
+ const grey = sample(line, column * (colorType === 4 ? 2 : 1), depth);
87718
+ out[at2] = out[at2 + 1] = out[at2 + 2] = to8(grey);
87719
+ if (colorType === 4) out[at2 + 3] = to8(sample(line, column * 2 + 1, depth));
87720
+ else out[at2 + 3] = transparency && transparency.length >= 2 && transparency.readUInt16BE(0) === grey ? 0 : 255;
87721
+ return;
87722
+ }
87723
+ const per = colorType === 6 ? 4 : 3;
87724
+ const r = sample(line, column * per, depth);
87725
+ const g = sample(line, column * per + 1, depth);
87726
+ const b = sample(line, column * per + 2, depth);
87727
+ out[at2] = to8(r);
87728
+ out[at2 + 1] = to8(g);
87729
+ out[at2 + 2] = to8(b);
87730
+ if (colorType === 6) out[at2 + 3] = to8(sample(line, column * 4 + 3, depth));
87731
+ else {
87732
+ const keyed = transparency && transparency.length >= 6 && transparency.readUInt16BE(0) === r && transparency.readUInt16BE(2) === g && transparency.readUInt16BE(4) === b;
87733
+ out[at2 + 3] = keyed ? 0 : 255;
87734
+ }
87735
+ }
87736
+ function decodeIco(buffer) {
87737
+ const count = buffer.readUInt16LE(4);
87738
+ let best;
87739
+ for (let i = 0; i < count; i++) {
87740
+ const at2 = 6 + i * 16;
87741
+ if (at2 + 16 > buffer.length) break;
87742
+ const area = (buffer[at2] || 256) * (buffer[at2 + 1] || 256);
87743
+ const bits = buffer.readUInt16LE(at2 + 6);
87744
+ if (!best || area > best.area || area === best.area && bits > best.bits) {
87745
+ best = { area, bits, size: buffer.readUInt32LE(at2 + 8), offset: buffer.readUInt32LE(at2 + 12) };
87746
+ }
87747
+ }
87748
+ if (!best) return void 0;
87749
+ const entry = buffer.subarray(best.offset, best.offset + best.size);
87750
+ if (entry.subarray(0, 8).equals(PNG_SIGNATURE)) return decodePng(entry);
87751
+ return decodeIcoBitmap(entry);
87752
+ }
87753
+ function decodeIcoBitmap(entry) {
87754
+ const headerSize = entry.readUInt32LE(0);
87755
+ const width = entry.readInt32LE(4);
87756
+ const height = entry.readInt32LE(8) / 2;
87757
+ const bits = entry.readUInt16LE(14);
87758
+ const compression = entry.readUInt32LE(16);
87759
+ if (width <= 0 || height <= 0 || width * height > MAX_DECODE_PIXELS || ![1, 4, 8, 24, 32].includes(bits)) return void 0;
87760
+ if (compression !== 0 && !(compression === 3 && bits === 32)) return void 0;
87761
+ const colorsUsed = entry.readUInt32LE(32);
87762
+ const paletteEntries = bits <= 8 ? colorsUsed || 1 << bits : 0;
87763
+ const paletteAt = headerSize + (compression === 3 && headerSize === 40 ? 12 : 0);
87764
+ const pixelsAt = paletteAt + paletteEntries * 4;
87765
+ const stride = Math.ceil(width * bits / 32) * 4;
87766
+ const maskAt = pixelsAt + stride * height;
87767
+ const maskStride = Math.ceil(width / 32) * 4;
87768
+ const hasMask = entry.length >= maskAt + maskStride * height;
87769
+ if (entry.length < maskAt) return void 0;
87770
+ const rgba = new Uint8Array(width * height * 4);
87771
+ let anyAlpha = false;
87772
+ for (let y = 0; y < height; y++) {
87773
+ const row = pixelsAt + (height - 1 - y) * stride;
87774
+ for (let x4 = 0; x4 < width; x4++) {
87775
+ const out = (y * width + x4) * 4;
87776
+ if (bits === 32 || bits === 24) {
87777
+ const at2 = row + x4 * (bits / 8);
87778
+ rgba[out] = entry[at2 + 2];
87779
+ rgba[out + 1] = entry[at2 + 1];
87780
+ rgba[out + 2] = entry[at2];
87781
+ rgba[out + 3] = bits === 32 ? entry[at2 + 3] : 255;
87782
+ if (bits === 32 && entry[at2 + 3] > 0) anyAlpha = true;
87783
+ } else {
87784
+ const index = sample(entry.subarray(row, row + stride), x4, bits);
87785
+ const color = paletteAt + index * 4;
87786
+ rgba[out] = entry[color + 2] ?? 0;
87787
+ rgba[out + 1] = entry[color + 1] ?? 0;
87788
+ rgba[out + 2] = entry[color] ?? 0;
87789
+ rgba[out + 3] = 255;
87790
+ }
87791
+ }
87792
+ }
87793
+ if (!anyAlpha && hasMask) {
87794
+ for (let y = 0; y < height; y++) {
87795
+ const row = maskAt + (height - 1 - y) * maskStride;
87796
+ for (let x4 = 0; x4 < width; x4++) {
87797
+ const transparent = entry[row + (x4 >> 3)] >> 7 - (x4 & 7) & 1;
87798
+ rgba[(y * width + x4) * 4 + 3] = transparent ? 0 : 255;
87799
+ }
87800
+ }
87801
+ }
87802
+ return { width, height, rgba };
87803
+ }
87804
+ function toSrgb8(linear) {
87805
+ const c = linear <= 31308e-7 ? linear * 12.92 : 1.055 * linear ** (1 / 2.4) - 0.055;
87806
+ return Math.max(0, Math.min(255, Math.round(c * 255)));
87807
+ }
87808
+ function coverage(source, target) {
87809
+ const scale = source / target;
87810
+ return Array.from({ length: target }, (_, i) => {
87811
+ const from = i * scale;
87812
+ const to = Math.min(source, (i + 1) * scale);
87813
+ const start = Math.floor(from);
87814
+ const end = Math.ceil(to);
87815
+ const weights = new Float32Array(end - start);
87816
+ for (let j4 = start; j4 < end; j4++) weights[j4 - start] = (Math.min(to, j4 + 1) - Math.max(from, j4)) / scale;
87817
+ return { start, weights };
87818
+ });
87819
+ }
87820
+ function resizeToFit(image, size) {
87821
+ const longest = Math.max(image.width, image.height);
87822
+ if (longest <= size) return image;
87823
+ const width = Math.max(1, Math.round(image.width * size / longest));
87824
+ const height = Math.max(1, Math.round(image.height * size / longest));
87825
+ const columns = coverage(image.width, width);
87826
+ const rows = coverage(image.height, height);
87827
+ const band = new Float32Array(width * image.height * 4);
87828
+ const src = image.rgba;
87829
+ for (let y = 0; y < image.height; y++) {
87830
+ for (let x4 = 0; x4 < width; x4++) {
87831
+ const { start, weights } = columns[x4];
87832
+ let r = 0, g = 0, b = 0, a = 0;
87833
+ for (let k4 = 0; k4 < weights.length; k4++) {
87834
+ const at2 = (y * image.width + start + k4) * 4;
87835
+ const alpha = src[at2 + 3] / 255 * weights[k4];
87836
+ r += TO_LINEAR[src[at2]] * alpha;
87837
+ g += TO_LINEAR[src[at2 + 1]] * alpha;
87838
+ b += TO_LINEAR[src[at2 + 2]] * alpha;
87839
+ a += alpha;
87840
+ }
87841
+ const out = (y * width + x4) * 4;
87842
+ band[out] = r;
87843
+ band[out + 1] = g;
87844
+ band[out + 2] = b;
87845
+ band[out + 3] = a;
87846
+ }
87847
+ }
87848
+ const rgba = new Uint8Array(width * height * 4);
87849
+ for (let y = 0; y < height; y++) {
87850
+ const { start, weights } = rows[y];
87851
+ for (let x4 = 0; x4 < width; x4++) {
87852
+ let r = 0, g = 0, b = 0, a = 0;
87853
+ for (let k4 = 0; k4 < weights.length; k4++) {
87854
+ const at2 = ((start + k4) * width + x4) * 4;
87855
+ const weight = weights[k4];
87856
+ r += band[at2] * weight;
87857
+ g += band[at2 + 1] * weight;
87858
+ b += band[at2 + 2] * weight;
87859
+ a += band[at2 + 3] * weight;
87860
+ }
87861
+ const out = (y * width + x4) * 4;
87862
+ if (a > 0) {
87863
+ rgba[out] = toSrgb8(r / a);
87864
+ rgba[out + 1] = toSrgb8(g / a);
87865
+ rgba[out + 2] = toSrgb8(b / a);
87866
+ }
87867
+ rgba[out + 3] = Math.max(0, Math.min(255, Math.round(a * 255)));
87868
+ }
87869
+ }
87870
+ return { width, height, rgba };
87871
+ }
87872
+ function crc32(bytes) {
87873
+ let c = 4294967295;
87874
+ for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ c >>> 8;
87875
+ return (c ^ 4294967295) >>> 0;
87876
+ }
87877
+ function chunk(type, body) {
87878
+ const out = Buffer.alloc(12 + body.length);
87879
+ out.writeUInt32BE(body.length, 0);
87880
+ out.write(type, 4, "latin1");
87881
+ out.set(body, 8);
87882
+ out.writeUInt32BE(crc32(out.subarray(4, 8 + body.length)), 8 + body.length);
87883
+ return out;
87884
+ }
87885
+ function encodePng(image) {
87886
+ const { width, height, rgba } = image;
87887
+ const rowBytes = width * 4;
87888
+ const filtered = Buffer.alloc((rowBytes + 1) * height);
87889
+ const candidate = new Uint8Array(rowBytes);
87890
+ const best = new Uint8Array(rowBytes);
87891
+ for (let y = 0; y < height; y++) {
87892
+ const line = rgba.subarray(y * rowBytes, (y + 1) * rowBytes);
87893
+ const above = y > 0 ? rgba.subarray((y - 1) * rowBytes, y * rowBytes) : new Uint8Array(rowBytes);
87894
+ let bestFilter = 0;
87895
+ let bestScore = Infinity;
87896
+ for (let filter = 0; filter < 5; filter++) {
87897
+ let score = 0;
87898
+ for (let i = 0; i < rowBytes; i++) {
87899
+ const left = i >= 4 ? line[i - 4] : 0;
87900
+ const up2 = above[i];
87901
+ const upperLeft = i >= 4 ? above[i - 4] : 0;
87902
+ const predictor = filter === 0 ? 0 : filter === 1 ? left : filter === 2 ? up2 : filter === 3 ? left + up2 >> 1 : paeth(left, up2, upperLeft);
87903
+ const value = line[i] - predictor & 255;
87904
+ candidate[i] = value;
87905
+ score += value < 128 ? value : 256 - value;
87906
+ }
87907
+ if (score < bestScore) {
87908
+ bestScore = score;
87909
+ bestFilter = filter;
87910
+ best.set(candidate);
87911
+ }
87912
+ }
87913
+ const at2 = y * (rowBytes + 1);
87914
+ filtered[at2] = bestFilter;
87915
+ filtered.set(best, at2 + 1);
87916
+ }
87917
+ const header = Buffer.alloc(13);
87918
+ header.writeUInt32BE(width, 0);
87919
+ header.writeUInt32BE(height, 4);
87920
+ header[8] = 8;
87921
+ header[9] = 6;
87922
+ return Buffer.concat([
87923
+ PNG_SIGNATURE,
87924
+ chunk("IHDR", header),
87925
+ chunk("IDAT", deflateSync(filtered, { level: 9 })),
87926
+ chunk("IEND", new Uint8Array(0))
87927
+ ]);
87928
+ }
87929
+ var MAX_DECODE_PIXELS, PNG_SIGNATURE, CHANNELS, ADAM7, TO_LINEAR, CRC_TABLE;
87930
+ var init_raster = __esm({
87931
+ "packages/server/src/raster.ts"() {
87932
+ "use strict";
87933
+ MAX_DECODE_PIXELS = 4096 * 4096;
87934
+ PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
87935
+ CHANNELS = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
87936
+ ADAM7 = [
87937
+ [0, 0, 8, 8],
87938
+ [4, 0, 8, 8],
87939
+ [0, 4, 4, 8],
87940
+ [2, 0, 4, 4],
87941
+ [0, 2, 2, 4],
87942
+ [1, 0, 2, 2],
87943
+ [0, 1, 1, 2]
87944
+ ];
87945
+ TO_LINEAR = Float32Array.from({ length: 256 }, (_, i) => {
87946
+ const c = i / 255;
87947
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
87948
+ });
87949
+ CRC_TABLE = Uint32Array.from({ length: 256 }, (_, n) => {
87950
+ let c = n;
87951
+ for (let k4 = 0; k4 < 8; k4++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
87952
+ return c >>> 0;
87953
+ });
87954
+ }
87955
+ });
87956
+
87957
+ // packages/server/src/icon-renditions.ts
87958
+ import { mkdirSync as mkdirSync26, readdirSync as readdirSync14, readFileSync as readFileSync35, renameSync as renameSync14, rmSync as rmSync14, writeFileSync as writeFileSync18 } from "node:fs";
87408
87959
  import { homedir as homedir20 } from "node:os";
87409
- import { basename as basename10, dirname as dirname23, extname as extname3, join as join49, relative as relative2, sep as sep4 } from "node:path";
87960
+ import { join as join49 } from "node:path";
87961
+ function iconRenditionDir(id, home = homedir20()) {
87962
+ return join49(frizzPaths({ home }).cache, "project-icons", id);
87963
+ }
87964
+ function renditionName(hash, size) {
87965
+ return `${hash}-${size}.v${RENDITION_VERSION}.png`;
87966
+ }
87967
+ function masterFor(hash, bytes) {
87968
+ const kept = decoded.get(hash);
87969
+ if (kept) return kept;
87970
+ const image = decodeRaster(bytes);
87971
+ if (!image) return void 0;
87972
+ const master = resizeToFit(image, DECODED_MAX_PX);
87973
+ decoded.set(hash, master);
87974
+ if (decoded.size > DECODED_KEPT) decoded.delete(decoded.keys().next().value);
87975
+ return master;
87976
+ }
87977
+ function projectIconRendition(id, bytes, hash, size, options = {}) {
87978
+ if (!Number.isInteger(size) || size < 1 || size > MAX_RENDITION_PX) return void 0;
87979
+ const dimensions = rasterDimensions(bytes);
87980
+ if (!dimensions || Math.max(dimensions.width, dimensions.height) <= size) return void 0;
87981
+ const dir = iconRenditionDir(id, options.home);
87982
+ const file = join49(dir, renditionName(hash, size));
87983
+ try {
87984
+ return readFileSync35(file);
87985
+ } catch {
87986
+ }
87987
+ const master = masterFor(hash, bytes);
87988
+ if (!master) return void 0;
87989
+ const png2 = encodePng(resizeToFit(master, size));
87990
+ try {
87991
+ mkdirSync26(dir, { recursive: true });
87992
+ for (const name of readdirSync14(dir)) if (!name.startsWith(`${hash}-`)) rmSync14(join49(dir, name), { force: true });
87993
+ const partial = `${file}.${process.pid}.tmp`;
87994
+ writeFileSync18(partial, png2);
87995
+ renameSync14(partial, file);
87996
+ } catch {
87997
+ }
87998
+ return png2;
87999
+ }
88000
+ var RENDITION_VERSION, MAX_RENDITION_PX, decoded, DECODED_KEPT, DECODED_MAX_PX;
88001
+ var init_icon_renditions = __esm({
88002
+ "packages/server/src/icon-renditions.ts"() {
88003
+ "use strict";
88004
+ init_frizz_paths();
88005
+ init_raster();
88006
+ RENDITION_VERSION = 1;
88007
+ MAX_RENDITION_PX = 256;
88008
+ decoded = /* @__PURE__ */ new Map();
88009
+ DECODED_KEPT = 8;
88010
+ DECODED_MAX_PX = 1024;
88011
+ }
88012
+ });
88013
+
88014
+ // packages/server/src/project-icon.ts
88015
+ import { readFileSync as readFileSync36, readdirSync as readdirSync15, realpathSync as realpathSync15, statSync as statSync24 } from "node:fs";
88016
+ import { homedir as homedir21 } from "node:os";
88017
+ import { basename as basename10, dirname as dirname23, extname as extname3, join as join50, relative as relative2, sep as sep4 } from "node:path";
87410
88018
  function normalizeStem(stem) {
87411
88019
  const sized = stem.toLowerCase().replace(/[@-]\d+(\.\d+)?x(\d+)?$/u, "").replace(/[-_]\d{2,4}$/u, "");
87412
88020
  const themed = sized.replace(VARIANT_SUFFIX, "");
@@ -87427,11 +88035,11 @@ function sizeScore(dimensions) {
87427
88035
  return Math.max(0, Math.min(40, Math.round(Math.log2(edge / 24) * 8)));
87428
88036
  }
87429
88037
  function under(root, relativeDirectory) {
87430
- return relativeDirectory ? join49(root, relativeDirectory) : root;
88038
+ return relativeDirectory ? join50(root, relativeDirectory) : root;
87431
88039
  }
87432
88040
  function listFiles(directory) {
87433
88041
  try {
87434
- return readdirSync14(directory, { withFileTypes: true }).filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => entry.name);
88042
+ return readdirSync15(directory, { withFileTypes: true }).filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => entry.name);
87435
88043
  } catch {
87436
88044
  return [];
87437
88045
  }
@@ -87440,7 +88048,7 @@ function iconDirectories(root) {
87440
88048
  let children2;
87441
88049
  try {
87442
88050
  children2 = new Set(
87443
- readdirSync14(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name)
88051
+ readdirSync15(root, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name)
87444
88052
  );
87445
88053
  } catch {
87446
88054
  return [root];
@@ -87449,19 +88057,19 @@ function iconDirectories(root) {
87449
88057
  for (const asset of ASSET_DIRECTORIES) directories.push(under(root, asset));
87450
88058
  for (const host of HOST_DIRECTORIES) {
87451
88059
  if (!children2.has(host)) continue;
87452
- for (const asset of ASSET_DIRECTORIES) directories.push(under(join49(root, host), asset));
88060
+ for (const asset of ASSET_DIRECTORIES) directories.push(under(join50(root, host), asset));
87453
88061
  }
87454
88062
  for (const extra of EXTRA_DIRECTORIES) directories.push(under(root, extra));
87455
88063
  for (const container of WORKSPACE_CONTAINERS) {
87456
88064
  if (!children2.has(container)) continue;
87457
88065
  let members;
87458
88066
  try {
87459
- members = readdirSync14(join49(root, container), { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
88067
+ members = readdirSync15(join50(root, container), { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name);
87460
88068
  } catch {
87461
88069
  continue;
87462
88070
  }
87463
88071
  for (const member of members) {
87464
- for (const asset of ASSET_DIRECTORIES) directories.push(under(join49(root, container, member), asset));
88072
+ for (const asset of ASSET_DIRECTORIES) directories.push(under(join50(root, container, member), asset));
87465
88073
  }
87466
88074
  }
87467
88075
  return [...new Set(directories)];
@@ -87469,13 +88077,13 @@ function iconDirectories(root) {
87469
88077
  function manifestIcons(manifestPath) {
87470
88078
  let parsed;
87471
88079
  try {
87472
- parsed = JSON.parse(readFileSync35(manifestPath, "utf8"));
88080
+ parsed = JSON.parse(readFileSync36(manifestPath, "utf8"));
87473
88081
  } catch {
87474
88082
  return [];
87475
88083
  }
87476
88084
  if (!Array.isArray(parsed?.icons)) return [];
87477
88085
  const directory = dirname23(manifestPath);
87478
- return parsed.icons.map((icon) => typeof icon?.src === "string" ? icon.src : void 0).filter((src) => !!src && !/^(https?:)?\/\//u.test(src) && !src.startsWith("data:")).map((src) => join49(directory, src.replace(/[?#].*$/u, "").replace(/^\//u, "")));
88086
+ return parsed.icons.map((icon) => typeof icon?.src === "string" ? icon.src : void 0).filter((src) => !!src && !/^(https?:)?\/\//u.test(src) && !src.startsWith("data:")).map((src) => join50(directory, src.replace(/[?#].*$/u, "").replace(/^\//u, "")));
87479
88087
  }
87480
88088
  function projectIconCandidates(root) {
87481
88089
  const projectStem = normalizeStem(basename10(root)).normalized;
@@ -87494,7 +88102,7 @@ function projectIconCandidates(root) {
87494
88102
  for (const name of listFiles(directory)) {
87495
88103
  const extension2 = extname3(name).toLowerCase();
87496
88104
  if (MANIFEST_NAMES.includes(name.toLowerCase())) {
87497
- for (const icon of manifestIcons(join49(directory, name))) {
88105
+ for (const icon of manifestIcons(join50(directory, name))) {
87498
88106
  if (MEASURABLE_IMAGE_EXTENSIONS.has(extname3(icon).toLowerCase())) {
87499
88107
  fromManifest.add(icon);
87500
88108
  files.push({ path: icon, directory: dirname23(icon) });
@@ -87505,7 +88113,7 @@ function projectIconCandidates(root) {
87505
88113
  if (!MEASURABLE_IMAGE_EXTENSIONS.has(extension2)) continue;
87506
88114
  const stem = name.slice(0, name.length - extension2.length);
87507
88115
  if (normalizeStem(stem).normalized === "favicon") iconHomes.add(directory);
87508
- files.push({ path: join49(directory, name), directory });
88116
+ files.push({ path: join50(directory, name), directory });
87509
88117
  if (files.length >= MAX_CANDIDATES) break;
87510
88118
  }
87511
88119
  }
@@ -87548,7 +88156,7 @@ function iconMediaType(path3) {
87548
88156
  }
87549
88157
  function resolveProjectIconResponse(id, options = {}) {
87550
88158
  if (!id) return { status: 400 };
87551
- const home = options.home ?? homedir20();
88159
+ const home = options.home ?? homedir21();
87552
88160
  const entry = readRegistry(home).projects.find((project) => project.id === id);
87553
88161
  if (!entry) return { status: 404 };
87554
88162
  const path3 = resolveProjectIcon(id, (root) => detectProjectIcon(root)?.path, { home });
@@ -87570,11 +88178,19 @@ function resolveProjectIconResponse(id, options = {}) {
87570
88178
  }
87571
88179
  });
87572
88180
  if (!roots.some((root) => real === root || real.startsWith(root + sep4))) return { status: 404 };
88181
+ let body;
87573
88182
  try {
87574
- return { status: 200, contentType, body: readFileSync35(real) };
88183
+ body = readFileSync36(real);
87575
88184
  } catch {
87576
88185
  return { status: 404 };
87577
88186
  }
88187
+ const hash = iconContentHash(body);
88188
+ if (entry.iconHash !== hash) recordProjectIconHash(id, path3, hash, home);
88189
+ const rendition = options.size ? projectIconRendition(id, body, hash, options.size, { home }) : void 0;
88190
+ if (rendition) {
88191
+ return { status: 200, contentType: "image/png", body: rendition, hash, etag: `W/"${hash}-${options.size}.v${RENDITION_VERSION}"` };
88192
+ }
88193
+ return { status: 200, contentType, body, hash, etag: `W/"${hash}"` };
87578
88194
  }
87579
88195
  var MAX_CANDIDATES, HOST_DIRECTORIES, BRAND_KIT_DIRECTORIES, ASSET_DIRECTORIES, EXTRA_DIRECTORIES, WORKSPACE_CONTAINERS, MANIFEST_NAMES, NAME_SCORES, COLOURLESS_SVG_PENALTY, GENERATED_DIRECTORIES, NEVER_AN_ICON, MIN_ASPECT, MAX_ASPECT, MIN_EDGE, VARIANT_SUFFIX, SQUARE_SUFFIX, FORMAT_SCORES, MEDIA_TYPES;
87580
88196
  var init_project_icon = __esm({
@@ -87583,6 +88199,7 @@ var init_project_icon = __esm({
87583
88199
  init_image_header();
87584
88200
  init_frizz_paths();
87585
88201
  init_project_registry();
88202
+ init_icon_renditions();
87586
88203
  MAX_CANDIDATES = 400;
87587
88204
  HOST_DIRECTORIES = [
87588
88205
  "site",
@@ -87719,8 +88336,8 @@ function openPanel(kind, command = panelCommand(kind)) {
87719
88336
  }
87720
88337
  });
87721
88338
  child.stderr.setEncoding("utf8");
87722
- child.stderr.on("data", (chunk) => {
87723
- stderr += chunk;
88339
+ child.stderr.on("data", (chunk2) => {
88340
+ stderr += chunk2;
87724
88341
  });
87725
88342
  child.stdin.on("error", () => {
87726
88343
  });
@@ -87928,12 +88545,12 @@ function run(argv) {
87928
88545
  });
87929
88546
 
87930
88547
  // packages/server/src/router.ts
87931
- import { readFileSync as readFileSync36, statSync as statSync25 } from "node:fs";
87932
- import { join as join50, resolve as resolve11 } from "node:path";
88548
+ import { readFileSync as readFileSync37, statSync as statSync25 } from "node:fs";
88549
+ import { join as join51, resolve as resolve11 } from "node:path";
87933
88550
  import { randomUUID as randomUUID20 } from "node:crypto";
87934
88551
  import { basename as basename11, dirname as dirname24 } from "node:path";
87935
- import { existsSync as existsSync21, mkdirSync as mkdirSync26, rmSync as rmSync14, writeFileSync as writeFileSync18 } from "node:fs";
87936
- import { homedir as homedir21 } from "node:os";
88552
+ import { existsSync as existsSync21, mkdirSync as mkdirSync27, rmSync as rmSync15, writeFileSync as writeFileSync19 } from "node:fs";
88553
+ import { homedir as homedir22 } from "node:os";
87937
88554
  function validateGithubDispatchProfile(input, codexModels) {
87938
88555
  if (input.backend === "acp") return;
87939
88556
  if (input.effort === void 0) throw new Error(`Unsupported ${input.backend} model/effort pair: ${input.model} / (no effort)`);
@@ -88089,7 +88706,10 @@ function projectCard(entry, stale) {
88089
88706
  path: entry.path,
88090
88707
  lastOpenedAt: entry.lastOpenedAt,
88091
88708
  stale,
88092
- iconVersion: entry.iconScannedAt,
88709
+ // The picture's own hash where it is known, so the URL changes when the picture does and never
88710
+ // otherwise. A miss has no hash, and takes the scan time: an old miss must be a NEW url, because
88711
+ // the request for it is what runs the rescan (see iconStatus below).
88712
+ iconVersion: entry.iconHash ?? entry.iconScannedAt,
88093
88713
  // `iconScannedAt` alone cannot answer this: it is stamped whenever a scan RAN, found or not. See
88094
88714
  // ProjectCard.iconStatus for why the never-scanned case has to stay distinguishable.
88095
88715
  //
@@ -88103,10 +88723,10 @@ function projectCard(entry, stale) {
88103
88723
  iconIsCustom: entry.iconSource === "custom" ? true : void 0
88104
88724
  };
88105
88725
  }
88106
- function addProjectAtPath(input, home = homedir21()) {
88726
+ function addProjectAtPath(input, home = homedir22()) {
88107
88727
  const typed = input.trim();
88108
88728
  if (!typed) throw new Error("Enter a folder path.");
88109
- const expanded = typed === "~" || typed.startsWith("~/") ? join50(home, typed.slice(1)) : typed;
88729
+ const expanded = typed === "~" || typed.startsWith("~/") ? join51(home, typed.slice(1)) : typed;
88110
88730
  const absolute = resolve11(expanded);
88111
88731
  let stats;
88112
88732
  try {
@@ -88138,15 +88758,15 @@ function storeProjectIcon(id, name, bytes) {
88138
88758
  if (!entry) throw new Error("No such project.");
88139
88759
  if (bytes.length === 0) throw new Error("That file is empty.");
88140
88760
  const path3 = customIconPath(id, `.${extension2}`);
88141
- mkdirSync26(dirname24(path3), { recursive: true });
88142
- writeFileSync18(path3, bytes);
88761
+ mkdirSync27(dirname24(path3), { recursive: true });
88762
+ writeFileSync19(path3, bytes);
88143
88763
  if (!imageDimensions(path3)) {
88144
- rmSync14(path3, { force: true });
88764
+ rmSync15(path3, { force: true });
88145
88765
  throw new Error("That file does not look like an image Frizz can draw.");
88146
88766
  }
88147
88767
  for (const stale of PROJECT_ICON_EXTENSIONS) {
88148
88768
  const other = customIconPath(id, `.${stale}`);
88149
- if (other !== path3) rmSync14(other, { force: true });
88769
+ if (other !== path3) rmSync15(other, { force: true });
88150
88770
  }
88151
88771
  const updated = setProjectIcon(id, path3);
88152
88772
  if (!updated) throw new Error("No such project.");
@@ -88160,7 +88780,7 @@ function iconPicker(id) {
88160
88780
  function setProjectIconFromFile(id, file) {
88161
88781
  let bytes;
88162
88782
  try {
88163
- bytes = readFileSync36(file);
88783
+ bytes = readFileSync37(file);
88164
88784
  } catch {
88165
88785
  throw new Error("That file could not be read.");
88166
88786
  }
@@ -88193,7 +88813,7 @@ function mergeSubAgentSteers(messages, steers) {
88193
88813
  return merged2;
88194
88814
  }
88195
88815
  function createRouter(ctx) {
88196
- const frizzDir = join50(ctx.project.dir, ".frizz");
88816
+ const frizzDir = join51(ctx.project.dir, ".frizz");
88197
88817
  const openRoots = openableFileRoots(ctx.project);
88198
88818
  const thisProject = { id: ctx.project.id, dir: ctx.project.dir };
88199
88819
  const audit = (action, base, run3, onResult) => audited(ctx.audit, action, base, run3, { onResult, servedBy: ctx.project.id });
@@ -88469,12 +89089,15 @@ ${gapNote}` : input.message;
88469
89089
  const send = { ...input, message, answers: void 0, hold: void 0 };
88470
89090
  if (input.hold && !input.interrupt && !input.freshProcess && !replay) {
88471
89091
  const row = ctx.storage.getSession(input.slug);
88472
- if (row && row.session_id === input.sessionId && ctx.tailer.get(input.slug)?.turn === "in-flight") {
89092
+ const inFlight2 = ctx.tailer.get(input.slug)?.turn === "in-flight";
89093
+ const items = row ? parseDeliveryLedger(row.delivery_ledger) : [];
89094
+ if (row && row.session_id === input.sessionId && (inFlight2 || heldSendMustWait(items))) {
88473
89095
  const id = input.deliveryId ?? randomUUID20();
88474
89096
  if (holdDelivery(ctx.storage, input.slug, { id, text: message })) {
88475
89097
  watchHeld(input.slug);
88476
89098
  ctx.transcriptChange.emit([input.slug]);
88477
89099
  ctx.board.refresh();
89100
+ if (!inFlight2) setTimeout(() => void releaseHeldFollowUps(input.slug), 0).unref?.();
88478
89101
  return;
88479
89102
  }
88480
89103
  }
@@ -88489,28 +89112,25 @@ ${gapNote}` : input.message;
88489
89112
  heldSlugs.delete(slug);
88490
89113
  return 0;
88491
89114
  }
88492
- const held = heldDeliveries(ctx.storage, slug);
88493
- if (held.length === 0) {
89115
+ const items = parseDeliveryLedger(row.delivery_ledger);
89116
+ if (!items.some((item2) => item2.state === "held")) {
88494
89117
  heldSlugs.delete(slug);
88495
89118
  return 0;
88496
89119
  }
88497
89120
  if (!opts.force && ctx.tailer.get(slug)?.turn === "in-flight") return 0;
88498
89121
  if (hasPendingPermissionChange(row)) return 0;
89122
+ const item = nextHeldRelease(items, { force: opts.force });
89123
+ if (!item) return 0;
88499
89124
  releasingHeld.add(slug);
88500
- let released = 0;
88501
89125
  try {
88502
- for (const item of held) {
88503
- try {
88504
- await deliverFollowUp({ slug, sessionId: row.session_id, message: item.text, deliveryId: item.id }, { release: true });
88505
- released++;
88506
- } catch (error) {
88507
- log.warn("server", `${slug}: releasing held follow-up ${item.id} failed: ${error instanceof Error ? error.message : String(error)}`);
88508
- }
88509
- }
89126
+ await deliverFollowUp({ slug, sessionId: row.session_id, message: item.text, deliveryId: item.id }, { release: true });
89127
+ return 1;
89128
+ } catch (error) {
89129
+ log.warn("server", `${slug}: releasing held follow-up ${item.id} failed: ${error instanceof Error ? error.message : String(error)}`);
89130
+ return 0;
88510
89131
  } finally {
88511
89132
  releasingHeld.delete(slug);
88512
89133
  }
88513
- return released;
88514
89134
  }
88515
89135
  const heldSlugs = /* @__PURE__ */ new Set();
88516
89136
  let heldSweep = null;
@@ -90903,7 +91523,7 @@ Say which way you went and why in your write-up, so the human can course-correct
90903
91523
  output: ProjectCard,
90904
91524
  handler: async ({ input }) => {
90905
91525
  for (const extension2 of PROJECT_ICON_EXTENSIONS) {
90906
- rmSync14(customIconPath(input.id, `.${extension2}`), { force: true });
91526
+ rmSync15(customIconPath(input.id, `.${extension2}`), { force: true });
90907
91527
  }
90908
91528
  if (!clearProjectIcon(input.id)) throw new Error("No such project.");
90909
91529
  resolveProjectIcon(input.id, (root) => detectProjectIcon(root)?.path);
@@ -91253,11 +91873,11 @@ var init_compression = __esm({
91253
91873
  });
91254
91874
 
91255
91875
  // packages/server/src/local-visualization.ts
91256
- import { readdirSync as readdirSync15, readFileSync as readFileSync37, realpathSync as realpathSync16, statSync as statSync26 } from "node:fs";
91257
- import { join as join51, sep as sep5 } from "node:path";
91876
+ import { readdirSync as readdirSync16, readFileSync as readFileSync38, realpathSync as realpathSync16, statSync as statSync26 } from "node:fs";
91877
+ import { join as join52, sep as sep5 } from "node:path";
91258
91878
  function children(path3, pattern) {
91259
91879
  try {
91260
- return readdirSync15(path3, { withFileTypes: true }).filter((entry) => entry.isDirectory() && pattern.test(entry.name)).map((entry) => entry.name).sort().reverse();
91880
+ return readdirSync16(path3, { withFileTypes: true }).filter((entry) => entry.isDirectory() && pattern.test(entry.name)).map((entry) => entry.name).sort().reverse();
91261
91881
  } catch {
91262
91882
  return [];
91263
91883
  }
@@ -91266,7 +91886,7 @@ function isUnder2(path3, root) {
91266
91886
  return path3 === root || path3.startsWith(root.endsWith(sep5) ? root : root + sep5);
91267
91887
  }
91268
91888
  function resolveFragment(projectDir, sessionId, file) {
91269
- const base = join51(projectDir, ".codex", "visualizations");
91889
+ const base = join52(projectDir, ".codex", "visualizations");
91270
91890
  let projectReal;
91271
91891
  let baseReal;
91272
91892
  try {
@@ -91277,12 +91897,12 @@ function resolveFragment(projectDir, sessionId, file) {
91277
91897
  }
91278
91898
  if (!isUnder2(baseReal, projectReal)) return null;
91279
91899
  for (const year of children(base, YEAR_PART)) {
91280
- const yearDir = join51(base, year);
91900
+ const yearDir = join52(base, year);
91281
91901
  for (const month of children(yearDir, DATE_PART)) {
91282
- const monthDir = join51(yearDir, month);
91902
+ const monthDir = join52(yearDir, month);
91283
91903
  for (const day of children(monthDir, DATE_PART)) {
91284
- const sessionRoot = join51(baseReal, year, month, day, sessionId);
91285
- const candidate = join51(monthDir, day, sessionId, file);
91904
+ const sessionRoot = join52(baseReal, year, month, day, sessionId);
91905
+ const candidate = join52(monthDir, day, sessionId, file);
91286
91906
  try {
91287
91907
  const real = realpathSync16(candidate);
91288
91908
  if (isUnder2(real, sessionRoot) && statSync26(real).isFile()) return real;
@@ -91372,7 +91992,7 @@ function resolveLocalVisualization(projectDir, sessionId, file) {
91372
91992
  try {
91373
91993
  const size = statSync26(path3).size;
91374
91994
  if (size > MAX_FRAGMENT_BYTES) return { status: 413 };
91375
- fragment = readFileSync37(path3, "utf8");
91995
+ fragment = readFileSync38(path3, "utf8");
91376
91996
  } catch {
91377
91997
  return { status: 404 };
91378
91998
  }
@@ -91415,9 +92035,9 @@ var init_local_visualization = __esm({
91415
92035
 
91416
92036
  // packages/server/src/launch-routing.ts
91417
92037
  import { realpathSync as realpathSync17 } from "node:fs";
91418
- import { homedir as homedir22 } from "node:os";
92038
+ import { homedir as homedir23 } from "node:os";
91419
92039
  import { isAbsolute as isAbsolute11 } from "node:path";
91420
- function classifyLaunch(dir, home = homedir22()) {
92040
+ function classifyLaunch(dir, home = homedir23()) {
91421
92041
  const candidate = realpathSync17(discoverProjectRoot(dir, home));
91422
92042
  const refused = isHomeDirectory(candidate, home);
91423
92043
  if (!refused && (isExistingProjectRoot(candidate) || findByPath(candidate, home) !== void 0)) {
@@ -91428,7 +92048,7 @@ function classifyLaunch(dir, home = homedir22()) {
91428
92048
  function offerPath(directory) {
91429
92049
  return `/?add=${encodeURIComponent(directory)}`;
91430
92050
  }
91431
- function routeLaunch(dir, open, home = homedir22()) {
92051
+ function routeLaunch(dir, open, home = homedir23()) {
91432
92052
  const launch = classifyLaunch(dir, home);
91433
92053
  if (launch.kind === "grid") return { path: "/" };
91434
92054
  if (launch.kind === "offer") return { path: offerPath(launch.directory) };
@@ -91464,8 +92084,8 @@ var init_launch_routing = __esm({
91464
92084
  });
91465
92085
 
91466
92086
  // packages/server/src/project-serving.ts
91467
- import { readFileSync as readFileSync38, renameSync as renameSync14, writeFileSync as writeFileSync19 } from "node:fs";
91468
- import { isAbsolute as isAbsolute12, join as join52 } from "node:path";
92087
+ import { readFileSync as readFileSync39, renameSync as renameSync15, writeFileSync as writeFileSync20 } from "node:fs";
92088
+ import { isAbsolute as isAbsolute12, join as join53 } from "node:path";
91469
92089
  function parse3(value) {
91470
92090
  if (!value || typeof value !== "object") return null;
91471
92091
  const record = value;
@@ -91483,17 +92103,17 @@ function parse3(value) {
91483
92103
  }
91484
92104
  function readProjectServing(stateDir) {
91485
92105
  try {
91486
- return parse3(JSON.parse(readFileSync38(join52(stateDir, PROJECT_SERVING_FILE), "utf8")));
92106
+ return parse3(JSON.parse(readFileSync39(join53(stateDir, PROJECT_SERVING_FILE), "utf8")));
91487
92107
  } catch {
91488
92108
  return null;
91489
92109
  }
91490
92110
  }
91491
92111
  function writeRecord(stateDir, record) {
91492
- const path3 = join52(stateDir, PROJECT_SERVING_FILE);
92112
+ const path3 = join53(stateDir, PROJECT_SERVING_FILE);
91493
92113
  const partial = `${path3}.${process.pid}.tmp`;
91494
- writeFileSync19(partial, `${JSON.stringify(record)}
92114
+ writeFileSync20(partial, `${JSON.stringify(record)}
91495
92115
  `, { mode: 384 });
91496
- renameSync14(partial, path3);
92116
+ renameSync15(partial, path3);
91497
92117
  }
91498
92118
  function servingRecordElsewhere(stateDir, projectId, adapter = defaultProcessPlatformAdapter) {
91499
92119
  const record = readProjectServing(stateDir);
@@ -91561,9 +92181,9 @@ var init_project_serving = __esm({
91561
92181
  });
91562
92182
 
91563
92183
  // packages/server/src/app.ts
91564
- import { createReadStream as createReadStream2, mkdirSync as mkdirSync27, writeFileSync as writeFileSync20 } from "node:fs";
92184
+ import { createReadStream as createReadStream2, mkdirSync as mkdirSync28, writeFileSync as writeFileSync21 } from "node:fs";
91565
92185
  import { Readable } from "node:stream";
91566
- import { join as join53 } from "node:path";
92186
+ import { join as join54 } from "node:path";
91567
92187
  import { randomUUID as randomUUID21 } from "node:crypto";
91568
92188
  function attachmentFileName(name) {
91569
92189
  let clean = (name.split(/[\\/]/).pop() ?? "").replace(/\s/g, " ").replace(/[\u0000-\u001f\u007f`]/g, "-").trim();
@@ -91688,16 +92308,25 @@ function createApp(ctx, options = {}) {
91688
92308
  return c.body(Readable.toWeb(stream2), 200, headers);
91689
92309
  });
91690
92310
  app.get(frizzRoute("/project-icon"), (c) => {
91691
- const r = resolveProjectIconResponse(c.req.query("id"));
92311
+ const size = Number(c.req.query("s")) || void 0;
92312
+ const r = resolveProjectIconResponse(c.req.query("id"), { size });
91692
92313
  if (r.status !== 200) return c.text(String(r.status), r.status);
91693
- return c.body(Uint8Array.from(r.body), 200, {
92314
+ const headers = {
91694
92315
  "content-type": r.contentType,
91695
- "cache-control": "private, max-age=300",
92316
+ "cache-control": c.req.query("v") === r.hash ? "private, max-age=300, stale-while-revalidate=2592000" : "private, no-cache",
92317
+ etag: r.etag,
91696
92318
  // An SVG icon is a file out of somebody's repository. It renders through <img>, where scripting
91697
92319
  // is already off; this makes that unconditional rather than a property of how it is embedded.
91698
92320
  "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
91699
92321
  "x-content-type-options": "nosniff"
91700
- });
92322
+ };
92323
+ const known = (c.req.header("if-none-match") ?? "").split(",").map((tag) => tag.trim().replace(/^W\//u, ""));
92324
+ if (known.includes(r.etag.replace(/^W\//u, "")) || known.includes("*")) return c.body(null, 304, headers);
92325
+ const encoding = r.contentType === "image/svg+xml" ? negotiateEncoding(c.req.header("accept-encoding")) : null;
92326
+ if (encoding && r.body.byteLength >= MIN_COMPRESS_BYTES) {
92327
+ return c.body(compress(r.body, encoding), 200, { ...headers, "content-encoding": encoding, vary: "Accept-Encoding" });
92328
+ }
92329
+ return c.body(Uint8Array.from(r.body), 200, headers);
91701
92330
  });
91702
92331
  app.get(frizzRoute("/local-visualization"), (c) => {
91703
92332
  const row = ctx.storage.getSession(c.req.query("slug") ?? "");
@@ -91720,10 +92349,10 @@ function createApp(ctx, options = {}) {
91720
92349
  if (!isAllowedAttachmentName(name)) return c.json({ error: "unsupported file type" }, 400);
91721
92350
  if (typeof body.data !== "string" || body.data.length > ATTACHMENT_MAX_BASE64_CHARS) return c.json({ error: "bad payload" }, 400);
91722
92351
  const buf = Buffer.from(body.data, "base64");
91723
- const dir = join53(ctx.project.stateDir, "attachments", `${Date.now()}-${randomUUID21().slice(0, 8)}`);
91724
- mkdirSync27(dir, { recursive: true });
91725
- const path3 = join53(dir, attachmentFileName(name));
91726
- writeFileSync20(path3, buf);
92352
+ const dir = join54(ctx.project.stateDir, "attachments", `${Date.now()}-${randomUUID21().slice(0, 8)}`);
92353
+ mkdirSync28(dir, { recursive: true });
92354
+ const path3 = join54(dir, attachmentFileName(name));
92355
+ writeFileSync21(path3, buf);
91727
92356
  return c.json({ path: path3 });
91728
92357
  });
91729
92358
  app.get(
@@ -91786,7 +92415,7 @@ var init_app = __esm({
91786
92415
  });
91787
92416
 
91788
92417
  // packages/server/src/app-socket.ts
91789
- import { createHash as createHash20 } from "node:crypto";
92418
+ import { createHash as createHash22 } from "node:crypto";
91790
92419
  function isWsPath(url) {
91791
92420
  return (url ?? "").split("?")[0] === WS_PATH;
91792
92421
  }
@@ -91990,7 +92619,7 @@ function createAppSocketServer(deps) {
91990
92619
  sendEncoded(ws2, frame, false);
91991
92620
  }
91992
92621
  function frameSignature(frame) {
91993
- return createHash20("sha256").update(frame.text).digest("base64url");
92622
+ return createHash22("sha256").update(frame.text).digest("base64url");
91994
92623
  }
91995
92624
  const globalReadTimes = [];
91996
92625
  const originReadTimes = /* @__PURE__ */ new Map();
@@ -92383,14 +93012,14 @@ function createAppSocketServer(deps) {
92383
93012
  closeSocket(ws2, 1003, "text frames required");
92384
93013
  return;
92385
93014
  }
92386
- let decoded;
93015
+ let decoded2;
92387
93016
  try {
92388
- decoded = JSON.parse(raw2.toString());
93017
+ decoded2 = JSON.parse(raw2.toString());
92389
93018
  } catch {
92390
93019
  closeSocket(ws2, 1008, "invalid message");
92391
93020
  return;
92392
93021
  }
92393
- const parsed = SocketClientMsg.safeParse(decoded);
93022
+ const parsed = SocketClientMsg.safeParse(decoded2);
92394
93023
  if (!parsed.success) {
92395
93024
  closeSocket(ws2, 1008, "invalid message");
92396
93025
  return;
@@ -92721,10 +93350,10 @@ var init_local_file_watch = __esm({
92721
93350
  });
92722
93351
 
92723
93352
  // packages/server/src/boot-progress.ts
92724
- import { mkdirSync as mkdirSync28, readFileSync as readFileSync39, renameSync as renameSync15, rmSync as rmSync15, writeFileSync as writeFileSync21 } from "node:fs";
92725
- import { basename as basename13, dirname as dirname26, join as join54 } from "node:path";
93353
+ import { mkdirSync as mkdirSync29, readFileSync as readFileSync40, renameSync as renameSync16, rmSync as rmSync16, writeFileSync as writeFileSync22 } from "node:fs";
93354
+ import { basename as basename13, dirname as dirname26, join as join55 } from "node:path";
92726
93355
  function bootProgressPath(stateDir) {
92727
- return join54(stateDir, BOOT_PROGRESS_NAME);
93356
+ return join55(stateDir, BOOT_PROGRESS_NAME);
92728
93357
  }
92729
93358
  function createBootProgressPublisher(stateDir, minIntervalMs = 200) {
92730
93359
  if (!stateDir) {
@@ -92744,18 +93373,18 @@ function createBootProgressPublisher(stateDir, minIntervalMs = 200) {
92744
93373
  lastAt = now;
92745
93374
  step++;
92746
93375
  try {
92747
- mkdirSync28(dirname26(path3), { recursive: true, mode: 448 });
92748
- const temp = join54(dirname26(path3), `.${basename13(path3)}.${process.pid}.tmp`);
92749
- writeFileSync21(temp, `${JSON.stringify({ pid: process.pid, step, phase, at: new Date(now).toISOString() })}
93376
+ mkdirSync29(dirname26(path3), { recursive: true, mode: 448 });
93377
+ const temp = join55(dirname26(path3), `.${basename13(path3)}.${process.pid}.tmp`);
93378
+ writeFileSync22(temp, `${JSON.stringify({ pid: process.pid, step, phase, at: new Date(now).toISOString() })}
92750
93379
  `, "utf8");
92751
- renameSync15(temp, path3);
93380
+ renameSync16(temp, path3);
92752
93381
  } catch {
92753
93382
  }
92754
93383
  };
92755
93384
  return Object.assign(write, {
92756
93385
  done: () => {
92757
93386
  try {
92758
- rmSync15(path3, { force: true });
93387
+ rmSync16(path3, { force: true });
92759
93388
  } catch {
92760
93389
  }
92761
93390
  }
@@ -92771,12 +93400,12 @@ var init_boot_progress = __esm({
92771
93400
  });
92772
93401
 
92773
93402
  // packages/server/src/runtime-lease.ts
92774
- import { existsSync as existsSync22, mkdirSync as mkdirSync29, readdirSync as readdirSync16, readFileSync as readFileSync40, unlinkSync as unlinkSync8, writeFileSync as writeFileSync22 } from "node:fs";
92775
- import { dirname as dirname27, join as join55 } from "node:path";
93403
+ import { existsSync as existsSync22, mkdirSync as mkdirSync30, readdirSync as readdirSync17, readFileSync as readFileSync41, unlinkSync as unlinkSync8, writeFileSync as writeFileSync23 } from "node:fs";
93404
+ import { dirname as dirname27, join as join56 } from "node:path";
92776
93405
  function runtimeVersionDir(bin) {
92777
93406
  let dir = dirname27(bin);
92778
93407
  for (let step = 0; step < MAX_ASCENT; step++) {
92779
- if (existsSync22(join55(dir, PROVISIONED_MARKER))) return dir;
93408
+ if (existsSync22(join56(dir, PROVISIONED_MARKER))) return dir;
92780
93409
  const parent = dirname27(dir);
92781
93410
  if (parent === dir) return void 0;
92782
93411
  dir = parent;
@@ -92795,11 +93424,11 @@ function leaseRuntime(bin, role) {
92795
93424
  const versionDir = runtimeVersionDir(bin);
92796
93425
  if (!versionDir) return () => {
92797
93426
  };
92798
- const path3 = join55(versionDir, LEASES_DIR, `${process.pid}.json`);
93427
+ const path3 = join56(versionDir, LEASES_DIR, `${process.pid}.json`);
92799
93428
  try {
92800
- mkdirSync29(dirname27(path3), { recursive: true });
93429
+ mkdirSync30(dirname27(path3), { recursive: true });
92801
93430
  const lease = { pid: process.pid, role, bin, at: (/* @__PURE__ */ new Date()).toISOString() };
92802
- writeFileSync22(path3, JSON.stringify(lease));
93431
+ writeFileSync23(path3, JSON.stringify(lease));
92803
93432
  } catch {
92804
93433
  return () => {
92805
93434
  };
@@ -92812,20 +93441,20 @@ function leaseRuntime(bin, role) {
92812
93441
  };
92813
93442
  }
92814
93443
  function liveRuntimeLeases(versionDir) {
92815
- const dir = join55(versionDir, LEASES_DIR);
93444
+ const dir = join56(versionDir, LEASES_DIR);
92816
93445
  let names;
92817
93446
  try {
92818
- names = readdirSync16(dir);
93447
+ names = readdirSync17(dir);
92819
93448
  } catch {
92820
93449
  return [];
92821
93450
  }
92822
93451
  const live2 = [];
92823
93452
  for (const name of names) {
92824
93453
  if (!name.endsWith(".json")) continue;
92825
- const path3 = join55(dir, name);
93454
+ const path3 = join56(dir, name);
92826
93455
  let lease;
92827
93456
  try {
92828
- lease = JSON.parse(readFileSync40(path3, "utf8"));
93457
+ lease = JSON.parse(readFileSync41(path3, "utf8"));
92829
93458
  } catch {
92830
93459
  continue;
92831
93460
  }
@@ -92852,29 +93481,29 @@ var init_runtime_lease = __esm({
92852
93481
  });
92853
93482
 
92854
93483
  // packages/server/src/runtimes.ts
92855
- import { createHash as createHash21 } from "node:crypto";
93484
+ import { createHash as createHash23 } from "node:crypto";
92856
93485
  import {
92857
93486
  chmodSync as chmodSync5,
92858
93487
  closeSync as closeSync19,
92859
93488
  existsSync as existsSync23,
92860
- mkdirSync as mkdirSync30,
93489
+ mkdirSync as mkdirSync31,
92861
93490
  openSync as openSync20,
92862
- readFileSync as readFileSync41,
92863
- readdirSync as readdirSync17,
92864
- renameSync as renameSync16,
92865
- rmSync as rmSync16,
93491
+ readFileSync as readFileSync42,
93492
+ readdirSync as readdirSync18,
93493
+ renameSync as renameSync17,
93494
+ rmSync as rmSync17,
92866
93495
  statSync as statSync28,
92867
- writeFileSync as writeFileSync23,
93496
+ writeFileSync as writeFileSync24,
92868
93497
  writeSync as writeSync3
92869
93498
  } from "node:fs";
92870
- import { dirname as dirname28, isAbsolute as isAbsolute13, join as join56, normalize, relative as relative3, sep as sep6 } from "node:path";
93499
+ import { dirname as dirname28, isAbsolute as isAbsolute13, join as join57, normalize, relative as relative3, sep as sep6 } from "node:path";
92871
93500
  import { Readable as Readable2, Transform, Writable as Writable4 } from "node:stream";
92872
93501
  import { pipeline } from "node:stream/promises";
92873
93502
  import { createGunzip } from "node:zlib";
92874
93503
  function runtimesRoot(env = process.env) {
92875
93504
  const override = env[RUNTIMES_DIR_ENV];
92876
93505
  if (override && isAbsolute13(override)) return override;
92877
- return join56(frizzRoots().cache, "runtimes");
93506
+ return join57(frizzRoots().cache, "runtimes");
92878
93507
  }
92879
93508
  function isMusl() {
92880
93509
  if (process.platform !== "linux") return false;
@@ -92891,15 +93520,15 @@ function runtimeCoordinates(backend, platform3 = process.platform, arch = proces
92891
93520
  return { pkg: "@openai/codex", packageVersion: `${CODEX_VERSION}-${platform3}-${arch}`, label: CODEX_VERSION, binary: `codex${exe2}` };
92892
93521
  }
92893
93522
  function provisionedBinary(backend, root, label) {
92894
- const dir = join56(root, backend, label);
93523
+ const dir = join57(root, backend, label);
92895
93524
  let marker;
92896
93525
  try {
92897
- marker = JSON.parse(readFileSync41(join56(dir, MARKER), "utf8"));
93526
+ marker = JSON.parse(readFileSync42(join57(dir, MARKER), "utf8"));
92898
93527
  } catch {
92899
93528
  return void 0;
92900
93529
  }
92901
93530
  if (typeof marker.binary !== "string" || marker.label !== label) return void 0;
92902
- const bin = join56(dir, marker.binary);
93531
+ const bin = join57(dir, marker.binary);
92903
93532
  return existsSync23(bin) ? bin : void 0;
92904
93533
  }
92905
93534
  function octal(buffer, offset, length) {
@@ -92914,25 +93543,25 @@ function safeEntryPath(dest, name) {
92914
93543
  if (parts.length < 2) return void 0;
92915
93544
  const rel = normalize(parts.slice(1).join(sep6));
92916
93545
  if (isAbsolute13(rel) || rel === ".." || rel.startsWith(`..${sep6}`)) return void 0;
92917
- const full = join56(dest, rel);
93546
+ const full = join57(dest, rel);
92918
93547
  const back = relative3(dest, full);
92919
93548
  if (back.startsWith("..") || isAbsolute13(back)) return void 0;
92920
93549
  return full;
92921
93550
  }
92922
93551
  function locateBinary(dir, backend, binary) {
92923
93552
  if (backend === "claude") {
92924
- const direct = join56(dir, binary);
93553
+ const direct = join57(dir, binary);
92925
93554
  return existsSync23(direct) ? direct : void 0;
92926
93555
  }
92927
- const vendor = join56(dir, "vendor");
93556
+ const vendor = join57(dir, "vendor");
92928
93557
  let triples;
92929
93558
  try {
92930
- triples = readdirSync17(vendor);
93559
+ triples = readdirSync18(vendor);
92931
93560
  } catch {
92932
93561
  return void 0;
92933
93562
  }
92934
93563
  for (const triple of triples) {
92935
- const candidate = join56(vendor, triple, "bin", binary);
93564
+ const candidate = join57(vendor, triple, "bin", binary);
92936
93565
  if (existsSync23(candidate)) return candidate;
92937
93566
  }
92938
93567
  return void 0;
@@ -92948,12 +93577,12 @@ async function provisionRuntime(backend, options) {
92948
93577
  const registry = options.registry ?? REGISTRY;
92949
93578
  const progress = options.onProgress ?? (() => {
92950
93579
  });
92951
- const backendDir = join56(root, backend);
92952
- const finalDir = join56(backendDir, coordinates.label);
92953
- const partial = join56(backendDir, `.partial-${coordinates.label}-${process.pid}`);
92954
- mkdirSync30(backendDir, { recursive: true });
92955
- rmSync16(partial, { recursive: true, force: true });
92956
- mkdirSync30(partial);
93580
+ const backendDir = join57(root, backend);
93581
+ const finalDir = join57(backendDir, coordinates.label);
93582
+ const partial = join57(backendDir, `.partial-${coordinates.label}-${process.pid}`);
93583
+ mkdirSync31(backendDir, { recursive: true });
93584
+ rmSync17(partial, { recursive: true, force: true });
93585
+ mkdirSync31(partial);
92957
93586
  try {
92958
93587
  const manifestUrl = `${registry}/${coordinates.pkg.replace("/", "%2F")}/${coordinates.packageVersion}`;
92959
93588
  progress(`resolving ${coordinates.pkg}@${coordinates.packageVersion}`);
@@ -92966,19 +93595,19 @@ async function provisionRuntime(backend, options) {
92966
93595
  const response = await fetchImpl(tarball);
92967
93596
  if (!response.ok || !response.body) throw new Error(`tarball download answered ${response.status}`);
92968
93597
  const total = Number(response.headers.get("content-length") ?? 0);
92969
- const hash = createHash21("sha512");
93598
+ const hash = createHash23("sha512");
92970
93599
  let seen = 0;
92971
93600
  let lastReport = 0;
92972
93601
  const hasher = new Transform({
92973
- transform(chunk, _encoding, callback) {
92974
- hash.update(chunk);
92975
- seen += chunk.length;
93602
+ transform(chunk2, _encoding, callback) {
93603
+ hash.update(chunk2);
93604
+ seen += chunk2.length;
92976
93605
  const now = Date.now();
92977
93606
  if (now - lastReport > 500) {
92978
93607
  lastReport = now;
92979
93608
  progress(total > 0 ? `downloading ${describeBytes(total)}, ${Math.min(99, Math.floor(seen / total * 100))}%` : `downloading, ${describeBytes(seen)} so far`);
92980
93609
  }
92981
- callback(null, chunk);
93610
+ callback(null, chunk2);
92982
93611
  }
92983
93612
  });
92984
93613
  progress(total > 0 ? `downloading ${describeBytes(total)}` : "downloading");
@@ -92997,9 +93626,9 @@ async function provisionRuntime(backend, options) {
92997
93626
  binary: relative3(partial, bin),
92998
93627
  at: (/* @__PURE__ */ new Date()).toISOString()
92999
93628
  };
93000
- writeFileSync23(join56(partial, MARKER), `${JSON.stringify(marker, null, 2)}
93629
+ writeFileSync24(join57(partial, MARKER), `${JSON.stringify(marker, null, 2)}
93001
93630
  `, "utf8");
93002
- const rename3 = options.rename ?? renameSync16;
93631
+ const rename3 = options.rename ?? renameSync17;
93003
93632
  try {
93004
93633
  for (let attempt = 1; ; attempt++) {
93005
93634
  try {
@@ -93013,29 +93642,29 @@ async function provisionRuntime(backend, options) {
93013
93642
  } catch (err) {
93014
93643
  const theirs = provisionedBinary(backend, root, coordinates.label);
93015
93644
  if (!theirs) throw err;
93016
- rmSync16(partial, { recursive: true, force: true });
93645
+ rmSync17(partial, { recursive: true, force: true });
93017
93646
  return { bin: theirs, label: coordinates.label, fetched: false };
93018
93647
  }
93019
93648
  progress("ready");
93020
- return { bin: join56(finalDir, marker.binary), label: coordinates.label, fetched: true };
93649
+ return { bin: join57(finalDir, marker.binary), label: coordinates.label, fetched: true };
93021
93650
  } catch (err) {
93022
- rmSync16(partial, { recursive: true, force: true });
93651
+ rmSync17(partial, { recursive: true, force: true });
93023
93652
  throw err;
93024
93653
  }
93025
93654
  }
93026
93655
  function sweepRuntimes(backend, root, keepLabel, now = Date.now(), deps = {}) {
93027
93656
  const rm4 = deps.rm ?? defaultSweepRm;
93028
- const backendDir = join56(root, backend);
93657
+ const backendDir = join57(root, backend);
93029
93658
  let entries2;
93030
93659
  try {
93031
- entries2 = readdirSync17(backendDir);
93660
+ entries2 = readdirSync18(backendDir);
93032
93661
  } catch {
93033
93662
  return { removed: [], kept: [] };
93034
93663
  }
93035
93664
  const sweep = { removed: [], kept: [] };
93036
93665
  for (const entry of entries2) {
93037
93666
  if (entry === keepLabel) continue;
93038
- const full = join56(backendDir, entry);
93667
+ const full = join57(backendDir, entry);
93039
93668
  if (entry.startsWith(".partial-")) {
93040
93669
  try {
93041
93670
  if (now - statSync28(full).mtimeMs < 24 * 60 * 60 * 1e3) continue;
@@ -93152,9 +93781,9 @@ var init_runtimes = __esm({
93152
93781
  paxBuffer;
93153
93782
  nameBuffer;
93154
93783
  written = [];
93155
- _write(chunk, _encoding, callback) {
93784
+ _write(chunk2, _encoding, callback) {
93156
93785
  try {
93157
- this.consume(chunk);
93786
+ this.consume(chunk2);
93158
93787
  callback();
93159
93788
  } catch (err) {
93160
93789
  callback(err instanceof Error ? err : new Error(String(err)));
@@ -93165,8 +93794,8 @@ var init_runtimes = __esm({
93165
93794
  this.fd = void 0;
93166
93795
  callback(this.remaining > 0 ? new Error("tarball ended inside a file entry") : null);
93167
93796
  }
93168
- consume(chunk) {
93169
- let data = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;
93797
+ consume(chunk2) {
93798
+ let data = this.pending.length ? Buffer.concat([this.pending, chunk2]) : chunk2;
93170
93799
  this.pending = Buffer.alloc(0);
93171
93800
  for (; ; ) {
93172
93801
  if (this.remaining > 0) {
@@ -93218,7 +93847,7 @@ var init_runtimes = __esm({
93218
93847
  return;
93219
93848
  case "5": {
93220
93849
  const dir = safeEntryPath(this.dest, name);
93221
- if (dir) mkdirSync30(dir, { recursive: true });
93850
+ if (dir) mkdirSync31(dir, { recursive: true });
93222
93851
  return;
93223
93852
  }
93224
93853
  case "0":
@@ -93226,7 +93855,7 @@ var init_runtimes = __esm({
93226
93855
  case "7": {
93227
93856
  const file = safeEntryPath(this.dest, name);
93228
93857
  if (!file) return;
93229
- mkdirSync30(dirname28(file), { recursive: true });
93858
+ mkdirSync31(dirname28(file), { recursive: true });
93230
93859
  this.fd = openSync20(file, "w", octal(header, 100, 8) & 511 || 420);
93231
93860
  this.written.push(file);
93232
93861
  return;
@@ -93270,7 +93899,7 @@ var init_runtimes = __esm({
93270
93899
  RENAME_RETRY_DELAY_MS = 200;
93271
93900
  TRANSIENT_HANDLE_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"]);
93272
93901
  errorCode4 = (err) => err?.code;
93273
- defaultSweepRm = (path3) => rmSync16(path3, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
93902
+ defaultSweepRm = (path3) => rmSync17(path3, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
93274
93903
  }
93275
93904
  });
93276
93905
 
@@ -93813,18 +94442,18 @@ var init_legacy_project_db = __esm({
93813
94442
  });
93814
94443
 
93815
94444
  // packages/server/src/frizz-db.ts
93816
- import { existsSync as existsSync24, mkdirSync as mkdirSync31, readdirSync as readdirSync18, renameSync as renameSync17, statSync as statSync29 } from "node:fs";
93817
- import { basename as basename14, dirname as dirname29, join as join57 } from "node:path";
94445
+ import { existsSync as existsSync24, mkdirSync as mkdirSync32, readdirSync as readdirSync19, renameSync as renameSync18, statSync as statSync29 } from "node:fs";
94446
+ import { basename as basename14, dirname as dirname29, join as join58 } from "node:path";
93818
94447
  function frizzDatabaseLocation(options) {
93819
94448
  if (options.stateDir !== void 0) {
93820
94449
  const projectsDir = dirname29(options.stateDir);
93821
94450
  if (basename14(projectsDir) === "projects") {
93822
- return { path: options.path ?? join57(dirname29(projectsDir), "ui.db"), projectsDir };
94451
+ return { path: options.path ?? join58(dirname29(projectsDir), "ui.db"), projectsDir };
93823
94452
  }
93824
- return { path: options.path ?? join57(options.stateDir, "ui.db"), projectsDir: void 0 };
94453
+ return { path: options.path ?? join58(options.stateDir, "ui.db"), projectsDir: void 0 };
93825
94454
  }
93826
94455
  const data = options.home ? frizzPaths({ home: options.home }).data : frizzRoots().data;
93827
- return { path: options.path ?? join57(data, "ui.db"), projectsDir: join57(data, "projects") };
94456
+ return { path: options.path ?? join58(data, "ui.db"), projectsDir: join58(data, "projects") };
93828
94457
  }
93829
94458
  function ensureFrizzSchema(db) {
93830
94459
  db.exec(`
@@ -93843,7 +94472,7 @@ function ensureFrizzSchema(db) {
93843
94472
  }
93844
94473
  function openFrizzDatabase(options = {}) {
93845
94474
  const { path: path3, projectsDir } = frizzDatabaseLocation(options);
93846
- mkdirSync31(dirname29(path3), { recursive: true });
94475
+ mkdirSync32(dirname29(path3), { recursive: true });
93847
94476
  const db = new sqlite_default(path3);
93848
94477
  db.pragma("busy_timeout = 5000");
93849
94478
  db.pragma("journal_mode = WAL");
@@ -93855,10 +94484,10 @@ function openFrizzDatabase(options = {}) {
93855
94484
  );
93856
94485
  for (const projectId of retiredLegacyProjectIds(projectsDir)) {
93857
94486
  if (alreadyImported.has(projectId)) continue;
93858
- const dir = join57(projectsDir, projectId);
94487
+ const dir = join58(projectsDir, projectId);
93859
94488
  try {
93860
- renameSync17(join57(dir, "ui.db.imported"), join57(dir, "ui.db"));
93861
- db.prepare("INSERT INTO imported_project (project_id, source, rows, imported_at) VALUES (?, ?, 0, ?)").run(projectId, join57(dir, "ui.db"), (/* @__PURE__ */ new Date()).toISOString());
94489
+ renameSync18(join58(dir, "ui.db.imported"), join58(dir, "ui.db"));
94490
+ db.prepare("INSERT INTO imported_project (project_id, source, rows, imported_at) VALUES (?, ?, 0, ?)").run(projectId, join58(dir, "ui.db"), (/* @__PURE__ */ new Date()).toISOString());
93862
94491
  alreadyImported.add(projectId);
93863
94492
  log.info("frizz-db", `${projectId}: restored ui.db.imported to ui.db and recorded it as imported`);
93864
94493
  } catch (error) {
@@ -93868,7 +94497,7 @@ function openFrizzDatabase(options = {}) {
93868
94497
  }
93869
94498
  for (const projectId of legacyProjectIds(projectsDir)) {
93870
94499
  if (alreadyImported.has(projectId)) continue;
93871
- const legacyPath = join57(projectsDir, projectId, "ui.db");
94500
+ const legacyPath = join58(projectsDir, projectId, "ui.db");
93872
94501
  try {
93873
94502
  const rows = importLegacyProject(db, projectId, legacyPath);
93874
94503
  imported.push({ projectId, rows });
@@ -93899,9 +94528,9 @@ function openFrizzDatabase(options = {}) {
93899
94528
  }
93900
94529
  function projectIdsWithFile(projectsDir, file) {
93901
94530
  if (!existsSync24(projectsDir)) return [];
93902
- return readdirSync18(projectsDir).filter((name) => {
94531
+ return readdirSync19(projectsDir).filter((name) => {
93903
94532
  try {
93904
- return statSync29(join57(projectsDir, name, file)).isFile();
94533
+ return statSync29(join58(projectsDir, name, file)).isFile();
93905
94534
  } catch {
93906
94535
  return false;
93907
94536
  }
@@ -93911,7 +94540,7 @@ function legacyProjectIds(projectsDir) {
93911
94540
  return projectIdsWithFile(projectsDir, "ui.db");
93912
94541
  }
93913
94542
  function retiredLegacyProjectIds(projectsDir) {
93914
- return projectIdsWithFile(projectsDir, "ui.db.imported").filter((id) => !existsSync24(join57(projectsDir, id, "ui.db")));
94543
+ return projectIdsWithFile(projectsDir, "ui.db.imported").filter((id) => !existsSync24(join58(projectsDir, id, "ui.db")));
93915
94544
  }
93916
94545
  function tableColumns(db, schema, table) {
93917
94546
  return db.prepare(`PRAGMA ${schema}.table_info(${table})`).all().map((c) => c.name);
@@ -94090,8 +94719,8 @@ var init_projects_changed = __esm({
94090
94719
  });
94091
94720
 
94092
94721
  // packages/server/src/project-teardown.ts
94093
- import { rmSync as rmSync17 } from "node:fs";
94094
- import { homedir as homedir23 } from "node:os";
94722
+ import { rmSync as rmSync18 } from "node:fs";
94723
+ import { homedir as homedir24 } from "node:os";
94095
94724
  import { dirname as dirname30, resolve as resolve12 } from "node:path";
94096
94725
  async function stopProjectWorkers(ctx) {
94097
94726
  let stopped = 0;
@@ -94107,7 +94736,7 @@ async function stopProjectWorkers(ctx) {
94107
94736
  }
94108
94737
  return stopped;
94109
94738
  }
94110
- function deleteProjectState(projectId, home = homedir23()) {
94739
+ function deleteProjectState(projectId, home = homedir24()) {
94111
94740
  const target = projectStateDir(projectId, home);
94112
94741
  if (!/^[\w.-]+$/u.test(projectId) || projectId === "." || projectId === "..") {
94113
94742
  throw new Error(`Refusing to delete state for a malformed project id: ${projectId}`);
@@ -94115,7 +94744,7 @@ function deleteProjectState(projectId, home = homedir23()) {
94115
94744
  if (dirname30(resolve12(target)) !== resolve12(dirname30(projectStateDir("x", home)))) {
94116
94745
  throw new Error(`Refusing to delete ${target} \u2014 it is not a project state directory`);
94117
94746
  }
94118
- rmSync17(target, { recursive: true, force: true });
94747
+ rmSync18(target, { recursive: true, force: true });
94119
94748
  }
94120
94749
  var init_project_teardown = __esm({
94121
94750
  "packages/server/src/project-teardown.ts"() {
@@ -94141,11 +94770,11 @@ __export(index_exports, {
94141
94770
  unknownProjectPage: () => unknownProjectPage
94142
94771
  });
94143
94772
  import { createServer } from "node:http";
94144
- import { readFileSync as readFileSync42, existsSync as existsSync25, statSync as statSync30 } from "node:fs";
94145
- import { dirname as dirname31, join as join58, resolve as resolve13, extname as extname4, posix as posix2, sep as sep7 } from "node:path";
94773
+ import { readFileSync as readFileSync43, existsSync as existsSync25, statSync as statSync30 } from "node:fs";
94774
+ import { dirname as dirname31, join as join59, resolve as resolve13, extname as extname4, posix as posix2, sep as sep7 } from "node:path";
94146
94775
  function readServerAddressHolder(path3) {
94147
94776
  try {
94148
- const value = JSON.parse(readFileSync42(path3, "utf8"));
94777
+ const value = JSON.parse(readFileSync43(path3, "utf8"));
94149
94778
  if (typeof value?.pid !== "number") return void 0;
94150
94779
  return { pid: value.pid, port: typeof value.port === "number" ? value.port : -1 };
94151
94780
  } catch {
@@ -94273,12 +94902,12 @@ function staticIsFresh(req, etag, mtimeMs) {
94273
94902
  }
94274
94903
  function serveStatic(distDir, req, res) {
94275
94904
  const rel = posix2.normalize((req.url ?? "/").split("?")[0].replace(/\\/g, "/")).replace(/^(\.\.[/\\])+/, "");
94276
- let file = join58(distDir, rel === "/" ? "index.html" : rel);
94277
- if (!file.startsWith(distDir + sep7)) file = join58(distDir, "index.html");
94278
- if (!existsSync25(file)) file = join58(distDir, "index.html");
94905
+ let file = join59(distDir, rel === "/" ? "index.html" : rel);
94906
+ if (!file.startsWith(distDir + sep7)) file = join59(distDir, "index.html");
94907
+ if (!existsSync25(file)) file = join59(distDir, "index.html");
94279
94908
  try {
94280
94909
  const stats = statSync30(file);
94281
- const cacheControl = file.startsWith(join58(distDir, "assets") + sep7) ? STATIC_CACHE_IMMUTABLE : STATIC_CACHE_REVALIDATE;
94910
+ const cacheControl = file.startsWith(join59(distDir, "assets") + sep7) ? STATIC_CACHE_IMMUTABLE : STATIC_CACHE_REVALIDATE;
94282
94911
  const etag = `"${stats.size.toString(16)}-${Math.trunc(stats.mtimeMs).toString(16)}"`;
94283
94912
  const headers = {
94284
94913
  "content-type": MIME[extname4(file)] ?? "application/octet-stream",
@@ -94294,7 +94923,7 @@ function serveStatic(distDir, req, res) {
94294
94923
  res.end();
94295
94924
  return;
94296
94925
  }
94297
- let body = readFileSync42(file);
94926
+ let body = readFileSync43(file);
94298
94927
  const accept = req.headers["accept-encoding"];
94299
94928
  const encoding = negotiateEncoding(Array.isArray(accept) ? accept.join(",") : accept);
94300
94929
  if (encoding && shouldCompress(new Headers({ "content-type": headers["content-type"] }), body.byteLength)) {
@@ -94705,7 +95334,7 @@ async function startServer(opts = {}) {
94705
95334
  }
94706
95335
  statusPath = serverLockPathFor(ctx.project);
94707
95336
  const webRoot = resolve13(import.meta.dirname, "..", "..", "web");
94708
- const distDir = opts.webDistDir ? resolve13(opts.webDistDir) : join58(webRoot, "dist");
95337
+ const distDir = opts.webDistDir ? resolve13(opts.webDistDir) : join59(webRoot, "dist");
94709
95338
  startupPhase = "Vite";
94710
95339
  if (opts.dev) {
94711
95340
  try {
@@ -94783,7 +95412,7 @@ async function startServer(opts = {}) {
94783
95412
  if (vite) {
94784
95413
  vite.middlewares(req, res, () => {
94785
95414
  try {
94786
- const html = readFileSync42(join58(webRoot, "index.html"), "utf8");
95415
+ const html = readFileSync43(join59(webRoot, "index.html"), "utf8");
94787
95416
  void vite.transformIndexHtml(url, html).then((out) => {
94788
95417
  res.writeHead(200, { "content-type": "text/html" });
94789
95418
  res.end(out);
@@ -94994,7 +95623,7 @@ var init_index = __esm({
94994
95623
  }
94995
95624
  };
94996
95625
  isApiUrl = (url) => url === FRIZZ_ROUTE_PREFIX || url.startsWith(`${FRIZZ_ROUTE_PREFIX}/`);
94997
- serverLockPathFor = (project) => join58(project.stateDir, "server.lock");
95626
+ serverLockPathFor = (project) => join59(project.stateDir, "server.lock");
94998
95627
  MIME = {
94999
95628
  ".html": "text/html",
95000
95629
  ".js": "text/javascript",
@@ -95019,7 +95648,7 @@ init_shutdown();
95019
95648
  init_logging();
95020
95649
  init_access_codes();
95021
95650
  import { existsSync as existsSync26 } from "node:fs";
95022
- import { join as join59 } from "node:path";
95651
+ import { join as join60 } from "node:path";
95023
95652
 
95024
95653
  // packages/server/src/session-epoch-child.ts
95025
95654
  init_access_codes();
@@ -95339,7 +95968,7 @@ try {
95339
95968
  ];
95340
95969
  if (!existsSync26(stableWebDist)) throw new Error("stable artifact launch is missing its verified web directory");
95341
95970
  for (const [name, directory, requiredFile] of required) {
95342
- if (!directory || !existsSync26(join59(directory, requiredFile)))
95971
+ if (!directory || !existsSync26(join60(directory, requiredFile)))
95343
95972
  throw new Error(`stable artifact launch is missing verified ${name}`);
95344
95973
  }
95345
95974
  }