@codexhost/cli-win32-x64 0.32.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +589 -30
  4. package/app/console-web.js +558 -30
  5. package/app/desktop-controller.mjs +883 -150
  6. package/app/host-runtime.mjs +8165 -3548
  7. package/app/plugins/antigravity/plugin.mjs +493 -55
  8. package/app/plugins/claude-code/assets/icon.svg +1 -1
  9. package/app/plugins/claude-code/manifest.json +1 -1
  10. package/app/plugins/claude-code/plugin.mjs +1106 -193
  11. package/app/plugins/codebuddy/plugin.mjs +465 -27
  12. package/app/plugins/codex-usage/plugin.mjs +367 -7
  13. package/app/plugins/copilot/assets/icon.svg +1 -1
  14. package/app/plugins/copilot/manifest.json +1 -1
  15. package/app/plugins/copilot/plugin.mjs +369 -9
  16. package/app/plugins/cursor-cli/plugin.mjs +367 -7
  17. package/app/plugins/deepseek-harness/assets/icon.svg +1 -1
  18. package/app/plugins/deepseek-harness/manifest.json +1 -1
  19. package/app/plugins/deepseek-harness/plugin.mjs +806 -148
  20. package/app/plugins/devin/assets/icon.svg +1 -1
  21. package/app/plugins/devin/manifest.json +1 -1
  22. package/app/plugins/devin/plugin.mjs +369 -8
  23. package/app/plugins/grok/plugin.mjs +367 -7
  24. package/app/plugins/hermes/plugin.mjs +367 -7
  25. package/app/plugins/kimi-code/plugin.mjs +367 -7
  26. package/app/plugins/kiro-cli/plugin.mjs +367 -7
  27. package/app/plugins/omp/assets/icon.svg +1 -1
  28. package/app/plugins/omp/plugin.mjs +393 -7
  29. package/app/plugins/opencode/plugin.mjs +371 -8
  30. package/app/plugins/pi/assets/icon.svg +1 -1
  31. package/app/plugins/pi/manifest.json +1 -1
  32. package/app/plugins/pi/plugin.mjs +395 -9
  33. package/app/plugins/qoder/assets/icon.svg +1 -1
  34. package/app/plugins/qoder/plugin.mjs +393 -7
  35. package/app/plugins/qoder-cn/assets/icon.svg +1 -1
  36. package/app/plugins/qoder-cn/plugin.mjs +393 -7
  37. package/app/plugins/qwen-code/assets/icon.svg +1 -1
  38. package/app/plugins/qwen-code/plugin.mjs +396 -7
  39. package/app/plugins/workbuddy/plugin.mjs +465 -27
  40. package/app/plugins/zcode/plugin.mjs +387 -14
  41. package/app/renderer-extension.js +581 -41
  42. package/app/web/assets/{abnfDiagram-XWFEHMT6-CnJyN70L.js → abnfDiagram-XWFEHMT6-VnfRaHM6.js} +1 -1
  43. package/app/web/assets/{architectureDiagram-CSQXQB3N-DH0ITYVE.js → architectureDiagram-CSQXQB3N-BA1ehtvi.js} +1 -1
  44. package/app/web/assets/{blockDiagram-BEDRHYPZ-WL3ZKoKg.js → blockDiagram-BEDRHYPZ-31BZSfd4.js} +1 -1
  45. package/app/web/assets/{c4Diagram-M2UUVUY5-XwSPKj5H.js → c4Diagram-M2UUVUY5-CNzGWc5k.js} +1 -1
  46. package/app/web/assets/{chunk-2Q5K7J3B-CKEzexjg.js → chunk-2Q5K7J3B-ahAIR-NM.js} +1 -1
  47. package/app/web/assets/{chunk-3GCGMST5-BdEgLpab.js → chunk-3GCGMST5-BIV5YeRJ.js} +1 -1
  48. package/app/web/assets/{chunk-5VM5RSS4-DyxL5-Ts.js → chunk-5VM5RSS4-CluTMPJG.js} +1 -1
  49. package/app/web/assets/{chunk-7U7NFRK5-FXLb4tYa.js → chunk-7U7NFRK5-4NIQuFbE.js} +1 -1
  50. package/app/web/assets/{chunk-CNRTWJTD-DcdC1OYr.js → chunk-CNRTWJTD-_0bEfGn3.js} +1 -1
  51. package/app/web/assets/{chunk-D5HYT7QG-BOz9vBX9.js → chunk-D5HYT7QG-_kTC6f8F.js} +1 -1
  52. package/app/web/assets/{chunk-EBZ3SEQC-Dmc_Z53x.js → chunk-EBZ3SEQC-CykaYOrL.js} +2 -2
  53. package/app/web/assets/{chunk-JWPE2WC7-CrFwSwYi.js → chunk-JWPE2WC7-3vVOQ_py.js} +1 -1
  54. package/app/web/assets/{chunk-KTR4FSNJ-BY3AzFaI.js → chunk-KTR4FSNJ-aVg5vgrm.js} +1 -1
  55. package/app/web/assets/{chunk-XXDRQBXY-CHgNy82n.js → chunk-XXDRQBXY-_gVwGeSp.js} +1 -1
  56. package/app/web/assets/{classDiagram-v2-KXABOMEV-ClM3-y5Z.js → classDiagram-v2-KXABOMEV-fI1LfeBf.js} +1 -1
  57. package/app/web/assets/{cose-bilkent-JH36ORCC-I7nd8GgO.js → cose-bilkent-JH36ORCC-DFXMlWov.js} +1 -1
  58. package/app/web/assets/{cynefin-EF2NZ3EQ-DzsXmyBH.js → cynefin-EF2NZ3EQ-lZy7X6FO.js} +1 -1
  59. package/app/web/assets/{cynefinDiagram-NJNITYFG-DLHq6igy.js → cynefinDiagram-NJNITYFG-N4DwFSW1.js} +1 -1
  60. package/app/web/assets/{dagre-KIHZ2IZ3-BK991Mno.js → dagre-KIHZ2IZ3-B7-8baTH.js} +1 -1
  61. package/app/web/assets/{diagram-7YQZDPLS-C4qiWdQU.js → diagram-7YQZDPLS-DLfjiBXV.js} +1 -1
  62. package/app/web/assets/{diagram-QBROCOUO-C_ZyBohC.js → diagram-QBROCOUO-CQnRzSTi.js} +1 -1
  63. package/app/web/assets/{diagram-RJJCUUZO-C5Aezm94.js → diagram-RJJCUUZO-DPnxazRT.js} +1 -1
  64. package/app/web/assets/{diagram-WERXNKYE-Ckc_umlF.js → diagram-WERXNKYE-BBuEFRvD.js} +1 -1
  65. package/app/web/assets/{diagram-YHHI257C-BHjReoZZ.js → diagram-YHHI257C-BQ92JNJs.js} +1 -1
  66. package/app/web/assets/{diagram-YR4HJLHV-DVTGi_y9.js → diagram-YR4HJLHV-Ce6BQO3J.js} +1 -1
  67. package/app/web/assets/{ebnfDiagram-N527522P-getuz1AR.js → ebnfDiagram-N527522P-DYknE2Jy.js} +1 -1
  68. package/app/web/assets/{elk-O5DQBFGD-C7mhTIuK.js → elk-O5DQBFGD-4S6_JJFF.js} +1 -1
  69. package/app/web/assets/{erDiagram-K3K3BIDK-sV-HZvUV.js → erDiagram-K3K3BIDK-DRtF7JVQ.js} +1 -1
  70. package/app/web/assets/{flowDiagram-Z6JWZHQI-D0L4wXUs.js → flowDiagram-Z6JWZHQI-7Ho8CyR9.js} +1 -1
  71. package/app/web/assets/{ganttDiagram-3PRQTZWP-BNt9Bjjo.js → ganttDiagram-3PRQTZWP-CW8Ig5y4.js} +1 -1
  72. package/app/web/assets/{gitGraphDiagram-VXDFKS5L-BABZzhHw.js → gitGraphDiagram-VXDFKS5L-CzS8Xg2D.js} +1 -1
  73. package/app/web/assets/{grid-E2QIVN74-DLe2FQ_d.js → grid-E2QIVN74-Cq284lCe.js} +1 -1
  74. package/app/web/assets/index-CINZ6P-q.css +1 -0
  75. package/app/web/assets/index-CvV6veuY.js +208 -0
  76. package/app/web/assets/{infoDiagram-EZ3ZOAHP-BKDuUqcr.js → infoDiagram-EZ3ZOAHP-BZgN6qlY.js} +1 -1
  77. package/app/web/assets/{ishikawaDiagram-S3EKX5GW-C75EGghg.js → ishikawaDiagram-S3EKX5GW-BH9YHc-1.js} +1 -1
  78. package/app/web/assets/{journeyDiagram-POQNLL5X-q7Obruqa.js → journeyDiagram-POQNLL5X-D50KYOLe.js} +1 -1
  79. package/app/web/assets/{kanban-definition-BH5XI6FM-CzAqhFED.js → kanban-definition-BH5XI6FM-Crw_5mMP.js} +1 -1
  80. package/app/web/assets/langs/{graphql-D6Z3qcRW.js → graphql-2R4AZ1iu.js} +1 -1
  81. package/app/web/assets/langs/{http-XiU9G9In.js → http-q2Qm0vBh.js} +1 -1
  82. package/app/web/assets/langs/{php-DL3xwS-7.js → php-Cz2gDBnd.js} +1 -1
  83. package/app/web/assets/langs/{rst-DudRVJ9g.js → rst-_9muvx-X.js} +1 -1
  84. package/app/web/assets/langs/{ruby-_FqsfqJi.js → ruby-cn7REk4H.js} +1 -1
  85. package/app/web/assets/langs/{svelte-ClsVJoBT.js → svelte-CPnL2mcy.js} +1 -1
  86. package/app/web/assets/langs/{vue-BiKMXCyK.js → vue-DO0YwyVz.js} +1 -1
  87. package/app/web/assets/{mermaid.core-Bysx44LR.js → mermaid.core-o2Qjrppc.js} +5 -5
  88. package/app/web/assets/{mindmap-definition-WVAN44T4-Ds5rXTrF.js → mindmap-definition-WVAN44T4-B_bEbpAH.js} +1 -1
  89. package/app/web/assets/{pegDiagram-D4NLKWP3-hmdERwtT.js → pegDiagram-D4NLKWP3-VecAHoyw.js} +1 -1
  90. package/app/web/assets/{pieDiagram-36ENHN4W-DfTnyG8D.js → pieDiagram-36ENHN4W-o3ei2T-6.js} +1 -1
  91. package/app/web/assets/{quadrantDiagram-ZQUDMS73-CreQWjZQ.js → quadrantDiagram-ZQUDMS73-DHndOAcn.js} +1 -1
  92. package/app/web/assets/{railroadDiagram-JIZHGYPL-Bhc_eO9G.js → railroadDiagram-JIZHGYPL-DRd_lfii.js} +1 -1
  93. package/app/web/assets/{render-VIF2ZAQL-BS1Zgk8K.js → render-VIF2ZAQL-awM3hUqB.js} +2 -2
  94. package/app/web/assets/{requirementDiagram-AXW2TVFA-Dlp7d6QT.js → requirementDiagram-AXW2TVFA-Ce1ePsOe.js} +1 -1
  95. package/app/web/assets/{sankeyDiagram-FBCJTAIF-DGBchL30.js → sankeyDiagram-FBCJTAIF-cP-LtgW-.js} +1 -1
  96. package/app/web/assets/{sequenceDiagram-3LA2ROMG-DauFg5_R.js → sequenceDiagram-3LA2ROMG-C3JStTuW.js} +1 -1
  97. package/app/web/assets/{sizeCapture-2Q2CQKSF-DR-zy7an.js → sizeCapture-2Q2CQKSF-Dyyelr9K.js} +1 -1
  98. package/app/web/assets/{stateDiagram-v2-ATKHQDJO-BSRBSGUi.js → stateDiagram-v2-ATKHQDJO-DkYRBVTd.js} +1 -1
  99. package/app/web/assets/{swimlanes-YQL5WMAO-BwzOr5Dv.js → swimlanes-YQL5WMAO-B2FwJU5_.js} +1 -1
  100. package/app/web/assets/swimlanesDiagram-UCCPES4V-BkMsxCPb.js +8 -0
  101. package/app/web/assets/{timeline-definition-7Z437IG3-BoZ-mNKc.js → timeline-definition-7Z437IG3-Di-qRIIi.js} +1 -1
  102. package/app/web/assets/{usecaseDiagram-RDK6N6HP-DikhgH2m.js → usecaseDiagram-RDK6N6HP-yAImn62t.js} +1 -1
  103. package/app/web/assets/{vendor-BKfNgqAm.js → vendor-BMCjWFMy.js} +20 -20
  104. package/app/web/assets/{vennDiagram-SHRQU5PJ-DY_oIxwl.js → vennDiagram-SHRQU5PJ-BEv8jpfv.js} +1 -1
  105. package/app/web/assets/{wardleyDiagram-F3OXNVQS-DrRIiB_M.js → wardleyDiagram-F3OXNVQS-7irksA0b.js} +1 -1
  106. package/app/web/assets/{xychartDiagram-GDYJKCDI-CzSPgHV7.js → xychartDiagram-GDYJKCDI-BokJGG2y.js} +1 -1
  107. package/app/web/codex-agent.png +0 -0
  108. package/app/web/codex.png +0 -0
  109. package/app/web/codexhost-settings.js +66 -66
  110. package/app/web/index.html +3 -3
  111. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +65 -65
  112. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  113. package/app/web/plugins/deepseek-ai__dsh-client-ui-attachment/client.js +1 -1
  114. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +75 -75
  115. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +78 -73
  116. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +92 -92
  117. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  118. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +114 -2
  119. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  120. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +79 -79
  121. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  122. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +70 -70
  123. package/app/web/role-avatars/builtin/architect-otter.webp +0 -0
  124. package/app/web/role-avatars/builtin/audio-otter.webp +0 -0
  125. package/app/web/role-avatars/builtin/backend-otter.webp +0 -0
  126. package/app/web/role-avatars/builtin/classic-otter.webp +0 -0
  127. package/app/web/role-avatars/builtin/data-otter.webp +0 -0
  128. package/app/web/role-avatars/builtin/debugger-otter.webp +0 -0
  129. package/app/web/role-avatars/builtin/frontend-otter.webp +0 -0
  130. package/app/web/role-avatars/builtin/idea-otter.webp +0 -0
  131. package/app/web/role-avatars/builtin/ops-otter.webp +0 -0
  132. package/app/web/role-avatars/builtin/pm-otter.webp +0 -0
  133. package/app/web/role-avatars/builtin/researcher-otter.webp +0 -0
  134. package/app/web/role-avatars/builtin/reviewer-otter.webp +0 -0
  135. package/app/web/role-avatars/builtin/scholar-otter.webp +0 -0
  136. package/app/web/role-avatars/builtin/security-otter.webp +0 -0
  137. package/app/web/role-avatars/builtin/tester-otter.webp +0 -0
  138. package/app/web/role-avatars/builtin/writer-otter.webp +0 -0
  139. package/app/web-modules/node_modules/@deepseek-ai/dsh-host-webserver/index.js +7 -1
  140. package/app/web-modules/server.mjs +1324 -252
  141. package/bin/codexhost.exe +0 -0
  142. package/libexec/codexhost-node-repl.exe +0 -0
  143. package/libexec/codexhost-screenshot.exe +0 -0
  144. package/libexec/codexhost-shell.exe +0 -0
  145. package/libexec/codexhost-shim.exe +0 -0
  146. package/libexec/codexhost-updater.exe +0 -0
  147. package/package.json +1 -1
  148. package/app/web/assets/index-BLmkBEoq.js +0 -205
  149. package/app/web/assets/index-Dwdnvinl.css +0 -1
  150. package/app/web/assets/swimlanesDiagram-UCCPES4V-CNV63-us.js +0 -8
