@codexhost/cli-win32-x64 0.29.2 → 0.31.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 (122) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +94 -20
  4. package/app/console-web.js +123 -31
  5. package/app/desktop-controller.mjs +113 -37
  6. package/app/host-runtime.mjs +3963 -2280
  7. package/app/plugins/antigravity/plugin.mjs +94 -20
  8. package/app/plugins/claude-code/plugin.mjs +105 -28
  9. package/app/plugins/codebuddy/plugin.mjs +767 -202
  10. package/app/plugins/codex-usage/plugin.mjs +112 -38
  11. package/app/plugins/copilot/plugin.mjs +94 -20
  12. package/app/plugins/cursor-cli/plugin.mjs +94 -20
  13. package/app/plugins/deepseek-harness/plugin.mjs +94 -20
  14. package/app/plugins/devin/plugin.mjs +94 -20
  15. package/app/plugins/grok/plugin.mjs +94 -20
  16. package/app/plugins/hermes/plugin.mjs +94 -20
  17. package/app/plugins/kimi-code/plugin.mjs +94 -20
  18. package/app/plugins/kiro-cli/plugin.mjs +94 -20
  19. package/app/plugins/omp/plugin.mjs +94 -20
  20. package/app/plugins/opencode/plugin.mjs +94 -20
  21. package/app/plugins/pi/plugin.mjs +94 -20
  22. package/app/plugins/qoder/plugin.mjs +94 -20
  23. package/app/plugins/qoder-cn/plugin.mjs +94 -20
  24. package/app/plugins/qwen-code/plugin.mjs +94 -20
  25. package/app/plugins/workbuddy/plugin.mjs +798 -202
  26. package/app/plugins/zcode/plugin.mjs +94 -20
  27. package/app/renderer-extension.js +702 -440
  28. package/app/web/assets/abnfDiagram-XWFEHMT6-Bqy7uOSy.js +1 -0
  29. package/app/web/assets/architectureDiagram-CSQXQB3N-6aaP1YoM.js +36 -0
  30. package/app/web/assets/blockDiagram-BEDRHYPZ-B4QSFXe0.js +140 -0
  31. package/app/web/assets/bpmnIcons-APHXDYXF-ByGoYv9M.js +1 -0
  32. package/app/web/assets/c4Diagram-M2UUVUY5-BYE-C8Gq.js +38 -0
  33. package/app/web/assets/chunk-2Q5K7J3B-CiEM-GTd.js +1 -0
  34. package/app/web/assets/chunk-3GCGMST5-hzY9BiB1.js +1 -0
  35. package/app/web/assets/chunk-5VM5RSS4-DYXznY0H.js +15 -0
  36. package/app/web/assets/chunk-7U7NFRK5-Bzw5MDPr.js +88 -0
  37. package/app/web/assets/chunk-CNRTWJTD-DMbxMfi3.js +1 -0
  38. package/app/web/assets/chunk-D5HYT7QG-By0ZVBtD.js +1 -0
  39. package/app/web/assets/chunk-EBZ3SEQC-Yyu_sMV7.js +2 -0
  40. package/app/web/assets/chunk-JWPE2WC7-DDzqxIPT.js +1 -0
  41. package/app/web/assets/chunk-KTR4FSNJ-GlKqhtpl.js +1 -0
  42. package/app/web/assets/chunk-XXDRQBXY-DNc-CvYu.js +1 -0
  43. package/app/web/assets/classDiagram-v2-KXABOMEV-4_PFS2N_.js +217 -0
  44. package/app/web/assets/cose-bilkent-JH36ORCC-BE3foHUY.js +1 -0
  45. package/app/web/assets/cynefin-EF2NZ3EQ-D2PqrYZ3.js +141 -0
  46. package/app/web/assets/cynefinDiagram-NJNITYFG-DOObpTbq.js +62 -0
  47. package/app/web/assets/cytoscape.esm-Cm0uQArZ.js +332 -0
  48. package/app/web/assets/d3-scale-4DPf7zan.js +1 -0
  49. package/app/web/assets/dagre-KIHZ2IZ3-Znm2jin9.js +4 -0
  50. package/app/web/assets/diagram-7YQZDPLS-ByZMD-uA.js +41 -0
  51. package/app/web/assets/diagram-QBROCOUO-BiRShpnN.js +200 -0
  52. package/app/web/assets/diagram-RJJCUUZO-D9wLVoK2.js +30 -0
  53. package/app/web/assets/diagram-WERXNKYE-BSbIh-yC.js +24 -0
  54. package/app/web/assets/diagram-YHHI257C-DMWrHMc8.js +3 -0
  55. package/app/web/assets/diagram-YR4HJLHV-C4sBAFb1.js +24 -0
  56. package/app/web/assets/ebnfDiagram-N527522P-BZLloaoQ.js +1 -0
  57. package/app/web/assets/elk-O5DQBFGD-Da3e5tn5.js +27 -0
  58. package/app/web/assets/erDiagram-K3K3BIDK-B2lKAIZF.js +99 -0
  59. package/app/web/assets/flowDiagram-Z6JWZHQI-q2EY_kmB.js +213 -0
  60. package/app/web/assets/ganttDiagram-3PRQTZWP-BGrNZ20b.js +292 -0
  61. package/app/web/assets/gitGraphDiagram-VXDFKS5L-DIZNXREy.js +106 -0
  62. package/app/web/assets/graph-D8UmR1vK.js +1 -0
  63. package/app/web/assets/grid-E2QIVN74-0cUkPG69.js +1 -0
  64. package/app/web/assets/{index-aSHN2MIG.css → index-BbmB5VLj.css} +1 -1
  65. package/app/web/assets/{index-0TnaYwHS.js → index-PN7K-15_.js} +78 -78
  66. package/app/web/assets/infoDiagram-EZ3ZOAHP-BHhUTQCn.js +2 -0
  67. package/app/web/assets/ishikawaDiagram-S3EKX5GW-DPOxtl4c.js +70 -0
  68. package/app/web/assets/journeyDiagram-POQNLL5X-D8RyXckG.js +139 -0
  69. package/app/web/assets/kanban-definition-BH5XI6FM-COJv3Hyh.js +89 -0
  70. package/app/web/assets/langs/{graphql-ChAeyPkT.js → graphql-D6Z3qcRW.js} +1 -1
  71. package/app/web/assets/langs/{http-BvreBIbD.js → http-XiU9G9In.js} +1 -1
  72. package/app/web/assets/langs/{php-D8omCIuJ.js → php-DL3xwS-7.js} +1 -1
  73. package/app/web/assets/langs/{rst-Do7RLLCS.js → rst-DudRVJ9g.js} +1 -1
  74. package/app/web/assets/langs/{ruby-rH_O_vse.js → ruby-_FqsfqJi.js} +1 -1
  75. package/app/web/assets/langs/{svelte-xZy73wAj.js → svelte-ClsVJoBT.js} +1 -1
  76. package/app/web/assets/langs/{vue-C4DW8agZ.js → vue-BiKMXCyK.js} +1 -1
  77. package/app/web/assets/mermaid.core-DYdcDKIt.js +314 -0
  78. package/app/web/assets/mindmap-definition-WVAN44T4-DnYIM4ja.js +98 -0
  79. package/app/web/assets/pegDiagram-D4NLKWP3-Ds3GAEJ6.js +1 -0
  80. package/app/web/assets/pieDiagram-36ENHN4W-BhLUJGEB.js +39 -0
  81. package/app/web/assets/quadrantDiagram-ZQUDMS73-DwtX-IxK.js +7 -0
  82. package/app/web/assets/railroadDiagram-JIZHGYPL-D2vmTTnJ.js +1 -0
  83. package/app/web/assets/render-VIF2ZAQL-DGU1ql-Z.js +2 -0
  84. package/app/web/assets/requirementDiagram-AXW2TVFA-u3j1sKkI.js +84 -0
  85. package/app/web/assets/sankeyDiagram-FBCJTAIF-k-An9VHW.js +40 -0
  86. package/app/web/assets/sequenceDiagram-3LA2ROMG-DUjbYb4R.js +169 -0
  87. package/app/web/assets/sizeCapture-2Q2CQKSF-DATTL7FZ.js +1 -0
  88. package/app/web/assets/stateDiagram-v2-ATKHQDJO-cCJX5M2u.js +291 -0
  89. package/app/web/assets/swimlanes-YQL5WMAO-B7grWEWt.js +1 -0
  90. package/app/web/assets/swimlanesDiagram-UCCPES4V-B8Jem9gq.js +8 -0
  91. package/app/web/assets/timeline-definition-7Z437IG3-BhsLa6l1.js +120 -0
  92. package/app/web/assets/usecaseDiagram-RDK6N6HP-CkPQYmQw.js +370 -0
  93. package/app/web/assets/vendor-BKfNgqAm.js +666 -0
  94. package/app/web/assets/vennDiagram-SHRQU5PJ-CufZSwvw.js +34 -0
  95. package/app/web/assets/wardleyDiagram-F3OXNVQS-CSkfpFOA.js +78 -0
  96. package/app/web/assets/xychartDiagram-GDYJKCDI-BhZf9scK.js +7 -0
  97. package/app/web/codexhost-settings.js +57 -57
  98. package/app/web/index.html +3 -3
  99. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +65 -65
  100. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
  101. package/app/web/plugins/deepseek-ai__dsh-api-workspace-controller/client.js +3 -3
  102. package/app/web/plugins/deepseek-ai__dsh-client-locale/client.js +1 -1
  103. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +75 -75
  104. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +12 -12
  105. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +16 -16
  106. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +3 -3
  107. package/app/web/plugins/deepseek-ai__dsh-client-ui-permission-presets/client.js +1 -1
  108. package/app/web/plugins/deepseek-ai__dsh-client-ui-plan/client.js +1 -1
  109. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
  110. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  111. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  112. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +70 -72
  113. package/app/web-modules/licenses/DSH-THIRD_PARTY_NOTICES.md +1 -1
  114. package/app/web-modules/server.mjs +724 -259
  115. package/bin/codexhost.exe +0 -0
  116. package/libexec/codexhost-node-repl.exe +0 -0
  117. package/libexec/codexhost-screenshot.exe +0 -0
  118. package/libexec/codexhost-shell.exe +0 -0
  119. package/libexec/codexhost-shim.exe +0 -0
  120. package/libexec/codexhost-updater.exe +0 -0
  121. package/package.json +1 -1
  122. package/app/web/assets/vendor-C9g2bw8s.js +0 -410
@@ -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, path12) {
832
- if (!path12)
831
+ function getElementAtPath(obj, path13) {
832
+ if (!path13)
833
833
  return obj;
834
- return path12.reduce((acc, key) => acc?.[key], obj);
834
+ return path13.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(path12, issues) {
1174
+ function prefixIssues(path13, issues) {
1175
1175
  return issues.map((iss) => {
1176
1176
  var _a3;
1177
1177
  (_a3 = iss).path ?? (_a3.path = []);
1178
- iss.path.unshift(path12);
1178
+ iss.path.unshift(path13);
1179
1179
  return iss;
1180
1180
  });
1181
1181
  }
@@ -1637,16 +1637,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
1637
1637
  }
1638
1638
  function formatError(error62, mapper = (issue2) => issue2.message) {
1639
1639
  const fieldErrors = { _errors: [] };
1640
- const processError = (error63, path12 = []) => {
1640
+ const processError = (error63, path13 = []) => {
1641
1641
  for (const issue2 of error63.issues) {
1642
1642
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1643
- issue2.errors.map((issues) => processError({ issues }, [...path12, ...issue2.path]));
1643
+ issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1644
1644
  } else if (issue2.code === "invalid_key") {
1645
- processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
1645
+ processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1646
1646
  } else if (issue2.code === "invalid_element") {
1647
- processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
1647
+ processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1648
1648
  } else {
1649
- const fullpath = [...path12, ...issue2.path];
1649
+ const fullpath = [...path13, ...issue2.path];
1650
1650
  if (fullpath.length === 0) {
1651
1651
  fieldErrors._errors.push(mapper(issue2));
1652
1652
  } else {
@@ -1685,17 +1685,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
1685
1685
  }
1686
1686
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
1687
1687
  const result = { errors: [] };
1688
- const processError = (error63, path12 = []) => {
1688
+ const processError = (error63, path13 = []) => {
1689
1689
  var _a3;
1690
1690
  for (const issue2 of error63.issues) {
1691
1691
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1692
- issue2.errors.map((issues) => processError({ issues }, [...path12, ...issue2.path]));
1692
+ issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1693
1693
  } else if (issue2.code === "invalid_key") {
1694
- processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
1694
+ processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1695
1695
  } else if (issue2.code === "invalid_element") {
1696
- processError({ issues: issue2.issues }, [...path12, ...issue2.path]);
1696
+ processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1697
1697
  } else {
1698
- const fullpath = [...path12, ...issue2.path];
1698
+ const fullpath = [...path13, ...issue2.path];
1699
1699
  if (fullpath.length === 0) {
1700
1700
  result.errors.push(mapper(issue2));
1701
1701
  continue;
@@ -1734,8 +1734,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
1734
1734
  }
1735
1735
  function toDotPath(_path) {
1736
1736
  const segs = [];
1737
- const path12 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1738
- for (const seg of path12) {
1737
+ const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1738
+ for (const seg of path13) {
1739
1739
  if (typeof seg === "number")
1740
1740
  segs.push(`[${seg}]`);
1741
1741
  else if (typeof seg === "symbol")
@@ -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 path12 = ref.slice(1).split("/").filter(Boolean);
18877
- if (path12.length === 0) {
18876
+ const path13 = ref.slice(1).split("/").filter(Boolean);
18877
+ if (path13.length === 0) {
18878
18878
  return ctx.rootSchema;
18879
18879
  }
18880
18880
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
18881
- if (path12[0] === defsKey) {
18882
- const key = path12[1] === void 0 ? void 0 : decodeJSONPointerSegment(path12[1]);
18881
+ if (path13[0] === defsKey) {
18882
+ const key = path13[1] === void 0 ? void 0 : decodeJSONPointerSegment(path13[1]);
18883
18883
  if (!key || !ctx.defs[key]) {
18884
18884
  throw new Error(`Reference not found: ${ref}`);
18885
18885
  }
@@ -20358,15 +20358,15 @@ var threadOwnershipListResultSchema = external_exports.object({
20358
20358
  threads: external_exports.array(threadOwnershipSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
20359
20359
  }).strict().superRefine(({ threads }, context) => {
20360
20360
  const seen = /* @__PURE__ */ new Set();
20361
- for (const [index, thread2] of threads.entries()) {
20362
- if (seen.has(thread2.threadId)) {
20361
+ for (const [index, thread3] of threads.entries()) {
20362
+ if (seen.has(thread3.threadId)) {
20363
20363
  context.addIssue({
20364
20364
  code: "custom",
20365
20365
  message: "Thread ownership-list results must be unique",
20366
20366
  path: ["threads", index, "threadId"]
20367
20367
  });
20368
20368
  }
20369
- seen.add(thread2.threadId);
20369
+ seen.add(thread3.threadId);
20370
20370
  }
20371
20371
  });
20372
20372
  var threadSteeringInspectParamsSchema = external_exports.object({
@@ -20564,7 +20564,7 @@ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("ty
20564
20564
  default: external_exports.string().optional()
20565
20565
  })
20566
20566
  ]).superRefine((field2, ctx) => {
20567
- const issue2 = (path12, message) => ctx.addIssue({ code: "custom", path: [path12], message });
20567
+ const issue2 = (path13, message) => ctx.addIssue({ code: "custom", path: [path13], message });
20568
20568
  if (field2.type === "number" || field2.type === "range") {
20569
20569
  const { min = -Infinity, max = Infinity, default: value } = field2;
20570
20570
  if (min > max)
@@ -20670,16 +20670,16 @@ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id2) => !reservedNa
20670
20670
  var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
20671
20671
  var hostExtensionDigestSchema = desktopExtensionHashSchema;
20672
20672
  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((path12) => path12.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
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((path13) => path13.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
20674
20674
  var legacy = desktopExtensionManifestSchema.shape;
20675
20675
  var localized = (max, min = 0) => external_exports.strictObject({
20676
20676
  en: external_exports.string().trim().min(min).max(max),
20677
20677
  "zh-CN": external_exports.string().trim().min(min).max(max)
20678
20678
  });
20679
- var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path12) => path12.endsWith(suffix), `Expected a ${suffix} file`);
20679
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path13) => path13.endsWith(suffix), `Expected a ${suffix} file`);
20680
20680
  var moduleEntry = resourceWithSuffix(".mjs");
20681
20681
  var style = resourceWithSuffix(".css").optional();
20682
- var hostExtensionCanonicalPath = (path12) => path12.normalize("NFC").toLowerCase();
20682
+ var hostExtensionCanonicalPath = (path13) => path13.normalize("NFC").toLowerCase();
20683
20683
  var hostExtensionManifestV2Schema = external_exports.strictObject({
20684
20684
  manifestVersion: external_exports.literal(2),
20685
20685
  id: hostExtensionIdSchema,
@@ -20689,8 +20689,8 @@ var hostExtensionManifestV2Schema = external_exports.strictObject({
20689
20689
  details: localized(16384).optional(),
20690
20690
  author: legacy.author,
20691
20691
  repository: legacy.repository,
20692
- icon: legacy.icon.refine((path12) => path12 === void 0 || hostExtensionResourcePathSchema.safeParse(path12).success),
20693
- screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path12) => hostExtensionResourcePathSchema.safeParse(path12).success)),
20692
+ icon: legacy.icon.refine((path13) => path13 === void 0 || hostExtensionResourcePathSchema.safeParse(path13).success),
20693
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path13) => hostExtensionResourcePathSchema.safeParse(path13).success)),
20694
20694
  categories: legacy.categories,
20695
20695
  settingsSchema: legacy.settingsSchema,
20696
20696
  slots: legacy.slots.removeDefault().optional(),
@@ -20812,7 +20812,7 @@ var active = {
20812
20812
  digest: hostExtensionDigestSchema
20813
20813
  };
20814
20814
  var optionalActivation = { ...id, activationId: active.activationId.optional() };
20815
- var filePath = external_exports.string().min(1).max(4096).refine((path12) => /^(?:\/|[a-z]:[/\\])/iu.test(path12) && !path12.includes("\0") && !path12.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
20815
+ var filePath = external_exports.string().min(1).max(4096).refine((path13) => /^(?:\/|[a-z]:[/\\])/iu.test(path13) && !path13.includes("\0") && !path13.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
20816
20816
  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
20817
  function base643(maxBytes) {
20818
20818
  return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
@@ -21102,9 +21102,71 @@ var productTelemetryHeartbeatSchema = external_exports.object({
21102
21102
  message: "Telemetry heartbeat must contain at least one countable field"
21103
21103
  });
21104
21104
 
21105
+ // ../../shared-contracts/dist/native-codex-goal.js
21106
+ var NATIVE_CODEX_GOAL_METHOD = "codexhost/thread/goal";
21107
+ var NATIVE_CODEX_GOAL_MAX_OBJECTIVE_CHARS = 4e3;
21108
+ var thread = { threadId: hostThreadIdSchema };
21109
+ var nativeCodexGoalRequestSchema = external_exports.discriminatedUnion("action", [
21110
+ external_exports.strictObject({ ...thread, action: external_exports.enum(["get", "pause", "resume", "clear"]) }),
21111
+ external_exports.strictObject({
21112
+ ...thread,
21113
+ action: external_exports.enum(["create", "edit"]),
21114
+ objective: external_exports.string().trim().min(1).refine((objective) => Array.from(objective).length <= NATIVE_CODEX_GOAL_MAX_OBJECTIVE_CHARS, `A goal objective can have up to ${NATIVE_CODEX_GOAL_MAX_OBJECTIVE_CHARS} characters.`)
21115
+ })
21116
+ ]);
21117
+ var nativeCodexGoalResultSchema = external_exports.object({
21118
+ goal: external_exports.object({
21119
+ threadId: hostThreadIdSchema,
21120
+ objective: external_exports.string(),
21121
+ status: external_exports.enum(["active", "paused", "blocked", "usageLimited", "budgetLimited", "complete"]),
21122
+ tokenBudget: external_exports.int().positive().nullable().default(null),
21123
+ tokensUsed: external_exports.int().nonnegative(),
21124
+ timeUsedSeconds: external_exports.int().nonnegative()
21125
+ }).nullable()
21126
+ });
21127
+
21105
21128
  // ../../shared-contracts/dist/client-channel.js
21106
21129
  var CLIENT_CHANNEL_VERSION = 1;
21107
21130
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
21131
+ var THREAD_SECTION_CAPABILITY = "threadSectionsV1";
21132
+ var threadSectionName = external_exports.string().trim().min(1);
21133
+ var threadSectionId = external_exports.string().min(1);
21134
+ var threadSectionAppearance = external_exports.object({
21135
+ icon: external_exports.string().nullable(),
21136
+ color: external_exports.string().nullable()
21137
+ });
21138
+ var clientThreadSectionAppearanceSchema = threadSectionAppearance.nullable();
21139
+ var CLIENT_THREAD_SECTION_MUTATIONS = {
21140
+ create: {
21141
+ method: "codexhost/thread/sections/create",
21142
+ params: external_exports.object({ name: threadSectionName }).strict()
21143
+ },
21144
+ update: {
21145
+ method: "codexhost/thread/sections/update",
21146
+ params: external_exports.object({
21147
+ sectionId: threadSectionId,
21148
+ name: threadSectionName,
21149
+ appearance: threadSectionAppearance.strict().nullable().optional()
21150
+ }).strict()
21151
+ },
21152
+ delete: {
21153
+ method: "codexhost/thread/sections/delete",
21154
+ params: external_exports.object({ sectionId: threadSectionId }).strict()
21155
+ }
21156
+ };
21157
+ var clientThreadSectionMutationResultSchema = external_exports.discriminatedUnion("status", [
21158
+ external_exports.object({ status: external_exports.literal("unknown") }),
21159
+ external_exports.object({
21160
+ status: external_exports.literal("confirmed"),
21161
+ sectionId: threadSectionId,
21162
+ section: external_exports.object({
21163
+ id: threadSectionId,
21164
+ name: external_exports.string().min(1),
21165
+ appearance: clientThreadSectionAppearanceSchema
21166
+ }).nullable(),
21167
+ syncPending: external_exports.boolean()
21168
+ })
21169
+ ]);
21108
21170
  var CLIENT_CHANNEL_METHODS = [
21109
21171
  "codexhost/skills/list",
21110
21172
  "codexhost/voice/status",
@@ -21114,10 +21176,12 @@ var CLIENT_CHANNEL_METHODS = [
21114
21176
  "codexhost/harness/display-settings/capabilities",
21115
21177
  "codexhost/harness/preferences/get",
21116
21178
  "codexhost/harness/preferences/patch",
21179
+ "experimentalFeature/list",
21117
21180
  "thread/list",
21118
21181
  "thread/metadata/update",
21119
21182
  "codexhost/thread/catalog/read",
21120
21183
  "thread/read",
21184
+ NATIVE_CODEX_GOAL_METHOD,
21121
21185
  "thread/resume",
21122
21186
  "thread/fork",
21123
21187
  "thread/turns/list",
@@ -21149,6 +21213,9 @@ var CLIENT_CHANNEL_METHODS = [
21149
21213
  "codexhost/thread/pins/list",
21150
21214
  "codexhost/thread/sections/list",
21151
21215
  "codexhost/thread/sections/move",
21216
+ CLIENT_THREAD_SECTION_MUTATIONS.create.method,
21217
+ CLIENT_THREAD_SECTION_MUTATIONS.update.method,
21218
+ CLIENT_THREAD_SECTION_MUTATIONS.delete.method,
21152
21219
  "codexhost/thread/pins/set",
21153
21220
  "codexhost/harness/plugins/list",
21154
21221
  "codexhost/harness/inspect",
@@ -21199,16 +21266,21 @@ var CLIENT_CHANNEL_METHODS = [
21199
21266
  "codexhost/sessions/loaded/list"
21200
21267
  ];
21201
21268
  var clientThreadSectionsSchema = external_exports.object({
21269
+ [THREAD_SECTION_CAPABILITY]: external_exports.literal(true).optional(),
21270
+ complete: external_exports.literal(false).optional(),
21202
21271
  sections: external_exports.array(external_exports.object({
21203
21272
  id: external_exports.string().min(1),
21204
21273
  name: external_exports.string().min(1),
21274
+ appearance: clientThreadSectionAppearanceSchema.optional(),
21205
21275
  threads: external_exports.array(jsonObjectSchema)
21206
- }).strict())
21207
- }).strict();
21276
+ }))
21277
+ });
21208
21278
  var clientThreadSectionMoveSchema = external_exports.object({
21209
21279
  threadId: external_exports.string().min(1).max(1024),
21210
- sectionId: external_exports.string().min(1).max(1024).nullable()
21211
- }).strict();
21280
+ sectionId: external_exports.string().min(1).max(1024).nullable(),
21281
+ beforeThreadId: external_exports.string().min(1).max(1024).nullable().optional(),
21282
+ expectedSourceSectionId: external_exports.string().min(1).max(1024).optional()
21283
+ }).refine((move) => move.expectedSourceSectionId === void 0 || move.sectionId === null);
21212
21284
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
21213
21285
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
21214
21286
  var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
@@ -21255,6 +21327,7 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
21255
21327
  harnessId: external_exports.string().min(1)
21256
21328
  }),
21257
21329
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
21330
+ external_exports.object({ type: external_exports.literal("sections-changed"), cursor: clientChannelCursorSchema }),
21258
21331
  external_exports.object({
21259
21332
  type: external_exports.literal("preferences-changed"),
21260
21333
  cursor: clientChannelCursorSchema,
@@ -21421,7 +21494,8 @@ var clientChannelDescriptorSchema = external_exports.object({
21421
21494
  startedAt: external_exports.number(),
21422
21495
  epoch: external_exports.string().uuid(),
21423
21496
  capabilities: external_exports.object({
21424
- peerDelegation: external_exports.literal(1).optional()
21497
+ peerDelegation: external_exports.literal(1).optional(),
21498
+ threadReferenceContext: external_exports.literal(1).optional()
21425
21499
  }).optional()
21426
21500
  });
21427
21501
  var clientChannelResponseSchema = external_exports.object({
@@ -23015,7 +23089,7 @@ var identity = external_exports.string().min(1).max(REMOTE_IDENTITY_MAX_LENGTH);
23015
23089
  var target = {
23016
23090
  hostId: identity.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)
23017
23091
  };
23018
- var thread = { ...target, threadId: identity };
23092
+ var thread2 = { ...target, threadId: identity };
23019
23093
  var text = external_exports.string().min(1).max(8e3);
23020
23094
  var input2 = { text, requestId: identity };
23021
23095
  var remoteDeliveryReplySchema = external_exports.discriminatedUnion("accepted", [
@@ -23066,7 +23140,7 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
23066
23140
  serviceTier: external_exports.enum(["priority", "ultrafast"]).optional(),
23067
23141
  reasoningEffort: identity.optional()
23068
23142
  }),
23069
- external_exports.strictObject({ kind: external_exports.literal("status"), ...thread }),
23143
+ external_exports.strictObject({ kind: external_exports.literal("status"), ...thread2 }),
23070
23144
  external_exports.strictObject({
23071
23145
  kind: external_exports.literal("list"),
23072
23146
  ...target,
@@ -23076,7 +23150,7 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
23076
23150
  }),
23077
23151
  external_exports.strictObject({
23078
23152
  kind: external_exports.literal("read"),
23079
- ...thread,
23153
+ ...thread2,
23080
23154
  page: external_exports.strictObject({
23081
23155
  cursor: external_exports.string().min(1).max(8192).nullable(),
23082
23156
  epoch: identity.optional(),
@@ -23086,10 +23160,10 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
23086
23160
  message: "A history continuation requires its connection epoch"
23087
23161
  }).optional()
23088
23162
  }),
23089
- external_exports.strictObject({ kind: external_exports.literal("usage"), ...thread, epoch: identity }),
23163
+ external_exports.strictObject({ kind: external_exports.literal("usage"), ...thread2, epoch: identity }),
23090
23164
  external_exports.strictObject({
23091
23165
  kind: external_exports.literal("configure"),
23092
- ...thread,
23166
+ ...thread2,
23093
23167
  epoch: identity,
23094
23168
  modelId: identity.optional(),
23095
23169
  serviceTier: harnessModelServiceTierSchema.optional(),
@@ -23100,15 +23174,15 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
23100
23174
  }),
23101
23175
  external_exports.strictObject({
23102
23176
  kind: external_exports.literal("prompt"),
23103
- ...thread,
23177
+ ...thread2,
23104
23178
  epoch: identity,
23105
23179
  text,
23106
23180
  requestId: identity.optional()
23107
23181
  }),
23108
- external_exports.strictObject({ kind: external_exports.literal("queue"), ...thread, epoch: identity }),
23182
+ external_exports.strictObject({ kind: external_exports.literal("queue"), ...thread2, epoch: identity }),
23109
23183
  external_exports.strictObject({
23110
23184
  kind: external_exports.literal("delivery"),
23111
- ...thread,
23185
+ ...thread2,
23112
23186
  epoch: identity,
23113
23187
  action: external_exports.discriminatedUnion("kind", [
23114
23188
  external_exports.strictObject({ kind: external_exports.literal("enqueue"), ...input2 }),
@@ -23122,17 +23196,17 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
23122
23196
  external_exports.strictObject({ kind: external_exports.literal("sendNow"), itemId: identity })
23123
23197
  ])
23124
23198
  }),
23125
- external_exports.strictObject({ kind: external_exports.literal("interrupt"), ...thread, epoch: identity, turnId: identity }),
23199
+ external_exports.strictObject({ kind: external_exports.literal("interrupt"), ...thread2, epoch: identity, turnId: identity }),
23126
23200
  external_exports.strictObject({
23127
23201
  kind: external_exports.literal("rename"),
23128
- ...thread,
23202
+ ...thread2,
23129
23203
  epoch: identity,
23130
23204
  name: external_exports.string().min(1).max(512)
23131
23205
  }),
23132
- external_exports.strictObject({ kind: external_exports.literal("archive"), ...thread, epoch: identity, archived: external_exports.boolean() }),
23206
+ external_exports.strictObject({ kind: external_exports.literal("archive"), ...thread2, epoch: identity, archived: external_exports.boolean() }),
23133
23207
  external_exports.strictObject({
23134
23208
  kind: external_exports.literal("respond"),
23135
- ...thread,
23209
+ ...thread2,
23136
23210
  epoch: identity,
23137
23211
  requestId: external_exports.union([identity, external_exports.number().int()]),
23138
23212
  result: external_exports.record(external_exports.string(), external_exports.unknown())
@@ -25403,7 +25477,8 @@ var CODEBUDDY_CAPABILITIES = {
25403
25477
  permissionModeScope: "live"
25404
25478
  },
25405
25479
  history: { fork: true, forkAcrossCwd: false, rollbackLastTurn: true },
25406
- subagents: { observe: true, readTranscript: true }
25480
+ subagents: { observe: true, readTranscript: true },
25481
+ autonomousTurns: { observe: true }
25407
25482
  };
25408
25483
  function capabilitiesForProfile(profile = CODEBUDDY_RUNTIME_PROFILE) {
25409
25484
  return {
@@ -25599,16 +25674,16 @@ var Diff = class {
25599
25674
  }
25600
25675
  }
25601
25676
  }
25602
- addToPath(path12, added, removed, oldPosInc, options) {
25603
- const last = path12.lastComponent;
25677
+ addToPath(path13, added, removed, oldPosInc, options) {
25678
+ const last = path13.lastComponent;
25604
25679
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
25605
25680
  return {
25606
- oldPos: path12.oldPos + oldPosInc,
25681
+ oldPos: path13.oldPos + oldPosInc,
25607
25682
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
25608
25683
  };
25609
25684
  } else {
25610
25685
  return {
25611
- oldPos: path12.oldPos + oldPosInc,
25686
+ oldPos: path13.oldPos + oldPosInc,
25612
25687
  lastComponent: { count: 1, added, removed, previousComponent: last }
25613
25688
  };
25614
25689
  }
@@ -26748,6 +26823,52 @@ function snapshotFromHistory(contents, ref, cwd, profile = CODEBUDDY_RUNTIME_PRO
26748
26823
  });
26749
26824
  return { turns };
26750
26825
  }
26826
+ function compactionEvidenceForTurn(contents, snapshot, turnKey, beforeItems, profile = CODEBUDDY_RUNTIME_PROFILE) {
26827
+ if (!nativeCommandsEnabled(profile))
26828
+ return [];
26829
+ const turnIndex = snapshot.turns.findIndex((turn) => turn.nativeTurnRef.nativeTurnKey === turnKey);
26830
+ if (turnIndex < 0)
26831
+ return [];
26832
+ const history = nativeDisplayHistoryRows(contents);
26833
+ const start = history.findIndex((row) => row.type === "message" && row.role === "user" && text2(row.id) === turnKey);
26834
+ if (start < 0)
26835
+ return [];
26836
+ const turnKeys = new Set(snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey));
26837
+ const attributable = /* @__PURE__ */ new Set();
26838
+ for (let index = start - 1; index >= 0; index -= 1) {
26839
+ const row = history[index];
26840
+ if (!row || !isNativeCompactionSummary(row))
26841
+ break;
26842
+ attributable.add(`compact-${text2(row.id)}`);
26843
+ }
26844
+ let nextTurn = history.length;
26845
+ for (let index = start + 1; index < history.length; index += 1) {
26846
+ const row = history[index];
26847
+ if (row?.type === "message" && row.role === "user" && turnKeys.has(text2(row.id))) {
26848
+ nextTurn = index;
26849
+ break;
26850
+ }
26851
+ }
26852
+ let bodyEnd = nextTurn - 1;
26853
+ if (nextTurn < history.length) {
26854
+ while (bodyEnd > start && isNativeCompactionSummary(history[bodyEnd] ?? {}))
26855
+ bodyEnd -= 1;
26856
+ }
26857
+ for (let index = start + 1; index <= bodyEnd; index += 1) {
26858
+ const row = history[index];
26859
+ if (!row)
26860
+ continue;
26861
+ const data = record3(row.providerData);
26862
+ if (isNativeCompactionSummary(row) || row.role === "assistant" && (data.agent === "compact" || data.isCompactInternal === true)) {
26863
+ attributable.add(`compact-${text2(row.id)}`);
26864
+ }
26865
+ }
26866
+ const candidates = [
26867
+ ...turnIndex > 0 ? snapshot.turns[turnIndex - 1]?.items ?? [] : [],
26868
+ ...snapshot.turns[turnIndex]?.items ?? []
26869
+ ];
26870
+ return candidates.filter(({ item }) => item.type === "contextCompaction" && !beforeItems.has(item.itemId) && attributable.has(item.itemId));
26871
+ }
26751
26872
  function usageCount(value) {
26752
26873
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
26753
26874
  }
@@ -26901,7 +27022,7 @@ function createCodeBuddyUsageStatistics(environment, profile) {
26901
27022
  import { stat as stat3 } from "node:fs/promises";
26902
27023
 
26903
27024
  // ../codebuddy/dist/acp-client.js
26904
- import { execFile as execFile3, spawn } from "node:child_process";
27025
+ import { spawn } from "node:child_process";
26905
27026
  import { Readable as Readable2, Writable } from "node:stream";
26906
27027
 
26907
27028
  // ../../../node_modules/@agentclientprotocol/sdk/dist/schema/index.js
@@ -31501,7 +31622,103 @@ function codeBuddyInvocation(environment, ephemeral, argumentsOverride) {
31501
31622
  var CODEBUDDY_DELEGATION_INSTRUCTIONS = `This Session runs inside codexhost.
31502
31623
  When the user requests cross-Harness agent delegation, use the executable at the CODEXHOST_CLI_PATH environment variable through your native shell tool. Start with its --help and harness list commands, then use delegate start and thread send/read/wait/cancel as documented by the CLI. Pass --format compact when reporting results. Keep the inherited CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID environment variables for all such calls; they identify this Runtime and parent Thread. Do not print or expose their values, replace the configured executable, or start delegation unless the user's request authorizes it. Native CodeBuddy Agent subagents remain available for CodeBuddy-only work.`;
31503
31624
 
31625
+ // ../codebuddy/dist/process-termination.js
31626
+ import { execFile as execFile3 } from "node:child_process";
31627
+ import path8 from "node:path";
31628
+ var WINDOWS_TASKKILL_TIMEOUT_MS = 45e3;
31629
+ var MAX_DIAGNOSTIC_LENGTH = 400;
31630
+ var taskkillQueue = Promise.resolve();
31631
+ function windowsTaskkillPath(env = process.env) {
31632
+ const root = env.SystemRoot ?? env.SYSTEMROOT;
31633
+ return root && path8.win32.isAbsolute(root) ? path8.win32.join(root, "System32", "taskkill.exe") : "taskkill";
31634
+ }
31635
+ function compactDiagnostic(value) {
31636
+ const sanitized = sanitizeDiagnosticTail(value).replace(/\s+/gu, " ").trim();
31637
+ return sanitized.length <= MAX_DIAGNOSTIC_LENGTH ? sanitized : `${sanitized.slice(0, MAX_DIAGNOSTIC_LENGTH)}...`;
31638
+ }
31639
+ function formatTaskkillError(error62, stderr) {
31640
+ const info = typeof error62 === "object" && error62 !== null ? error62 : {};
31641
+ const parts = [
31642
+ ...info.code != null ? [`code=${String(info.code)}`] : [],
31643
+ ...info.signal ? [`signal=${info.signal}`] : [],
31644
+ `killed=${Boolean(info.killed)}`
31645
+ ];
31646
+ const rawStderr = typeof stderr === "string" ? stderr : Buffer.isBuffer(stderr) ? stderr.toString("utf8") : typeof info.stderr === "string" ? info.stderr : "";
31647
+ const detail = compactDiagnostic(rawStderr);
31648
+ if (detail)
31649
+ parts.push(`stderr=${detail}`);
31650
+ else {
31651
+ const message = compactDiagnostic(error62 instanceof Error ? error62.message : String(error62));
31652
+ if (message)
31653
+ parts.push(`error=${message}`);
31654
+ }
31655
+ return `taskkill failed (${parts.join(", ")})`;
31656
+ }
31657
+ async function terminateWindowsProcessTree(child, exited, timeoutMs = WINDOWS_TASKKILL_TIMEOUT_MS) {
31658
+ const exitedNow = () => child.exitCode !== null || child.signalCode !== null;
31659
+ if (!child.pid || exitedNow())
31660
+ return void 0;
31661
+ const deadline = Date.now() + timeoutMs;
31662
+ const previous = taskkillQueue;
31663
+ const slot = Promise.withResolvers();
31664
+ taskkillQueue = previous.then(() => slot.promise);
31665
+ let timer;
31666
+ const status = await Promise.race([
31667
+ previous.then(() => "ready"),
31668
+ exited.then(() => "exited"),
31669
+ new Promise((resolve) => {
31670
+ timer = setTimeout(() => resolve("timeout"), Math.max(0, deadline - Date.now()));
31671
+ })
31672
+ ]).finally(() => clearTimeout(timer));
31673
+ if (status === "exited" || exitedNow()) {
31674
+ slot.resolve();
31675
+ return void 0;
31676
+ }
31677
+ const remainingMs = deadline - Date.now();
31678
+ if (status === "timeout" || remainingMs <= 0) {
31679
+ slot.resolve();
31680
+ return `taskkill timed out waiting in termination queue after ${timeoutMs}ms`;
31681
+ }
31682
+ const execution = new Promise((resolve) => {
31683
+ try {
31684
+ execFile3(windowsTaskkillPath(), ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, timeout: remainingMs }, (error62, _stdout, stderr) => {
31685
+ slot.resolve();
31686
+ resolve(error62 ? formatTaskkillError(error62, stderr) : void 0);
31687
+ });
31688
+ } catch (error62) {
31689
+ slot.resolve();
31690
+ resolve(formatTaskkillError(error62));
31691
+ }
31692
+ });
31693
+ return Promise.race([execution, exited.then(() => void 0)]);
31694
+ }
31695
+
31504
31696
  // ../codebuddy/dist/acp-client.js
31697
+ var sessionEndCarrier = "codexhost.codebuddy/sessionEnd";
31698
+ function carrySessionEnd(message) {
31699
+ if (!("method" in message) || message.method !== "session/update")
31700
+ return message;
31701
+ const params = record3(message.params);
31702
+ const update = record3(params.update);
31703
+ if (update.sessionUpdate !== "session_end")
31704
+ return message;
31705
+ return {
31706
+ ...message,
31707
+ params: {
31708
+ ...params,
31709
+ update: { sessionUpdate: "session_info_update", _meta: { [sessionEndCarrier]: update } }
31710
+ }
31711
+ };
31712
+ }
31713
+ function restoreSessionEnd(notification) {
31714
+ const update = notification.update;
31715
+ if (update.sessionUpdate !== "session_info_update" || !update._meta?.[sessionEndCarrier])
31716
+ return notification;
31717
+ return {
31718
+ ...notification,
31719
+ update: update._meta[sessionEndCarrier]
31720
+ };
31721
+ }
31505
31722
  var CodeBuddyAcpClient = class {
31506
31723
  options;
31507
31724
  operationTimeoutMs;
@@ -31510,6 +31727,9 @@ var CodeBuddyAcpClient = class {
31510
31727
  #child;
31511
31728
  #connection;
31512
31729
  #exited;
31730
+ #exitedSettled = false;
31731
+ #closeRequested = false;
31732
+ #stdinEnded = false;
31513
31733
  #closing;
31514
31734
  #failure;
31515
31735
  #exitFailure;
@@ -31534,14 +31754,17 @@ var CodeBuddyAcpClient = class {
31534
31754
  windowsVerbatimArguments: invocation.windowsVerbatimArguments,
31535
31755
  detached: process.platform !== "win32"
31536
31756
  });
31537
- this.#exited = new Promise((resolve) => this.#child.once("close", () => resolve()));
31757
+ this.#exited = new Promise((resolve) => this.#child.once("close", () => {
31758
+ this.#exitedSettled = true;
31759
+ resolve();
31760
+ }));
31538
31761
  this.#child.stderr.on("data", () => {
31539
31762
  });
31540
31763
  this.#child.on("error", (error62) => {
31541
31764
  this.#fault(error62);
31542
31765
  });
31543
31766
  this.#child.once("exit", (code, signal) => {
31544
- if (this.#closing || this.#failure)
31767
+ if (this.#closeRequested || this.#failure)
31545
31768
  return;
31546
31769
  const error62 = new CodeBuddyError("processExited", `ACP process exited (${code ?? signal ?? "unknown"})`);
31547
31770
  this.#exitFailure = error62;
@@ -31551,26 +31774,37 @@ var CodeBuddyAcpClient = class {
31551
31774
  });
31552
31775
  this.#connection = new ClientSideConnection(() => ({
31553
31776
  sessionUpdate: async (notification) => {
31554
- if (!this.#closing && !this.#failure)
31555
- options.handlers.update(notification);
31777
+ if (!this.#closeRequested && !this.#failure)
31778
+ options.handlers.update(restoreSessionEnd(notification));
31556
31779
  },
31557
- requestPermission: (request) => !this.#exitFailure && !this.#closing && !this.#failure ? options.handlers.permission(request) : Promise.resolve({ outcome: { outcome: "cancelled" } }),
31780
+ requestPermission: (request) => !this.#exitFailure && !this.#closeRequested && !this.#failure ? options.handlers.permission(request) : Promise.resolve({ outcome: { outcome: "cancelled" } }),
31558
31781
  extMethod: async (method, params) => {
31559
31782
  if (method !== "_codebuddy.ai/question")
31560
31783
  throw RequestError.methodNotFound(method);
31561
- if (this.#exitFailure || this.#closing || this.#failure)
31784
+ if (this.#exitFailure || this.#closeRequested || this.#failure)
31562
31785
  return { outcome: "cancelled" };
31563
31786
  return options.handlers.question(params);
31564
31787
  }
31565
- }), ndJsonStream2(Writable.toWeb(this.#child.stdin), Readable2.toWeb(this.#copyCleanup?.protocolOutput(this.#child.stdout) ?? (invocation.arguments.includes("--serve") ? codeBuddyAcpOutput(this.#child.stdout) : this.#child.stdout))));
31788
+ }), this.#protocolStream(invocation.arguments.includes("--serve")));
31566
31789
  void this.#connection.closed.then(() => {
31567
31790
  this.#fault(new CodeBuddyError("processExited", "ACP connection closed"));
31568
31791
  }).catch((error62) => {
31569
31792
  this.#fault(error62);
31570
31793
  });
31571
31794
  }
31795
+ #protocolStream(serve) {
31796
+ const stream = ndJsonStream2(Writable.toWeb(this.#child.stdin), Readable2.toWeb(this.#copyCleanup?.protocolOutput(this.#child.stdout) ?? (serve ? codeBuddyAcpOutput(this.#child.stdout) : this.#child.stdout)));
31797
+ return {
31798
+ writable: stream.writable,
31799
+ readable: stream.readable.pipeThrough(new TransformStream({
31800
+ transform: (message, controller) => {
31801
+ controller.enqueue(carrySessionEnd(message));
31802
+ }
31803
+ }))
31804
+ };
31805
+ }
31572
31806
  #fault(error62) {
31573
- if (this.#closing || this.#failure)
31807
+ if (this.#closeRequested || this.#failure)
31574
31808
  return;
31575
31809
  clearTimeout(this.#exitDrainTimer);
31576
31810
  this.#failure = error62;
@@ -31584,7 +31818,7 @@ var CodeBuddyAcpClient = class {
31584
31818
  throw this.#failure;
31585
31819
  if (this.#exitFailure)
31586
31820
  throw this.#exitFailure;
31587
- if (this.#closing)
31821
+ if (this.#closeRequested)
31588
31822
  throw new CodeBuddyError("invalidState", "ACP client is closed");
31589
31823
  const work = Promise.race([operation(), this.#failed]);
31590
31824
  return label ? bounded(work, timeout, label, (error62) => this.#fault(error62)) : work;
@@ -31637,16 +31871,29 @@ var CodeBuddyAcpClient = class {
31637
31871
  throw new CodeBuddyError("protocolError", "Native question is no longer pending");
31638
31872
  }
31639
31873
  close() {
31874
+ this.#closeRequested = true;
31640
31875
  clearTimeout(this.#exitDrainTimer);
31641
31876
  this.#rejectFailure(new CodeBuddyError("invalidState", "ACP client is closed"));
31642
- this.#closing ??= this.#closeProcess();
31643
- return this.#closing;
31877
+ if (this.#closing)
31878
+ return this.#closing;
31879
+ const closing = this.#closeProcess().catch((error62) => {
31880
+ if (this.#closing === closing)
31881
+ this.#closing = void 0;
31882
+ throw error62;
31883
+ });
31884
+ this.#closing = closing;
31885
+ return closing;
31644
31886
  }
31645
31887
  async #closeProcess() {
31646
- this.#child.stdin.end();
31647
- const exited = await bounded(this.#exited.then(() => true), 1e3, "ACP shutdown").catch(() => false);
31648
- if (exited)
31888
+ if (this.#exitedSettled)
31649
31889
  return;
31890
+ if (!this.#stdinEnded) {
31891
+ this.#stdinEnded = true;
31892
+ this.#child.stdin.end();
31893
+ const exited = await bounded(this.#exited.then(() => true), 1e3, "ACP shutdown").catch(() => false);
31894
+ if (exited)
31895
+ return;
31896
+ }
31650
31897
  if (this.#child.exitCode !== null || this.#child.signalCode !== null) {
31651
31898
  this.#child.stdout.destroy();
31652
31899
  this.#child.stderr.destroy();
@@ -31654,23 +31901,31 @@ var CodeBuddyAcpClient = class {
31654
31901
  return;
31655
31902
  }
31656
31903
  const pid = this.#child.pid;
31904
+ let terminationDetail;
31657
31905
  if (pid && process.platform === "win32") {
31658
- await new Promise((resolve) => execFile3("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 }, () => resolve()));
31906
+ terminationDetail = await terminateWindowsProcessTree(this.#child, this.#exited);
31659
31907
  } else if (pid) {
31660
31908
  try {
31661
31909
  process.kill(-pid, "SIGKILL");
31662
31910
  } catch {
31663
31911
  }
31664
31912
  }
31665
- await bounded(this.#exited, 3e3, "ACP process exit");
31913
+ try {
31914
+ await bounded(this.#exited, 3e3, "ACP process exit");
31915
+ } catch (error62) {
31916
+ if (terminationDetail && error62 instanceof CodeBuddyError) {
31917
+ throw new CodeBuddyError(error62.code, `${error62.message} (${terminationDetail})`);
31918
+ }
31919
+ throw error62;
31920
+ }
31666
31921
  }
31667
31922
  };
31668
31923
 
31669
31924
  // ../codebuddy/dist/derivation.js
31670
31925
  import { randomUUID as randomUUID3 } from "node:crypto";
31671
- import { execFile as execFile4, spawn as spawn2 } from "node:child_process";
31926
+ import { spawn as spawn2 } from "node:child_process";
31672
31927
  import { lstat as lstat3, mkdir, readFile as readFile3, realpath as realpath4, unlink, writeFile } from "node:fs/promises";
31673
- import path8 from "node:path";
31928
+ import path9 from "node:path";
31674
31929
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
31675
31930
 
31676
31931
  // ../codebuddy/dist/child-provenance.js
@@ -31907,8 +32162,10 @@ async function copyCodeBuddySession(cwd, sourceId, targetId, environment, signal
31907
32162
  windowsVerbatimArguments: invocation.windowsVerbatimArguments,
31908
32163
  detached: process.platform !== "win32"
31909
32164
  });
32165
+ const exited = new Promise((resolve2) => child.once("close", () => resolve2()));
31910
32166
  let output2 = "", bytes = 0, failed = false;
31911
32167
  let termination = Promise.resolve();
32168
+ let terminationDetail;
31912
32169
  const stop = () => {
31913
32170
  if (failed)
31914
32171
  return;
@@ -31917,11 +32174,10 @@ async function copyCodeBuddySession(cwd, sourceId, targetId, environment, signal
31917
32174
  child.stdout.destroy();
31918
32175
  child.stderr.destroy();
31919
32176
  } else if (process.platform === "win32" && child.pid) {
31920
- termination = new Promise((done) => {
31921
- execFile4("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 }, () => {
32177
+ termination = terminateWindowsProcessTree(child, exited).then((detail) => {
32178
+ terminationDetail = detail;
32179
+ if (child.exitCode === null && child.signalCode === null)
31922
32180
  child.kill();
31923
- done();
31924
- });
31925
32181
  });
31926
32182
  } else if (child.pid) {
31927
32183
  try {
@@ -31951,7 +32207,8 @@ async function copyCodeBuddySession(cwd, sourceId, targetId, environment, signal
31951
32207
  clearTimeout(timer);
31952
32208
  signal.removeEventListener("abort", stop);
31953
32209
  if (failed || signal.aborted || code !== 0) {
31954
- reject(new CodeBuddyError("nativeFailure", "Native history copy failed or was interrupted"));
32210
+ const message = terminationDetail ? `Native history copy failed or was interrupted (${terminationDetail})` : "Native history copy failed or was interrupted";
32211
+ reject(new CodeBuddyError("nativeFailure", message));
31955
32212
  return;
31956
32213
  }
31957
32214
  try {
@@ -32027,14 +32284,14 @@ async function bridgeCopyToTarget(sourceCwd, targetCwd, ref, contents, environme
32027
32284
  const targetFile = codeBuddyPrimaryHistoryPath(targetCwd, ref, environment, profile);
32028
32285
  if (sameResolvedPath(sourceFile, targetFile))
32029
32286
  return void 0;
32030
- const targetDirectory = path8.dirname(targetFile);
32031
- const projectsDirectory = path8.dirname(targetDirectory);
32287
+ const targetDirectory = path9.dirname(targetFile);
32288
+ const projectsDirectory = path9.dirname(targetDirectory);
32032
32289
  await mkdir(targetDirectory, { recursive: true });
32033
32290
  const [realProjects, realTargetDirectory] = await Promise.all([
32034
32291
  realpath4(projectsDirectory),
32035
32292
  realpath4(targetDirectory)
32036
32293
  ]);
32037
- if (!sameResolvedPath(realTargetDirectory, path8.join(realProjects, codeBuddyProjectSlug(targetCwd, profile))))
32294
+ if (!sameResolvedPath(realTargetDirectory, path9.join(realProjects, codeBuddyProjectSlug(targetCwd, profile))))
32038
32295
  throw new CodeBuddyError("invalidRequest", "Cross-directory history bridge target escaped the native projects root");
32039
32296
  const expected = Buffer.from(contents, "utf8");
32040
32297
  await writeFile(targetFile, expected, { flag: "wx", mode: 384 });
@@ -32144,7 +32401,7 @@ function assertChildRanges(rows2, child) {
32144
32401
  }
32145
32402
  }
32146
32403
  async function plainDirectory(parent, name) {
32147
- const directory = path8.join(parent, name);
32404
+ const directory = path9.join(parent, name);
32148
32405
  await mkdir(directory, { mode: 448 }).catch((error62) => {
32149
32406
  if (record3(error62).code !== "EEXIST")
32150
32407
  throw error62;
@@ -32190,18 +32447,18 @@ async function copyInheritedChildren(options) {
32190
32447
  if (!references.length)
32191
32448
  return { descriptors: [], created: [] };
32192
32449
  const sourceHistoryFile = await realpath4(options.sourceHistoryFile);
32193
- const sourceProject = path8.dirname(sourceHistoryFile);
32194
- if (!sameResolvedPath(sourceHistoryFile, path8.join(sourceProject, `${options.sourceRef.nativeSessionId}.jsonl`)))
32450
+ const sourceProject = path9.dirname(sourceHistoryFile);
32451
+ if (!sameResolvedPath(sourceHistoryFile, path9.join(sourceProject, `${options.sourceRef.nativeSessionId}.jsonl`)))
32195
32452
  throw new CodeBuddyError("invalidRequest", "Unexpected source history location");
32196
- const sourceDirectory = path8.join(sourceProject, options.sourceRef.nativeSessionId, "subagents");
32453
+ const sourceDirectory = path9.join(sourceProject, options.sourceRef.nativeSessionId, "subagents");
32197
32454
  const sourceDirectoryInfo = await lstat3(sourceDirectory);
32198
32455
  if (!sourceDirectoryInfo.isDirectory() || sourceDirectoryInfo.isSymbolicLink())
32199
32456
  throw new CodeBuddyError("invalidRequest", "Redirected source Subagent directory");
32200
32457
  if (!sameResolvedPath(await realpath4(sourceDirectory), sourceDirectory))
32201
32458
  throw new CodeBuddyError("invalidRequest", "Redirected source Subagent directory");
32202
32459
  const targetHistoryFile = await realpath4(options.targetHistoryFile);
32203
- const targetProject = path8.dirname(targetHistoryFile);
32204
- if (!sameResolvedPath(targetHistoryFile, path8.join(targetProject, `${options.targetRef.nativeSessionId}.jsonl`)))
32460
+ const targetProject = path9.dirname(targetHistoryFile);
32461
+ if (!sameResolvedPath(targetHistoryFile, path9.join(targetProject, `${options.targetRef.nativeSessionId}.jsonl`)))
32205
32462
  throw new CodeBuddyError("invalidRequest", "Unexpected target history location");
32206
32463
  const targetSessionDirectory = await plainDirectory(targetProject, options.targetRef.nativeSessionId);
32207
32464
  const targetDirectory = await plainDirectory(targetSessionDirectory, "subagents");
@@ -32209,7 +32466,7 @@ async function copyInheritedChildren(options) {
32209
32466
  const created = [];
32210
32467
  try {
32211
32468
  for (const reference of references) {
32212
- const sourceFile = path8.join(sourceDirectory, `${reference.childId}.jsonl`);
32469
+ const sourceFile = path9.join(sourceDirectory, `${reference.childId}.jsonl`);
32213
32470
  const sourceInfo = await lstat3(sourceFile);
32214
32471
  if (!sourceInfo.isFile() || sourceInfo.isSymbolicLink())
32215
32472
  throw new CodeBuddyError("invalidRequest", "Redirected source Subagent transcript");
@@ -32228,7 +32485,7 @@ async function copyInheritedChildren(options) {
32228
32485
  throw new CodeBuddyError("protocolError", "Missing Agent result child range");
32229
32486
  const prefix = await codeBuddyChildPrefixThrough(source.contents, last, validated);
32230
32487
  const expected = Buffer.from(prefix.contents, "utf8");
32231
- const targetFile = path8.join(targetDirectory, `${reference.childId}.jsonl`);
32488
+ const targetFile = path9.join(targetDirectory, `${reference.childId}.jsonl`);
32232
32489
  const copy = await persistChildCopy(targetFile, expected);
32233
32490
  if (copy)
32234
32491
  created.push(copy);
@@ -32468,7 +32725,7 @@ async function deriveCodeBuddySession(options) {
32468
32725
  // ../codebuddy/dist/session-import.js
32469
32726
  import { createReadStream as createReadStream2 } from "node:fs";
32470
32727
  import { opendir, readFile as readFile4, stat as stat2 } from "node:fs/promises";
32471
- import path9 from "node:path";
32728
+ import path10 from "node:path";
32472
32729
  import { createInterface as createInterface2 } from "node:readline";
32473
32730
 
32474
32731
  // ../../harness-adapter/dist/session-import.js
@@ -32631,7 +32888,7 @@ async function readFacts(file2, signal) {
32631
32888
  return null;
32632
32889
  }
32633
32890
  const row = record3(parsed);
32634
- if (typeof row.cwd === "string" && path9.isAbsolute(row.cwd))
32891
+ if (typeof row.cwd === "string" && path10.isAbsolute(row.cwd))
32635
32892
  cwd ??= row.cwd;
32636
32893
  if (typeof row.timestamp === "number" && Number.isFinite(row.timestamp))
32637
32894
  updatedAt = row.timestamp;
@@ -32704,7 +32961,7 @@ var CodeBuddySessionImport = class {
32704
32961
  /** IDs a live native process registered in `<config>/sessions/<pid>.json`. */
32705
32962
  async #activeSessions(signal) {
32706
32963
  const active2 = /* @__PURE__ */ new Set();
32707
- const directory = path9.join(this.#root(), "sessions");
32964
+ const directory = path10.join(this.#root(), "sessions");
32708
32965
  const markers = await opendir(directory).catch((error62) => {
32709
32966
  if (isMissingFileError(error62) || record3(error62).code === "ENOTDIR")
32710
32967
  return null;
@@ -32717,7 +32974,7 @@ var CodeBuddySessionImport = class {
32717
32974
  if (!marker.isFile() || !marker.name.endsWith(".json"))
32718
32975
  continue;
32719
32976
  try {
32720
- const file2 = path9.join(directory, marker.name);
32977
+ const file2 = path10.join(directory, marker.name);
32721
32978
  if ((await stat2(file2)).size > MAX_MARKER_BYTES)
32722
32979
  continue;
32723
32980
  const entry = record3(JSON.parse(await readFile4(file2, { encoding: "utf8", signal })));
@@ -32733,7 +32990,7 @@ var CodeBuddySessionImport = class {
32733
32990
  }
32734
32991
  /** Session ID to every project file claiming it. Enumerated links are not followed. */
32735
32992
  async #sessionFiles(signal) {
32736
- const root = path9.join(this.#root(), "projects");
32993
+ const root = path10.join(this.#root(), "projects");
32737
32994
  const found = /* @__PURE__ */ new Map();
32738
32995
  const info = await optionalLstat(root);
32739
32996
  if (!info)
@@ -32744,7 +33001,7 @@ var CodeBuddySessionImport = class {
32744
33001
  signal.throwIfAborted();
32745
33002
  if (!project2.isDirectory())
32746
33003
  continue;
32747
- const projectDirectory = path9.join(root, project2.name);
33004
+ const projectDirectory = path10.join(root, project2.name);
32748
33005
  const entries = await opendir(projectDirectory).catch((error62) => {
32749
33006
  if (isMissingFileError(error62))
32750
33007
  return null;
@@ -32758,7 +33015,7 @@ var CodeBuddySessionImport = class {
32758
33015
  if (!nativeSessionId)
32759
33016
  continue;
32760
33017
  const files = found.get(nativeSessionId) ?? [];
32761
- files.push(path9.join(projectDirectory, entry.name));
33018
+ files.push(path10.join(projectDirectory, entry.name));
32762
33019
  found.set(nativeSessionId, files);
32763
33020
  }
32764
33021
  }
@@ -32773,7 +33030,7 @@ var CodeBuddySessionImport = class {
32773
33030
  const facts = await readFacts(file2, signal);
32774
33031
  if (!facts)
32775
33032
  return null;
32776
- const cwd = path9.resolve(facts.cwd);
33033
+ const cwd = path10.resolve(facts.cwd);
32777
33034
  if (!(await stat2(cwd)).isDirectory())
32778
33035
  return null;
32779
33036
  const nativeRef = nativeSessionRefSchema.parse({
@@ -32783,7 +33040,7 @@ var CodeBuddySessionImport = class {
32783
33040
  });
32784
33041
  signal.throwIfAborted();
32785
33042
  const history = await codeBuddyNativeHistory(cwd, nativeRef, this.#environment, this.#profile);
32786
- if (path9.resolve(history.file) !== path9.resolve(file2))
33043
+ if (path10.resolve(history.file) !== path10.resolve(file2))
32787
33044
  return null;
32788
33045
  const candidate = sessionImportCandidate({
32789
33046
  nativeSessionId,
@@ -32804,6 +33061,125 @@ var CodeBuddySessionImport = class {
32804
33061
  }
32805
33062
  };
32806
33063
 
33064
+ // ../codebuddy/dist/session.js
33065
+ import { randomUUID as randomUUID4 } from "node:crypto";
33066
+
33067
+ // ../codebuddy/dist/autonomous.js
33068
+ import { Buffer as Buffer3 } from "node:buffer";
33069
+ function readUnsolicitedTurn(update) {
33070
+ if (update.sessionUpdate !== "session_info_update")
33071
+ return;
33072
+ const announcement = record3(record3(update._meta)["codebuddy.ai/unsolicitedTurn"]);
33073
+ return announcement.reason === "background_drain" ? text2(announcement.requestId) || void 0 : void 0;
33074
+ }
33075
+ var AutonomousBufferBudget = class {
33076
+ #frames = 0;
33077
+ #bytes = 0;
33078
+ hold(value) {
33079
+ const bytes = Buffer3.byteLength(JSON.stringify(value), "utf8");
33080
+ if (this.#frames >= 2048 || this.#bytes + bytes > 4 * 1024 * 1024)
33081
+ throw new CodeBuddyError("protocolError", "Native autonomous Turn output exceeded its buffer bound");
33082
+ this.#frames += 1;
33083
+ this.#bytes += bytes;
33084
+ return bytes;
33085
+ }
33086
+ release(frames, bytes) {
33087
+ this.#frames -= frames;
33088
+ this.#bytes -= bytes;
33089
+ }
33090
+ };
33091
+ var CodeBuddyAutonomousFrames = class {
33092
+ budget;
33093
+ #frames = [];
33094
+ #bytes = 0;
33095
+ constructor(budget) {
33096
+ this.budget = budget;
33097
+ }
33098
+ push(frame) {
33099
+ this.#bytes += this.budget.hold(frame);
33100
+ this.#frames.push(frame);
33101
+ }
33102
+ drain() {
33103
+ this.budget.release(this.#frames.length, this.#bytes);
33104
+ this.#bytes = 0;
33105
+ return this.#frames.splice(0);
33106
+ }
33107
+ };
33108
+ var CodeBuddyAutonomousTurns = class {
33109
+ #rounds = [];
33110
+ #budget = new AutonomousBufferBudget();
33111
+ #open;
33112
+ #announcements = 0;
33113
+ get announcements() {
33114
+ return this.#announcements;
33115
+ }
33116
+ announce(requestId) {
33117
+ if (this.#open)
33118
+ throw new CodeBuddyError("protocolError", "Native autonomous Turns overlapped");
33119
+ const announcementBytes = this.#budget.hold({
33120
+ sessionUpdate: "session_info_update",
33121
+ requestId
33122
+ });
33123
+ const identity2 = Promise.withResolvers();
33124
+ const round = {
33125
+ frames: new CodeBuddyAutonomousFrames(this.#budget),
33126
+ identity: identity2.promise,
33127
+ resolveIdentity: identity2.resolve,
33128
+ announcementBytes,
33129
+ ended: false,
33130
+ started: false
33131
+ };
33132
+ this.#announcements += 1;
33133
+ this.#rounds.push(round);
33134
+ this.#open = round;
33135
+ return round;
33136
+ }
33137
+ /** IDs can be reused or change during admission; the connection interval owns the end. */
33138
+ end(requestId) {
33139
+ const round = this.#open;
33140
+ if (!round)
33141
+ return;
33142
+ round.terminalBytes = this.#budget.hold({ sessionUpdate: "session_end", requestId });
33143
+ round.ended = true;
33144
+ this.#open = void 0;
33145
+ return round;
33146
+ }
33147
+ start(round, turnId) {
33148
+ round.started = true;
33149
+ round.resolveIdentity(turnId);
33150
+ }
33151
+ owner() {
33152
+ return this.#open;
33153
+ }
33154
+ hasRounds() {
33155
+ return this.#rounds.length > 0;
33156
+ }
33157
+ interactionIdentity(round, request) {
33158
+ const bytes = this.#budget.hold(request);
33159
+ return round.identity.finally(() => this.#budget.release(1, bytes));
33160
+ }
33161
+ next() {
33162
+ return this.#rounds.find((round) => !round.started);
33163
+ }
33164
+ finish(round) {
33165
+ const index = this.#rounds.indexOf(round);
33166
+ if (index < 0)
33167
+ return;
33168
+ round.frames.drain();
33169
+ this.#budget.release(1, round.announcementBytes);
33170
+ if (round.terminalBytes !== void 0)
33171
+ this.#budget.release(1, round.terminalBytes);
33172
+ this.#rounds.splice(index, 1);
33173
+ if (this.#open === round)
33174
+ this.#open = void 0;
33175
+ round.resolveIdentity(void 0);
33176
+ }
33177
+ close() {
33178
+ for (const round of [...this.#rounds])
33179
+ this.finish(round);
33180
+ }
33181
+ };
33182
+
32807
33183
  // ../codebuddy/dist/interactions.js
32808
33184
  var CodeBuddyInteractions = class {
32809
33185
  emit;
@@ -32947,7 +33323,7 @@ var CodeBuddyInteractions = class {
32947
33323
 
32948
33324
  // ../codebuddy/dist/subagent-history.js
32949
33325
  import { readdir as readdir3, realpath as realpath5 } from "node:fs/promises";
32950
- import path10 from "node:path";
33326
+ import path11 from "node:path";
32951
33327
  var equalPath2 = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
32952
33328
  var MAX_CACHED_CHILDREN = 16;
32953
33329
  var CodeBuddyChildObserver = class {
@@ -33011,8 +33387,8 @@ var CodeBuddyChildObserver = class {
33011
33387
  }
33012
33388
  async #directory() {
33013
33389
  const history = await this.#parentHistory();
33014
- const project2 = path10.dirname(await realpath5(history.file));
33015
- const expected = path10.join(project2, this.parent.nativeSessionId, "subagents");
33390
+ const project2 = path11.dirname(await realpath5(history.file));
33391
+ const expected = path11.join(project2, this.parent.nativeSessionId, "subagents");
33016
33392
  const actual = await realpath5(expected);
33017
33393
  this.#assertOpen();
33018
33394
  if (!equalPath2(actual, expected))
@@ -33022,7 +33398,7 @@ var CodeBuddyChildObserver = class {
33022
33398
  async #child(directory, childId) {
33023
33399
  if (!validCodeBuddyChildId(childId))
33024
33400
  throw new CodeBuddyError("invalidRequest", "Invalid native Subagent ID");
33025
- const file2 = path10.join(directory, `${childId}.jsonl`);
33401
+ const file2 = path11.join(directory, `${childId}.jsonl`);
33026
33402
  const before = await codeBuddyFileVersion(file2);
33027
33403
  if (!equalPath2(before.realFile, file2))
33028
33404
  throw new CodeBuddyError("invalidRequest", "Redirected Subagent transcript");
@@ -33346,8 +33722,10 @@ var CodeBuddySession = class {
33346
33722
  #ref;
33347
33723
  #state = {};
33348
33724
  #active;
33725
+ #autonomous = new CodeBuddyAutonomousTurns();
33349
33726
  #busy = false;
33350
33727
  #closed = false;
33728
+ #closeNotified = false;
33351
33729
  #closing;
33352
33730
  #fault;
33353
33731
  #hasTurn = false;
@@ -33416,22 +33794,7 @@ var CodeBuddySession = class {
33416
33794
  }
33417
33795
  return;
33418
33796
  }
33419
- if (this.#replay)
33420
- return;
33421
- if ((text2(record3(update._meta)["codebuddy.ai/parentToolCallId"]) || !this.#active?.output.hasItem(`tool-${text2(update.toolCallId)}`)) && this.subagents.update(update))
33422
- return;
33423
- if (update.sessionUpdate === "config_option_update" && this.#config)
33424
- this.#apply(configuration(update.configOptions, this.profile));
33425
- if (update.sessionUpdate === "usage_update" && typeof update.used === "number" && typeof update.size === "number" && update.size > 0) {
33426
- this.#context = {
33427
- contextUsedTokens: update.used,
33428
- contextWindowTokens: update.size,
33429
- contextUsagePercent: update.used / update.size * 100
33430
- };
33431
- this.#emitUsage();
33432
- void this.refreshUsage();
33433
- }
33434
- this.#active?.output.update(update);
33797
+ this.#dispatchUpdate(update);
33435
33798
  } catch (error62) {
33436
33799
  if (this.#replay)
33437
33800
  this.#replay.fault ??= { error: error62 };
@@ -33439,8 +33802,12 @@ var CodeBuddySession = class {
33439
33802
  this.#onFault(error62);
33440
33803
  }
33441
33804
  },
33442
- permission: (request) => generation === this.#generation && !this.#closed && !this.#fault && !this.#replay && this.#active && !this.#active.cancelled && request.sessionId === this.#ref?.nativeSessionId ? this.#interactions.permission(this.#active.command.turnId, request) : Promise.resolve({ outcome: { outcome: "cancelled" } }),
33443
- question: (params) => generation === this.#generation && !this.#closed && !this.#fault && !this.#replay && this.#active && !this.#active.cancelled && params.sessionId === this.#ref?.nativeSessionId ? this.#interactions.question(this.#active.command.turnId, params) : Promise.resolve({ outcome: "cancelled" })
33805
+ permission: (request) => generation !== this.#generation || request.sessionId !== this.#ref?.nativeSessionId ? Promise.resolve({ outcome: { outcome: "cancelled" } }) : this.#interactionTurn(request, (turnId) => this.#interactions.permission(turnId, request), {
33806
+ outcome: { outcome: "cancelled" }
33807
+ }),
33808
+ question: (params) => generation !== this.#generation || params.sessionId !== this.#ref?.nativeSessionId ? Promise.resolve({ outcome: "cancelled" }) : this.#interactionTurn(params, (turnId) => this.#interactions.question(turnId, params), {
33809
+ outcome: "cancelled"
33810
+ })
33444
33811
  }
33445
33812
  });
33446
33813
  }
@@ -33487,31 +33854,40 @@ var CodeBuddySession = class {
33487
33854
  const saved = this.input.kind === "resume" && record3(this.input.nativeRef.locator).codebuddyDerived === 1 ? record3(record3(this.input.nativeRef.locator).configuration) : {};
33488
33855
  if (this.input.kind === "resume")
33489
33856
  this.#ref = this.input.nativeRef;
33490
- const opened = await this.#openClient();
33491
- this.#ref = nativeSessionRefSchema.parse({
33492
- harnessId: this.profile.harnessId,
33493
- nativeSessionId: opened.sessionId,
33494
- formatVersion: 1,
33495
- ...this.#ref?.locator || this.capabilities.history.fork ? {
33496
- locator: {
33497
- ...record3(this.#ref?.locator),
33498
- ...this.capabilities.history.fork ? { boundCwd: codeBuddyCanonicalCwd(this.input.cwd) } : {}
33499
- }
33500
- } : {}
33501
- });
33502
- this.#apply(configuration(opened.configOptions, this.profile), false);
33503
- if (this.input.kind === "create" && this.input.executionPolicy === "unattended-full-access") {
33504
- await this.#configure("mode", "fullAccess");
33505
- } else if (this.input.permissionModeId || text2(saved.mode))
33506
- await this.#configure("mode", this.input.permissionModeId ?? text2(saved.mode));
33507
- if (this.input.model || text2(saved.model))
33508
- await this.#configure("model", this.input.model?.id ?? text2(saved.model));
33509
- if (this.input.thinkingOptionId || text2(saved.thinking))
33510
- await this.#configure("thought_level", this.input.thinkingOptionId ?? text2(saved.thinking));
33511
- if (this.#fault || this.#closed)
33512
- throw new CodeBuddyError("invalidState", "Native Session failed while opening");
33513
- this.initialState = { ...this.#state };
33514
- this.initialUsage = this.#usage;
33857
+ const replay = {};
33858
+ this.#replay = replay;
33859
+ const generation = this.#generation;
33860
+ try {
33861
+ const opened = await this.#openClient();
33862
+ this.#ref = nativeSessionRefSchema.parse({
33863
+ harnessId: this.profile.harnessId,
33864
+ nativeSessionId: opened.sessionId,
33865
+ formatVersion: 1,
33866
+ ...this.#ref?.locator || this.capabilities.history.fork ? {
33867
+ locator: {
33868
+ ...record3(this.#ref?.locator),
33869
+ ...this.capabilities.history.fork ? { boundCwd: codeBuddyCanonicalCwd(this.input.cwd) } : {}
33870
+ }
33871
+ } : {}
33872
+ });
33873
+ this.#apply(configuration(opened.configOptions, this.profile), false);
33874
+ if (this.input.kind === "create" && this.input.executionPolicy === "unattended-full-access") {
33875
+ await this.#configure("mode", "fullAccess");
33876
+ } else if (this.input.permissionModeId || text2(saved.mode))
33877
+ await this.#configure("mode", this.input.permissionModeId ?? text2(saved.mode));
33878
+ if (this.input.model || text2(saved.model))
33879
+ await this.#configure("model", this.input.model?.id ?? text2(saved.model));
33880
+ if (this.input.thinkingOptionId || text2(saved.thinking))
33881
+ await this.#configure("thought_level", this.input.thinkingOptionId ?? text2(saved.thinking));
33882
+ this.#assertClient(generation);
33883
+ if (!this.profile.staticCommandCatalog && replay.commands)
33884
+ this.#commands = replay.commands;
33885
+ this.initialState = { ...this.#state };
33886
+ this.initialUsage = this.#usage;
33887
+ } finally {
33888
+ this.#replay = void 0;
33889
+ }
33890
+ this.#flushAutonomous();
33515
33891
  }
33516
33892
  #emit(event) {
33517
33893
  event = configureSubagentEvent(event, this.#subagentConfiguration());
@@ -33536,6 +33912,140 @@ var CodeBuddySession = class {
33536
33912
  if (historical || !complete)
33537
33913
  this.#emit({ type: "usage.history", complete });
33538
33914
  }
33915
+ /** Routes one native frame to the Host Turn, a native drain round, or its buffer. */
33916
+ #dispatchUpdate(update) {
33917
+ const unsolicited = readUnsolicitedTurn(update);
33918
+ if (unsolicited) {
33919
+ this.#autonomous.announce(unsolicited);
33920
+ this.#flushAutonomous();
33921
+ return;
33922
+ }
33923
+ if (update.sessionUpdate === "session_end") {
33924
+ const round = this.#autonomous.end(text2(record3(update._meta)["codebuddy.ai/requestId"]));
33925
+ if (!round)
33926
+ return;
33927
+ if (round.started)
33928
+ void this.#finishAutonomous(round);
33929
+ else
33930
+ this.#flushAutonomous();
33931
+ return;
33932
+ }
33933
+ const route = this.#autonomous.owner();
33934
+ if (route?.started) {
33935
+ if (!this.#replay)
33936
+ this.#applyUpdate(update);
33937
+ return;
33938
+ }
33939
+ if (route) {
33940
+ route.frames.push(update);
33941
+ return;
33942
+ }
33943
+ if (this.#replay)
33944
+ return;
33945
+ this.#applyUpdate(update);
33946
+ }
33947
+ /** An announced native interval owns Interactions before the prior prompt's finally runs. */
33948
+ #interactionTurn(request, run, cancelled) {
33949
+ if (this.#closed || this.#fault)
33950
+ return Promise.resolve(cancelled);
33951
+ const round = this.#autonomous.owner();
33952
+ if (round) {
33953
+ let identity2;
33954
+ try {
33955
+ identity2 = this.#autonomous.interactionIdentity(round, request);
33956
+ } catch (error62) {
33957
+ if (this.#replay)
33958
+ this.#replay.fault ??= { error: error62 };
33959
+ else
33960
+ this.#onFault(error62);
33961
+ return Promise.resolve(cancelled);
33962
+ }
33963
+ return identity2.then((turnId) => {
33964
+ const active3 = this.#active;
33965
+ return turnId && active3?.autonomous?.round === round && !active3.cancelled && !active3.done ? run(turnId) : cancelled;
33966
+ });
33967
+ }
33968
+ const active2 = this.#active;
33969
+ return active2 && !this.#replay && !active2.cancelled && !active2.autonomous && !active2.promptSettled ? run(active2.command.turnId) : Promise.resolve(cancelled);
33970
+ }
33971
+ /** Frames of the active Turn, including a native drain Turn that now owns the Session. */
33972
+ #applyUpdate(update) {
33973
+ if ((text2(record3(update._meta)["codebuddy.ai/parentToolCallId"]) || !this.#active?.output.hasItem(`tool-${text2(update.toolCallId)}`)) && this.subagents.update(update))
33974
+ return;
33975
+ if (update.sessionUpdate === "config_option_update" && this.#config)
33976
+ this.#apply(configuration(update.configOptions, this.profile));
33977
+ if (update.sessionUpdate === "usage_update" && typeof update.used === "number" && typeof update.size === "number" && update.size > 0) {
33978
+ this.#context = {
33979
+ contextUsedTokens: update.used,
33980
+ contextWindowTokens: update.size,
33981
+ contextUsagePercent: update.used / update.size * 100
33982
+ };
33983
+ this.#emitUsage();
33984
+ void this.refreshUsage();
33985
+ }
33986
+ if (!this.#active?.cancelled)
33987
+ this.#active?.output.update(update);
33988
+ }
33989
+ #flushAutonomous() {
33990
+ if (this.#active || this.#replay || this.#closed || this.#fault)
33991
+ return;
33992
+ const round = this.#autonomous.next();
33993
+ if (!round)
33994
+ return;
33995
+ this.#startAutonomous(round);
33996
+ try {
33997
+ for (const frame of round.frames.drain())
33998
+ this.#applyUpdate(frame);
33999
+ } catch (error62) {
34000
+ this.#onFault(error62);
34001
+ return;
34002
+ }
34003
+ if (round.ended)
34004
+ void this.#finishAutonomous(round);
34005
+ }
34006
+ #startAutonomous(round) {
34007
+ const turnId = hostTurnIdSchema.parse(randomUUID4());
34008
+ const completion = Promise.withResolvers();
34009
+ const active2 = {
34010
+ command: { type: "turn.start", turnId, input: [] },
34011
+ output: new CodeBuddyTurnOutput(turnId, this.input.cwd, (event) => this.#emit(event), this.profile),
34012
+ completion: completion.promise,
34013
+ nativeCommand: false,
34014
+ cancelled: false,
34015
+ done: false,
34016
+ autonomous: { round },
34017
+ settle: () => completion.resolve(void 0)
34018
+ };
34019
+ this.#active = active2;
34020
+ this.#autonomous.start(round, turnId);
34021
+ this.subagents.begin(turnId);
34022
+ this.#emit({ type: "turn.autonomous.started", turnId, input: [] });
34023
+ this.#emit({ type: "turn.started", turnId });
34024
+ }
34025
+ /** Completes the live interval without assigning persisted identity or inferring success. */
34026
+ async #finishAutonomous(round) {
34027
+ const active2 = this.#active;
34028
+ if (!active2?.autonomous || active2.autonomous.round !== round || active2.done)
34029
+ return;
34030
+ try {
34031
+ const outcome = { status: active2.cancelled ? "cancelled" : "succeeded" };
34032
+ if (active2.cancelled) {
34033
+ const recovery = (async () => {
34034
+ await this.#retireClient();
34035
+ if (this.#closed || this.#fault)
34036
+ return;
34037
+ await this.#resumeClient();
34038
+ })();
34039
+ void recovery.catch(() => {
34040
+ });
34041
+ await bounded(Promise.race([recovery, active2.completion]), 3e4, "ACP autonomous cancel recovery");
34042
+ }
34043
+ if (!active2.done && !this.#closed && !this.#fault)
34044
+ this.#finish(active2, outcome);
34045
+ } catch (error62) {
34046
+ this.#onFault(error62);
34047
+ }
34048
+ }
33539
34049
  #apply(config2, emit = true) {
33540
34050
  if (this.#state.effectiveModel && this.#state.effectiveModel.id !== config2.state.effectiveModel?.id) {
33541
34051
  this.#context = {};
@@ -33587,6 +34097,9 @@ var CodeBuddySession = class {
33587
34097
  }
33588
34098
  }
33589
34099
  async #snapshot(historyTimeout) {
34100
+ return (await this.#snapshotWithHistory(historyTimeout)).snapshot;
34101
+ }
34102
+ async #snapshotWithHistory(historyTimeout) {
33590
34103
  if (!this.#ref)
33591
34104
  throw new CodeBuddyError("invalidState", "Session is not open");
33592
34105
  const read = this.#history(this.#ref);
@@ -33598,7 +34111,7 @@ var CodeBuddySession = class {
33598
34111
  this.#hasTurn = true;
33599
34112
  this.#usage = historyUsage(history);
33600
34113
  this.#meterHistory(history, false);
33601
- return { ...this.subagents.project(snapshot), state: this.#state };
34114
+ return { snapshot: { ...this.subagents.project(snapshot), state: this.#state }, history };
33602
34115
  }
33603
34116
  /** Read persisted request usage without waiting for the ACP prompt (including tool waits). */
33604
34117
  async refreshUsage() {
@@ -33633,7 +34146,7 @@ var CodeBuddySession = class {
33633
34146
  async #readSnapshot() {
33634
34147
  if (this.#closed || this.#fault)
33635
34148
  return failure2("invalidState", "Session is closed or faulted", this.profile);
33636
- if (this.#busy || this.#active)
34149
+ if (this.#busy || this.#replay || this.#active && (!this.#active.autonomous || this.#active.cancelled))
33637
34150
  return failure2("sessionBusy", "Session is executing an operation", this.profile);
33638
34151
  this.#busy = true;
33639
34152
  try {
@@ -33654,6 +34167,14 @@ var CodeBuddySession = class {
33654
34167
  return failure2("unsupported", "Command is not available in this Session", this.profile);
33655
34168
  return this.#execute(command, invocation);
33656
34169
  }
34170
+ /** ACP `session/cancel` carries only the Session ID; send it only while this Turn owns execution. */
34171
+ #ownsNativeExecution(active2) {
34172
+ if (active2.done || this.#needsResume)
34173
+ return false;
34174
+ if (active2.autonomous)
34175
+ return !active2.autonomous.round.ended && this.#autonomous.owner() === active2.autonomous.round;
34176
+ return !active2.promptSettled && !this.#autonomous.hasRounds();
34177
+ }
33657
34178
  async #execute(command, invocation) {
33658
34179
  if (this.#closed || this.#fault)
33659
34180
  return failure2("invalidState", "Session is closed or faulted", this.profile);
@@ -33665,27 +34186,29 @@ var CodeBuddySession = class {
33665
34186
  const active2 = this.#active;
33666
34187
  if (!active2 || active2.command.turnId !== command.turnId || !this.#ref)
33667
34188
  return failure2("invalidRequest", "Turn is not active", this.profile);
33668
- if (!active2.cancelled) {
33669
- active2.cancelled = true;
33670
- const generation = this.#generation;
33671
- try {
33672
- const requested = this.#client.cancel(this.#ref.nativeSessionId);
33673
- this.#interactions.close();
33674
- await requested;
33675
- } catch (error62) {
33676
- if (generation === this.#generation) {
33677
- if (this.#active === active2)
33678
- this.#onFault(error62);
33679
- return { ok: false, error: nativeError(error62, this.profile) };
33680
- }
33681
- }
33682
- if (this.#active === active2 && !this.#closed) {
33683
- void bounded(active2.completion, 3e4, "ACP cancel acknowledgement").catch((error62) => {
33684
- if (this.#active === active2 && !this.#needsResume)
33685
- this.#onFault(error62);
33686
- });
34189
+ if (active2.cancelled)
34190
+ return { ok: true, value: { cancellationRequested: true } };
34191
+ if (!this.#ownsNativeExecution(active2))
34192
+ return failure2("invalidState", "Turn is already completing", this.profile);
34193
+ active2.cancelled = true;
34194
+ const generation = this.#generation;
34195
+ try {
34196
+ const requested = this.#client.cancel(this.#ref.nativeSessionId);
34197
+ this.#interactions.close();
34198
+ await requested;
34199
+ } catch (error62) {
34200
+ if (generation === this.#generation) {
34201
+ if (this.#active === active2)
34202
+ this.#onFault(error62);
34203
+ return { ok: false, error: nativeError(error62, this.profile) };
33687
34204
  }
33688
34205
  }
34206
+ if (this.#active === active2 && !this.#closed) {
34207
+ void bounded(active2.completion, 3e4, "ACP cancel acknowledgement").catch((error62) => {
34208
+ if (this.#active === active2 && (active2.autonomous || !this.#needsResume))
34209
+ this.#onFault(error62);
34210
+ });
34211
+ }
33689
34212
  return { ok: true, value: { cancellationRequested: true } };
33690
34213
  }
33691
34214
  if (this.#busy || this.#active && (this.#active.cancelled || command.type !== "model.select" && command.type !== "thinking.select"))
@@ -33695,8 +34218,14 @@ var CodeBuddySession = class {
33695
34218
  if (command.type === "turn.start" || command.type === "command.execute") {
33696
34219
  if (!command.turnId.trim() || command.type === "turn.start" && (!command.input.length || command.input.some((item) => item.type !== "text") || !command.input.map((item) => item.text).join("").trim()))
33697
34220
  return failure2("invalidRequest", "A nonempty text prompt is required", this.profile);
33698
- if (this.#needsResume)
34221
+ const drainBefore = this.#autonomous.announcements;
34222
+ if (this.#needsResume) {
33699
34223
  await this.#resumeClient();
34224
+ if (this.#closed || this.#fault)
34225
+ return failure2("invalidState", "Session is closed or faulted", this.profile);
34226
+ if (this.#active || this.#autonomous.announcements !== drainBefore)
34227
+ return failure2("sessionBusy", "Session is executing an operation", this.profile);
34228
+ }
33700
34229
  const nativeCommand = command.type === "command.execute" || nativeCommandsEnabled(this.profile) && this.#commands.commands.some((entry) => entry.invocation === invocation);
33701
34230
  if (command.type === "command.execute") {
33702
34231
  const parsed = commandPrompt(command, this.#commands, this.profile);
@@ -33709,14 +34238,12 @@ var CodeBuddySession = class {
33709
34238
  };
33710
34239
  }
33711
34240
  const snapshot = await this.#snapshot();
33712
- const before = new Set(snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey));
33713
- const beforeItems = new Set(snapshot.turns.flatMap((turn) => turn.items.map((snapshot2) => snapshot2.item.itemId)));
33714
34241
  if (this.#closed || this.#fault)
33715
34242
  return failure2("invalidState", "Session closed before Turn start", this.profile);
34243
+ if (this.#active || this.#autonomous.announcements !== drainBefore)
34244
+ return failure2("sessionBusy", "Session is executing an operation", this.profile);
33716
34245
  const active2 = {
33717
34246
  command,
33718
- before,
33719
- beforeItems,
33720
34247
  output: new CodeBuddyTurnOutput(command.turnId, this.input.cwd, (event) => this.#emit(event), this.profile),
33721
34248
  nativeCommand,
33722
34249
  cancelled: false,
@@ -33726,11 +34253,16 @@ var CodeBuddySession = class {
33726
34253
  this.#active = active2;
33727
34254
  this.subagents.begin(command.turnId);
33728
34255
  this.#emit({ type: "turn.started", turnId: command.turnId });
33729
- active2.completion = this.#run(active2);
34256
+ active2.completion = this.#run(active2, new Set(snapshot.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)), new Set(snapshot.turns.flatMap((turn) => turn.items.map(({ item }) => item.itemId))), drainBefore);
33730
34257
  return { ok: true, value: { turnId: command.turnId } };
33731
34258
  }
33732
- if (this.#needsResume)
34259
+ if (this.#needsResume) {
33733
34260
  await this.#resumeClient();
34261
+ if (this.#closed || this.#fault)
34262
+ return failure2("invalidState", "Session is closed or faulted", this.profile);
34263
+ if (this.#active && (this.#active.cancelled || command.type !== "model.select" && command.type !== "thinking.select"))
34264
+ return failure2("sessionBusy", "Session is executing an operation", this.profile);
34265
+ }
33734
34266
  await this.#configure(command.type === "model.select" ? "model" : command.type === "thinking.select" ? "thought_level" : "mode", command.type === "model.select" ? command.model.id : command.type === "thinking.select" ? command.thinkingOptionId : command.permissionModeId);
33735
34267
  return { ok: true, value: { completed: true } };
33736
34268
  } catch (error62) {
@@ -33739,12 +34271,14 @@ var CodeBuddySession = class {
33739
34271
  this.#busy = false;
33740
34272
  }
33741
34273
  }
33742
- async #run(active2) {
34274
+ async #run(active2, before, beforeItems, drainBefore) {
33743
34275
  let cancellationConfirmed = false;
33744
34276
  try {
33745
34277
  if (!this.#ref)
33746
34278
  throw new CodeBuddyError("invalidState", "Session is not open");
33747
- const response = await this.#client.prompt(this.#ref.nativeSessionId, active2.command.input.map((item) => item.text).join("\n"));
34279
+ const response = await this.#client.prompt(this.#ref.nativeSessionId, active2.command.input.map((item) => item.text).join("\n")).finally(() => {
34280
+ active2.promptSettled = true;
34281
+ });
33748
34282
  if (active2.done || this.#closed)
33749
34283
  return;
33750
34284
  const stop = response.stopReason, meta3 = record3(response._meta);
@@ -33756,39 +34290,42 @@ var CodeBuddySession = class {
33756
34290
  };
33757
34291
  if (outcome.status === "cancelled") {
33758
34292
  active2.cancelled = true;
33759
- ++this.#generation;
33760
- this.#interactions.close();
33761
34293
  try {
33762
- await this.#client.close();
34294
+ await this.#retireClient();
33763
34295
  } catch (error62) {
33764
34296
  this.#onFault(error62);
33765
34297
  return;
33766
34298
  }
33767
34299
  if (active2.done || this.#closed)
33768
34300
  return;
33769
- this.#needsResume = true;
33770
34301
  cancellationConfirmed = true;
33771
34302
  }
33772
- const snapshot = await this.#snapshot(cancellationConfirmed ? 1e3 : void 0);
34303
+ const { snapshot, history } = await this.#snapshotWithHistory(cancellationConfirmed ? 1e3 : void 0);
33773
34304
  if (active2.done || this.#closed)
33774
34305
  return;
33775
- const added = snapshot.turns.filter((turn) => !active2.before.has(turn.nativeTurnRef.nativeTurnKey));
33776
- if (added.length > 1 || !active2.nativeCommand && outcome.status === "succeeded" && added.length !== 1)
33777
- throw new CodeBuddyError("protocolError", "Could not identify exactly one persisted Native Turn");
33778
- const nativeTurnRef = added[0]?.nativeTurnRef;
33779
- if (response.userMessageId && nativeTurnRef?.nativeTurnKey !== response.userMessageId)
34306
+ const drainOverlapped = this.#autonomous.announcements !== drainBefore;
34307
+ const userMessageId = text2(response.userMessageId);
34308
+ const added = snapshot.turns.filter((turn) => !before.has(turn.nativeTurnRef.nativeTurnKey));
34309
+ const persisted = userMessageId ? added.find((turn) => turn.nativeTurnRef.nativeTurnKey === userMessageId) : !drainOverlapped && added.length === 1 ? added[0] : void 0;
34310
+ if (userMessageId && !persisted)
33780
34311
  throw new CodeBuddyError("protocolError", "ACP terminal and native history disagree on Turn identity");
33781
- active2.output.confirmCompaction(snapshot.turns.flatMap((turn) => turn.items).filter((snapshot2) => !active2.beforeItems.has(snapshot2.item.itemId)));
34312
+ if (!persisted && !active2.nativeCommand && outcome.status === "succeeded")
34313
+ throw new CodeBuddyError("protocolError", "Could not identify exactly one persisted Native Turn");
34314
+ const compactionItems = persisted ? compactionEvidenceForTurn(history, snapshot, persisted.nativeTurnRef.nativeTurnKey, beforeItems, this.profile) : drainOverlapped ? [] : snapshot.turns.flatMap((turn) => turn.items).filter(({ item }) => !beforeItems.has(item.itemId));
34315
+ active2.output.confirmCompaction(compactionItems);
33782
34316
  if (active2.nativeCommand)
33783
- active2.output.replayCommandResult((added[0]?.items ?? []).filter(({ item }) => !this.subagents.hasItem(item.itemId)));
34317
+ active2.output.replayCommandResult((persisted?.items ?? []).filter(({ item }) => !this.subagents.hasItem(item.itemId)));
34318
+ const nativeTurnRef = persisted?.nativeTurnRef;
34319
+ if (nativeTurnRef)
34320
+ this.#hasTurn = true;
33784
34321
  const compactCommand = outcome.status !== "cancelled" && active2.nativeCommand && /^\/compact(?:\s|$)/u.test(active2.command.input.map((item) => item.text).join("\n").trim());
33785
- const persisted = compactCommand ? added[0]?.outcome : void 0;
33786
- if (compactCommand && (!persisted || persisted.status === "unknown"))
34322
+ const persistedOutcome = compactCommand ? persisted?.outcome : void 0;
34323
+ if (compactCommand && (!persistedOutcome || persistedOutcome.status === "unknown"))
33787
34324
  throw new CodeBuddyError("protocolError", "Native compaction terminal outcome was not persisted");
33788
- const terminalOutcome = persisted && persisted.status !== "unknown" ? persisted : outcome;
34325
+ const terminalOutcome = persistedOutcome && persistedOutcome.status !== "unknown" ? persistedOutcome : outcome;
33789
34326
  this.#finish(active2, {
33790
34327
  ...terminalOutcome,
33791
- ...added[0]?.checkpoint ? { checkpoint: added[0].checkpoint } : {}
34328
+ ...persisted?.checkpoint ? { checkpoint: persisted.checkpoint } : {}
33792
34329
  }, nativeTurnRef);
33793
34330
  if (this.#usage)
33794
34331
  this.#emitUsage();
@@ -33797,6 +34334,13 @@ var CodeBuddySession = class {
33797
34334
  this.#finish(active2, cancellationConfirmed ? { status: "cancelled" } : { status: "failed", error: nativeError(error62, this.profile) });
33798
34335
  }
33799
34336
  }
34337
+ async #retireClient() {
34338
+ ++this.#generation;
34339
+ this.#interactions.close();
34340
+ this.#autonomous.close();
34341
+ await this.#client.close();
34342
+ this.#needsResume = true;
34343
+ }
33800
34344
  /** Runs only under the native operation gate, after the old process has exited. */
33801
34345
  async #resumeClient() {
33802
34346
  const replay = {};
@@ -33812,8 +34356,11 @@ var CodeBuddySession = class {
33812
34356
  if (!this.profile.staticCommandCatalog)
33813
34357
  this.#commands = replay.commands ?? { commands: [] };
33814
34358
  this.#needsResume = false;
34359
+ this.#replay = void 0;
34360
+ this.#flushAutonomous();
33815
34361
  } catch (error62) {
33816
34362
  ++this.#generation;
34363
+ this.#autonomous.close();
33817
34364
  try {
33818
34365
  await candidate?.close();
33819
34366
  } catch (closeError) {
@@ -33828,6 +34375,9 @@ var CodeBuddySession = class {
33828
34375
  if (active2.done)
33829
34376
  return;
33830
34377
  active2.done = true;
34378
+ active2.settle?.();
34379
+ if (active2.autonomous)
34380
+ this.#autonomous.finish(active2.autonomous.round);
33831
34381
  this.subagents.finish(outcome);
33832
34382
  this.#interactions.close();
33833
34383
  active2.output.finish(outcome.status, outcome.status === "failed" ? outcome.error : void 0);
@@ -33835,15 +34385,19 @@ var CodeBuddySession = class {
33835
34385
  type: "turn.completed",
33836
34386
  turnId: active2.command.turnId,
33837
34387
  outcome,
34388
+ ...active2.autonomous ? { ephemeral: true } : {},
33838
34389
  ...nativeTurnRef ? { nativeTurnRef } : {}
33839
34390
  });
33840
34391
  if (this.#active === active2)
33841
34392
  this.#active = void 0;
34393
+ this.#flushAutonomous();
33842
34394
  }
33843
34395
  #onFault(error62) {
33844
34396
  if (this.#fault || this.#closed)
33845
34397
  return;
33846
34398
  this.#fault = nativeError(error62, this.profile);
34399
+ this.#replay = void 0;
34400
+ this.#autonomous.close();
33847
34401
  if (this.#active)
33848
34402
  this.#finish(this.#active, { status: "failed", error: this.#fault });
33849
34403
  this.#interactions.close();
@@ -33853,11 +34407,19 @@ var CodeBuddySession = class {
33853
34407
  this.#channel.end();
33854
34408
  }
33855
34409
  close() {
33856
- this.#closing ??= this.#close();
33857
- return this.#closing;
34410
+ if (this.#closing)
34411
+ return this.#closing;
34412
+ const closing = this.#close().catch((error62) => {
34413
+ if (this.#closing === closing)
34414
+ this.#closing = void 0;
34415
+ throw error62;
34416
+ });
34417
+ this.#closing = closing;
34418
+ return closing;
33858
34419
  }
33859
34420
  async #close() {
33860
34421
  this.#closed = true;
34422
+ this.#autonomous.close();
33861
34423
  this.#interactions.close();
33862
34424
  try {
33863
34425
  await this.#client.close();
@@ -33870,7 +34432,10 @@ var CodeBuddySession = class {
33870
34432
  } finally {
33871
34433
  this.subagents.close();
33872
34434
  this.#channel.end();
33873
- this.onClose();
34435
+ if (!this.#closeNotified) {
34436
+ this.#closeNotified = true;
34437
+ this.onClose();
34438
+ }
33874
34439
  }
33875
34440
  }
33876
34441
  };
@@ -34317,17 +34882,44 @@ var linuxSpec = {
34317
34882
  command: "workbuddy",
34318
34883
  installRoots: { posix: linuxRoots }
34319
34884
  };
34320
- function resolveWorkBuddyInstallDirectory(directory, environment, platform, isExecutable) {
34885
+ function resolveWorkBuddyInstallDirectory(directory, environment, platform, isExecutable, subdirectories = subdirectoryNames) {
34321
34886
  const paths = targetPath(platform);
34322
- const entries = platform === "win32" ? ["WorkBuddy.exe", "WorkBuddy AI.exe", "WorkBuddyAI.exe"] : platform === "darwin" ? [paths.join("Contents", "MacOS", "Electron")] : platform === "linux" ? ["workbuddy"] : [];
34887
+ const entries = platform === "win32" ? ["WorkBuddy-app.exe", "WorkBuddy.exe", "WorkBuddy AI.exe", "WorkBuddyAI.exe"] : platform === "darwin" ? [paths.join("Contents", "MacOS", "Electron")] : platform === "linux" ? ["workbuddy"] : [];
34323
34888
  for (const entry of entries) {
34324
- const bundle = resolveWorkBuddyBundle(environment, platform, isExecutable, paths.join(directory, entry));
34889
+ const bundle = resolveWorkBuddyBundle(environment, platform, isExecutable, paths.join(directory, entry), subdirectories);
34325
34890
  if (bundle)
34326
34891
  return bundle;
34327
34892
  }
34328
34893
  return void 0;
34329
34894
  }
34330
- function resolveWorkBuddyBundle(environment, platform, isExecutable, explicitExecutable) {
34895
+ function resolveWorkBuddyLauncherLayout(directory, platform, isExecutable, subdirectories) {
34896
+ if (platform !== "win32")
34897
+ return void 0;
34898
+ const paths = targetPath(platform);
34899
+ const versions = paths.join(directory, "versions");
34900
+ let names;
34901
+ try {
34902
+ names = newestFirst(subdirectories(versions));
34903
+ } catch {
34904
+ return void 0;
34905
+ }
34906
+ for (const name of names) {
34907
+ const root = paths.join(versions, name);
34908
+ for (const entry of [
34909
+ "WorkBuddy-app.exe",
34910
+ "WorkBuddy.exe",
34911
+ "WorkBuddy AI.exe",
34912
+ "WorkBuddyAI.exe"
34913
+ ]) {
34914
+ const executable = paths.join(root, entry);
34915
+ const cli = paths.join(root, "resources", "app.asar.unpacked", "cli", "bin", "codebuddy");
34916
+ if (isExecutable(executable) && isExecutable(cli))
34917
+ return { executable, cli };
34918
+ }
34919
+ }
34920
+ return void 0;
34921
+ }
34922
+ function resolveWorkBuddyBundle(environment, platform, isExecutable, explicitExecutable, subdirectories = subdirectoryNames) {
34331
34923
  const specs = platform === "darwin" ? [macSpec] : platform === "win32" ? ["WorkBuddy AI", "WorkBuddy", "WorkBuddyAI"].map((command) => ({
34332
34924
  id: "workbuddy",
34333
34925
  command,
@@ -34342,6 +34934,9 @@ function resolveWorkBuddyBundle(environment, platform, isExecutable, explicitExe
34342
34934
  continue;
34343
34935
  if (!isExecutable(candidate))
34344
34936
  continue;
34937
+ const launcher = resolveWorkBuddyLauncherLayout(paths.dirname(candidate), platform, isExecutable, subdirectories);
34938
+ if (launcher)
34939
+ return launcher;
34345
34940
  const resources = platform === "darwin" ? paths.resolve(paths.dirname(candidate), "..", "Resources") : paths.join(paths.dirname(candidate), "resources");
34346
34941
  const cli = paths.join(resources, "app.asar.unpacked", "cli", "bin", "codebuddy");
34347
34942
  if (isExecutable(cli))
@@ -34418,11 +35013,12 @@ function resolveWorkBuddyLaunch(environment, dependencies = {}) {
34418
35013
  if (!configured && platform !== "darwin" && platform !== "win32" && platform !== "linux")
34419
35014
  throw new CodeBuddyError("notInstalled", "WorkBuddy app discovery is unavailable on this platform; set CODEXHOST_WORKBUDDY_COMMAND for a compatible native runtime");
34420
35015
  const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
35016
+ const subdirectories = dependencies.subdirectories ?? subdirectoryNames;
34421
35017
  const configuredDirectory = configured && (dependencies.isDirectory ?? isDirectory)(configured) ? configured : void 0;
34422
35018
  const explicitExecutable = configured && !configuredDirectory ? resolveHarnessExecutable(workBuddyDiscoverySpec, { environment, platform, command: configured }, { isExecutable })?.executable : void 0;
34423
- const explicitBundle = explicitExecutable ? resolveWorkBuddyBundle(environment, platform, isExecutable, explicitExecutable) : void 0;
34424
- const explicitDesktop = explicitExecutable !== void 0 && (platform === "win32" && /^(?:WorkBuddy|WorkBuddy AI|WorkBuddyAI)\.exe$/iu.test(targetPath(platform).basename(explicitExecutable)) || platform === "darwin" && /\/(?:WorkBuddy|WorkBuddy AI)\.app\/Contents\/MacOS\/Electron$/u.test(explicitExecutable) || platform === "linux" && targetPath(platform).basename(explicitExecutable) === "workbuddy");
34425
- const bundle = configuredDirectory ? resolveWorkBuddyInstallDirectory(configuredDirectory, environment, platform, isExecutable) : !configured ? resolveWorkBuddyBundle(environment, platform, isExecutable) : explicitDesktop ? explicitBundle : void 0;
35019
+ const explicitBundle = explicitExecutable ? resolveWorkBuddyBundle(environment, platform, isExecutable, explicitExecutable, subdirectories) : void 0;
35020
+ const explicitDesktop = explicitExecutable !== void 0 && (platform === "win32" && /^(?:WorkBuddy(?:-app)?|WorkBuddy AI|WorkBuddyAI)\.exe$/iu.test(targetPath(platform).basename(explicitExecutable)) || platform === "darwin" && /\/(?:WorkBuddy|WorkBuddy AI)\.app\/Contents\/MacOS\/Electron$/u.test(explicitExecutable) || platform === "linux" && targetPath(platform).basename(explicitExecutable) === "workbuddy");
35021
+ const bundle = configuredDirectory ? resolveWorkBuddyInstallDirectory(configuredDirectory, environment, platform, isExecutable, subdirectories) : !configured ? resolveWorkBuddyBundle(environment, platform, isExecutable, void 0, subdirectories) : explicitDesktop ? explicitBundle : void 0;
34426
35022
  const executable = configured && !explicitDesktop && !configuredDirectory ? explicitExecutable : bundle?.executable;
34427
35023
  if (!executable)
34428
35024
  throw new CodeBuddyError("notInstalled", "WorkBuddy AI app or its bundled CLI is unavailable");
@@ -34513,7 +35109,7 @@ var WORKBUDDY_RUNTIME_PROFILE = {
34513
35109
 
34514
35110
  // dist/product-models.js
34515
35111
  import { readFile as readFile5, stat as stat4 } from "node:fs/promises";
34516
- import path11 from "node:path";
35112
+ import path12 from "node:path";
34517
35113
  var MAX_PRODUCT_SNAPSHOT_BYTES = 8 * 1024 * 1024;
34518
35114
  var PRODUCT_CONFIG_PATH_ENV = "ACC_PRODUCT_CONFIG_PATH";
34519
35115
  var PRODUCT_CONFIG_INLINE_ENVS = [
@@ -34575,7 +35171,7 @@ function bundledFallbackProductPath(invocation) {
34575
35171
  const cli = invocation.bundledCliPath;
34576
35172
  if (!cli)
34577
35173
  return;
34578
- return path11.join(path11.dirname(path11.dirname(cli)), "product.json");
35174
+ return path12.join(path12.dirname(path12.dirname(cli)), "product.json");
34579
35175
  }
34580
35176
  async function loadWorkBuddyProductModels(environment) {
34581
35177
  const invocation = workBuddyInvocation(environment, true);