@@ -828,10 +828,10 @@ function mergeDefs(...defs) {
828
828
  function cloneDef(schema) {
829
829
  return mergeDefs(schema._zod.def);
830
830
  }
831
- function getElementAtPath(obj, path18) {
832
- if (!path18)
831
+ function getElementAtPath(obj, path19) {
832
+ if (!path19)
833
833
  return obj;
834
- return path18.reduce((acc, key) => acc?.[key], obj);
834
+ return path19.reduce((acc, key) => acc?.[key], obj);
835
835
  }
836
836
  function promiseAllObject(promisesObj) {
837
837
  const keys = Object.keys(promisesObj);
@@ -1171,11 +1171,11 @@ function explicitlyAborted(x, startIndex = 0) {
1171
1171
  }
1172
1172
  return false;
1173
1173
  }
1174
- function prefixIssues(path18, issues) {
1174
+ function prefixIssues(path19, issues) {
1175
1175
  return issues.map((iss) => {
1176
1176
  var _a4;
1177
1177
  (_a4 = iss).path ?? (_a4.path = []);
1178
- iss.path.unshift(path18);
1178
+ iss.path.unshift(path19);
1179
1179
  return iss;
1180
1180
  });
1181
1181
  }
@@ -1637,16 +1637,16 @@ function flattenError(error63, mapper = (issue2) => issue2.message) {
1637
1637
  }
1638
1638
  function formatError(error63, mapper = (issue2) => issue2.message) {
1639
1639
  const fieldErrors = { _errors: [] };
1640
- const processError = (error64, path18 = []) => {
1640
+ const processError = (error64, path19 = []) => {
1641
1641
  for (const issue2 of error64.issues) {
1642
1642
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1643
- issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
1643
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1644
1644
  } else if (issue2.code === "invalid_key") {
1645
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1645
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1646
1646
  } else if (issue2.code === "invalid_element") {
1647
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1647
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1648
1648
  } else {
1649
- const fullpath = [...path18, ...issue2.path];
1649
+ const fullpath = [...path19, ...issue2.path];
1650
1650
  if (fullpath.length === 0) {
1651
1651
  fieldErrors._errors.push(mapper(issue2));
1652
1652
  } else {
@@ -1685,17 +1685,17 @@ function formatError(error63, mapper = (issue2) => issue2.message) {
1685
1685
  }
1686
1686
  function treeifyError(error63, mapper = (issue2) => issue2.message) {
1687
1687
  const result = { errors: [] };
1688
- const processError = (error64, path18 = []) => {
1688
+ const processError = (error64, path19 = []) => {
1689
1689
  var _a4;
1690
1690
  for (const issue2 of error64.issues) {
1691
1691
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1692
- issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
1692
+ issue2.errors.map((issues) => processError({ issues }, [...path19, ...issue2.path]));
1693
1693
  } else if (issue2.code === "invalid_key") {
1694
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1694
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1695
1695
  } else if (issue2.code === "invalid_element") {
1696
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1696
+ processError({ issues: issue2.issues }, [...path19, ...issue2.path]);
1697
1697
  } else {
1698
- const fullpath = [...path18, ...issue2.path];
1698
+ const fullpath = [...path19, ...issue2.path];
1699
1699
  if (fullpath.length === 0) {
1700
1700
  result.errors.push(mapper(issue2));
1701
1701
  continue;
@@ -1734,8 +1734,8 @@ function treeifyError(error63, mapper = (issue2) => issue2.message) {
1734
1734
  }
1735
1735
  function toDotPath(_path) {
1736
1736
  const segs = [];
1737
- const path18 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1738
- for (const seg of path18) {
1737
+ const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1738
+ for (const seg of path19) {
1739
1739
  if (typeof seg === "number")
1740
1740
  segs.push(`[${seg}]`);
1741
1741
  else if (typeof seg === "symbol")
@@ -16664,8 +16664,8 @@ function rewriteKeyNames(ctx) {
16664
16664
  bySchema.set(entry.schema, entry);
16665
16665
  }
16666
16666
  const rewrites = /* @__PURE__ */ new Map();
16667
- for (const record3 of pendingRecords.get(ctx) ?? []) {
16668
- const seen = ctx.seen.get(record3);
16667
+ for (const record4 of pendingRecords.get(ctx) ?? []) {
16668
+ const seen = ctx.seen.get(record4);
16669
16669
  const names = (seen?.def ?? seen?.schema)?.propertyNames;
16670
16670
  if (!names || names === true || rewrites.has(names))
16671
16671
  continue;
@@ -18873,13 +18873,13 @@ function resolveRef(ref, ctx) {
18873
18873
  if (!ref.startsWith("#")) {
18874
18874
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
18875
18875
  }
18876
- const path18 = ref.slice(1).split("/").filter(Boolean);
18877
- if (path18.length === 0) {
18876
+ const path19 = ref.slice(1).split("/").filter(Boolean);
18877
+ if (path19.length === 0) {
18878
18878
  return ctx.rootSchema;
18879
18879
  }
18880
18880
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
18881
- if (path18[0] === defsKey) {
18882
- const key = path18[1] === void 0 ? void 0 : decodeJSONPointerSegment(path18[1]);
18881
+ if (path19[0] === defsKey) {
18882
+ const key = path19[1] === void 0 ? void 0 : decodeJSONPointerSegment(path19[1]);
18883
18883
  if (!key || !ctx.defs[key]) {
18884
18884
  throw new Error(`Reference not found: ${ref}`);
18885
18885
  }
@@ -19815,6 +19815,8 @@ var harnessIdSchema = opaqueIdSchema.brand();
19815
19815
  var hostThreadIdSchema = opaqueIdSchema.brand();
19816
19816
  var hostTurnIdSchema = opaqueIdSchema.brand();
19817
19817
  var hostItemIdSchema = opaqueIdSchema.brand();
19818
+ var HARNESS_THINKING_OPTION_ID_MAX_LENGTH = 128;
19819
+ var harnessThinkingOptionIdSchema = opaqueIdSchema.max(HARNESS_THINKING_OPTION_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Thinking option ID must use transport-safe characters").brand();
19818
19820
  var hostInteractionIdSchema = opaqueIdSchema.brand();
19819
19821
 
19820
19822
  // ../../shared-contracts/dist/harness-permission-modes.js
@@ -19896,6 +19898,122 @@ var threadHandoffResultSchema = external_exports.object({
19896
19898
  handoff: threadHandoffMetadataSchema
19897
19899
  }).strict();
19898
19900
 
19901
+ // ../../shared-contracts/dist/agent-role.js
19902
+ var roleSlugSchema = external_exports.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/u);
19903
+ var roleModelSchema = external_exports.string().min(1).max(512).refine((value) => !new RegExp("\\p{Cc}", "u").test(value), "Role model must not contain control characters");
19904
+ var roleAccentColorSchema = external_exports.enum(["stone", "rose", "mist", "sage", "amber", "aqua"]);
19905
+ var BUILTIN_ROLE_AVATAR_IDS = [
19906
+ "pm-otter",
19907
+ "frontend-otter",
19908
+ "backend-otter",
19909
+ "reviewer-otter",
19910
+ "idea-otter",
19911
+ "researcher-otter",
19912
+ "writer-otter",
19913
+ "architect-otter",
19914
+ "debugger-otter",
19915
+ "tester-otter",
19916
+ "classic-otter",
19917
+ "ops-otter",
19918
+ "security-otter",
19919
+ "audio-otter",
19920
+ "scholar-otter",
19921
+ "data-otter"
19922
+ ];
19923
+ var builtinRoleAvatarSchema = external_exports.templateLiteral([
19924
+ "builtin:",
19925
+ external_exports.enum(BUILTIN_ROLE_AVATAR_IDS)
19926
+ ]);
19927
+ var ROLE_AVATAR_FILENAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}\.(png|jpg|jpeg|webp)$/u;
19928
+ var customRoleAvatarSchema = external_exports.templateLiteral([
19929
+ "custom:",
19930
+ external_exports.string().regex(ROLE_AVATAR_FILENAME_PATTERN)
19931
+ ]);
19932
+ var catalogRoleAvatarSchema = external_exports.templateLiteral([
19933
+ "catalog:",
19934
+ external_exports.string().regex(ROLE_AVATAR_FILENAME_PATTERN)
19935
+ ]);
19936
+ var roleAvatarSchema = external_exports.union([builtinRoleAvatarSchema, customRoleAvatarSchema]);
19937
+ var roleCatalogAvatarSchema = external_exports.union([builtinRoleAvatarSchema, catalogRoleAvatarSchema]);
19938
+ var saveRoleAvatarSchema = external_exports.union([roleAvatarSchema, catalogRoleAvatarSchema]);
19939
+ var httpsUrlSchema = external_exports.string().url().max(2048).refine((value) => /^https:\/\//i.test(value), "URL must use https://");
19940
+ var localizedRoleTextSchema = external_exports.object({
19941
+ en: external_exports.string().trim().min(1).max(2e3),
19942
+ "zh-CN": external_exports.string().trim().min(1).max(2e3)
19943
+ });
19944
+ var roleCatalogEntrySchema = external_exports.object({
19945
+ slug: roleSlugSchema,
19946
+ name: localizedRoleTextSchema,
19947
+ description: localizedRoleTextSchema,
19948
+ avatar: roleCatalogAvatarSchema,
19949
+ accentColor: roleAccentColorSchema,
19950
+ recommendedHarnessId: harnessIdSchema.optional(),
19951
+ author: external_exports.string().trim().min(1).max(128),
19952
+ authorUrl: httpsUrlSchema.optional(),
19953
+ sourceUrl: httpsUrlSchema.optional(),
19954
+ license: external_exports.string().trim().min(1).max(64).optional(),
19955
+ official: external_exports.boolean().optional(),
19956
+ instructions: external_exports.string().trim().min(1).max(1e5),
19957
+ updatedAt: external_exports.iso.datetime()
19958
+ });
19959
+ var roleCatalogDocumentSchema = external_exports.object({
19960
+ formatVersion: external_exports.literal(1),
19961
+ generatedAt: external_exports.iso.datetime(),
19962
+ roles: external_exports.array(roleCatalogEntrySchema)
19963
+ });
19964
+ var roleIdentitySchema = external_exports.object({
19965
+ slug: roleSlugSchema,
19966
+ name: external_exports.string().refine((name) => name.trim().length > 0),
19967
+ avatar: roleAvatarSchema,
19968
+ accentColor: roleAccentColorSchema
19969
+ });
19970
+ var threadRoleSnapshotSchema = roleIdentitySchema.readonly();
19971
+ var agentRoleSchema = roleIdentitySchema.extend({
19972
+ description: external_exports.string(),
19973
+ harnessId: harnessIdSchema,
19974
+ model: roleModelSchema.optional(),
19975
+ thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
19976
+ instructions: external_exports.string(),
19977
+ updatedAt: external_exports.iso.datetime()
19978
+ });
19979
+ var saveAgentRoleInputSchema = agentRoleSchema.omit({ updatedAt: true, avatar: true }).extend({ avatar: saveRoleAvatarSchema }).partial({ slug: true });
19980
+ var ROLES_LIST_METHOD = "codexhost/roles/list";
19981
+ var ROLES_GET_METHOD = "codexhost/roles/get";
19982
+ var ROLES_SAVE_METHOD = "codexhost/roles/save";
19983
+ var ROLES_DELETE_METHOD = "codexhost/roles/delete";
19984
+ var ROLES_CATALOG_METHOD = "codexhost/roles/catalog";
19985
+ var ROLES_LIKE_METHOD = "codexhost/roles/like";
19986
+ var ROLE_LIKES_MAX_PER_ROLE = 5;
19987
+ var rolesListParamsSchema = external_exports.object({
19988
+ locale: external_exports.string().trim().min(1).max(64).optional()
19989
+ });
19990
+ var rolesListResultSchema = external_exports.object({ roles: external_exports.array(agentRoleSchema) });
19991
+ var rolesGetParamsSchema = external_exports.object({ slug: roleSlugSchema });
19992
+ var rolesGetResultSchema = external_exports.object({ role: agentRoleSchema.nullable() });
19993
+ var rolesSaveResultSchema = external_exports.object({ role: agentRoleSchema });
19994
+ var rolesDeleteResultSchema = external_exports.object({ deleted: external_exports.boolean() });
19995
+ var rolesCatalogParamsSchema = external_exports.object({
19996
+ refresh: external_exports.boolean().optional()
19997
+ });
19998
+ var rolesCatalogResultSchema = external_exports.object({
19999
+ roles: external_exports.array(roleCatalogEntrySchema),
20000
+ fetchedAt: external_exports.iso.datetime(),
20001
+ likes: external_exports.record(roleSlugSchema, external_exports.number().int().nonnegative()).optional(),
20002
+ myLikes: external_exports.record(roleSlugSchema, external_exports.number().int().min(0).max(ROLE_LIKES_MAX_PER_ROLE)).optional(),
20003
+ stale: external_exports.boolean().optional(),
20004
+ error: external_exports.string().optional()
20005
+ });
20006
+ var rolesLikeParamsSchema = external_exports.object({
20007
+ slug: roleSlugSchema
20008
+ });
20009
+ var rolesLikeResultSchema = external_exports.object({
20010
+ slug: roleSlugSchema,
20011
+ likes: external_exports.number().int().nonnegative(),
20012
+ myLikes: external_exports.number().int().min(0).max(ROLE_LIKES_MAX_PER_ROLE),
20013
+ maxLikes: external_exports.literal(ROLE_LIKES_MAX_PER_ROLE),
20014
+ limitReached: external_exports.boolean().optional()
20015
+ });
20016
+
19899
20017
  // ../../shared-contracts/dist/thread-usage.js
19900
20018
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
19901
20019
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -20077,7 +20195,6 @@ var threadUsageInspectionSchema = external_exports.object({
20077
20195
  // ../../shared-contracts/dist/harness-models.js
20078
20196
  var HARNESS_MODEL_REF_MAX_LENGTH = 512;
20079
20197
  var HARNESS_MODEL_LABEL_MAX_LENGTH = 256;
20080
- var HARNESS_THINKING_OPTION_ID_MAX_LENGTH = 128;
20081
20198
  var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
20082
20199
  var nonBlankTextSchema3 = external_exports.string().refine((value) => value.trim().length > 0, {
20083
20200
  message: "Value must not be empty or whitespace"
@@ -20091,7 +20208,6 @@ var harnessModelRefSchema = external_exports.object({
20091
20208
  function sameHarnessModelRef(left, right) {
20092
20209
  return left?.id === right?.id && left?.serviceTier === right?.serviceTier;
20093
20210
  }
20094
- var harnessThinkingOptionIdSchema = nonBlankTextSchema3.max(HARNESS_THINKING_OPTION_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Thinking option ID must use transport-safe characters").brand();
20095
20211
  var harnessResolvedModelLabelSchema = nonBlankTextSchema3.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
20096
20212
  var harnessThinkingOptionSchema = external_exports.object({
20097
20213
  id: harnessThinkingOptionIdSchema,
@@ -20304,8 +20420,10 @@ var codexThreadInspectionSchema = external_exports.object({
20304
20420
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
20305
20421
  history: harnessHistoryCapabilitiesSchema.optional(),
20306
20422
  supportsThreadReferences: external_exports.literal(true).optional(),
20307
- handoff: threadHandoffMetadataSchema.optional()
20308
- }).strict();
20423
+ handoff: threadHandoffMetadataSchema.optional(),
20424
+ roleSnapshot: threadRoleSnapshotSchema.optional(),
20425
+ nativeSessionRef: external_exports.never().optional()
20426
+ });
20309
20427
  var externalThreadInspectionSchema = external_exports.object({
20310
20428
  owner: external_exports.literal("external"),
20311
20429
  harnessId: nonBlankTextSchema3.max(256),
@@ -20320,8 +20438,10 @@ var externalThreadInspectionSchema = external_exports.object({
20320
20438
  history: harnessHistoryCapabilitiesSchema,
20321
20439
  usage: threadUsageSnapshotSchema.optional(),
20322
20440
  handoff: threadHandoffMetadataSchema.optional(),
20441
+ roleSnapshot: threadRoleSnapshotSchema.optional(),
20442
+ nativeSessionRef: external_exports.never().optional(),
20323
20443
  locked: external_exports.literal(true)
20324
- }).strict();
20444
+ });
20325
20445
  var threadInspectionSchema = external_exports.discriminatedUnion("owner", [
20326
20446
  codexThreadInspectionSchema,
20327
20447
  externalThreadInspectionSchema
@@ -20564,7 +20684,7 @@ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("ty
20564
20684
  default: external_exports.string().optional()
20565
20685
  })
20566
20686
  ]).superRefine((field2, ctx) => {
20567
- const issue2 = (path18, message) => ctx.addIssue({ code: "custom", path: [path18], message });
20687
+ const issue2 = (path19, message) => ctx.addIssue({ code: "custom", path: [path19], message });
20568
20688
  if (field2.type === "number" || field2.type === "range") {
20569
20689
  const { min = -Infinity, max = Infinity, default: value } = field2;
20570
20690
  if (min > max)
@@ -20670,16 +20790,16 @@ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id3) => !reservedNa
20670
20790
  var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
20671
20791
  var hostExtensionDigestSchema = desktopExtensionHashSchema;
20672
20792
  var hostExtensionActivationIdSchema = external_exports.uuid();
20673
- var hostExtensionResourcePathSchema = pluginRelativeResourceSchema.refine((resource) => !/[\x00-\x1f\x7f<>"|*]/u.test(resource) && resource.split("/").every((part) => !/[. ]$/u.test(part) && !reservedName.test(part)), "Expected a portable relative resource path").refine((path18) => path18.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
20793
+ var hostExtensionResourcePathSchema = pluginRelativeResourceSchema.refine((resource) => !/[\x00-\x1f\x7f<>"|*]/u.test(resource) && resource.split("/").every((part) => !/[. ]$/u.test(part) && !reservedName.test(part)), "Expected a portable relative resource path").refine((path19) => path19.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
20674
20794
  var legacy = desktopExtensionManifestSchema.shape;
20675
20795
  var localized = (max, min = 0) => external_exports.strictObject({
20676
20796
  en: external_exports.string().trim().min(min).max(max),
20677
20797
  "zh-CN": external_exports.string().trim().min(min).max(max)
20678
20798
  });
20679
- var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path18) => path18.endsWith(suffix), `Expected a ${suffix} file`);
20799
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path19) => path19.endsWith(suffix), `Expected a ${suffix} file`);
20680
20800
  var moduleEntry = resourceWithSuffix(".mjs");
20681
20801
  var style = resourceWithSuffix(".css").optional();
20682
- var hostExtensionCanonicalPath = (path18) => path18.normalize("NFC").toLowerCase();
20802
+ var hostExtensionCanonicalPath = (path19) => path19.normalize("NFC").toLowerCase();
20683
20803
  var hostExtensionManifestV2Schema = external_exports.strictObject({
20684
20804
  manifestVersion: external_exports.literal(2),
20685
20805
  id: hostExtensionIdSchema,
@@ -20689,8 +20809,8 @@ var hostExtensionManifestV2Schema = external_exports.strictObject({
20689
20809
  details: localized(16384).optional(),
20690
20810
  author: legacy.author,
20691
20811
  repository: legacy.repository,
20692
- icon: legacy.icon.refine((path18) => path18 === void 0 || hostExtensionResourcePathSchema.safeParse(path18).success),
20693
- screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path18) => hostExtensionResourcePathSchema.safeParse(path18).success)),
20812
+ icon: legacy.icon.refine((path19) => path19 === void 0 || hostExtensionResourcePathSchema.safeParse(path19).success),
20813
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path19) => hostExtensionResourcePathSchema.safeParse(path19).success)),
20694
20814
  categories: legacy.categories,
20695
20815
  settingsSchema: legacy.settingsSchema,
20696
20816
  slots: legacy.slots.removeDefault().optional(),
@@ -20724,6 +20844,9 @@ var hostExtensionBackendMethodSchema = desktopExtensionBackendMethodSchema;
20724
20844
  // ../../shared-contracts/dist/thread-tree-watch.js
20725
20845
  var THREAD_TREE_MAX_NODES = 5e3;
20726
20846
  var threadTreeStatusSchema = external_exports.enum(["running", "waiting", "idle", "unknown"]);
20847
+ var threadTreeDelegationSchema = external_exports.object({
20848
+ createdAtMs: external_exports.number().int().nonnegative()
20849
+ });
20727
20850
  var threadTreeHandoffSchema = external_exports.strictObject({
20728
20851
  sourceThreadId: hostThreadIdSchema,
20729
20852
  createdAtMs: external_exports.number().int().nonnegative()
@@ -20735,13 +20858,14 @@ var threadTreeNodeSchema = external_exports.strictObject({
20735
20858
  archived: external_exports.boolean(),
20736
20859
  updatedAtMs: external_exports.number().int().nonnegative().optional()
20737
20860
  });
20738
- var threadTreeSnapshotSchema = external_exports.strictObject({
20861
+ var threadTreeSnapshotSchema = external_exports.object({
20739
20862
  revision: external_exports.int().nonnegative(),
20740
20863
  parents: external_exports.record(hostThreadIdSchema, hostThreadIdSchema),
20864
+ delegations: external_exports.record(hostThreadIdSchema, threadTreeDelegationSchema).optional(),
20741
20865
  handoffs: external_exports.record(hostThreadIdSchema, threadTreeHandoffSchema).optional(),
20742
20866
  nodes: external_exports.record(hostThreadIdSchema, threadTreeNodeSchema),
20743
20867
  truncated: external_exports.boolean()
20744
- }).refine((snapshot) => Object.keys(snapshot.nodes).length <= THREAD_TREE_MAX_NODES, "Too many Thread tree nodes").refine(({ parents, handoffs, nodes }) => Object.entries(parents).every(([child, parent]) => Object.hasOwn(nodes, child) && Object.hasOwn(nodes, parent)) && Object.entries(handoffs ?? {}).every(([target2, { sourceThreadId }]) => Object.hasOwn(nodes, target2) && Object.hasOwn(nodes, sourceThreadId)), "Missing Thread tree node");
20868
+ }).refine((snapshot) => Object.keys(snapshot.nodes).length <= THREAD_TREE_MAX_NODES, "Too many Thread tree nodes").refine(({ parents, handoffs, nodes }) => Object.entries(parents).every(([child, parent]) => Object.hasOwn(nodes, child) && Object.hasOwn(nodes, parent)) && Object.entries(handoffs ?? {}).every(([target2, { sourceThreadId }]) => Object.hasOwn(nodes, target2) && Object.hasOwn(nodes, sourceThreadId)), "Missing Thread tree node").refine(({ parents, delegations }) => Object.keys(delegations ?? {}).every((child) => Object.hasOwn(parents, child)), "Delegation metadata requires a matching parent edge");
20745
20869
  var subscriptionId = external_exports.string().min(1).max(128);
20746
20870
  var threadTreeWatchParamsSchema = external_exports.strictObject({});
20747
20871
  var threadTreeUnwatchParamsSchema = external_exports.strictObject({ subscriptionId });
@@ -20812,7 +20936,7 @@ var active = {
20812
20936
  digest: hostExtensionDigestSchema
20813
20937
  };
20814
20938
  var optionalActivation = { ...id, activationId: active.activationId.optional() };
20815
- var filePath = external_exports.string().min(1).max(4096).refine((path18) => /^(?:\/|[a-z]:[/\\])/iu.test(path18) && !path18.includes("\0") && !path18.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
20939
+ var filePath = external_exports.string().min(1).max(4096).refine((path19) => /^(?:\/|[a-z]:[/\\])/iu.test(path19) && !path19.includes("\0") && !path19.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
20816
20940
  var gitRef = external_exports.string().min(1).max(256).refine((ref) => ref.split("/").every((part) => part && /^[a-z0-9_.-]+$/iu.test(part) && part !== "." && part !== ".."), "Invalid GitHub ref");
20817
20941
  function base643(maxBytes) {
20818
20942
  return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
@@ -20888,6 +21012,7 @@ var HOST_EXTENSIONS_RPC = {
20888
21012
  snapshot: "codexhost/extensions/snapshot",
20889
21013
  catalog: "codexhost/extensions/catalog",
20890
21014
  catalogIcon: "codexhost/extensions/catalogIcon",
21015
+ catalogScreenshot: "codexhost/extensions/catalogScreenshot",
20891
21016
  install: "codexhost/extensions/install",
20892
21017
  update: "codexhost/extensions/update",
20893
21018
  enable: "codexhost/extensions/enable",
@@ -20924,6 +21049,11 @@ var hostExtensionsCatalogIconResultSchema = external_exports.strictObject({
20924
21049
  mimeType: external_exports.enum(["image/png", "image/jpeg", "image/webp"]),
20925
21050
  base64: base643(DESKTOP_EXTENSION_ICON_MAX_BYTES)
20926
21051
  });
21052
+ var hostExtensionCatalogScreenshotIndexSchema = external_exports.int().min(0).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT - 1);
21053
+ var hostExtensionsCatalogScreenshotResultSchema = external_exports.strictObject({
21054
+ mimeType: external_exports.enum(["image/png", "image/jpeg", "image/webp"]),
21055
+ base64: base643(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)
21056
+ });
20927
21057
  var hostExtensionSettingsSchema = external_exports.strictObject({
20928
21058
  settingsRevision: hostExtensionRevisionSchema,
20929
21059
  values: jsonObjectSchema
@@ -20942,6 +21072,10 @@ var hostExtensionsRpcSchemas = {
20942
21072
  params: external_exports.strictObject({ ...id }),
20943
21073
  result: hostExtensionsCatalogIconResultSchema
20944
21074
  },
21075
+ [HOST_EXTENSIONS_RPC.catalogScreenshot]: {
21076
+ params: external_exports.strictObject({ ...id, index: hostExtensionCatalogScreenshotIndexSchema }),
21077
+ result: hostExtensionsCatalogScreenshotResultSchema
21078
+ },
20945
21079
  [HOST_EXTENSIONS_RPC.install]: {
20946
21080
  params: external_exports.strictObject({ source: hostExtensionInstallSourceSchema }),
20947
21081
  result: installationResult
@@ -20999,6 +21133,206 @@ var hostExtensionsRpcSchemas = {
20999
21133
  }
21000
21134
  };
21001
21135
 
21136
+ // ../../shared-contracts/dist/group-chat.js
21137
+ var DEFAULT_GROUP_MAX_AGENT_HOPS = 5;
21138
+ var MAX_GROUP_AGENT_HOPS = 20;
21139
+ var remoteGroupRoomIdSchema = external_exports.string().regex(/^remote:[A-Za-z0-9_-]{8,512}$/u);
21140
+ var groupRoomIdSchema = external_exports.union([external_exports.uuidv4(), remoteGroupRoomIdSchema]);
21141
+ var groupMemberIdSchema = external_exports.uuidv4();
21142
+ var groupMemberHandleSchema = external_exports.string().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u);
21143
+ var groupUnmentionedPolicySchema = external_exports.enum(["none", "last_speaker", "all"]);
21144
+ var groupMemberStatusSchema = external_exports.enum(["active", "muted", "removed"]);
21145
+ var nonnegativeInteger = external_exports.int().nonnegative();
21146
+ var positiveInteger = external_exports.int().positive();
21147
+ var maxAgentHopsSchema = positiveInteger.max(MAX_GROUP_AGENT_HOPS);
21148
+ var nonblankString = external_exports.string().refine((value) => value.trim().length > 0);
21149
+ var timestamp = external_exports.iso.datetime();
21150
+ var optionalMemberEdits = {
21151
+ handle: groupMemberHandleSchema.optional(),
21152
+ displayName: nonblankString.optional(),
21153
+ note: external_exports.string().optional()
21154
+ };
21155
+ var groupMemberSchema = external_exports.object({
21156
+ memberId: groupMemberIdSchema,
21157
+ threadId: hostThreadIdSchema,
21158
+ handle: groupMemberHandleSchema,
21159
+ displayName: nonblankString,
21160
+ note: external_exports.string().optional(),
21161
+ roleSlug: roleSlugSchema.optional(),
21162
+ roleSnapshot: threadRoleSnapshotSchema.optional(),
21163
+ harnessId: harnessIdSchema,
21164
+ status: groupMemberStatusSchema,
21165
+ joinedAtSeq: nonnegativeInteger,
21166
+ lastDeliveredSeq: nonnegativeInteger,
21167
+ lastRosterVersion: nonnegativeInteger,
21168
+ createdAt: timestamp
21169
+ });
21170
+ var groupRoomRemoteHostSchema = external_exports.object({
21171
+ hostId: nonblankString,
21172
+ displayName: nonblankString,
21173
+ state: nonblankString.optional(),
21174
+ color: external_exports.string().optional(),
21175
+ filePreview: external_exports.boolean().optional()
21176
+ });
21177
+ var groupRoomSchema = external_exports.object({
21178
+ roomId: groupRoomIdSchema,
21179
+ title: nonblankString,
21180
+ defaultCwd: nonblankString,
21181
+ unmentionedPolicy: groupUnmentionedPolicySchema.default("none"),
21182
+ allowAgentMentions: external_exports.boolean().default(true),
21183
+ maxAgentHops: maxAgentHopsSchema.default(DEFAULT_GROUP_MAX_AGENT_HOPS),
21184
+ lastSeq: nonnegativeInteger,
21185
+ lastSpeakerMemberId: groupMemberIdSchema.optional(),
21186
+ rosterVersion: nonnegativeInteger,
21187
+ humanEpoch: nonnegativeInteger,
21188
+ relayPaused: external_exports.boolean(),
21189
+ pinned: external_exports.boolean(),
21190
+ createdAt: timestamp,
21191
+ updatedAt: timestamp,
21192
+ members: external_exports.array(groupMemberSchema),
21193
+ remote: groupRoomRemoteHostSchema.optional()
21194
+ }).superRefine(({ members: members2 }, context) => {
21195
+ const handles = /* @__PURE__ */ new Set();
21196
+ for (const [index, { handle, status }] of members2.entries()) {
21197
+ if (status === "removed")
21198
+ continue;
21199
+ if (handles.has(handle)) {
21200
+ context.addIssue({
21201
+ code: "custom",
21202
+ path: ["members", index, "handle"],
21203
+ message: "Handle must be unique among non-removed members"
21204
+ });
21205
+ }
21206
+ handles.add(handle);
21207
+ }
21208
+ });
21209
+ var groupAttachmentSchema = external_exports.object({
21210
+ kind: external_exports.enum(["image", "file"]),
21211
+ attachmentId: nonblankString.max(256),
21212
+ name: nonblankString.max(256),
21213
+ path: nonblankString.max(4096),
21214
+ bytes: nonnegativeInteger,
21215
+ mediaType: nonblankString.max(128).optional(),
21216
+ width: positiveInteger.optional(),
21217
+ height: positiveInteger.optional()
21218
+ });
21219
+ var groupMessageSchema = external_exports.object({
21220
+ roomId: groupRoomIdSchema,
21221
+ seq: positiveInteger,
21222
+ messageId: nonblankString,
21223
+ senderType: external_exports.enum(["user", "agent", "system"]),
21224
+ senderMemberId: groupMemberIdSchema.optional(),
21225
+ senderHandle: groupMemberHandleSchema.optional(),
21226
+ senderName: external_exports.string().optional(),
21227
+ senderThreadId: hostThreadIdSchema.optional(),
21228
+ sourceTurnId: nonblankString.optional(),
21229
+ replyToSeq: positiveInteger.optional(),
21230
+ content: external_exports.string(),
21231
+ attachments: external_exports.array(groupAttachmentSchema).max(12).optional(),
21232
+ mentionedMemberIds: external_exports.array(groupMemberIdSchema),
21233
+ mentionAll: external_exports.boolean().optional(),
21234
+ hopCount: nonnegativeInteger,
21235
+ createdAt: timestamp
21236
+ });
21237
+ var newThreadOptions = {
21238
+ ...optionalMemberEdits,
21239
+ model: roleModelSchema.optional(),
21240
+ thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
21241
+ worktree: external_exports.boolean().optional()
21242
+ };
21243
+ var groupCreateMemberInputSchema = external_exports.discriminatedUnion("kind", [
21244
+ external_exports.strictObject({ kind: external_exports.literal("role"), roleSlug: roleSlugSchema, ...newThreadOptions }),
21245
+ external_exports.strictObject({ kind: external_exports.literal("harness"), harnessId: harnessIdSchema, ...newThreadOptions }),
21246
+ external_exports.strictObject({
21247
+ kind: external_exports.literal("existing"),
21248
+ threadId: hostThreadIdSchema,
21249
+ ...optionalMemberEdits,
21250
+ includeRecentHistory: external_exports.boolean().default(true).optional()
21251
+ })
21252
+ ]);
21253
+ var GROUPS_LIST_METHOD = "codexhost/groups/list";
21254
+ var GROUPS_GET_METHOD = "codexhost/groups/get";
21255
+ var GROUPS_CREATE_METHOD = "codexhost/groups/create";
21256
+ var GROUPS_UPDATE_METHOD = "codexhost/groups/update";
21257
+ var GROUPS_DELETE_METHOD = "codexhost/groups/delete";
21258
+ var GROUPS_ADD_MEMBER_METHOD = "codexhost/groups/member/add";
21259
+ var GROUPS_UPDATE_MEMBER_METHOD = "codexhost/groups/member/update";
21260
+ var GROUPS_REMOVE_MEMBER_METHOD = "codexhost/groups/member/remove";
21261
+ var GROUPS_POST_MESSAGE_METHOD = "codexhost/groups/message/post";
21262
+ var GROUPS_READ_MESSAGES_METHOD = "codexhost/groups/messages/read";
21263
+ var roomIdentity = { roomId: groupRoomIdSchema };
21264
+ var memberIdentity = { ...roomIdentity, memberId: groupMemberIdSchema };
21265
+ var roomEdits = {
21266
+ title: nonblankString.optional(),
21267
+ unmentionedPolicy: groupUnmentionedPolicySchema.optional(),
21268
+ allowAgentMentions: external_exports.boolean().optional(),
21269
+ maxAgentHops: maxAgentHopsSchema.optional()
21270
+ };
21271
+ var groupsListParamsSchema = external_exports.strictObject({});
21272
+ var groupsListResultSchema = external_exports.object({ rooms: external_exports.array(groupRoomSchema) });
21273
+ var groupsGetParamsSchema = external_exports.strictObject({
21274
+ ...roomIdentity,
21275
+ limit: positiveInteger.optional(),
21276
+ beforeSeq: positiveInteger.optional()
21277
+ });
21278
+ var groupsGetResultSchema = external_exports.object({
21279
+ room: groupRoomSchema.nullable(),
21280
+ messages: external_exports.array(groupMessageSchema),
21281
+ hasMore: external_exports.boolean()
21282
+ });
21283
+ var groupsCreateParamsSchema = external_exports.strictObject({
21284
+ ...roomEdits,
21285
+ defaultCwd: nonblankString,
21286
+ members: external_exports.array(groupCreateMemberInputSchema)
21287
+ });
21288
+ var groupsCreateResultSchema = external_exports.object({ room: groupRoomSchema });
21289
+ var groupsUpdateParamsSchema = external_exports.strictObject({
21290
+ ...roomIdentity,
21291
+ ...roomEdits,
21292
+ pinned: external_exports.boolean().optional(),
21293
+ relayPaused: external_exports.boolean().optional()
21294
+ });
21295
+ var groupsDeleteParamsSchema = external_exports.strictObject(roomIdentity);
21296
+ var groupsDeleteResultSchema = external_exports.object({ deleted: external_exports.boolean() });
21297
+ var groupsAddMemberParamsSchema = external_exports.strictObject({
21298
+ ...roomIdentity,
21299
+ member: groupCreateMemberInputSchema
21300
+ });
21301
+ var groupsAddMemberResultSchema = external_exports.object({
21302
+ room: groupRoomSchema,
21303
+ member: groupMemberSchema
21304
+ });
21305
+ var groupsUpdateMemberParamsSchema = external_exports.strictObject({
21306
+ ...memberIdentity,
21307
+ ...optionalMemberEdits,
21308
+ status: groupMemberStatusSchema.optional()
21309
+ });
21310
+ var groupsRemoveMemberParamsSchema = external_exports.strictObject(memberIdentity);
21311
+ var groupsPostMessageParamsSchema = external_exports.strictObject({
21312
+ ...roomIdentity,
21313
+ content: external_exports.string().max(64e3),
21314
+ attachments: external_exports.array(groupAttachmentSchema).max(12).optional(),
21315
+ replyToSeq: positiveInteger.optional(),
21316
+ targetMemberIds: external_exports.array(groupMemberIdSchema).optional(),
21317
+ mentionAll: external_exports.boolean().optional()
21318
+ }).refine((value) => value.content.trim().length > 0 || (value.attachments?.length ?? 0) > 0, "Message content or at least one attachment is required");
21319
+ var groupsPostMessageResultSchema = external_exports.object({
21320
+ room: groupRoomSchema,
21321
+ message: groupMessageSchema,
21322
+ awakenedMemberIds: external_exports.array(groupMemberIdSchema)
21323
+ });
21324
+ var groupsReadMessagesParamsSchema = external_exports.strictObject({
21325
+ ...roomIdentity,
21326
+ fromSeq: positiveInteger.optional(),
21327
+ toSeq: positiveInteger.optional(),
21328
+ limit: positiveInteger.optional()
21329
+ });
21330
+ var groupsReadMessagesResultSchema = external_exports.object({
21331
+ ...roomIdentity,
21332
+ messages: external_exports.array(groupMessageSchema),
21333
+ totalSeq: nonnegativeInteger
21334
+ });
21335
+
21002
21336
  // ../../shared-contracts/dist/thread-archive-confirm.js
21003
21337
  var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
21004
21338
  var threadArchiveConfirmParamsSchema = external_exports.object({ threadId: hostThreadIdSchema }).strict();
@@ -21169,6 +21503,22 @@ var clientThreadSectionMutationResultSchema = external_exports.discriminatedUnio
21169
21503
  ]);
21170
21504
  var CLIENT_CHANNEL_METHODS = [
21171
21505
  "codexhost/skills/list",
21506
+ ROLES_LIST_METHOD,
21507
+ ROLES_GET_METHOD,
21508
+ ROLES_SAVE_METHOD,
21509
+ ROLES_DELETE_METHOD,
21510
+ ROLES_CATALOG_METHOD,
21511
+ ROLES_LIKE_METHOD,
21512
+ GROUPS_LIST_METHOD,
21513
+ GROUPS_GET_METHOD,
21514
+ GROUPS_CREATE_METHOD,
21515
+ GROUPS_UPDATE_METHOD,
21516
+ GROUPS_DELETE_METHOD,
21517
+ GROUPS_ADD_MEMBER_METHOD,
21518
+ GROUPS_UPDATE_MEMBER_METHOD,
21519
+ GROUPS_REMOVE_MEMBER_METHOD,
21520
+ GROUPS_POST_MESSAGE_METHOD,
21521
+ GROUPS_READ_MESSAGES_METHOD,
21172
21522
  "codexhost/voice/status",
21173
21523
  "codexhost/voice/transcribe",
21174
21524
  "codexhost/harness/display-settings/get",
@@ -21330,6 +21680,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
21330
21680
  }),
21331
21681
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
21332
21682
  external_exports.object({ type: external_exports.literal("sections-changed"), cursor: clientChannelCursorSchema }),
21683
+ external_exports.object({
21684
+ type: external_exports.literal("groups-changed"),
21685
+ cursor: clientChannelCursorSchema,
21686
+ roomId: external_exports.string().optional()
21687
+ }),
21333
21688
  external_exports.object({
21334
21689
  type: external_exports.literal("preferences-changed"),
21335
21690
  cursor: clientChannelCursorSchema,
@@ -21463,6 +21818,7 @@ var clientThreadSnapshotSchema = external_exports.object({
21463
21818
  status: external_exports.object({ type: external_exports.string() }).passthrough(),
21464
21819
  name: external_exports.string().nullable().optional(),
21465
21820
  preview: external_exports.string().optional(),
21821
+ roleSnapshot: threadRoleSnapshotSchema.optional(),
21466
21822
  codexhostImportSource: clientThreadImportSourceSchema.optional(),
21467
21823
  turns: external_exports.array(clientTurnSchema).length(0)
21468
21824
  }).passthrough(),
@@ -22490,6 +22846,10 @@ var webToolOutputPreviewSchema = external_exports.object({
22490
22846
  bytes: external_exports.number().int().nonnegative()
22491
22847
  });
22492
22848
 
22849
+ // ../../shared-contracts/dist/desktop-shell.js
22850
+ var desktopShellOpenParamsSchema = external_exports.strictObject({});
22851
+ var desktopShellOpenResultSchema = external_exports.strictObject({});
22852
+
22493
22853
  // ../../shared-contracts/dist/console.js
22494
22854
  var consoleAnnouncementSchema = external_exports.strictObject({
22495
22855
  title: external_exports.string().trim().min(1).max(200),
@@ -23055,7 +23415,7 @@ function desktopImageAttachmentPaths(text3) {
23055
23415
  const context = end < 0 ? text3 : text3.slice(0, end);
23056
23416
  if (!ATTACHED_FILES_HEADING.test(context))
23057
23417
  return [];
23058
- return [...context.matchAll(IMAGE_ATTACHMENT_PATTERN)].map((match) => match[1] ?? "").filter((path18) => path18.length > 0 && !CONTROL_CHARACTER_PATTERN.test(path18));
23418
+ return [...context.matchAll(IMAGE_ATTACHMENT_PATTERN)].map((match) => match[1] ?? "").filter((path19) => path19.length > 0 && !CONTROL_CHARACTER_PATTERN.test(path19));
23059
23419
  }
23060
23420
 
23061
23421
  // ../../shared-contracts/dist/thread-watch-notice.js
@@ -24135,7 +24495,7 @@ var harnessErrorSchema = external_exports.object({
24135
24495
  var harnessSessionStateSchema = external_exports.custom((value) => {
24136
24496
  if (!value || typeof value !== "object" || Array.isArray(value))
24137
24497
  return false;
24138
- const record3 = value;
24498
+ const record4 = value;
24139
24499
  const allowed2 = /* @__PURE__ */ new Set([
24140
24500
  "nativeRef",
24141
24501
  "effectiveModel",
@@ -24144,12 +24504,12 @@ var harnessSessionStateSchema = external_exports.custom((value) => {
24144
24504
  "availableThinkingOptions",
24145
24505
  "effectivePermissionModeId"
24146
24506
  ]);
24147
- if (Object.keys(record3).some((key) => !allowed2.has(key)))
24507
+ if (Object.keys(record4).some((key) => !allowed2.has(key)))
24148
24508
  return false;
24149
- if (record3.nativeRef !== void 0 && !nativeSessionRefSchema.safeParse(record3.nativeRef).success) {
24509
+ if (record4.nativeRef !== void 0 && !nativeSessionRefSchema.safeParse(record4.nativeRef).success) {
24150
24510
  return false;
24151
24511
  }
24152
- const { nativeRef: _nativeRef, ...configuration } = record3;
24512
+ const { nativeRef: _nativeRef, ...configuration } = record4;
24153
24513
  void _nativeRef;
24154
24514
  return harnessConfigurationStateSchema.safeParse(configuration).success;
24155
24515
  });
@@ -25277,9 +25637,9 @@ function claudeUsageHistory(entries) {
25277
25637
  }
25278
25638
  const requests = [];
25279
25639
  for (const [id3, { model: model2, usage }] of usages) {
25280
- const record3 = claudeUsageRecord(id3, model2, usage, { historical: true });
25281
- if (record3.kind === "request")
25282
- requests.push(record3.request);
25640
+ const record4 = claudeUsageRecord(id3, model2, usage, { historical: true });
25641
+ if (record4.kind === "request")
25642
+ requests.push(record4.request);
25283
25643
  else
25284
25644
  complete = false;
25285
25645
  }
@@ -25495,8 +25855,8 @@ async function readClaudeUsage(file2, signal) {
25495
25855
  }
25496
25856
  const entries = [];
25497
25857
  for (const [id3, { model: model2, usage, at: at2 }] of messages) {
25498
- const record3 = claudeUsageRecord(id3, model2, usage);
25499
- const entry = record3.kind === "request" && at2 !== null && usageEntryFromRequest(record3.request, at2);
25858
+ const record4 = claudeUsageRecord(id3, model2, usage);
25859
+ const entry = record4.kind === "request" && at2 !== null && usageEntryFromRequest(record4.request, at2);
25500
25860
  if (entry)
25501
25861
  entries.push(withUsageSession(entry, {
25502
25862
  sessionId: text2(sessionId),
@@ -25590,7 +25950,7 @@ function claudePromptCacheIndicators(accountCreditsSupported, lastResponseAtUnix
25590
25950
 
25591
25951
  // dist/claude-code-adapter.js
25592
25952
  import { randomUUID as randomUUID5 } from "node:crypto";
25593
- import path15 from "node:path";
25953
+ import path16 from "node:path";
25594
25954
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
25595
25955
 
25596
25956
  // ../../../node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs
@@ -38987,12 +39347,12 @@ var fJ = T(function(dJ) {
38987
39347
  var _J = T(function(hJ) {
38988
39348
  Object.defineProperty(hJ, "__esModule", { value: true });
38989
39349
  hJ.extendSubschemaMode = hJ.extendSubschemaData = hJ.getSubschema = void 0;
38990
- var os8 = Ie(), mJ = We();
39350
+ var os9 = Ie(), mJ = We();
38991
39351
  function V4e(e, { keyword: t, schemaProp: n, schema: r, schemaPath: o, errSchemaPath: s, topSchemaRef: i }) {
38992
39352
  if (t !== void 0 && r !== void 0) throw Error('both "keyword" and "schema" passed, only one allowed');
38993
39353
  if (t !== void 0) {
38994
39354
  let a = e.schema[t];
38995
- return n === void 0 ? { schema: a, schemaPath: os8._`${e.schemaPath}${os8.getProperty(t)}`, errSchemaPath: `${e.errSchemaPath}/${t}` } : { schema: a[n], schemaPath: os8._`${e.schemaPath}${os8.getProperty(t)}${os8.getProperty(n)}`, errSchemaPath: `${e.errSchemaPath}/${t}/${mJ.escapeFragment(n)}` };
39355
+ return n === void 0 ? { schema: a, schemaPath: os9._`${e.schemaPath}${os9.getProperty(t)}`, errSchemaPath: `${e.errSchemaPath}/${t}` } : { schema: a[n], schemaPath: os9._`${e.schemaPath}${os9.getProperty(t)}${os9.getProperty(n)}`, errSchemaPath: `${e.errSchemaPath}/${t}/${mJ.escapeFragment(n)}` };
38996
39356
  }
38997
39357
  if (r !== void 0) {
38998
39358
  if (o === void 0 || s === void 0 || i === void 0) throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
@@ -39005,11 +39365,11 @@ var _J = T(function(hJ) {
39005
39365
  if (o !== void 0 && n !== void 0) throw Error('both "data" and "dataProp" passed, only one allowed');
39006
39366
  let { gen: a } = t;
39007
39367
  if (n !== void 0) {
39008
- let { errorPath: l, dataPathArr: u, opts: p } = t, f = a.let("data", os8._`${t.data}${os8.getProperty(n)}`, true);
39009
- c(f), e.errorPath = os8.str`${l}${mJ.getErrorPath(n, r, p.jsPropertySyntax)}`, e.parentDataProperty = os8._`${n}`, e.dataPathArr = [...u, e.parentDataProperty];
39368
+ let { errorPath: l, dataPathArr: u, opts: p } = t, f = a.let("data", os9._`${t.data}${os9.getProperty(n)}`, true);
39369
+ c(f), e.errorPath = os9.str`${l}${mJ.getErrorPath(n, r, p.jsPropertySyntax)}`, e.parentDataProperty = os9._`${n}`, e.dataPathArr = [...u, e.parentDataProperty];
39010
39370
  }
39011
39371
  if (o !== void 0) {
39012
- let l = o instanceof os8.Name ? o : a.let("data", o, true);
39372
+ let l = o instanceof os9.Name ? o : a.let("data", o, true);
39013
39373
  if (c(l), i !== void 0) e.propertyName = i;
39014
39374
  }
39015
39375
  if (s) e.dataTypes = s;
@@ -61193,6 +61553,317 @@ var ClaudeBackgroundOccupancy = class {
61193
61553
  }
61194
61554
  };
61195
61555
 
61556
+ // dist/custom-provider-quota.js
61557
+ import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
61558
+ import os3 from "node:os";
61559
+ import path4 from "node:path";
61560
+ var SEAT_QUOTA_PATH = "/quota-api/seats";
61561
+ var KEY_QUOTA_PATH = "/v1/me/quota";
61562
+ var REQUEST_TIMEOUT_MS = 1e4;
61563
+ var SEAT_QUOTA_TIMEOUT_MS = 5e3;
61564
+ var MAX_CUSTOM_PROVIDER_ACCOUNTS = 8;
61565
+ function record3(value) {
61566
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
61567
+ }
61568
+ function trimmedString(value) {
61569
+ if (typeof value !== "string")
61570
+ return void 0;
61571
+ const trimmed = value.trim();
61572
+ return trimmed.length > 0 ? trimmed : void 0;
61573
+ }
61574
+ function finiteNonNegative(value) {
61575
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
61576
+ }
61577
+ function finitePositive(value) {
61578
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
61579
+ }
61580
+ function validResetAt(value) {
61581
+ const text3 = trimmedString(value);
61582
+ return text3 && Number.isFinite(Date.parse(text3)) ? text3 : void 0;
61583
+ }
61584
+ function roundTwoDecimals(value) {
61585
+ return Math.round(value * 100) / 100;
61586
+ }
61587
+ function isOfficialAnthropicHost(hostname3) {
61588
+ const normalized = hostname3.toLowerCase().replace(/\.+$/u, "");
61589
+ return normalized === "anthropic.com" || normalized.endsWith(".anthropic.com");
61590
+ }
61591
+ function parseCustomProviderBaseUrl(baseUrl) {
61592
+ let url2;
61593
+ try {
61594
+ url2 = new URL(baseUrl);
61595
+ } catch {
61596
+ return null;
61597
+ }
61598
+ if (url2.protocol !== "https:" && url2.protocol !== "http:" || !url2.hostname)
61599
+ return null;
61600
+ if (isOfficialAnthropicHost(url2.hostname))
61601
+ return null;
61602
+ return url2;
61603
+ }
61604
+ function customProviderEndpoint(baseUrl, pathname) {
61605
+ const url2 = parseCustomProviderBaseUrl(baseUrl);
61606
+ if (!url2)
61607
+ return null;
61608
+ url2.username = "";
61609
+ url2.password = "";
61610
+ url2.pathname = pathname;
61611
+ url2.search = "";
61612
+ url2.hash = "";
61613
+ return url2.toString();
61614
+ }
61615
+ function claudeConfigDirectory(environment) {
61616
+ const home = environment.HOME || environment.USERPROFILE || os3.homedir();
61617
+ const configured = trimmedString(environment.CLAUDE_CONFIG_DIR);
61618
+ return configured ? path4.resolve(home, configured) : path4.join(home, ".claude");
61619
+ }
61620
+ async function readUserSettingsEnv(environment, signal) {
61621
+ const file2 = path4.join(claudeConfigDirectory(environment), "settings.json");
61622
+ try {
61623
+ signal?.throwIfAborted();
61624
+ if (!(await stat2(file2)).isFile())
61625
+ return {};
61626
+ const text3 = await readFile3(file2, {
61627
+ encoding: "utf8",
61628
+ ...signal ? { signal } : {}
61629
+ });
61630
+ const parsed = JSON.parse(text3);
61631
+ const env = record3(record3(parsed).env);
61632
+ const result = {};
61633
+ for (const [key, value] of Object.entries(env)) {
61634
+ if (typeof value === "string")
61635
+ result[key] = value;
61636
+ }
61637
+ return result;
61638
+ } catch {
61639
+ return {};
61640
+ }
61641
+ }
61642
+ async function readClaudeCustomProviderConfig(environment = process.env, signal) {
61643
+ const settingsEnv = await readUserSettingsEnv(environment, signal);
61644
+ const env = { ...environment, ...settingsEnv };
61645
+ const baseUrl = trimmedString(env.ANTHROPIC_BASE_URL);
61646
+ const apiKey = trimmedString(env.ANTHROPIC_AUTH_TOKEN) ?? trimmedString(env.ANTHROPIC_API_KEY);
61647
+ if (!baseUrl || !apiKey)
61648
+ return null;
61649
+ const parsedUrl = parseCustomProviderBaseUrl(baseUrl);
61650
+ if (!parsedUrl)
61651
+ return null;
61652
+ return {
61653
+ baseUrl,
61654
+ apiKey,
61655
+ hostLabel: parsedUrl.hostname
61656
+ };
61657
+ }
61658
+ function creditsFromWindows(windows) {
61659
+ const [primary, ...others] = windows;
61660
+ if (!primary)
61661
+ return null;
61662
+ const genericPrimary = !primary.scope && (primary.product === "5-hour window" || primary.product === "7-day window");
61663
+ return {
61664
+ usedPercent: primary.usagePercent,
61665
+ periodType: primary.periodType,
61666
+ ...primary.scope ? { scope: primary.scope } : {},
61667
+ ...!genericPrimary ? { label: primary.product } : {},
61668
+ ...primary.used !== void 0 ? { used: primary.used } : {},
61669
+ ...primary.limit !== void 0 ? { limit: primary.limit } : {},
61670
+ ...primary.unit ? { unit: primary.unit } : {},
61671
+ ...primary.resetsAt ? { resetsAt: primary.resetsAt } : {},
61672
+ ...others.length ? {
61673
+ productUsage: others.map(({ product, periodType, scope, usagePercent, used, limit, unit, resetsAt }) => ({
61674
+ product,
61675
+ periodType,
61676
+ ...scope ? { scope } : {},
61677
+ usagePercent,
61678
+ ...used !== void 0 ? { used } : {},
61679
+ ...limit !== void 0 ? { limit } : {},
61680
+ ...unit ? { unit } : {},
61681
+ ...resetsAt ? { resetsAt } : {}
61682
+ }))
61683
+ } : {}
61684
+ };
61685
+ }
61686
+ function readSeatWindow(value, product, periodType, scope) {
61687
+ const window2 = record3(value);
61688
+ const ratio = finiteNonNegative(window2.used);
61689
+ if (ratio === null || ratio > 1)
61690
+ return null;
61691
+ const resetsAt = validResetAt(window2.reset_at);
61692
+ return {
61693
+ product,
61694
+ periodType,
61695
+ ...scope ? { scope: { id: scope, label: scope } } : {},
61696
+ usagePercent: Math.round(ratio * 1e4) / 100,
61697
+ ...resetsAt ? { resetsAt } : {}
61698
+ };
61699
+ }
61700
+ function projectCustomProviderSeatQuota(payload, fallbackLabel) {
61701
+ const data = record3(payload);
61702
+ if (data.object !== "key_seats" || !Array.isArray(data.seats))
61703
+ return [];
61704
+ const baseLabel = trimmedString(data.name) ?? trimmedString(fallbackLabel);
61705
+ const multiSeat = data.seats.length > 1;
61706
+ const accounts = [];
61707
+ for (const [index, entry] of data.seats.entries()) {
61708
+ if (accounts.length >= MAX_CUSTOM_PROVIDER_ACCOUNTS)
61709
+ break;
61710
+ const seat = record3(entry);
61711
+ const windows = [
61712
+ readSeatWindow(seat.w5h, "5-hour window", "five_hour"),
61713
+ readSeatWindow(seat.w7d, "7-day window", "seven_day"),
61714
+ readSeatWindow(seat.opus7d, "Opus · 7-day", "seven_day", "Opus"),
61715
+ readSeatWindow(seat.sonnet7d, "Sonnet · 7-day", "seven_day", "Sonnet"),
61716
+ readSeatWindow(seat.fable7d, "Fable · 7-day", "seven_day", "Fable")
61717
+ ].filter((window2) => window2 !== null);
61718
+ const credits = creditsFromWindows(windows);
61719
+ if (!credits)
61720
+ continue;
61721
+ const seatNo = typeof seat.no === "number" && Number.isSafeInteger(seat.no) && seat.no > 0 ? seat.no : index + 1;
61722
+ const label = multiSeat ? baseLabel ? `${baseLabel} · #${seatNo}` : `#${seatNo}` : baseLabel ?? `#${seatNo}`;
61723
+ const plan = trimmedString(seat.tier);
61724
+ const parsed = harnessAccountSnapshotSchema.safeParse({
61725
+ ...label ? { label: label.slice(0, 256) } : {},
61726
+ ...plan ? { plan: plan.slice(0, 128) } : {},
61727
+ credits
61728
+ });
61729
+ if (parsed.success)
61730
+ accounts.push(parsed.data);
61731
+ }
61732
+ return accounts;
61733
+ }
61734
+ function readCappedUsdWindow(value, product, periodType) {
61735
+ const window2 = record3(value);
61736
+ const limit = finitePositive(window2.limit);
61737
+ const used = finiteNonNegative(window2.used);
61738
+ if (limit === null || used === null)
61739
+ return null;
61740
+ const resetsAt = validResetAt(window2.reset_at);
61741
+ return {
61742
+ product,
61743
+ periodType,
61744
+ usagePercent: Math.min(100, Math.round(used / limit * 1e4) / 100),
61745
+ used: roundTwoDecimals(used),
61746
+ limit: roundTwoDecimals(limit),
61747
+ unit: "USD",
61748
+ ...resetsAt ? { resetsAt } : {}
61749
+ };
61750
+ }
61751
+ function projectCustomProviderKeyQuota(payload, fallbackLabel) {
61752
+ const data = record3(payload);
61753
+ if (data.object !== "api_key_quota")
61754
+ return null;
61755
+ const key = record3(data.key);
61756
+ if (key.expired === true)
61757
+ return null;
61758
+ if (typeof key.status === "string" && key.status !== "active")
61759
+ return null;
61760
+ const label = trimmedString(key.name) ?? trimmedString(fallbackLabel);
61761
+ const windowsMap = record3(data.windows);
61762
+ const windows = [
61763
+ readCappedUsdWindow(windowsMap["5h"], "5-hour window", "five_hour"),
61764
+ readCappedUsdWindow(windowsMap["7d"], "7-day window", "seven_day")
61765
+ ].filter((window2) => window2 !== null);
61766
+ const credits = creditsFromWindows(windows);
61767
+ if (credits) {
61768
+ const parsed2 = harnessAccountSnapshotSchema.safeParse({
61769
+ ...label ? { label: label.slice(0, 256) } : {},
61770
+ credits
61771
+ });
61772
+ return parsed2.success ? parsed2.data : null;
61773
+ }
61774
+ const usd = record3(data.usd);
61775
+ const limit = finitePositive(usd.limit);
61776
+ if (limit === null)
61777
+ return null;
61778
+ const used = finiteNonNegative(usd.used);
61779
+ const remaining = finiteNonNegative(usd.remaining) ?? (used !== null ? Math.max(0, limit - used) : null);
61780
+ if (remaining === null)
61781
+ return null;
61782
+ const parsed = harnessAccountSnapshotSchema.safeParse({
61783
+ ...label ? { label: label.slice(0, 256) } : {},
61784
+ balance: {
61785
+ amount: roundTwoDecimals(remaining),
61786
+ currency: "USD",
61787
+ ...label ? { label: label.slice(0, 128) } : {}
61788
+ }
61789
+ });
61790
+ return parsed.success ? parsed.data : null;
61791
+ }
61792
+ async function fetchJson(url2, apiKey, fetchImpl, signal) {
61793
+ const response = await fetchImpl(url2, {
61794
+ headers: {
61795
+ Authorization: `Bearer ${apiKey}`,
61796
+ Accept: "application/json"
61797
+ },
61798
+ redirect: "error",
61799
+ signal
61800
+ });
61801
+ if (!response.ok) {
61802
+ void response.body?.cancel().catch(() => void 0);
61803
+ return null;
61804
+ }
61805
+ return await response.json();
61806
+ }
61807
+ async function withTimeout(callerSignal, timeoutMs, task) {
61808
+ callerSignal?.throwIfAborted();
61809
+ const controller = new AbortController();
61810
+ let rejectOnAbort;
61811
+ const aborted2 = new Promise((_resolve, reject) => {
61812
+ rejectOnAbort = reject;
61813
+ });
61814
+ const abort = (reason) => {
61815
+ if (!controller.signal.aborted)
61816
+ controller.abort(reason);
61817
+ rejectOnAbort(reason);
61818
+ };
61819
+ const onCallerAbort = () => abort(callerSignal?.reason ?? new Error("Aborted"));
61820
+ callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
61821
+ const timer = setTimeout(() => abort(new Error("Custom Provider quota request timed out")), timeoutMs);
61822
+ timer.unref();
61823
+ const pending = Promise.resolve().then(() => task(controller.signal));
61824
+ void pending.catch(() => void 0);
61825
+ try {
61826
+ return await Promise.race([pending, aborted2]);
61827
+ } finally {
61828
+ clearTimeout(timer);
61829
+ callerSignal?.removeEventListener("abort", onCallerAbort);
61830
+ }
61831
+ }
61832
+ async function fetchClaudeCustomProviderAccounts(input3 = {}) {
61833
+ try {
61834
+ const callerSignal = input3.signal;
61835
+ callerSignal?.throwIfAborted();
61836
+ const deadline = Date.now() + REQUEST_TIMEOUT_MS;
61837
+ const remainingMs = () => Math.max(0, deadline - Date.now());
61838
+ const environment = input3.environment ?? process.env;
61839
+ const config2 = await withTimeout(callerSignal, remainingMs(), (signal) => input3.readConfig ? input3.readConfig(signal) : readClaudeCustomProviderConfig(environment, signal));
61840
+ if (!config2 || callerSignal?.aborted)
61841
+ return [];
61842
+ const fetchImpl = input3.fetch ?? fetch;
61843
+ const seatsUrl = customProviderEndpoint(config2.baseUrl, SEAT_QUOTA_PATH);
61844
+ const seatsBudget = Math.min(SEAT_QUOTA_TIMEOUT_MS, remainingMs());
61845
+ if (seatsUrl && seatsBudget > 0) {
61846
+ const seatsPayload = await withTimeout(callerSignal, seatsBudget, (signal) => fetchJson(seatsUrl, config2.apiKey, fetchImpl, signal)).catch(() => null);
61847
+ if (callerSignal?.aborted)
61848
+ return [];
61849
+ const seats = projectCustomProviderSeatQuota(seatsPayload, config2.hostLabel);
61850
+ if (seats.length > 0)
61851
+ return seats;
61852
+ }
61853
+ const quotaUrl = customProviderEndpoint(config2.baseUrl, KEY_QUOTA_PATH);
61854
+ const quotaBudget = remainingMs();
61855
+ if (!quotaUrl || quotaBudget <= 0 || callerSignal?.aborted)
61856
+ return [];
61857
+ const quotaPayload = await withTimeout(callerSignal, quotaBudget, (signal) => fetchJson(quotaUrl, config2.apiKey, fetchImpl, signal)).catch(() => null);
61858
+ if (callerSignal?.aborted)
61859
+ return [];
61860
+ const account = projectCustomProviderKeyQuota(quotaPayload, config2.hostLabel);
61861
+ return account ? [account] : [];
61862
+ } catch {
61863
+ return [];
61864
+ }
61865
+ }
61866
+
61196
61867
  // dist/ultracode.js
61197
61868
  var CLAUDE_ULTRACODE_MINIMUM_VERSION = "2.1.154";
61198
61869
  var FAILURES = {
@@ -61283,9 +61954,9 @@ function claudeUltracodeUnavailableReason(settings, environment = {}) {
61283
61954
 
61284
61955
  // dist/claude-session-import.js
61285
61956
  import { createReadStream as createReadStream3 } from "node:fs";
61286
- import { opendir, realpath as realpath3, stat as stat2 } from "node:fs/promises";
61287
- import os3 from "node:os";
61288
- import path4 from "node:path";
61957
+ import { opendir, realpath as realpath3, stat as stat3 } from "node:fs/promises";
61958
+ import os4 from "node:os";
61959
+ import path5 from "node:path";
61289
61960
  import { createInterface as createInterface2 } from "node:readline";
61290
61961
 
61291
61962
  // ../../harness-adapter/dist/session-import.js
@@ -61399,8 +62070,8 @@ function userText(message) {
61399
62070
  return text3 && !CLAUDE_INTERNAL_USER_TEXT.test(text3) ? text3 : null;
61400
62071
  }
61401
62072
  function claudeProjectsDirectory2(environment) {
61402
- const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os3.homedir();
61403
- return path4.join(path4.resolve(environment.CLAUDE_CONFIG_DIR ?? path4.join(home, ".claude")), "projects");
62073
+ const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os4.homedir();
62074
+ return path5.join(path5.resolve(environment.CLAUDE_CONFIG_DIR ?? path5.join(home, ".claude")), "projects");
61404
62075
  }
61405
62076
  async function sessionFiles(directory, signal) {
61406
62077
  signal.throwIfAborted();
@@ -61416,7 +62087,7 @@ async function sessionFiles(directory, signal) {
61416
62087
  signal.throwIfAborted();
61417
62088
  if (!project2.isDirectory())
61418
62089
  continue;
61419
- const entries = await opendir(path4.join(directory, project2.name)).catch((error63) => {
62090
+ const entries = await opendir(path5.join(directory, project2.name)).catch((error63) => {
61420
62091
  if (isMissingFileError(error63))
61421
62092
  return null;
61422
62093
  throw error63;
@@ -61426,17 +62097,17 @@ async function sessionFiles(directory, signal) {
61426
62097
  for await (const entry of entries) {
61427
62098
  signal.throwIfAborted();
61428
62099
  if (entry.isFile() && entry.name.endsWith(".jsonl")) {
61429
- files.push(path4.join(directory, project2.name, entry.name));
62100
+ files.push(path5.join(directory, project2.name, entry.name));
61430
62101
  }
61431
62102
  }
61432
62103
  }
61433
62104
  return files;
61434
62105
  }
61435
62106
  async function readCandidate(file2, signal) {
61436
- const nativeSessionId = path4.basename(file2, ".jsonl");
62107
+ const nativeSessionId = path5.basename(file2, ".jsonl");
61437
62108
  if (!external_exports.uuid().safeParse(nativeSessionId).success)
61438
62109
  return null;
61439
- const before = await stat2(file2);
62110
+ const before = await stat3(file2);
61440
62111
  if (!before.isFile() || before.size === 0)
61441
62112
  return null;
61442
62113
  const stream = createReadStream3(file2, { encoding: "utf8", signal, end: before.size - 1 });
@@ -61463,7 +62134,7 @@ async function readCandidate(file2, signal) {
61463
62134
  return null;
61464
62135
  if (entry.isSidechain === true)
61465
62136
  continue;
61466
- if (typeof entry.cwd === "string" && path4.isAbsolute(entry.cwd))
62137
+ if (typeof entry.cwd === "string" && path5.isAbsolute(entry.cwd))
61467
62138
  cwd = entry.cwd;
61468
62139
  if (entry.type === "custom-title") {
61469
62140
  customTitle = cleanText(entry.customTitle);
@@ -61483,11 +62154,11 @@ async function readCandidate(file2, signal) {
61483
62154
  }
61484
62155
  if (!hasConversation || !cwd)
61485
62156
  return null;
61486
- const after = await stat2(file2);
62157
+ const after = await stat3(file2);
61487
62158
  if (!sameFileFingerprint(before, after))
61488
62159
  throw new SessionImportChangedError(CLAUDE_SESSION_CHANGED);
61489
62160
  const resolvedCwd = await realpath3(cwd);
61490
- if (!(await stat2(resolvedCwd)).isDirectory())
62161
+ if (!(await stat3(resolvedCwd)).isDirectory())
61491
62162
  return null;
61492
62163
  const candidate = sessionImportCandidate({
61493
62164
  nativeSessionId,
@@ -61522,17 +62193,17 @@ var ClaudeSessionImportIndex = class {
61522
62193
  const sources = [];
61523
62194
  for (const file2 of await sessionFiles(this.#directory, signal)) {
61524
62195
  signal.throwIfAborted();
61525
- const nativeSessionId = path4.basename(file2, ".jsonl");
62196
+ const nativeSessionId = path5.basename(file2, ".jsonl");
61526
62197
  if (identities.has(nativeSessionId))
61527
62198
  ambiguous.add(nativeSessionId);
61528
62199
  identities.add(nativeSessionId);
61529
62200
  try {
61530
- const fingerprint = await stat2(file2);
62201
+ const fingerprint = await stat3(file2);
61531
62202
  const cached2 = this.#cache.get(file2);
61532
62203
  const source = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source : await readCandidate(file2, signal);
61533
62204
  if (!source)
61534
62205
  continue;
61535
- if (!(await stat2(source.candidate.cwd)).isDirectory())
62206
+ if (!(await stat3(source.candidate.cwd)).isDirectory())
61536
62207
  continue;
61537
62208
  next.set(file2, { fingerprint, source });
61538
62209
  sources.push(source);
@@ -61550,7 +62221,7 @@ var ClaudeSessionImportIndex = class {
61550
62221
  let selected;
61551
62222
  for (const file2 of await sessionFiles(this.#directory, signal)) {
61552
62223
  signal.throwIfAborted();
61553
- if (path4.basename(file2, ".jsonl") !== nativeSessionId)
62224
+ if (path5.basename(file2, ".jsonl") !== nativeSessionId)
61554
62225
  continue;
61555
62226
  if (selected)
61556
62227
  throw new Error("Claude Code Session identity is ambiguous across files");
@@ -61570,13 +62241,13 @@ var ClaudeSessionImportIndex = class {
61570
62241
  };
61571
62242
 
61572
62243
  // dist/command.js
61573
- import path9 from "node:path";
62244
+ import path10 from "node:path";
61574
62245
 
61575
62246
  // ../../harness-discovery/dist/environment.js
61576
62247
  import fs2 from "node:fs";
61577
- import path5 from "node:path";
62248
+ import path6 from "node:path";
61578
62249
  function targetPath(platform) {
61579
- return platform === "win32" ? path5.win32 : path5.posix;
62250
+ return platform === "win32" ? path6.win32 : path6.posix;
61580
62251
  }
61581
62252
  function environmentValue(environment, name) {
61582
62253
  const lowered = name.toLowerCase();
@@ -61619,9 +62290,9 @@ function newestFirst(names) {
61619
62290
  }
61620
62291
 
61621
62292
  // ../../harness-discovery/dist/invocation.js
61622
- import path6 from "node:path";
62293
+ import path7 from "node:path";
61623
62294
  function commandInvocation(command, arguments_, environment, platform = process.platform) {
61624
- const extension = path6.win32.extname(command).toLowerCase();
62295
+ const extension = path7.win32.extname(command).toLowerCase();
61625
62296
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
61626
62297
  return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
61627
62298
  }
@@ -61635,11 +62306,11 @@ function commandInvocation(command, arguments_, environment, platform = process.
61635
62306
  }
61636
62307
 
61637
62308
  // ../../harness-discovery/dist/node-runtime.js
61638
- import path7 from "node:path";
62309
+ import path8 from "node:path";
61639
62310
  function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
61640
62311
  const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
61641
62312
  const delimiter2 = platform === "win32" ? ";" : ":";
61642
- const runtimeDirectory = path7.dirname(runtimeExecutable);
62313
+ const runtimeDirectory = path8.dirname(runtimeExecutable);
61643
62314
  const directories = (environment[pathKey] ?? "").split(delimiter2).filter(Boolean);
61644
62315
  const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
61645
62316
  if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
@@ -61649,7 +62320,7 @@ function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath
61649
62320
  }
61650
62321
 
61651
62322
  // ../../harness-discovery/dist/resolve.js
61652
- import os4 from "node:os";
62323
+ import os5 from "node:os";
61653
62324
 
61654
62325
  // ../../harness-discovery/dist/version-managers.js
61655
62326
  function versionManagerBinaryDirectories(context) {
@@ -61715,7 +62386,7 @@ function installRootExtensions(platform) {
61715
62386
  return platform === "win32" ? [".exe", ".cmd"] : [""];
61716
62387
  }
61717
62388
  function resolveHomeDirectory(input3) {
61718
- return input3.homeDirectory ?? environmentValue(input3.environment, "HOME") ?? environmentValue(input3.environment, "USERPROFILE") ?? os4.homedir();
62389
+ return input3.homeDirectory ?? environmentValue(input3.environment, "HOME") ?? environmentValue(input3.environment, "USERPROFILE") ?? os5.homedir();
61719
62390
  }
61720
62391
  function templateVariables(environment, platform, home) {
61721
62392
  const pathFlavor = targetPath(platform);
@@ -61924,8 +62595,8 @@ async function fetchInstallationText(url2) {
61924
62595
  }
61925
62596
 
61926
62597
  // ../../harness-discovery/dist/npm-installation.js
61927
- import { readFile as readFile3, realpath as realpath4 } from "node:fs/promises";
61928
- import path8 from "node:path";
62598
+ import { readFile as readFile4, realpath as realpath4 } from "node:fs/promises";
62599
+ import path9 from "node:path";
61929
62600
  function referencesNpmBin(shim, name, bin) {
61930
62601
  if (bin.includes(".."))
61931
62602
  return false;
@@ -61947,22 +62618,22 @@ function withAllowedScripts(environment, allowScripts) {
61947
62618
  async function npmInstallation(command, packages, environment, options = {}) {
61948
62619
  let selected = await realpath4(command);
61949
62620
  if (process.platform === "win32" && /\.(cmd|bat)$/i.test(selected)) {
61950
- const shim = (await readFile3(selected, "utf8")).replaceAll("\\", "/");
61951
- const root = path8.dirname(selected);
62621
+ const shim = (await readFile4(selected, "utf8")).replaceAll("\\", "/");
62622
+ const root = path9.dirname(selected);
61952
62623
  for (const name of packages) {
61953
- const directory2 = path8.join(root, "node_modules", ...name.split("/"));
61954
- const metadata = await readFile3(path8.join(directory2, "package.json"), "utf8").then((text3) => JSON.parse(text3)).catch(() => null);
62624
+ const directory2 = path9.join(root, "node_modules", ...name.split("/"));
62625
+ const metadata = await readFile4(path9.join(directory2, "package.json"), "utf8").then((text3) => JSON.parse(text3)).catch(() => null);
61955
62626
  const bins = typeof metadata?.bin === "string" ? [metadata.bin] : Object.values(metadata?.bin ?? {});
61956
62627
  const bin = bins.find((entry) => referencesNpmBin(shim, name, entry));
61957
62628
  if (bin) {
61958
- selected = await realpath4(path8.join(directory2, bin));
62629
+ selected = await realpath4(path9.join(directory2, bin));
61959
62630
  break;
61960
62631
  }
61961
62632
  }
61962
62633
  }
61963
- let directory = path8.dirname(selected);
62634
+ let directory = path9.dirname(selected);
61964
62635
  for (let depth = 0; depth < 8; depth++) {
61965
- const metadata = await readFile3(path8.join(directory, "package.json"), "utf8").then((text3) => JSON.parse(text3)).catch(() => null);
62636
+ const metadata = await readFile4(path9.join(directory, "package.json"), "utf8").then((text3) => JSON.parse(text3)).catch(() => null);
61966
62637
  if (metadata?.name && packages.includes(metadata.name)) {
61967
62638
  const name = metadata.name;
61968
62639
  const currentVersion = installationVersion(metadata.version);
@@ -61970,22 +62641,22 @@ async function npmInstallation(command, packages, environment, options = {}) {
61970
62641
  const segments = name.split("/");
61971
62642
  let modules = directory;
61972
62643
  for (let index = 0; index < segments.length; index++)
61973
- modules = path8.dirname(modules);
61974
- const prefix = process.platform === "win32" ? path8.dirname(modules) : path8.dirname(path8.dirname(modules));
61975
- const globalRoot = process.platform === "win32" ? path8.join(prefix, "node_modules") : path8.join(prefix, "lib", "node_modules");
62644
+ modules = path9.dirname(modules);
62645
+ const prefix = process.platform === "win32" ? path9.dirname(modules) : path9.dirname(path9.dirname(modules));
62646
+ const globalRoot = process.platform === "win32" ? path9.join(prefix, "node_modules") : path9.join(prefix, "lib", "node_modules");
61976
62647
  const env = withNodeRuntimeOnPath(environment);
61977
62648
  const npm = resolveHarnessExecutable({ id: "npm", command: "npm", installRoots: { posix: [], windows: [] } }, { environment: env });
61978
62649
  let globalInstall = modules === globalRoot;
61979
62650
  if (process.platform === "win32") {
61980
- const project2 = (await Promise.all(["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((file2) => readFile3(path8.join(prefix, file2), "utf8").then(() => true, (error63) => error63.code !== "ENOENT")))).some(Boolean);
62651
+ const project2 = (await Promise.all(["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((file2) => readFile4(path9.join(prefix, file2), "utf8").then(() => true, (error63) => error63.code !== "ENOENT")))).some(Boolean);
61981
62652
  const bins = typeof metadata.bin === "string" ? { [name.split("/").at(-1) ?? name]: metadata.bin } : metadata.bin ?? {};
61982
62653
  const launchers = await Promise.all(Object.entries(bins).map(async ([bin, entry]) => {
61983
- if (path8.basename(bin) !== bin || entry.includes(".."))
62654
+ if (path9.basename(bin) !== bin || entry.includes(".."))
61984
62655
  return false;
61985
- const target2 = await realpath4(path8.join(directory, entry)).catch(() => "");
62656
+ const target2 = await realpath4(path9.join(directory, entry)).catch(() => "");
61986
62657
  if (target2.toLowerCase() !== selected.toLowerCase())
61987
62658
  return false;
61988
- const shim = await readFile3(path8.join(prefix, `${bin}.cmd`), "utf8").catch(() => "");
62659
+ const shim = await readFile4(path9.join(prefix, `${bin}.cmd`), "utf8").catch(() => "");
61989
62660
  return referencesNpmBin(shim, name, entry);
61990
62661
  }));
61991
62662
  globalInstall = globalInstall && !project2 && launchers.some(Boolean);
@@ -62016,7 +62687,7 @@ async function npmInstallation(command, packages, environment, options = {}) {
62016
62687
  }
62017
62688
  };
62018
62689
  }
62019
- const parent = path8.dirname(directory);
62690
+ const parent = path9.dirname(directory);
62020
62691
  if (parent === directory)
62021
62692
  break;
62022
62693
  directory = parent;
@@ -62124,14 +62795,14 @@ function resolveClaudeCodeExecutable(input3 = {}, dependencies = {}) {
62124
62795
  }, dependencies);
62125
62796
  if (!resolution)
62126
62797
  throw new ClaudeCodeExecutableError("Claude Code is not installed");
62127
- return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path9.resolve(resolution.executable);
62798
+ return targetPath(platform).isAbsolute(resolution.executable) ? resolution.executable : path10.resolve(resolution.executable);
62128
62799
  }
62129
62800
 
62130
62801
  // dist/pending-session.js
62131
62802
  import { randomUUID as randomUUID3 } from "node:crypto";
62132
- import { mkdir as mkdir3, open as open4, readFile as readFile4, rename as rename3, rm as rm4, stat as stat3, unlink as unlink2 } from "node:fs/promises";
62133
- import os5 from "node:os";
62134
- import path10 from "node:path";
62803
+ import { mkdir as mkdir3, open as open4, readFile as readFile5, rename as rename3, rm as rm4, stat as stat4, unlink as unlink2 } from "node:fs/promises";
62804
+ import os6 from "node:os";
62805
+ import path11 from "node:path";
62135
62806
  var reservationSchema = external_exports.strictObject({
62136
62807
  version: external_exports.literal(1),
62137
62808
  sessionId: external_exports.uuid(),
@@ -62144,13 +62815,13 @@ function isPendingClaudeSession(ref) {
62144
62815
  var ClaudePendingSessions = class {
62145
62816
  #directory;
62146
62817
  constructor(environment) {
62147
- this.#directory = path10.join(path10.resolve(environment.CLAUDE_CONFIG_DIR ?? path10.join(os5.homedir(), ".claude")), "codexhost", "pending-sessions");
62818
+ this.#directory = path11.join(path11.resolve(environment.CLAUDE_CONFIG_DIR ?? path11.join(os6.homedir(), ".claude")), "codexhost", "pending-sessions");
62148
62819
  }
62149
62820
  #path(ref, cwd) {
62150
- if (ref.harnessId !== "claude-code" || !external_exports.uuid().safeParse(ref.nativeSessionId).success || !external_exports.strictObject({ pendingSession: external_exports.literal(1) }).safeParse(ref.locator).success || !path10.isAbsolute(cwd)) {
62821
+ if (ref.harnessId !== "claude-code" || !external_exports.uuid().safeParse(ref.nativeSessionId).success || !external_exports.strictObject({ pendingSession: external_exports.literal(1) }).safeParse(ref.locator).success || !path11.isAbsolute(cwd)) {
62151
62822
  throw new Error("Claude Code pending Session identity is invalid");
62152
62823
  }
62153
- return path10.join(this.#directory, ref.nativeSessionId);
62824
+ return path11.join(this.#directory, ref.nativeSessionId);
62154
62825
  }
62155
62826
  async create(cwd, configuration) {
62156
62827
  const ref = nativeSessionRefSchema.parse({
@@ -62169,7 +62840,7 @@ var ClaudePendingSessions = class {
62169
62840
  await mkdir3(this.#directory, { recursive: true, mode: 448 });
62170
62841
  await mkdir3(directory, { mode: 448 });
62171
62842
  try {
62172
- const file2 = await open4(path10.join(directory, "session.json"), "wx", 384);
62843
+ const file2 = await open4(path11.join(directory, "session.json"), "wx", 384);
62173
62844
  try {
62174
62845
  await file2.writeFile(JSON.stringify(reservation));
62175
62846
  await file2.sync();
@@ -62186,13 +62857,13 @@ var ClaudePendingSessions = class {
62186
62857
  }
62187
62858
  async read(ref, cwd) {
62188
62859
  const directory = this.#path(ref, cwd);
62189
- const reservation = reservationSchema.parse(JSON.parse(await readFile4(path10.join(directory, "session.json"), "utf8")));
62860
+ const reservation = reservationSchema.parse(JSON.parse(await readFile5(path11.join(directory, "session.json"), "utf8")));
62190
62861
  if (reservation.sessionId !== ref.nativeSessionId || reservation.cwd !== cwd) {
62191
62862
  throw new Error("Claude Code pending Session does not belong to this working directory");
62192
62863
  }
62193
62864
  let started = false;
62194
62865
  try {
62195
- const claim2 = await stat3(path10.join(directory, "started"));
62866
+ const claim2 = await stat4(path11.join(directory, "started"));
62196
62867
  if (!claim2.isFile())
62197
62868
  throw new Error("Claude Code pending Session claim is invalid");
62198
62869
  started = true;
@@ -62205,7 +62876,7 @@ var ClaudePendingSessions = class {
62205
62876
  async saveConfiguration(ref, cwd, configuration) {
62206
62877
  await this.read(ref, cwd);
62207
62878
  const directory = this.#path(ref, cwd);
62208
- const temporary = path10.join(directory, `${randomUUID3()}.tmp`);
62879
+ const temporary = path11.join(directory, `${randomUUID3()}.tmp`);
62209
62880
  try {
62210
62881
  const file2 = await open4(temporary, "wx", 384);
62211
62882
  try {
@@ -62219,7 +62890,7 @@ var ClaudePendingSessions = class {
62219
62890
  } finally {
62220
62891
  await file2.close();
62221
62892
  }
62222
- await rename3(temporary, path10.join(directory, "session.json"));
62893
+ await rename3(temporary, path11.join(directory, "session.json"));
62223
62894
  await this.#sync(directory);
62224
62895
  } finally {
62225
62896
  await rm4(temporary, { force: true });
@@ -62237,7 +62908,7 @@ var ClaudePendingSessions = class {
62237
62908
  }
62238
62909
  async claim(ref, cwd) {
62239
62910
  await this.read(ref, cwd);
62240
- const claim2 = await open4(path10.join(this.#path(ref, cwd), "started"), "wx", 384);
62911
+ const claim2 = await open4(path11.join(this.#path(ref, cwd), "started"), "wx", 384);
62241
62912
  try {
62242
62913
  await claim2.sync();
62243
62914
  } finally {
@@ -62247,7 +62918,7 @@ var ClaudePendingSessions = class {
62247
62918
  }
62248
62919
  /** Only the claim owner may release, after proven close and before submitting any native input. */
62249
62920
  async release(ref, cwd) {
62250
- await unlink2(path10.join(this.#path(ref, cwd), "started"));
62921
+ await unlink2(path11.join(this.#path(ref, cwd), "started"));
62251
62922
  await this.#sync(this.#path(ref, cwd));
62252
62923
  }
62253
62924
  async discard(ref, cwd) {
@@ -62259,7 +62930,7 @@ var ClaudePendingSessions = class {
62259
62930
  import { isDeepStrictEqual } from "node:util";
62260
62931
 
62261
62932
  // dist/file-change.js
62262
- import path11 from "node:path";
62933
+ import path12 from "node:path";
62263
62934
  var hunkSchema = external_exports.object({
62264
62935
  oldStart: external_exports.number().int().nonnegative(),
62265
62936
  oldLines: external_exports.number().int().nonnegative(),
@@ -62307,10 +62978,10 @@ function parseClaudeNativeFileChange(toolName, value) {
62307
62978
  };
62308
62979
  }
62309
62980
  function displayPath(nativePath, cwd) {
62310
- const resolvedCwd = path11.resolve(cwd);
62311
- const resolvedPath = path11.isAbsolute(nativePath) ? path11.resolve(nativePath) : path11.resolve(cwd, nativePath);
62312
- const relative2 = path11.relative(resolvedCwd, resolvedPath);
62313
- const selected = relative2.length > 0 && relative2 !== ".." && !relative2.startsWith(`..${path11.sep}`) ? relative2 : resolvedPath;
62981
+ const resolvedCwd = path12.resolve(cwd);
62982
+ const resolvedPath = path12.isAbsolute(nativePath) ? path12.resolve(nativePath) : path12.resolve(cwd, nativePath);
62983
+ const relative2 = path12.relative(resolvedCwd, resolvedPath);
62984
+ const selected = relative2.length > 0 && relative2 !== ".." && !relative2.startsWith(`..${path12.sep}`) ? relative2 : resolvedPath;
62314
62985
  const normalized = selected.replaceAll("\\", "/");
62315
62986
  return validNativePath(normalized) && normalized !== "." ? normalized : null;
62316
62987
  }
@@ -62322,7 +62993,7 @@ function projectClaudeFileChange(value, cwd) {
62322
62993
  `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
62323
62994
  ...hunk.lines
62324
62995
  ]);
62325
- const absoluteDisplayPath = path11.posix.isAbsolute(normalizedPath);
62996
+ const absoluteDisplayPath = path12.posix.isAbsolute(normalizedPath);
62326
62997
  const oldHeader = value.kind === "add" ? "/dev/null" : absoluteDisplayPath ? normalizedPath : `a/${normalizedPath}`;
62327
62998
  const newHeader = absoluteDisplayPath ? normalizedPath : `b/${normalizedPath}`;
62328
62999
  const unifiedDiff = [`--- ${oldHeader}`, `+++ ${newHeader}`, ...body, ""].join("\n");
@@ -62558,6 +63229,13 @@ var ABORTED_TERMINALS = /* @__PURE__ */ new Set(["aborted_streaming", "aborted_t
62558
63229
  var AUTHENTICATION_ERRORS = /* @__PURE__ */ new Set(["authentication_failed", "oauth_org_not_allowed"]);
62559
63230
  var MAX_SAFE_UNIX_SECONDS = 864e10;
62560
63231
  var CLAUDE_SUBAGENT_TOOLS = /* @__PURE__ */ new Set(["Agent", "Task", "SendMessage"]);
63232
+ var CROSS_SESSION_SEND_TARGET_PATTERN = /^(?:uds:|pipe:|\\\\\.\\pipe\\)/iu;
63233
+ var CROSS_SESSION_SEND_RESULT_MARKERS = [
63234
+ "another Claude session",
63235
+ "in that session's inbox",
63236
+ "[Cross-session delivery notice]",
63237
+ "will send one notice when it is next idle"
63238
+ ];
62561
63239
  var CLAUDE_WORKFLOW_TOOL = "Workflow";
62562
63240
  var BACKGROUND_OUTPUT_FILE_PATTERN = /Output is being written to: (.+?\.output)\./u;
62563
63241
  var SUBAGENT_DESCRIPTION_LIMIT = 500;
@@ -62635,6 +63313,32 @@ function sendResultFromText(outputText) {
62635
63313
  function claudeSendMessageFailed(nativeResult, outputText) {
62636
63314
  return isRecord9(nativeResult) && typeof nativeResult.success === "boolean" ? !nativeResult.success : sendResultFromText(outputText)?.success === false;
62637
63315
  }
63316
+ function isCrossSessionSendArguments(argumentsValue) {
63317
+ if (!isRecord9(argumentsValue))
63318
+ return false;
63319
+ if (argumentsValue.notify_when_idle === true)
63320
+ return true;
63321
+ const target2 = targetedSubagentId(argumentsValue);
63322
+ return target2 !== void 0 && CROSS_SESSION_SEND_TARGET_PATTERN.test(target2);
63323
+ }
63324
+ function isClaudeSubagentToolUse(toolName, input3) {
63325
+ if (!CLAUDE_SUBAGENT_TOOLS.has(toolName))
63326
+ return false;
63327
+ return toolName !== "SendMessage" || !isCrossSessionSendArguments(input3);
63328
+ }
63329
+ function claudeSendMessageTargetsPeerSession(nativeResult, outputText) {
63330
+ if (isRecord9(nativeResult)) {
63331
+ if (typeof nativeResult.msg_id === "string" && nativeResult.msg_id.length > 0)
63332
+ return true;
63333
+ const fields = [nativeResult.message, nativeResult.display];
63334
+ if (fields.some((field2) => typeof field2 === "string" && CROSS_SESSION_SEND_RESULT_MARKERS.some((marker) => field2.includes(marker)))) {
63335
+ return true;
63336
+ }
63337
+ }
63338
+ if (!outputText)
63339
+ return false;
63340
+ return CROSS_SESSION_SEND_RESULT_MARKERS.some((marker) => outputText.includes(marker));
63341
+ }
62638
63342
  function includesAuthenticationFailure(errors) {
62639
63343
  return errors.some((error63) => AUTHENTICATION_ERRORS.has(error63));
62640
63344
  }
@@ -63458,7 +64162,7 @@ var ClaudeNativeTurnAccumulator = class {
63458
64162
  this.#protocolConflict = true;
63459
64163
  continue;
63460
64164
  }
63461
- const subagent = CLAUDE_SUBAGENT_TOOLS.has(block.name);
64165
+ const subagent = isClaudeSubagentToolUse(block.name, argumentsResult.data);
63462
64166
  const workflow = block.name === CLAUDE_WORKFLOW_TOOL;
63463
64167
  const spawnName = subagent && block.name !== "SendMessage" && isRecord9(argumentsResult.data) ? boundedString(argumentsResult.data.name, SUBAGENT_DESCRIPTION_LIMIT) : void 0;
63464
64168
  this.#tools.set(block.id, {
@@ -63558,9 +64262,9 @@ var ClaudeNativeTurnAccumulator = class {
63558
64262
  const resultSummary = boundedString(outputText, SUBAGENT_SUMMARY_LIMIT);
63559
64263
  const send = tool.name === "SendMessage";
63560
64264
  const result = send && !isRecord9(nativeResult) ? sendResultFromText(outputText) : nativeResult;
63561
- const failed = isError || send && claudeSendMessageFailed(result, outputText);
64265
+ const failed2 = isError || send && claudeSendMessageFailed(result, outputText);
63562
64266
  const agentId = nativeSubagentId(result, outputText);
63563
- if (!failed) {
64267
+ if (!failed2) {
63564
64268
  if (tool.spawnName && agentId)
63565
64269
  this.#subagentIdsByName.set(tool.spawnName, agentId);
63566
64270
  if (send && isRecord9(result) && isRecord9(result.pin)) {
@@ -63570,18 +64274,21 @@ var ClaudeNativeTurnAccumulator = class {
63570
64274
  this.#subagentIdsByName.set(name, id3);
63571
64275
  }
63572
64276
  }
64277
+ const crossSessionPeer = send && !failed2 && !agentId && claudeSendMessageTargetsPeerSession(result, outputText);
64278
+ const continuesInBackground = crossSessionPeer ? false : subagentContinuesInBackground(nativeResult, outputText) ? true : void 0;
63573
64279
  events.push({
63574
64280
  type: "subagent.completed",
63575
64281
  callId,
63576
- isError: failed,
63577
- ...subagentContinuesInBackground(nativeResult, outputText) ? { continuesInBackground: true } : {},
64282
+ isError: failed2,
64283
+ ...continuesInBackground !== void 0 ? { continuesInBackground } : {},
63578
64284
  ...agentId ? { nativeSubagentId: agentId } : {},
63579
64285
  ...resultSummary ? { resultSummary } : {}
63580
64286
  });
63581
64287
  continue;
63582
64288
  }
63583
- const fileChange = isError ? null : parseClaudeNativeFileChange(tool.name, nativeResult);
63584
- const backgroundTaskId = tool.name === "Bash" && !isError && isRecord9(nativeResult) && typeof nativeResult.backgroundTaskId === "string" && nativeResult.backgroundTaskId.length > 0 ? nativeResult.backgroundTaskId : void 0;
64289
+ const failed = isError || tool.name === "SendMessage" && claudeSendMessageFailed(nativeResult, outputText);
64290
+ const fileChange = failed ? null : parseClaudeNativeFileChange(tool.name, nativeResult);
64291
+ const backgroundTaskId = tool.name === "Bash" && !failed && isRecord9(nativeResult) && typeof nativeResult.backgroundTaskId === "string" && nativeResult.backgroundTaskId.length > 0 ? nativeResult.backgroundTaskId : void 0;
63585
64292
  const outputFile = backgroundTaskId !== void 0 ? BACKGROUND_OUTPUT_FILE_PATTERN.exec(outputText ?? "")?.[1] : void 0;
63586
64293
  const backgroundOutputFile = typeof outputFile === "string" && outputFile.length > 0 ? outputFile : void 0;
63587
64294
  events.push({
@@ -63590,7 +64297,7 @@ var ClaudeNativeTurnAccumulator = class {
63590
64297
  toolName: tool.name,
63591
64298
  ...outputText ? { outputText } : {},
63592
64299
  ...structuredResult?.success ? { structuredResult: structuredResult.data } : {},
63593
- isError,
64300
+ isError: failed,
63594
64301
  ...fileChange ? { fileChange } : {},
63595
64302
  ...backgroundTaskId ? { backgroundTaskId } : {},
63596
64303
  ...backgroundOutputFile ? { backgroundOutputFile } : {}
@@ -63693,6 +64400,27 @@ function isPersistedClaudeMessageId(expectedId, persistedIds) {
63693
64400
  function isRecord11(value) {
63694
64401
  return typeof value === "object" && value !== null && !Array.isArray(value);
63695
64402
  }
64403
+ function parseTimestampMs(value) {
64404
+ if (typeof value === "number") {
64405
+ return Number.isFinite(value) && value >= 0 ? Math.floor(value) : void 0;
64406
+ }
64407
+ if (typeof value === "string") {
64408
+ const parsed = Date.parse(value);
64409
+ return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : void 0;
64410
+ }
64411
+ return void 0;
64412
+ }
64413
+ function turnTimestampRange(messages) {
64414
+ let startedAtMs;
64415
+ let completedAtMs;
64416
+ for (const entry of messages) {
64417
+ if (entry.timestampMs === void 0)
64418
+ continue;
64419
+ startedAtMs ??= entry.timestampMs;
64420
+ completedAtMs = Math.max(startedAtMs, entry.timestampMs);
64421
+ }
64422
+ return startedAtMs !== void 0 && completedAtMs !== void 0 ? { startedAtMs, completedAtMs } : void 0;
64423
+ }
63696
64424
  function textParts(value) {
63697
64425
  if (typeof value === "string")
63698
64426
  return value.length > 0 ? [value] : [];
@@ -63814,10 +64542,12 @@ function conversationMessages(values, sessionId) {
63814
64542
  throw new Error("Claude history contains duplicate message IDs");
63815
64543
  ids.add(value.uuid);
63816
64544
  const interrupted = isInterruptionRecord(value, turnPromptIds);
64545
+ const timestampMs = parseTimestampMs(value.timestamp) ?? parseTimestampMs(value.message.timestamp);
63817
64546
  const message = {
63818
64547
  type: value.type,
63819
64548
  uuid: value.uuid,
63820
64549
  message: value.message,
64550
+ ...timestampMs !== void 0 ? { timestampMs } : {},
63821
64551
  // Failure metadata belongs to the outer SDK/transcript record, not its Message.
63822
64552
  failed: value.type === "assistant" && (typeof value.error === "string" || value.isApiErrorMessage === true),
63823
64553
  nested: typeof value.parent_tool_use_id === "string" && value.parent_tool_use_id.length > 0,
@@ -63846,8 +64576,9 @@ function conversationMessages(values, sessionId) {
63846
64576
  } else if (event.type === "subagent.completed") {
63847
64577
  if (sends.has(event.callId)) {
63848
64578
  const agentId = event.nativeSubagentId ?? sends.get(event.callId);
63849
- if (!event.isError && agentId)
64579
+ if (!event.isError && event.continuesInBackground !== false && agentId) {
63850
64580
  occupancy.occupyAgent(agentId);
64581
+ }
63851
64582
  sends.delete(event.callId);
63852
64583
  } else if (!event.isError && event.continuesInBackground) {
63853
64584
  occupancy.occupySpawn(event.callId, event.nativeSubagentId);
@@ -63967,6 +64698,7 @@ function mapClaudeSnapshotWithCheckpointIds(values, sessionId, mcpServers, tasks
63967
64698
  let reasoningOrdinal = 0;
63968
64699
  let toolOrdinal = 0;
63969
64700
  turnCheckpointIds.push(turnMessages.filter(isCheckpointCandidate).map((message) => message.uuid));
64701
+ const timing = turnTimestampRange(turnMessages);
63970
64702
  turns.push({
63971
64703
  nativeTurnRef: nativeTurnRefSchema.parse({
63972
64704
  harnessId: claudeCodeHarnessId,
@@ -63974,6 +64706,7 @@ function mapClaudeSnapshotWithCheckpointIds(values, sessionId, mcpServers, tasks
63974
64706
  nativeTurnKey: user.uuid,
63975
64707
  formatVersion: 1
63976
64708
  }),
64709
+ ...timing ? timing : {},
63977
64710
  ...checkpointMessage ? {
63978
64711
  checkpoint: nativeCheckpointRefSchema.parse({
63979
64712
  harnessId: claudeCodeHarnessId,
@@ -64077,7 +64810,7 @@ function mapClaudeSnapshotWithCheckpointIds(values, sessionId, mcpServers, tasks
64077
64810
  if (block.type !== "tool_use" || typeof block.id !== "string" || typeof block.name !== "string") {
64078
64811
  continue;
64079
64812
  }
64080
- const toolItem = !message.nested && !CLAUDE_SUBAGENT_TOOLS.has(block.name) ? toolOrdinal += 1 : null;
64813
+ const toolItem = !message.nested && !isClaudeSubagentToolUse(block.name, block.input) ? toolOrdinal += 1 : null;
64081
64814
  const result = results.get(block.id);
64082
64815
  if (!result)
64083
64816
  continue;
@@ -64278,6 +65011,7 @@ function mapClaudeSubagentSnapshot(values, parentSessionId, nativeSubagentId2, p
64278
65011
  }
64279
65012
  }
64280
65013
  const checkpointMessage = turnMessages.findLast(({ type }) => type === "assistant");
65014
+ const timing = turnTimestampRange(turnMessages);
64281
65015
  turns.push({
64282
65016
  nativeTurnRef: nativeTurnRefSchema.parse({
64283
65017
  harnessId: claudeCodeHarnessId,
@@ -64285,6 +65019,7 @@ function mapClaudeSubagentSnapshot(values, parentSessionId, nativeSubagentId2, p
64285
65019
  nativeTurnKey: turns.length === 0 ? `subagent-${nativeSubagentId2}-initial` : `subagent-turn-${user?.uuid ?? index}`,
64286
65020
  formatVersion: 1
64287
65021
  }),
65022
+ ...timing ? timing : {},
64288
65023
  ...checkpointMessage ? {
64289
65024
  checkpoint: nativeCheckpointRefSchema.parse({
64290
65025
  harnessId: claudeCodeHarnessId,
@@ -64489,30 +65224,30 @@ async function forkClaudeSession(input3) {
64489
65224
 
64490
65225
  // dist/claude-fork-references.js
64491
65226
  import { randomUUID as randomUUID4 } from "node:crypto";
64492
- import { readFile as readFile5, rename as rename4, rm as rm5, stat as stat5, writeFile as writeFile2 } from "node:fs/promises";
65227
+ import { readFile as readFile6, rename as rename4, rm as rm5, stat as stat6, writeFile as writeFile2 } from "node:fs/promises";
64493
65228
 
64494
65229
  // dist/claude-transcript.js
64495
65230
  import { createReadStream as createReadStream4 } from "node:fs";
64496
- import os6 from "node:os";
64497
- import path12 from "node:path";
64498
- import { readdir as readdir4, stat as stat4 } from "node:fs/promises";
65231
+ import os7 from "node:os";
65232
+ import path13 from "node:path";
65233
+ import { readdir as readdir4, stat as stat5 } from "node:fs/promises";
64499
65234
  function projectDirectoryName(cwd) {
64500
65235
  return cwd.replace(/[^A-Za-z0-9]/gu, "-");
64501
65236
  }
64502
65237
  function configDirectory(environment) {
64503
- return environment.CLAUDE_CONFIG_DIR ? path12.resolve(environment.CLAUDE_CONFIG_DIR) : path12.join(os6.homedir(), ".claude");
65238
+ return environment.CLAUDE_CONFIG_DIR ? path13.resolve(environment.CLAUDE_CONFIG_DIR) : path13.join(os7.homedir(), ".claude");
64504
65239
  }
64505
65240
  async function existingFile(file2) {
64506
65241
  try {
64507
- return (await stat4(file2)).isFile();
65242
+ return (await stat5(file2)).isFile();
64508
65243
  } catch {
64509
65244
  return false;
64510
65245
  }
64511
65246
  }
64512
65247
  async function findClaudeTranscript(input3) {
64513
- const projectsDirectory = path12.join(configDirectory(input3.environment), "projects");
65248
+ const projectsDirectory = path13.join(configDirectory(input3.environment), "projects");
64514
65249
  const name = `${input3.sessionId}.jsonl`;
64515
- const expected = path12.join(projectsDirectory, projectDirectoryName(input3.cwd), name);
65250
+ const expected = path13.join(projectsDirectory, projectDirectoryName(input3.cwd), name);
64516
65251
  if (await existingFile(expected))
64517
65252
  return expected;
64518
65253
  let projects;
@@ -64522,7 +65257,7 @@ async function findClaudeTranscript(input3) {
64522
65257
  return null;
64523
65258
  }
64524
65259
  for (const project2 of projects) {
64525
- const candidate = path12.join(projectsDirectory, project2, name);
65260
+ const candidate = path13.join(projectsDirectory, project2, name);
64526
65261
  if (await existingFile(candidate))
64527
65262
  return candidate;
64528
65263
  }
@@ -64611,7 +65346,7 @@ async function remapForkedSessionReferences(input3) {
64611
65346
  const transcript = await findClaudeTranscript(input3);
64612
65347
  if (!transcript)
64613
65348
  return 0;
64614
- const contents = await readFile5(transcript, "utf8");
65349
+ const contents = await readFile6(transcript, "utf8");
64615
65350
  if (!contents.includes('"sameAs"'))
64616
65351
  return 0;
64617
65352
  const lines = contents.split("\n");
@@ -64640,7 +65375,7 @@ async function remapForkedSessionReferences(input3) {
64640
65375
  try {
64641
65376
  await writeFile2(temporary, output2.join("\n"), {
64642
65377
  flag: "wx",
64643
- mode: (await stat5(transcript)).mode & 511
65378
+ mode: (await stat6(transcript)).mode & 511
64644
65379
  });
64645
65380
  await rename4(temporary, transcript);
64646
65381
  } finally {
@@ -64651,9 +65386,9 @@ async function remapForkedSessionReferences(input3) {
64651
65386
 
64652
65387
  // dist/model-catalog.js
64653
65388
  import { Buffer as Buffer3 } from "node:buffer";
64654
- import { readFile as readFile6 } from "node:fs/promises";
64655
- import os7 from "node:os";
64656
- import path13 from "node:path";
65389
+ import { readFile as readFile7 } from "node:fs/promises";
65390
+ import os8 from "node:os";
65391
+ import path14 from "node:path";
64657
65392
 
64658
65393
  // dist/thinking-options.js
64659
65394
  var option = (id3, label) => ({
@@ -64822,7 +65557,7 @@ function normalizeStoredClaudeModelRef(ref, catalog) {
64822
65557
  return tied ? void 0 : best?.ref;
64823
65558
  }
64824
65559
  function resolveClaudeConfigDirectory(environment = process.env) {
64825
- return path13.resolve(environment.CLAUDE_CONFIG_DIR ?? path13.join(os7.homedir(), ".claude"));
65560
+ return path14.resolve(environment.CLAUDE_CONFIG_DIR ?? path14.join(os8.homedir(), ".claude"));
64826
65561
  }
64827
65562
  function parseModelPickerOptions(value) {
64828
65563
  if (!Array.isArray(value))
@@ -64864,10 +65599,10 @@ function parseClaudeModelPickerSettings(value) {
64864
65599
  };
64865
65600
  }
64866
65601
  async function readClaudeUserModelPicker(environment = process.env) {
64867
- const settingsPath = path13.join(resolveClaudeConfigDirectory(environment), "settings.json");
65602
+ const settingsPath = path14.join(resolveClaudeConfigDirectory(environment), "settings.json");
64868
65603
  let raw;
64869
65604
  try {
64870
- raw = await readFile6(settingsPath, "utf8");
65605
+ raw = await readFile7(settingsPath, "utf8");
64871
65606
  } catch {
64872
65607
  return void 0;
64873
65608
  }
@@ -65139,15 +65874,15 @@ function parseClaudeSlashCommands(value) {
65139
65874
  return value.flatMap((entry) => {
65140
65875
  if (typeof entry !== "object" || entry === null)
65141
65876
  return [];
65142
- const record3 = entry;
65143
- const name = typeof record3.name === "string" ? record3.name.trim().replace(/^\//u, "") : "";
65877
+ const record4 = entry;
65878
+ const name = typeof record4.name === "string" ? record4.name.trim().replace(/^\//u, "") : "";
65144
65879
  if (!name)
65145
65880
  return [];
65146
65881
  return [
65147
65882
  {
65148
65883
  name,
65149
- description: typeof record3.description === "string" ? record3.description : "",
65150
- argumentHint: typeof record3.argumentHint === "string" ? record3.argumentHint : ""
65884
+ description: typeof record4.description === "string" ? record4.description : "",
65885
+ argumentHint: typeof record4.argumentHint === "string" ? record4.argumentHint : ""
65151
65886
  }
65152
65887
  ];
65153
65888
  });
@@ -65214,7 +65949,7 @@ function projectClaudeAccountUsage(usage, account) {
65214
65949
 
65215
65950
  // dist/process-fence.js
65216
65951
  import { execFile as execFile3 } from "node:child_process";
65217
- import path14 from "node:path";
65952
+ import path15 from "node:path";
65218
65953
  import { setTimeout as setTimeout2 } from "node:timers/promises";
65219
65954
  import { promisify } from "node:util";
65220
65955
  var executeFile = promisify(execFile3);
@@ -65238,9 +65973,9 @@ async function closeClaudeProcessGroup(child, timeoutMs, retry) {
65238
65973
  if (child.exitCode !== null || child.signalCode !== null)
65239
65974
  throw new Error("Claude process tree cannot be confirmed after its Windows root exited");
65240
65975
  const root = process.env.SystemRoot ?? process.env.SYSTEMROOT;
65241
- if (!root || !path14.win32.isAbsolute(root))
65976
+ if (!root || !path15.win32.isAbsolute(root))
65242
65977
  throw new Error("Windows SystemRoot is unavailable");
65243
- await executeFile(path14.win32.join(root, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], {
65978
+ await executeFile(path15.win32.join(root, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], {
65244
65979
  timeout: timeoutMs,
65245
65980
  windowsHide: true
65246
65981
  });
@@ -65630,6 +66365,7 @@ var ClaudeSdkTransport = class {
65630
66365
  environment: this.#environment
65631
66366
  });
65632
66367
  const thinking = claudeThinkingConfiguration(this.#thinkingOptionId);
66368
+ const entrypoint = this.#environment.CODEXHOST_CLAUDE_CODE_ENTRYPOINT === "cli" ? "cli" : SESSION_ENTRYPOINT;
65633
66369
  const activeQuery = this.#queryFactory({
65634
66370
  prompt: this.#input,
65635
66371
  options: {
@@ -65648,6 +66384,9 @@ var ClaudeSdkTransport = class {
65648
66384
  pathToClaudeCodeExecutable: executable,
65649
66385
  // Omitted settingSources loads user, project and local settings like the
65650
66386
  // Claude Code CLI, so project CLAUDE.md and .claude/skills apply.
66387
+ // The SDK sends an empty system prompt when this option is omitted; the
66388
+ // Claude Code preset keeps the default prompt consistent with the CLI.
66389
+ systemPrompt: { type: "preset", preset: "claude_code" },
65651
66390
  permissionMode: this.#permissionMode,
65652
66391
  ...this.#allowDangerouslySkipPermissions ? { allowDangerouslySkipPermissions: true } : {},
65653
66392
  canUseTool: (toolName, input3, options) => this.#canUseTool(toolName, input3, options),
@@ -65661,7 +66400,7 @@ var ClaudeSdkTransport = class {
65661
66400
  // stays unset because it hides these tools again.
65662
66401
  CLAUDE_CODE_ENABLE_TODO_TOOLS: "1",
65663
66402
  ...this.#environment,
65664
- CLAUDE_CODE_ENTRYPOINT: SESSION_ENTRYPOINT,
66403
+ CLAUDE_CODE_ENTRYPOINT: entrypoint,
65665
66404
  CLAUDE_AGENT_SDK_CLIENT_APP: CLIENT_APP
65666
66405
  }),
65667
66406
  spawnClaudeCodeProcess: (options) => this.#spawn(options)
@@ -66765,7 +67504,7 @@ var ClaudeSubagentLifecycle = class {
66765
67504
  if (!current)
66766
67505
  throw new Error("Claude Code Subagent delegation has no Agent state");
66767
67506
  this.#retireSendTarget(active2.item, current.nativeSubagentId, event.nativeSubagentId);
66768
- const status = cancellationRequested ? "interrupted" : event.isError ? "failed" : active2.item.operation === "send" || event.continuesInBackground ? "running" : "completed";
67507
+ const status = cancellationRequested ? "interrupted" : event.isError ? "failed" : event.continuesInBackground ?? active2.item.operation === "send" ? "running" : "completed";
66769
67508
  const subagent = {
66770
67509
  ...current,
66771
67510
  status,
@@ -69218,9 +69957,9 @@ var ClaudeHarnessSession = class {
69218
69957
  }
69219
69958
  }
69220
69959
  /** Publishes one live request to Host metering; an unusable one marks history incomplete. */
69221
- #meterUsage(record3) {
69222
- if (record3.kind === "request")
69223
- this.#event({ type: "usage.request", request: record3.request });
69960
+ #meterUsage(record4) {
69961
+ if (record4.kind === "request")
69962
+ this.#event({ type: "usage.request", request: record4.request });
69224
69963
  else
69225
69964
  this.#event({ type: "usage.history", complete: false });
69226
69965
  }
@@ -69818,8 +70557,12 @@ var ClaudeHarnessSession = class {
69818
70557
  */
69819
70558
  #handlePlanLimit(planLimit) {
69820
70559
  const effective = this.#onPlanLimitObserved(planLimit);
69821
- if (effective)
69822
- this.publishPlanLimit(effective);
70560
+ if (!effective)
70561
+ return;
70562
+ if (effective.replace)
70563
+ this.replacePlanLimit(effective.planLimit);
70564
+ else
70565
+ this.publishPlanLimit(effective.planLimit);
69823
70566
  }
69824
70567
  #observePromptCacheTtl(ttlSeconds) {
69825
70568
  this.#promptCacheTtlSeconds = ttlSeconds;
@@ -69852,6 +70595,54 @@ var ClaudeHarnessSession = class {
69852
70595
  }
69853
70596
  this.#mergeAndPublishUsage(delta, this.#active?.command.turnId);
69854
70597
  }
70598
+ /**
70599
+ * Replace all plan-limit fields on `#latestUsage`, clearing removed windows
70600
+ * when custom Provider quota changes or expires while preserving other usage.
70601
+ */
70602
+ replacePlanLimit(planLimit) {
70603
+ if (this.#phase !== "open")
70604
+ return;
70605
+ const { planFiveHourUsedPercent: _fiveHourUsed, planFiveHourResetsAtUnix: _fiveHourReset, planSevenDayUsedPercent: _sevenDayUsed, planSevenDayResetsAtUnix: _sevenDayReset, ...base } = this.#latestUsage ?? {};
70606
+ const next = { ...base };
70607
+ if (planLimit?.fiveHour) {
70608
+ next.planFiveHourUsedPercent = planLimit.fiveHour.utilizationPercent;
70609
+ if (planLimit.fiveHour.resetsAtUnix !== void 0) {
70610
+ next.planFiveHourResetsAtUnix = planLimit.fiveHour.resetsAtUnix;
70611
+ }
70612
+ }
70613
+ if (planLimit?.sevenDay) {
70614
+ next.planSevenDayUsedPercent = planLimit.sevenDay.utilizationPercent;
70615
+ if (planLimit.sevenDay.resetsAtUnix !== void 0) {
70616
+ next.planSevenDayResetsAtUnix = planLimit.sevenDay.resetsAtUnix;
70617
+ }
70618
+ }
70619
+ if (Object.keys(next).length === 0) {
70620
+ if (this.#latestUsage === null)
70621
+ return;
70622
+ this.#latestUsage = null;
70623
+ this.#event({
70624
+ type: "session.usage.changed",
70625
+ ...this.#active?.command.turnId !== void 0 ? { observedForTurnId: this.#active.command.turnId } : {},
70626
+ usage: null
70627
+ });
70628
+ return;
70629
+ }
70630
+ let usage;
70631
+ try {
70632
+ usage = parseHostUsage(next);
70633
+ } catch {
70634
+ return;
70635
+ }
70636
+ if (this.#latestUsage && Object.keys(this.#latestUsage).length === Object.keys(usage).length && Object.keys(usage).every((key) => this.#latestUsage?.[key] === usage[key])) {
70637
+ return;
70638
+ }
70639
+ this.#latestUsage = usage;
70640
+ this.#event({
70641
+ type: "session.usage.changed",
70642
+ ...this.#active?.command.turnId !== void 0 ? { observedForTurnId: this.#active.command.turnId } : {},
70643
+ usage
70644
+ });
70645
+ }
69855
70646
  /**
69856
70647
  * Every Usage observation replaces `#latestUsage` in full: unaffected fields
69857
70648
  * from the prior snapshot are carried forward, never cleared by an
@@ -70064,6 +70855,7 @@ var ClaudeHarnessSession = class {
70064
70855
  this.#channel.emit({ kind: "event", event });
70065
70856
  }
70066
70857
  };
70858
+ var CUSTOM_PROVIDER_REFRESH_INTERVAL_MS = 6e4;
70067
70859
  var ClaudeCodeAdapter = class {
70068
70860
  normalizeStoredModelRef = normalizeStoredClaudeModelRef;
70069
70861
  commandCatalog = claudeCommandCatalog;
@@ -70210,6 +71002,7 @@ var ClaudeCodeAdapter = class {
70210
71002
  #inspectionTasks = /* @__PURE__ */ new Set();
70211
71003
  #inspectors = /* @__PURE__ */ new Set();
70212
71004
  #sessions = /* @__PURE__ */ new Set();
71005
+ #abortController = new AbortController();
70213
71006
  #closePromise = null;
70214
71007
  #latestPlanLimit = null;
70215
71008
  // Seeded once on cold start (or by the first passive push / explicit account inspection);
@@ -70217,6 +71010,13 @@ var ClaudeCodeAdapter = class {
70217
71010
  #creditsSeeded = false;
70218
71011
  #accountInspection = null;
70219
71012
  #accountCreditsSupported = false;
71013
+ #quotaGeneration = 0;
71014
+ #committedQuotaGeneration = 0;
71015
+ #customProviderActive = false;
71016
+ #customProviderCredits = null;
71017
+ #customProviderBalance = null;
71018
+ #customProviderRefreshAt = Number.NEGATIVE_INFINITY;
71019
+ #customProviderRefresh = null;
70220
71020
  constructor(options = {}, dependencies) {
70221
71021
  const environment = options.environment ?? process.env;
70222
71022
  this.#environment = environment;
@@ -70245,6 +71045,10 @@ var ClaudeCodeAdapter = class {
70245
71045
  environment: options.environment ?? process.env
70246
71046
  });
70247
71047
  },
71048
+ inspectCustomProviderAccounts: (signal) => fetchClaudeCustomProviderAccounts({
71049
+ environment: options.environment ?? process.env,
71050
+ ...signal ? { signal } : {}
71051
+ }),
70248
71052
  createInspector: (input3) => new ClaudeSdkModelInspector({
70249
71053
  ...input3,
70250
71054
  ...options.command ? { command: options.command } : {},
@@ -70295,7 +71099,7 @@ var ClaudeCodeAdapter = class {
70295
71099
  error: invalidState("Claude Code Adapter is closing")
70296
71100
  };
70297
71101
  }
70298
- const cwd = path15.resolve(input3.cwd ?? process.cwd());
71102
+ const cwd = path16.resolve(input3.cwd ?? process.cwd());
70299
71103
  const current = this.#inspectionInFlight.get(cwd);
70300
71104
  if (input3.refresh) {
70301
71105
  this.#inspectionCache.clear();
@@ -70327,25 +71131,102 @@ var ClaudeCodeAdapter = class {
70327
71131
  });
70328
71132
  return inspection;
70329
71133
  }
70330
- inspectAccount() {
71134
+ inspectAccounts() {
70331
71135
  if (this.#closePromise)
70332
- return Promise.resolve(null);
71136
+ return Promise.resolve([]);
70333
71137
  if (this.#accountInspection)
70334
71138
  return this.#accountInspection;
70335
- this.#accountInspection = this.#readAccount().finally(() => {
71139
+ this.#accountInspection = this.#readAccounts().finally(() => {
70336
71140
  this.#accountInspection = null;
70337
71141
  });
70338
71142
  return this.#accountInspection;
70339
71143
  }
70340
- async #readAccount() {
70341
- const planLimitAtStart = this.#latestPlanLimit;
71144
+ async inspectAccount() {
71145
+ return (await this.inspectAccounts())[0] ?? null;
71146
+ }
71147
+ #applyCustomProviderAccounts(accounts, generation) {
71148
+ if (this.#closePromise || generation < this.#committedQuotaGeneration)
71149
+ return false;
71150
+ this.#committedQuotaGeneration = generation;
71151
+ const primary = accounts[0] ?? null;
71152
+ if (primary)
71153
+ this.#latestPlanLimit = null;
71154
+ this.#customProviderCredits = primary?.credits ?? null;
71155
+ this.#customProviderBalance = this.#customProviderCredits ? null : primary?.balance ?? null;
71156
+ this.#accountCreditsSupported = this.#customProviderCredits !== null || this.#customProviderBalance !== null;
71157
+ const inspected = planLimitFromAccountCredits(this.#customProviderCredits);
71158
+ for (const session of this.#sessions) {
71159
+ if (inspected) {
71160
+ session.replacePlanLimit(inspected);
71161
+ } else if (this.#latestPlanLimit === null) {
71162
+ session.replacePlanLimit(null);
71163
+ }
71164
+ session.publishAccountCreditsSupport(this.#accountCreditsSupported);
71165
+ }
71166
+ return true;
71167
+ }
71168
+ #refreshCustomProvider() {
71169
+ if (this.#closePromise)
71170
+ return Promise.resolve();
71171
+ if (this.#accountInspection)
71172
+ return this.#accountInspection.then(() => void 0);
71173
+ if (this.#customProviderRefresh)
71174
+ return this.#customProviderRefresh;
71175
+ const generation = ++this.#quotaGeneration;
71176
+ this.#customProviderRefresh = (async () => {
71177
+ let committed = false;
71178
+ try {
71179
+ const accounts = await this.#dependencies.inspectCustomProviderAccounts?.(this.#abortController.signal) ?? [];
71180
+ committed = this.#applyCustomProviderAccounts(accounts, generation);
71181
+ } catch {
71182
+ committed = this.#applyCustomProviderAccounts([], generation);
71183
+ } finally {
71184
+ if (committed && !this.#closePromise)
71185
+ this.#customProviderRefreshAt = Date.now();
71186
+ }
71187
+ })().finally(() => {
71188
+ this.#customProviderRefresh = null;
71189
+ });
71190
+ return this.#customProviderRefresh;
71191
+ }
71192
+ async #readAccounts() {
71193
+ const generation = ++this.#quotaGeneration;
71194
+ try {
71195
+ const customAccounts = await this.#dependencies.inspectCustomProviderAccounts?.(this.#abortController.signal) ?? [];
71196
+ if (this.#closePromise)
71197
+ return [];
71198
+ if (customAccounts.length > 0) {
71199
+ if (this.#applyCustomProviderAccounts(customAccounts, generation)) {
71200
+ this.#customProviderActive = true;
71201
+ this.#creditsSeeded = true;
71202
+ this.#customProviderRefreshAt = Date.now();
71203
+ }
71204
+ return customAccounts;
71205
+ }
71206
+ } catch {
71207
+ if (this.#closePromise)
71208
+ return [];
71209
+ }
71210
+ if (generation >= this.#committedQuotaGeneration) {
71211
+ this.#committedQuotaGeneration = generation;
71212
+ const hadCustomProvider = this.#customProviderActive || this.#customProviderCredits !== null;
71213
+ this.#customProviderActive = false;
71214
+ this.#customProviderCredits = null;
71215
+ this.#customProviderBalance = null;
71216
+ if (hadCustomProvider && this.#latestPlanLimit === null) {
71217
+ for (const session of this.#sessions) {
71218
+ session.replacePlanLimit(null);
71219
+ }
71220
+ }
71221
+ }
70342
71222
  let inspector;
70343
71223
  try {
70344
71224
  this.#dependencies.inspectInstallation();
70345
71225
  inspector = this.#dependencies.createInspector({ cwd: process.cwd() });
70346
71226
  this.#inspectors.add(inspector);
70347
71227
  const account = await inspector.inspectAccount?.() ?? null;
70348
- if (this.#latestPlanLimit === planLimitAtStart) {
71228
+ if (!this.#closePromise && generation >= this.#committedQuotaGeneration) {
71229
+ this.#committedQuotaGeneration = generation;
70349
71230
  this.#accountCreditsSupported = account?.credits !== void 0;
70350
71231
  const inspected = planLimitFromAccountCredits(account?.credits);
70351
71232
  if (inspected) {
@@ -70365,9 +71246,9 @@ var ClaudeCodeAdapter = class {
70365
71246
  session.publishPlanLimit(this.#latestPlanLimit);
70366
71247
  }
70367
71248
  }
70368
- return account;
71249
+ return account ? [account] : [];
70369
71250
  } catch {
70370
- return null;
71251
+ return [];
70371
71252
  } finally {
70372
71253
  if (inspector) {
70373
71254
  await inspector.close().catch(() => void 0);
@@ -70525,7 +71406,7 @@ var ClaudeCodeAdapter = class {
70525
71406
  }
70526
71407
  requestedPermissionModeId = CLAUDE_DEFAULT_PERMISSION_MODE_ID;
70527
71408
  }
70528
- const cwd = path15.resolve(input3.cwd);
71409
+ const cwd = path16.resolve(input3.cwd);
70529
71410
  if (input3.kind === "rollbackLastTurn") {
70530
71411
  for (const source of this.#sessions) {
70531
71412
  const ready = await source.prepareRollback(input3.sourceRef.nativeSessionId);
@@ -70659,31 +71540,63 @@ var ClaudeCodeAdapter = class {
70659
71540
  } catch {
70660
71541
  return null;
70661
71542
  }
71543
+ const hadCustomProvider = this.#customProviderActive || this.#customProviderCredits !== null;
70662
71544
  this.#latestPlanLimit = next.fiveHour || next.sevenDay ? next : null;
70663
71545
  if (this.#latestPlanLimit) {
71546
+ this.#committedQuotaGeneration = ++this.#quotaGeneration;
71547
+ this.#customProviderActive = false;
71548
+ this.#customProviderCredits = null;
71549
+ this.#customProviderBalance = null;
70664
71550
  this.#creditsSeeded = true;
70665
71551
  this.#accountCreditsSupported = true;
70666
71552
  for (const session of this.#sessions) {
70667
- session.publishAccountCreditsSupport(true);
70668
- if (session !== origin)
70669
- session.publishPlanLimit(this.#latestPlanLimit);
71553
+ if (hadCustomProvider && session !== origin) {
71554
+ session.replacePlanLimit(this.#latestPlanLimit);
71555
+ session.publishAccountCreditsSupport(true);
71556
+ } else {
71557
+ session.publishAccountCreditsSupport(true);
71558
+ if (session !== origin)
71559
+ session.publishPlanLimit(this.#latestPlanLimit);
71560
+ }
70670
71561
  }
70671
71562
  }
70672
- return this.#latestPlanLimit;
71563
+ return this.#latestPlanLimit ? { planLimit: this.#latestPlanLimit, replace: hadCustomProvider } : null;
70673
71564
  }
70674
71565
  credits() {
70675
- return projectClaudePlanLimitToCredits(this.#latestPlanLimit);
71566
+ return this.#closePromise ? null : projectClaudePlanLimitToCredits(this.#latestPlanLimit) ?? this.#customProviderCredits;
71567
+ }
71568
+ balance() {
71569
+ return this.#closePromise || this.credits() !== null ? null : this.#customProviderBalance;
70676
71570
  }
70677
71571
  refreshCredits() {
70678
71572
  if (this.#closePromise)
70679
71573
  return Promise.resolve(null);
70680
- if (this.#creditsSeeded || this.#latestPlanLimit)
71574
+ if (this.#latestPlanLimit)
70681
71575
  return Promise.resolve(this.credits());
70682
- return this.inspectAccount().then(() => this.#closePromise ? null : this.credits());
71576
+ if (this.#customProviderActive) {
71577
+ if (!this.#customProviderRefresh && !this.#accountInspection && Date.now() - this.#customProviderRefreshAt < CUSTOM_PROVIDER_REFRESH_INTERVAL_MS) {
71578
+ return Promise.resolve(this.credits());
71579
+ }
71580
+ return this.#refreshCustomProvider().then(() => this.#closePromise ? null : this.credits());
71581
+ }
71582
+ if (this.#creditsSeeded)
71583
+ return Promise.resolve(this.credits());
71584
+ return this.inspectAccounts().then(() => this.#closePromise ? null : this.credits());
71585
+ }
71586
+ refreshBalance() {
71587
+ if (this.#closePromise || this.credits() !== null)
71588
+ return Promise.resolve(null);
71589
+ return this.refreshCredits().then(() => this.#closePromise ? null : this.balance());
70683
71590
  }
70684
71591
  close() {
70685
71592
  if (!this.#closePromise) {
71593
+ this.#abortController.abort();
71594
+ this.#committedQuotaGeneration = ++this.#quotaGeneration;
70686
71595
  this.#creditsSeeded = false;
71596
+ this.#customProviderActive = false;
71597
+ this.#customProviderCredits = null;
71598
+ this.#customProviderBalance = null;
71599
+ this.#customProviderRefreshAt = Number.NEGATIVE_INFINITY;
70687
71600
  this.#inspectionCache.clear();
70688
71601
  this.#closePromise = Promise.all([
70689
71602
  this.#importScope.close(),
@@ -70697,11 +71610,11 @@ var ClaudeCodeAdapter = class {
70697
71610
  };
70698
71611
 
70699
71612
  // dist/installation.js
70700
- import { readFile as readFile7, realpath as realpath5 } from "node:fs/promises";
71613
+ import { readFile as readFile8, realpath as realpath5 } from "node:fs/promises";
70701
71614
  import { homedir as homedir2 } from "node:os";
70702
- import path16 from "node:path";
71615
+ import path17 from "node:path";
70703
71616
  async function readSettings(file2) {
70704
- const text3 = await readFile7(file2, "utf8").catch((error63) => {
71617
+ const text3 = await readFile8(file2, "utf8").catch((error63) => {
70705
71618
  if (error63.code === "ENOENT")
70706
71619
  return "{}";
70707
71620
  throw error63;
@@ -70720,9 +71633,9 @@ function createClaudeInstallation(environment, command) {
70720
71633
  ...command ? { command } : {}
70721
71634
  });
70722
71635
  const home = environment.HOME ?? environment.USERPROFILE ?? homedir2();
70723
- const config2 = environment.CLAUDE_CONFIG_DIR ? path16.resolve(home, environment.CLAUDE_CONFIG_DIR) : path16.join(home, ".claude");
70724
- const managedFile = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? path16.join(environment.ProgramFiles ?? "C:\\Program Files", "ClaudeCode", "managed-settings.json") : "/etc/claude-code/managed-settings.json";
70725
- const user = await readSettings(path16.join(config2, "settings.json"));
71636
+ const config2 = environment.CLAUDE_CONFIG_DIR ? path17.resolve(home, environment.CLAUDE_CONFIG_DIR) : path17.join(home, ".claude");
71637
+ const managedFile = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? path17.join(environment.ProgramFiles ?? "C:\\Program Files", "ClaudeCode", "managed-settings.json") : "/etc/claude-code/managed-settings.json";
71638
+ const user = await readSettings(path17.join(config2, "settings.json"));
70726
71639
  const managed = await readSettings(managedFile);
70727
71640
  const settings = { ...user, ...managed, env: { ...user.env, ...managed.env } };
70728
71641
  const env = { ...environment, ...settings.env };
@@ -70735,10 +71648,10 @@ function createClaudeInstallation(environment, command) {
70735
71648
  throw new Error("Unknown Claude release channel");
70736
71649
  const latestVersion = installationVersion(await fetchInstallationText(`https://downloads.claude.ai/claude-code-releases/${channel}`));
70737
71650
  const npm = await npmInstallation(executable, ["@anthropic-ai/claude-code"], env);
70738
- const launcher = path16.join(home, ".local", "bin", process.platform === "win32" ? "claude.exe" : "claude");
71651
+ const launcher = path17.join(home, ".local", "bin", process.platform === "win32" ? "claude.exe" : "claude");
70739
71652
  const selected = await realpath5(executable);
70740
- const versions = path16.join(home, ".local", "share", "claude", "versions") + path16.sep;
70741
- const native = path16.resolve(executable) === launcher && (selected.startsWith(versions) || process.platform === "win32" && selected === launcher);
71653
+ const versions = path17.join(home, ".local", "share", "claude", "versions") + path17.sep;
71654
+ const native = path17.resolve(executable) === launcher && (selected.startsWith(versions) || process.platform === "win32" && selected === launcher);
70742
71655
  const blocked = !!env.DISABLE_UPDATES && env.DISABLE_UPDATES !== "0" || !!settings.minimumVersion && newerInstallationVersion(latestVersion, installationVersion(settings.minimumVersion)) || !!settings.requiredMaximumVersion && newerInstallationVersion(installationVersion(settings.requiredMaximumVersion), latestVersion);
70743
71656
  const canUpdate = !blocked && (npm?.canUpdate ?? native);
70744
71657
  update = async () => {
@@ -70769,7 +71682,7 @@ function createClaudeInstallation(environment, command) {
70769
71682
  }
70770
71683
 
70771
71684
  // dist/user-shell-environment.js
70772
- import path17 from "node:path";
71685
+ import path18 from "node:path";
70773
71686
  import { execFile as execFile4 } from "node:child_process";
70774
71687
  var ENVIRONMENT_MARKER = Buffer.from("\0CODEXHOST_USER_SHELL_ENV_V1\0");
70775
71688
  var ENVIRONMENT_COMMAND = "printf '\\0CODEXHOST_USER_SHELL_ENV_V1\\0'; /usr/bin/env -0";
@@ -70803,9 +71716,9 @@ function mergeMissingEnvironment(environment, shellEnvironment, platform) {
70803
71716
  const merged = { ...environment };
70804
71717
  for (const [name, value] of Object.entries(shellEnvironment)) {
70805
71718
  if (name === "PATH" && platform === "darwin") {
70806
- const path18 = mergeMacPath(merged.PATH, value);
70807
- if (path18 !== void 0)
70808
- merged.PATH = path18;
71719
+ const path19 = mergeMacPath(merged.PATH, value);
71720
+ if (path19 !== void 0)
71721
+ merged.PATH = path19;
70809
71722
  continue;
70810
71723
  }
70811
71724
  if (merged[name] === void 0)
@@ -70814,13 +71727,13 @@ function mergeMissingEnvironment(environment, shellEnvironment, platform) {
70814
71727
  return merged;
70815
71728
  }
70816
71729
  function mergeMacPath(hostPath, shellPath) {
70817
- const hostEntries = hostPath?.split(path17.posix.delimiter) ?? [];
70818
- const seen = new Set(hostEntries.filter((entry) => entry.length > 0 && path17.posix.isAbsolute(entry)).map((entry) => path17.posix.resolve(entry)));
71730
+ const hostEntries = hostPath?.split(path18.posix.delimiter) ?? [];
71731
+ const seen = new Set(hostEntries.filter((entry) => entry.length > 0 && path18.posix.isAbsolute(entry)).map((entry) => path18.posix.resolve(entry)));
70819
71732
  const additions = [];
70820
- for (const entry of shellPath.split(path17.posix.delimiter)) {
70821
- if (entry.length === 0 || !path17.posix.isAbsolute(entry))
71733
+ for (const entry of shellPath.split(path18.posix.delimiter)) {
71734
+ if (entry.length === 0 || !path18.posix.isAbsolute(entry))
70822
71735
  continue;
70823
- const normalized = path17.posix.resolve(entry);
71736
+ const normalized = path18.posix.resolve(entry);
70824
71737
  if (seen.has(normalized))
70825
71738
  continue;
70826
71739
  seen.add(normalized);
@@ -70828,14 +71741,14 @@ function mergeMacPath(hostPath, shellPath) {
70828
71741
  }
70829
71742
  if (hostPath === void 0 && additions.length === 0)
70830
71743
  return void 0;
70831
- return [...hostEntries, ...additions].join(path17.posix.delimiter);
71744
+ return [...hostEntries, ...additions].join(path18.posix.delimiter);
70832
71745
  }
70833
71746
  async function withUserShellEnvironment(environment, dependencies) {
70834
71747
  const platform = dependencies?.platform ?? process.platform;
70835
71748
  if (platform === "win32" || !environment.HOME)
70836
71749
  return environment;
70837
71750
  const shell = environment.SHELL?.trim() || defaultShell(platform);
70838
- if (!shell || !SUPPORTED_SHELLS.has(path17.basename(shell)))
71751
+ if (!shell || !SUPPORTED_SHELLS.has(path18.basename(shell)))
70839
71752
  return environment;
70840
71753
  const cacheKey = `${platform}\0${shell}\0${environment.HOME}`;
70841
71754
  const cached2 = dependencies ? void 0 : shellEnvironmentCache.get(cacheKey);