@codexhost/cli-darwin-x64 0.22.0 → 0.24.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 (59) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +3117 -274
  4. package/app/console-web.js +15645 -4413
  5. package/app/desktop-controller.mjs +14057 -969
  6. package/app/host-runtime.mjs +11518 -8277
  7. package/app/plugins/antigravity/plugin.mjs +2030 -678
  8. package/app/plugins/claude-code/plugin.mjs +2116 -929
  9. package/app/plugins/codebuddy/plugin.mjs +1247 -353
  10. package/app/plugins/codex-usage/plugin.mjs +786 -163
  11. package/app/plugins/copilot/plugin.mjs +938 -296
  12. package/app/plugins/cursor-cli/plugin.mjs +1021 -232
  13. package/app/plugins/deepseek-harness/plugin.mjs +1552 -664
  14. package/app/plugins/devin/plugin.mjs +826 -185
  15. package/app/plugins/grok/plugin.mjs +1083 -424
  16. package/app/plugins/hermes/plugin.mjs +961 -338
  17. package/app/plugins/kimi-code/plugin.mjs +854 -237
  18. package/app/plugins/kiro-cli/plugin.mjs +821 -184
  19. package/app/plugins/omp/plugin.mjs +1316 -633
  20. package/app/plugins/opencode/plugin.mjs +1293 -606
  21. package/app/plugins/pi/plugin.mjs +1540 -867
  22. package/app/plugins/qoder/plugin.mjs +961 -332
  23. package/app/plugins/qoder-cn/plugin.mjs +961 -332
  24. package/app/plugins/qwen-code/plugin.mjs +937 -321
  25. package/app/plugins/workbuddy/plugin.mjs +1311 -370
  26. package/app/plugins/zcode/plugin.mjs +1516 -423
  27. package/app/renderer-extension.js +21297 -9060
  28. package/app/web/assets/index-CTCFIQbU.css +1 -0
  29. package/app/web/assets/index-IvFk9KT-.js +203 -0
  30. package/app/web/codexhost-settings.js +6753 -31616
  31. package/app/web/index.html +2 -2
  32. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  33. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  34. package/app/web/plugins/deepseek-ai__dsh-client-ui-approval/client.js +1 -1
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +14 -14
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +75 -64
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +94 -91
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +2 -2
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +2 -2
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-browser/client.js +1 -1
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +79 -79
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +3 -3
  49. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +7 -7
  50. package/app/web/sw.js +8 -1
  51. package/app/web-modules/licenses/werift-NOTICES.txt +123 -0
  52. package/app/web-modules/licenses/werift-libwebrtc-NOTICES.txt +58 -0
  53. package/app/web-modules/server.mjs +40416 -11283
  54. package/bin/codexhost +0 -0
  55. package/libexec/codexhost-shim +0 -0
  56. package/libexec/codexhost-updater +0 -0
  57. package/package.json +1 -1
  58. package/app/web/assets/index-CN4a4sj0.js +0 -201
  59. package/app/web/assets/index-DJW4bmyx.css +0 -1
@@ -32,10 +32,10 @@ function executableExtensions(command, platform, environment) {
32
32
  return [""];
33
33
  return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
34
34
  }
35
- function isExecutableFile(filePath, platform) {
35
+ function isExecutableFile(filePath2, platform) {
36
36
  try {
37
- fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
38
- return fs.statSync(filePath).isFile();
37
+ fs.accessSync(filePath2, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
38
+ return fs.statSync(filePath2).isFile();
39
39
  } catch {
40
40
  return false;
41
41
  }
@@ -412,7 +412,7 @@ function createHarnessInstaller(environment, source) {
412
412
  import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
413
413
  import { randomUUID as randomUUID2 } from "node:crypto";
414
414
  import { stat as stat2 } from "node:fs/promises";
415
- import path12 from "node:path";
415
+ import path13 from "node:path";
416
416
 
417
417
  // ../../../node_modules/zod/v4/classic/external.js
418
418
  var external_exports = {};
@@ -1180,10 +1180,10 @@ function mergeDefs(...defs) {
1180
1180
  function cloneDef(schema) {
1181
1181
  return mergeDefs(schema._zod.def);
1182
1182
  }
1183
- function getElementAtPath(obj, path13) {
1184
- if (!path13)
1183
+ function getElementAtPath(obj, path14) {
1184
+ if (!path14)
1185
1185
  return obj;
1186
- return path13.reduce((acc, key) => acc?.[key], obj);
1186
+ return path14.reduce((acc, key) => acc?.[key], obj);
1187
1187
  }
1188
1188
  function promiseAllObject(promisesObj) {
1189
1189
  const keys = Object.keys(promisesObj);
@@ -1592,11 +1592,11 @@ function explicitlyAborted(x, startIndex = 0) {
1592
1592
  }
1593
1593
  return false;
1594
1594
  }
1595
- function prefixIssues(path13, issues) {
1595
+ function prefixIssues(path14, issues) {
1596
1596
  return issues.map((iss) => {
1597
1597
  var _a3;
1598
1598
  (_a3 = iss).path ?? (_a3.path = []);
1599
- iss.path.unshift(path13);
1599
+ iss.path.unshift(path14);
1600
1600
  return iss;
1601
1601
  });
1602
1602
  }
@@ -1667,8 +1667,8 @@ function cleanEnum(obj) {
1667
1667
  return Number.isNaN(Number.parseInt(k, 10));
1668
1668
  }).map((el) => el[1]);
1669
1669
  }
1670
- function base64ToUint8Array(base643) {
1671
- const binaryString = atob(base643);
1670
+ function base64ToUint8Array(base644) {
1671
+ const binaryString = atob(base644);
1672
1672
  const bytes = new Uint8Array(binaryString.length);
1673
1673
  for (let i = 0; i < binaryString.length; i++) {
1674
1674
  bytes[i] = binaryString.charCodeAt(i);
@@ -1683,9 +1683,9 @@ function uint8ArrayToBase64(bytes) {
1683
1683
  return btoa(binaryString);
1684
1684
  }
1685
1685
  function base64urlToUint8Array(base64url3) {
1686
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1687
- const padding = "=".repeat((4 - base643.length % 4) % 4);
1688
- return base64ToUint8Array(base643 + padding);
1686
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1687
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
1688
+ return base64ToUint8Array(base644 + padding);
1689
1689
  }
1690
1690
  function uint8ArrayToBase64url(bytes) {
1691
1691
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -1743,16 +1743,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1743
1743
  }
1744
1744
  function formatError(error51, mapper = (issue2) => issue2.message) {
1745
1745
  const fieldErrors = { _errors: [] };
1746
- const processError = (error52, path13 = []) => {
1746
+ const processError = (error52, path14 = []) => {
1747
1747
  for (const issue2 of error52.issues) {
1748
1748
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1749
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1749
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1750
1750
  } else if (issue2.code === "invalid_key") {
1751
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1751
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1752
1752
  } else if (issue2.code === "invalid_element") {
1753
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1753
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1754
1754
  } else {
1755
- const fullpath = [...path13, ...issue2.path];
1755
+ const fullpath = [...path14, ...issue2.path];
1756
1756
  if (fullpath.length === 0) {
1757
1757
  fieldErrors._errors.push(mapper(issue2));
1758
1758
  } else {
@@ -1779,17 +1779,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1779
1779
  }
1780
1780
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1781
1781
  const result = { errors: [] };
1782
- const processError = (error52, path13 = []) => {
1782
+ const processError = (error52, path14 = []) => {
1783
1783
  var _a3, _b;
1784
1784
  for (const issue2 of error52.issues) {
1785
1785
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1786
- issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1786
+ issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
1787
1787
  } else if (issue2.code === "invalid_key") {
1788
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1788
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1789
1789
  } else if (issue2.code === "invalid_element") {
1790
- processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1790
+ processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
1791
1791
  } else {
1792
- const fullpath = [...path13, ...issue2.path];
1792
+ const fullpath = [...path14, ...issue2.path];
1793
1793
  if (fullpath.length === 0) {
1794
1794
  result.errors.push(mapper(issue2));
1795
1795
  continue;
@@ -1821,8 +1821,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1821
1821
  }
1822
1822
  function toDotPath(_path) {
1823
1823
  const segs = [];
1824
- const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1825
- for (const seg of path13) {
1824
+ const path14 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1825
+ for (const seg of path14) {
1826
1826
  if (typeof seg === "number")
1827
1827
  segs.push(`[${seg}]`);
1828
1828
  else if (typeof seg === "symbol")
@@ -3051,8 +3051,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
3051
3051
  function isValidBase64URL(data) {
3052
3052
  if (!base64url.test(data))
3053
3053
  return false;
3054
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
3055
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
3054
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
3055
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
3056
3056
  return isValidBase64(padded);
3057
3057
  }
3058
3058
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -3506,42 +3506,42 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3506
3506
  }
3507
3507
  doc.write(`const newResult = {};`);
3508
3508
  for (const key of normalized.keys) {
3509
- const id = ids[key];
3509
+ const id2 = ids[key];
3510
3510
  const k = esc(key);
3511
3511
  const schema = shape[key];
3512
3512
  const isOptionalIn = schema?._zod?.optin === "optional";
3513
3513
  const isOptionalOut = schema?._zod?.optout === "optional";
3514
- doc.write(`const ${id} = ${parseStr(key)};`);
3514
+ doc.write(`const ${id2} = ${parseStr(key)};`);
3515
3515
  if (isOptionalIn && isOptionalOut) {
3516
3516
  doc.write(`
3517
- if (${id}.issues.length) {
3517
+ if (${id2}.issues.length) {
3518
3518
  if (${k} in input) {
3519
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3519
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3520
3520
  ...iss,
3521
3521
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3522
3522
  })));
3523
3523
  }
3524
3524
  }
3525
3525
 
3526
- if (${id}.value === undefined) {
3526
+ if (${id2}.value === undefined) {
3527
3527
  if (${k} in input) {
3528
3528
  newResult[${k}] = undefined;
3529
3529
  }
3530
3530
  } else {
3531
- newResult[${k}] = ${id}.value;
3531
+ newResult[${k}] = ${id2}.value;
3532
3532
  }
3533
3533
 
3534
3534
  `);
3535
3535
  } else if (!isOptionalIn) {
3536
3536
  doc.write(`
3537
- const ${id}_present = ${k} in input;
3538
- if (${id}.issues.length) {
3539
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3537
+ const ${id2}_present = ${k} in input;
3538
+ if (${id2}.issues.length) {
3539
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3540
3540
  ...iss,
3541
3541
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3542
3542
  })));
3543
3543
  }
3544
- if (!${id}_present && !${id}.issues.length) {
3544
+ if (!${id2}_present && !${id2}.issues.length) {
3545
3545
  payload.issues.push({
3546
3546
  code: "invalid_type",
3547
3547
  expected: "nonoptional",
@@ -3550,30 +3550,30 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3550
3550
  });
3551
3551
  }
3552
3552
 
3553
- if (${id}_present) {
3554
- if (${id}.value === undefined) {
3553
+ if (${id2}_present) {
3554
+ if (${id2}.value === undefined) {
3555
3555
  newResult[${k}] = undefined;
3556
3556
  } else {
3557
- newResult[${k}] = ${id}.value;
3557
+ newResult[${k}] = ${id2}.value;
3558
3558
  }
3559
3559
  }
3560
3560
 
3561
3561
  `);
3562
3562
  } else {
3563
3563
  doc.write(`
3564
- if (${id}.issues.length) {
3565
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3564
+ if (${id2}.issues.length) {
3565
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3566
3566
  ...iss,
3567
3567
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3568
3568
  })));
3569
3569
  }
3570
3570
 
3571
- if (${id}.value === undefined) {
3571
+ if (${id2}.value === undefined) {
3572
3572
  if (${k} in input) {
3573
3573
  newResult[${k}] = undefined;
3574
3574
  }
3575
3575
  } else {
3576
- newResult[${k}] = ${id}.value;
3576
+ newResult[${k}] = ${id2}.value;
3577
3577
  }
3578
3578
 
3579
3579
  `);
@@ -11905,26 +11905,26 @@ function extractDefs(ctx, schema) {
11905
11905
  throw new Error("Unprocessed schema. This is a bug in Zod.");
11906
11906
  const idToSchema = /* @__PURE__ */ new Map();
11907
11907
  for (const entry of ctx.seen.entries()) {
11908
- const id = ctx.metadataRegistry.get(entry[0])?.id;
11909
- if (id) {
11910
- const existing = idToSchema.get(id);
11908
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
11909
+ if (id2) {
11910
+ const existing = idToSchema.get(id2);
11911
11911
  if (existing && existing !== entry[0]) {
11912
- throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
11912
+ throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
11913
11913
  }
11914
- idToSchema.set(id, entry[0]);
11914
+ idToSchema.set(id2, entry[0]);
11915
11915
  }
11916
11916
  }
11917
11917
  const makeURI = (entry) => {
11918
11918
  const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
11919
11919
  if (ctx.external) {
11920
11920
  const externalId = ctx.external.registry.get(entry[0])?.id;
11921
- const uriGenerator = ctx.external.uri ?? ((id2) => id2);
11921
+ const uriGenerator = ctx.external.uri ?? ((id3) => id3);
11922
11922
  if (externalId) {
11923
11923
  return { ref: uriGenerator(externalId) };
11924
11924
  }
11925
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
11926
- entry[1].defId = id;
11927
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
11925
+ const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
11926
+ entry[1].defId = id2;
11927
+ return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
11928
11928
  }
11929
11929
  if (entry[1] === root) {
11930
11930
  return { ref: "#" };
@@ -11972,8 +11972,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11972
11972
  continue;
11973
11973
  }
11974
11974
  }
11975
- const id = ctx.metadataRegistry.get(entry[0])?.id;
11976
- if (id) {
11975
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
11976
+ if (id2) {
11977
11977
  extractToDef(entry);
11978
11978
  continue;
11979
11979
  }
@@ -12069,10 +12069,10 @@ function finalize(ctx, schema) {
12069
12069
  } else {
12070
12070
  }
12071
12071
  if (ctx.external?.uri) {
12072
- const id = ctx.external.registry.get(schema)?.id;
12073
- if (!id)
12072
+ const id2 = ctx.external.registry.get(schema)?.id;
12073
+ if (!id2)
12074
12074
  throw new Error("Schema is missing an `id` property");
12075
- result.$id = ctx.external.uri(id);
12075
+ result.$id = ctx.external.uri(id2);
12076
12076
  }
12077
12077
  Object.assign(result, root.def ?? root.schema);
12078
12078
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
@@ -12232,9 +12232,9 @@ var numberProcessor = (schema, ctx, _json, _params) => {
12232
12232
  json2.type = "number";
12233
12233
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
12234
12234
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
12235
- const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
12235
+ const legacy2 = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
12236
12236
  if (exMin) {
12237
- if (legacy) {
12237
+ if (legacy2) {
12238
12238
  json2.minimum = exclusiveMinimum;
12239
12239
  json2.exclusiveMinimum = true;
12240
12240
  } else {
@@ -12244,7 +12244,7 @@ var numberProcessor = (schema, ctx, _json, _params) => {
12244
12244
  json2.minimum = minimum;
12245
12245
  }
12246
12246
  if (exMax) {
12247
- if (legacy) {
12247
+ if (legacy2) {
12248
12248
  json2.maximum = exclusiveMaximum;
12249
12249
  json2.exclusiveMaximum = true;
12250
12250
  } else {
@@ -13106,7 +13106,7 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
13106
13106
 
13107
13107
  // ../../../node_modules/zod/v4/classic/schemas.js
13108
13108
  var _installedGroups = /* @__PURE__ */ new WeakMap();
13109
- function _installLazyMethods(inst, group, methods2) {
13109
+ function _installLazyMethods(inst, group, methods3) {
13110
13110
  const proto = Object.getPrototypeOf(inst);
13111
13111
  let installed = _installedGroups.get(proto);
13112
13112
  if (!installed) {
@@ -13116,8 +13116,8 @@ function _installLazyMethods(inst, group, methods2) {
13116
13116
  if (installed.has(group))
13117
13117
  return;
13118
13118
  installed.add(group);
13119
- for (const key in methods2) {
13120
- const fn = methods2[key];
13119
+ for (const key in methods3) {
13120
+ const fn = methods3[key];
13121
13121
  Object.defineProperty(proto, key, {
13122
13122
  configurable: true,
13123
13123
  enumerable: false,
@@ -14514,13 +14514,13 @@ function resolveRef(ref, ctx) {
14514
14514
  if (!ref.startsWith("#")) {
14515
14515
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14516
14516
  }
14517
- const path13 = ref.slice(1).split("/").filter(Boolean);
14518
- if (path13.length === 0) {
14517
+ const path14 = ref.slice(1).split("/").filter(Boolean);
14518
+ if (path14.length === 0) {
14519
14519
  return ctx.rootSchema;
14520
14520
  }
14521
14521
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14522
- if (path13[0] === defsKey) {
14523
- const key = path13[1];
14522
+ if (path14[0] === defsKey) {
14523
+ const key = path14[1];
14524
14524
  if (!key || !ctx.defs[key]) {
14525
14525
  throw new Error(`Reference not found: ${ref}`);
14526
14526
  }
@@ -15061,6 +15061,9 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
15061
15061
  permissionModeId: harnessPermissionModeIdSchema
15062
15062
  }).strict();
15063
15063
 
15064
+ // ../../shared-contracts/dist/harness-route-limit.js
15065
+ var HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH = 8192;
15066
+
15064
15067
  // ../../shared-contracts/dist/thread-usage.js
15065
15068
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15066
15069
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -15093,7 +15096,7 @@ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15093
15096
  expiresAtUnix: nonNegativeSafeIntegerSchema,
15094
15097
  label: indicatorTextSchema(256).optional(),
15095
15098
  tooltip: indicatorTextSchema(1024).optional()
15096
- }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
15099
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, {
15097
15100
  message: "Composer indicator IDs must be unique"
15098
15101
  });
15099
15102
  var threadUsageSnapshotSchema = external_exports.object({
@@ -15119,6 +15122,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15119
15122
  planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15120
15123
  sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15121
15124
  timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15125
+ latestRequestTimeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15122
15126
  costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15123
15127
  unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
15124
15128
  }).strict().superRefine((usage, context) => {
@@ -15216,6 +15220,13 @@ var accountCreditsSnapshotSchema = external_exports.object({
15216
15220
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
15217
15221
  resetCredits: accountResetCreditsSchema.optional()
15218
15222
  }).strict();
15223
+ var accountBalanceSnapshotSchema = external_exports.object({
15224
+ amount: external_exports.number().finite().nonnegative(),
15225
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
15226
+ currency: external_exports.string().trim().min(1).max(8),
15227
+ /** Native label when the Harness exposes several Billing Sources. */
15228
+ label: external_exports.string().trim().min(1).max(128).optional()
15229
+ }).strict();
15219
15230
  var threadUsageInspectionParamsSchema = external_exports.object({
15220
15231
  threadId: hostThreadIdSchema,
15221
15232
  refresh: external_exports.literal("exact").optional()
@@ -15224,7 +15235,10 @@ var threadUsageInspectionSchema = external_exports.object({
15224
15235
  threadId: hostThreadIdSchema,
15225
15236
  usage: threadUsageSnapshotSchema.nullable(),
15226
15237
  accountCredits: accountCreditsSnapshotSchema.optional(),
15227
- /** Whether this source can provide cached account quota independently of usage. */
15238
+ /** Prepaid funds for the Thread's Billing Source; shown only when no percentage quota exists. */
15239
+ accountBalance: accountBalanceSnapshotSchema.optional(),
15240
+ /** Whether this source can provide cached account quota (credits or a prepaid balance)
15241
+ * independently of usage. */
15228
15242
  accountCreditsSupported: external_exports.boolean().optional()
15229
15243
  }).strict();
15230
15244
 
@@ -15236,10 +15250,15 @@ var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
15236
15250
  var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
15237
15251
  message: "Value must not be empty or whitespace"
15238
15252
  });
15239
- var harnessModelRefIdSchema = nonBlankTextSchema2.max(HARNESS_MODEL_REF_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Model Ref must use transport-safe opaque characters").brand();
15253
+ var harnessModelRefIdSchema = external_exports.string().min(1).max(HARNESS_MODEL_REF_MAX_LENGTH).refine((id2) => !new RegExp("\\p{Cc}", "u").test(id2), "Model Ref must not contain control characters").brand();
15254
+ var harnessModelServiceTierSchema = external_exports.enum(["priority", "ultrafast"]);
15240
15255
  var harnessModelRefSchema = external_exports.object({
15241
- id: harnessModelRefIdSchema
15256
+ id: harnessModelRefIdSchema,
15257
+ serviceTier: harnessModelServiceTierSchema.optional()
15242
15258
  }).strict();
15259
+ function sameHarnessModelRef(left, right) {
15260
+ return left?.id === right?.id && left?.serviceTier === right?.serviceTier;
15261
+ }
15243
15262
  var harnessThinkingOptionIdSchema = nonBlankTextSchema2.max(HARNESS_THINKING_OPTION_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Thinking option ID must use transport-safe characters").brand();
15244
15263
  var harnessResolvedModelLabelSchema = nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
15245
15264
  var harnessThinkingOptionSchema = external_exports.object({
@@ -15253,7 +15272,15 @@ var harnessModelSchema = external_exports.object({
15253
15272
  /** Optional opaque selection for this same Model with priority processing enabled. */
15254
15273
  fastModel: harnessModelRefSchema.optional(),
15255
15274
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
15256
- }).strict();
15275
+ }).strict().refine((model2) => model2.fastModel?.serviceTier === void 0 || model2.fastModel.id === model2.ref.id, {
15276
+ path: ["fastModel", "id"],
15277
+ message: "A tiered Fast Model must share the base Model ID"
15278
+ });
15279
+ function catalogModelForRef(catalog, ref) {
15280
+ if (!ref)
15281
+ return void 0;
15282
+ return catalog?.models.find((model2) => sameHarnessModelRef(model2.ref, ref) || sameHarnessModelRef(model2.fastModel, ref));
15283
+ }
15257
15284
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
15258
15285
  const ids = /* @__PURE__ */ new Set();
15259
15286
  for (const [index, option] of options.entries()) {
@@ -15273,26 +15300,26 @@ var harnessModelCatalogSchema = external_exports.object({
15273
15300
  thinkingOptions: harnessThinkingOptionsSchema,
15274
15301
  defaultThinkingOptionId: harnessThinkingOptionIdSchema.optional()
15275
15302
  }).strict().superRefine((catalog, context) => {
15276
- const refs = /* @__PURE__ */ new Set();
15277
- const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15303
+ const refs = [];
15304
+ const thinkingIds = new Set(catalog.thinkingOptions.map(({ id: id2 }) => id2));
15278
15305
  for (const [index, model2] of catalog.models.entries()) {
15279
- if (refs.has(model2.ref.id)) {
15306
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.ref))) {
15280
15307
  context.addIssue({
15281
15308
  code: "custom",
15282
15309
  message: "Model Catalog refs must be unique",
15283
15310
  path: ["models", index, "ref", "id"]
15284
15311
  });
15285
15312
  }
15286
- refs.add(model2.ref.id);
15313
+ refs.push(model2.ref);
15287
15314
  if (model2.fastModel) {
15288
- if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
15315
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.fastModel))) {
15289
15316
  context.addIssue({
15290
15317
  code: "custom",
15291
15318
  message: "Fast Model refs must be distinct and unique",
15292
15319
  path: ["models", index, "fastModel"]
15293
15320
  });
15294
15321
  }
15295
- refs.add(model2.fastModel.id);
15322
+ refs.push(model2.fastModel);
15296
15323
  }
15297
15324
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15298
15325
  for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
@@ -15313,7 +15340,7 @@ var harnessModelCatalogSchema = external_exports.object({
15313
15340
  }
15314
15341
  }
15315
15342
  }
15316
- if (catalog.defaultModel && !refs.has(catalog.defaultModel.id)) {
15343
+ if (catalog.defaultModel && !catalogModelForRef(catalog, catalog.defaultModel)) {
15317
15344
  context.addIssue({
15318
15345
  code: "custom",
15319
15346
  message: "Default Model must exist in the Model Catalog",
@@ -15353,7 +15380,12 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15353
15380
  observe: external_exports.boolean()
15354
15381
  }).strict().optional(),
15355
15382
  /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15356
- steer: external_exports.boolean().optional()
15383
+ steer: external_exports.boolean().optional(),
15384
+ /**
15385
+ * True when the native plan (task list) outlives the Turn that changed it, so a reopened
15386
+ * Thread gets its latest plan again. Otherwise a plan stays with the Turn that made it.
15387
+ */
15388
+ persistentPlan: external_exports.boolean().optional()
15357
15389
  }).strict();
15358
15390
  var harnessConfigurationStateSchema = external_exports.object({
15359
15391
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15362,7 +15394,7 @@ var harnessConfigurationStateSchema = external_exports.object({
15362
15394
  availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15363
15395
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional()
15364
15396
  }).strict().superRefine((state, context) => {
15365
- if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id }) => id === state.effectiveThinkingOptionId)) {
15397
+ if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id: id2 }) => id2 === state.effectiveThinkingOptionId)) {
15366
15398
  context.addIssue({
15367
15399
  code: "custom",
15368
15400
  message: "Effective Thinking option must be currently available",
@@ -15402,7 +15434,8 @@ var harnessInspectParamsSchema = external_exports.object({
15402
15434
  cwd: nonBlankTextSchema2.max(16384).optional(),
15403
15435
  refresh: external_exports.boolean().optional(),
15404
15436
  /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15405
- purpose: external_exports.literal("availability").optional()
15437
+ purpose: external_exports.literal("availability").optional(),
15438
+ credentialAccess: external_exports.enum(["allow", "retry"]).optional()
15406
15439
  }).strict();
15407
15440
  var harnessWebUiOpenParamsSchema = external_exports.object({
15408
15441
  harnessId: harnessIdSchema
@@ -15433,7 +15466,7 @@ var codexThreadInspectionSchema = external_exports.object({
15433
15466
  var externalThreadInspectionSchema = external_exports.object({
15434
15467
  owner: external_exports.literal("external"),
15435
15468
  harnessId: nonBlankTextSchema2.max(256),
15436
- transportModelId: nonBlankTextSchema2.max(1024),
15469
+ transportModelId: nonBlankTextSchema2.max(HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH),
15437
15470
  effectiveModel: harnessModelRefSchema.optional(),
15438
15471
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15439
15472
  effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -15515,13 +15548,635 @@ var threadSteeringInspectResultSchema = external_exports.object({
15515
15548
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15516
15549
  }).strict();
15517
15550
 
15551
+ // ../../shared-contracts/dist/harness-plugins.js
15552
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15553
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15554
+ var HARNESS_PLUGIN_LIMIT = 128;
15555
+ var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
15556
+ var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
15557
+ var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id2) => id2 !== "codex", "The official Codex identity is reserved");
15558
+ var pluginRelativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
15559
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15560
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
15561
+ var harnessInstallationGuideSchema = external_exports.object({
15562
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
15563
+ before: localizedTextSchema.optional(),
15564
+ after: localizedTextSchema.optional(),
15565
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
15566
+ }).strict();
15567
+ var pluginPresentationShape = {
15568
+ id: installedHarnessPluginIdSchema,
15569
+ name: external_exports.string().trim().min(1).max(128),
15570
+ version: external_exports.string().min(1).max(128),
15571
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
15572
+ kind: external_exports.literal("usage").optional(),
15573
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
15574
+ iconStyle: external_exports.object({
15575
+ vector: external_exports.object({
15576
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
15577
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
15578
+ paths: external_exports.array(external_exports.object({
15579
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
15580
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
15581
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
15582
+ }).strict()).min(1).max(32)
15583
+ }).strict().optional(),
15584
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
15585
+ borderRadius: external_exports.number().min(0).max(50).optional(),
15586
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
15587
+ }).strict().optional(),
15588
+ installation: harnessInstallationGuideSchema.optional(),
15589
+ notice: localizedTextSchema.optional(),
15590
+ /** The factory accepts a persisted local entrypoint through its construction context. */
15591
+ launchCommand: external_exports.literal(true).optional(),
15592
+ links: external_exports.object({
15593
+ website: documentationUrlSchema.optional(),
15594
+ documentation: documentationUrlSchema.optional(),
15595
+ installation: documentationUrlSchema.optional()
15596
+ }).strict().optional()
15597
+ };
15598
+ var harnessPluginManifestSchema = external_exports.object({
15599
+ manifestVersion: external_exports.literal(1),
15600
+ ...pluginPresentationShape,
15601
+ adapterApiVersion: external_exports.number().int().positive(),
15602
+ entry: pluginRelativeResourceSchema,
15603
+ icon: pluginRelativeResourceSchema.optional()
15604
+ }).strict();
15605
+ var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
15606
+ var harnessPluginDescriptorSchema = external_exports.object({
15607
+ ...pluginPresentationShape,
15608
+ icon: harnessPluginIconSchema.optional()
15609
+ }).strict();
15610
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15611
+ var harnessPluginListResultSchema = external_exports.object({
15612
+ plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
15613
+ }).strict();
15614
+ var harnessPluginConfigurationSchema = external_exports.object({
15615
+ version: external_exports.literal(1),
15616
+ enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15617
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15618
+ message: "Enabled plugin IDs must be unique",
15619
+ path: ["enabled"]
15620
+ });
15621
+
15622
+ // ../../shared-contracts/dist/desktop-extensions.js
15623
+ var DESKTOP_EXTENSION_API_VERSION = 1;
15624
+ var DESKTOP_EXTENSION_LIMIT = 64;
15625
+ var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
15626
+ var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
15627
+ var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
15628
+ var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
15629
+ var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
15630
+ var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
15631
+ var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
15632
+ var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
15633
+ var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
15634
+ var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
15635
+ var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
15636
+ var desktopExtensionIdSchema = installedPluginIdSchema;
15637
+ var desktopExtensionSlotSchema = external_exports.enum([
15638
+ "sidebar.thread-layout",
15639
+ "sidebar.thread-badge",
15640
+ "appearance.theme"
15641
+ ]);
15642
+ var desktopExtensionCategorySchema = external_exports.enum([
15643
+ "appearance",
15644
+ "interface",
15645
+ "workflow",
15646
+ "analytics",
15647
+ "integrations",
15648
+ "tools"
15649
+ ]);
15650
+ var extensionName = external_exports.string().trim().min(1).max(128);
15651
+ function desktopExtensionScreenshotMimeType(resource) {
15652
+ switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15653
+ case "png":
15654
+ return "image/png";
15655
+ case "jpg":
15656
+ case "jpeg":
15657
+ return "image/jpeg";
15658
+ case "webp":
15659
+ return "image/webp";
15660
+ default:
15661
+ return void 0;
15662
+ }
15663
+ }
15664
+ var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
15665
+ var imagePathSchema = pluginRelativeResourceSchema.refine((resource) => desktopExtensionScreenshotMimeType(resource) !== void 0 && hasPortableSegments(resource), "Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space");
15666
+ var desktopExtensionHttpUrlSchema = external_exports.string().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu, "Expected an HTTP(S) URL").pipe(external_exports.url({ protocol: /^https?$/u })).refine((value) => {
15667
+ const { username, password } = new URL(value);
15668
+ return !username && !password && !/[\\\s]/u.test(value);
15669
+ }, "URL must not contain credentials, backslashes, or whitespace");
15670
+ function localizedText(text2) {
15671
+ return external_exports.strictObject({ en: text2, "zh-CN": text2 });
15672
+ }
15673
+ var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
15674
+ var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
15675
+ var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
15676
+ var settingField = {
15677
+ key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
15678
+ label: desktopExtensionLocalizedTextSchema,
15679
+ description: desktopExtensionLocalizedTextSchema.optional()
15680
+ };
15681
+ var numericSetting = {
15682
+ ...settingField,
15683
+ step: external_exports.number().positive().optional(),
15684
+ default: external_exports.number().optional()
15685
+ };
15686
+ var settingOption = external_exports.strictObject({
15687
+ value: external_exports.string(),
15688
+ label: desktopExtensionLocalizedTextSchema
15689
+ });
15690
+ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
15691
+ external_exports.strictObject({
15692
+ ...settingField,
15693
+ type: external_exports.literal("boolean"),
15694
+ default: external_exports.boolean().optional()
15695
+ }),
15696
+ external_exports.strictObject({
15697
+ ...settingField,
15698
+ type: external_exports.literal("string"),
15699
+ placeholder: desktopExtensionLocalizedTextSchema.optional(),
15700
+ default: external_exports.string().optional()
15701
+ }),
15702
+ external_exports.strictObject({
15703
+ ...numericSetting,
15704
+ type: external_exports.literal("number"),
15705
+ min: external_exports.number().optional(),
15706
+ max: external_exports.number().optional()
15707
+ }),
15708
+ external_exports.strictObject({
15709
+ ...numericSetting,
15710
+ type: external_exports.literal("range"),
15711
+ min: external_exports.number(),
15712
+ max: external_exports.number()
15713
+ }),
15714
+ external_exports.strictObject({
15715
+ ...settingField,
15716
+ type: external_exports.literal("select"),
15717
+ options: external_exports.array(settingOption).min(1),
15718
+ default: external_exports.string().optional()
15719
+ })
15720
+ ]).superRefine((field3, ctx) => {
15721
+ const issue2 = (path14, message3) => ctx.addIssue({ code: "custom", path: [path14], message: message3 });
15722
+ if (field3.type === "number" || field3.type === "range") {
15723
+ const { min = -Infinity, max = Infinity, default: value } = field3;
15724
+ if (min > max)
15725
+ issue2("max", "Must be at least min");
15726
+ if (value !== void 0 && (value < min || value > max))
15727
+ issue2("default", "Must be within min and max");
15728
+ } else if (field3.type === "select") {
15729
+ const values = new Set(field3.options.map(({ value }) => value));
15730
+ if (values.size !== field3.options.length)
15731
+ issue2("options", "Duplicate option values");
15732
+ if (field3.default !== void 0 && !values.has(field3.default))
15733
+ issue2("default", "Must match an option value");
15734
+ }
15735
+ });
15736
+ var manifestHeader = external_exports.object({
15737
+ manifestVersion: external_exports.int().positive(),
15738
+ id: desktopExtensionIdSchema,
15739
+ name: external_exports.union([extensionName, localizedText(extensionName)]),
15740
+ version: external_exports.string().min(1).max(128),
15741
+ desktopApi: external_exports.int().positive()
15742
+ }).passthrough();
15743
+ var desktopExtensionManifestSchema = manifestHeader.extend({
15744
+ manifestVersion: external_exports.literal(1),
15745
+ desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
15746
+ description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
15747
+ author: external_exports.string().trim().min(1).max(128).optional(),
15748
+ repository: desktopExtensionHttpUrlSchema.optional(),
15749
+ details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
15750
+ icon: imagePathSchema.optional(),
15751
+ screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
15752
+ desktop: external_exports.strictObject({
15753
+ script: pluginRelativeResourceSchema,
15754
+ style: pluginRelativeResourceSchema.optional()
15755
+ }).optional(),
15756
+ backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
15757
+ slots: slotsSchema.default(() => []),
15758
+ settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
15759
+ categories: categoriesSchema.optional()
15760
+ }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
15761
+ var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
15762
+ var desktopExtensionStatusSchema = external_exports.strictObject({
15763
+ state: external_exports.enum([
15764
+ "running",
15765
+ "disabled",
15766
+ "invalid",
15767
+ "incompatible",
15768
+ "conflict",
15769
+ "failed",
15770
+ "waiting"
15771
+ ]),
15772
+ hash: desktopExtensionHashSchema.optional(),
15773
+ error: external_exports.string().optional(),
15774
+ conflictWith: desktopExtensionIdSchema.optional()
15775
+ });
15776
+ var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
15777
+ controllerPid: external_exports.int().positive(),
15778
+ targetId: external_exports.string().nullable(),
15779
+ updatedAt: external_exports.iso.datetime(),
15780
+ handledReloadToken: external_exports.uuid().optional(),
15781
+ extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema),
15782
+ surfaces: external_exports.record(external_exports.string(), desktopExtensionStatusSchema).optional()
15783
+ });
15784
+ var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
15785
+ function isGitHubDesktopExtensionZipballUrl(url2) {
15786
+ return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
15787
+ }
15788
+ var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
15789
+ const url2 = new URL(input);
15790
+ return /\.zip$/iu.test(url2.pathname) || isGitHubDesktopExtensionZipballUrl(url2) || url2.origin === "https://github.com" && /^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(url2.pathname) || url2.origin === "https://codeload.github.com" && /^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(url2.pathname);
15791
+ }, "Expected a .zip download URL or a GitHub zipball URL");
15792
+ var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
15793
+ id: desktopExtensionIdSchema,
15794
+ version: external_exports.string().trim().min(1).max(128),
15795
+ name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
15796
+ description: localizedText(external_exports.string().trim().min(1).max(4096)),
15797
+ details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
15798
+ author: external_exports.string().trim().min(1).max(128),
15799
+ repository: desktopExtensionHttpUrlSchema,
15800
+ stars: external_exports.number().int().min(0).optional(),
15801
+ downloads: external_exports.number().int().min(0).optional(),
15802
+ categories: categoriesSchema.optional(),
15803
+ trustTier: desktopExtensionTrustTierSchema.default("community"),
15804
+ icon: desktopExtensionHttpUrlSchema.optional(),
15805
+ screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15806
+ downloadUrl: desktopExtensionZipUrlSchema,
15807
+ sha256: desktopExtensionHashSchema,
15808
+ slots: slotsSchema.optional(),
15809
+ publishedAt: external_exports.string().optional(),
15810
+ updatedAt: external_exports.string().optional(),
15811
+ minCodexHostVersion: external_exports.string().optional()
15812
+ });
15813
+ var desktopExtensionCatalogSchema = external_exports.strictObject({
15814
+ schemaVersion: external_exports.literal(1),
15815
+ generatedAt: external_exports.string(),
15816
+ extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15817
+ });
15818
+ var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
15819
+
15820
+ // ../../shared-contracts/dist/host-extensions.js
15821
+ var reservedName = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu;
15822
+ var HOST_EXTENSION_PAGE_API_VERSION = 1;
15823
+ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id2) => !reservedName.test(id2), "Reserved extension ID");
15824
+ var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
15825
+ var hostExtensionDigestSchema = desktopExtensionHashSchema;
15826
+ var hostExtensionActivationIdSchema = external_exports.uuid();
15827
+ 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((path14) => path14.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
15828
+ var legacy = desktopExtensionManifestSchema.shape;
15829
+ var localized = (max, min = 0) => external_exports.strictObject({
15830
+ en: external_exports.string().trim().min(min).max(max),
15831
+ "zh-CN": external_exports.string().trim().min(min).max(max)
15832
+ });
15833
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path14) => path14.endsWith(suffix), `Expected a ${suffix} file`);
15834
+ var moduleEntry = resourceWithSuffix(".mjs");
15835
+ var style = resourceWithSuffix(".css").optional();
15836
+ var hostExtensionCanonicalPath = (path14) => path14.normalize("NFC").toLowerCase();
15837
+ var hostExtensionManifestV2Schema = external_exports.strictObject({
15838
+ manifestVersion: external_exports.literal(2),
15839
+ id: hostExtensionIdSchema,
15840
+ name: localized(128, 1),
15841
+ version: external_exports.string().trim().min(1).max(128),
15842
+ description: localized(4096),
15843
+ details: localized(16384).optional(),
15844
+ author: legacy.author,
15845
+ repository: legacy.repository,
15846
+ icon: legacy.icon.refine((path14) => path14 === void 0 || hostExtensionResourcePathSchema.safeParse(path14).success),
15847
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path14) => hostExtensionResourcePathSchema.safeParse(path14).success)),
15848
+ categories: legacy.categories,
15849
+ settingsSchema: legacy.settingsSchema,
15850
+ slots: legacy.slots.removeDefault().optional(),
15851
+ page: external_exports.strictObject({
15852
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15853
+ entry: moduleEntry,
15854
+ style,
15855
+ title: localized(128, 1).optional()
15856
+ }).optional(),
15857
+ widget: external_exports.strictObject({
15858
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15859
+ entry: moduleEntry,
15860
+ style
15861
+ }).optional(),
15862
+ desktop: external_exports.strictObject({ apiVersion: external_exports.literal(1), script: resourceWithSuffix(".js"), style }).optional(),
15863
+ web: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry.optional(), style }).refine(({ entry, style: style2 }) => entry !== void 0 || style2 !== void 0, "Expected a Web entry or style").optional(),
15864
+ backend: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry }).optional()
15865
+ }).refine(({ page, widget, desktop, web, backend }) => Boolean(page || widget || desktop || web || backend), "Expected at least one page, widget, desktop, web, or backend entry").refine(({ page, widget, web, backend }) => !backend || [page?.entry, widget?.entry, web?.entry].every((entry) => entry === void 0 || hostExtensionCanonicalPath(entry) !== hostExtensionCanonicalPath(backend.entry)), { path: ["backend", "entry"], message: "A backend entry cannot also be a frontend entry" });
15866
+ function targetsForCapabilities({ hasPage, hasWidget, hasDesktop, hasWeb, hasBackend }) {
15867
+ if (hasPage || hasWidget || hasBackend && !hasDesktop && !hasWeb)
15868
+ return ["desktop", "web"];
15869
+ const targets = [];
15870
+ if (hasDesktop)
15871
+ targets.push("desktop");
15872
+ if (hasWeb)
15873
+ targets.push("web");
15874
+ return targets;
15875
+ }
15876
+ var hostExtensionBackendMethodSchema = desktopExtensionBackendMethodSchema;
15877
+
15878
+ // ../../shared-contracts/dist/host-extension-management.js
15879
+ var HOST_EXTENSION_ZIP_MAX_BYTES = DESKTOP_EXTENSION_ZIP_MAX_BYTES;
15880
+ var hostExtensionRevisionSchema = external_exports.int().nonnegative();
15881
+ var hostExtensionConfigurationSchema = external_exports.strictObject({
15882
+ revision: hostExtensionRevisionSchema,
15883
+ enabled: external_exports.array(hostExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs")
15884
+ });
15885
+ var { downloadUrl, ...catalogMetadata } = desktopExtensionCatalogEntrySchema.shape;
15886
+ var hostExtensionCatalogEntrySchema = external_exports.object({
15887
+ ...catalogMetadata,
15888
+ id: hostExtensionIdSchema,
15889
+ format: external_exports.literal("codexhost"),
15890
+ targets: external_exports.array(hostExtensionTargetSchema).min(1).max(2).refine((targets) => new Set(targets).size === targets.length, "Duplicate targets"),
15891
+ apis: external_exports.strictObject({
15892
+ page: external_exports.int().positive().optional(),
15893
+ widget: external_exports.int().positive().optional(),
15894
+ desktop: external_exports.int().positive().optional(),
15895
+ web: external_exports.int().positive().optional(),
15896
+ backend: external_exports.int().positive().optional()
15897
+ }),
15898
+ downloadUrl: downloadUrl.refine((url2) => url2.startsWith("https://"), "Expected HTTPS")
15899
+ }).refine(({ targets, apis }) => {
15900
+ const derived = targetsForCapabilities({
15901
+ hasPage: Boolean(apis.page),
15902
+ hasWidget: Boolean(apis.widget),
15903
+ hasDesktop: Boolean(apis.desktop),
15904
+ hasWeb: Boolean(apis.web),
15905
+ hasBackend: Boolean(apis.backend)
15906
+ });
15907
+ return targets.length === derived.length && derived.every((target2) => targets.includes(target2));
15908
+ }, "Catalog targets must match the declared APIs");
15909
+ var hostExtensionCatalogSchema = external_exports.object({
15910
+ schemaVersion: external_exports.literal(2),
15911
+ generatedAt: external_exports.string().min(1),
15912
+ extensions: external_exports.array(hostExtensionCatalogEntrySchema).max(1e4).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15913
+ });
15914
+ var hostExtensionsCatalogResultSchema = hostExtensionCatalogSchema.extend({
15915
+ catalogUrl: desktopExtensionHttpUrlSchema,
15916
+ fetchedAt: external_exports.iso.datetime(),
15917
+ cached: external_exports.boolean()
15918
+ });
15919
+ var id = { id: hostExtensionIdSchema };
15920
+ var active = {
15921
+ ...id,
15922
+ activationId: hostExtensionActivationIdSchema,
15923
+ digest: hostExtensionDigestSchema
15924
+ };
15925
+ var optionalActivation = { ...id, activationId: active.activationId.optional() };
15926
+ var filePath = external_exports.string().min(1).max(4096).refine((path14) => /^(?:\/|[a-z]:[/\\])/iu.test(path14) && !path14.includes("\0") && !path14.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
15927
+ 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");
15928
+ function base643(maxBytes) {
15929
+ return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
15930
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
15931
+ return value.length % 4 === 0 && value.length * 3 / 4 - padding <= maxBytes && /^[A-Za-z0-9+/]*={0,2}$/u.test(value);
15932
+ }, "Expected bounded standard padded base64");
15933
+ }
15934
+ var hostExtensionGitHubSourceSchema = external_exports.strictObject({
15935
+ type: external_exports.literal("github"),
15936
+ repository: external_exports.string().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),
15937
+ ref: gitRef.optional(),
15938
+ tag: gitRef.optional(),
15939
+ asset: external_exports.string().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),
15940
+ subpath: hostExtensionResourcePathSchema.optional()
15941
+ }).refine(({ ref, tag, asset }) => !ref || !tag && !asset, "Use either a zipball ref or a release tag/asset");
15942
+ var hostExtensionInstallSourceSchema = external_exports.union([
15943
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
15944
+ hostExtensionGitHubSourceSchema,
15945
+ external_exports.strictObject({ type: external_exports.literal("zip"), base64: base643(HOST_EXTENSION_ZIP_MAX_BYTES).min(4) }),
15946
+ external_exports.strictObject({ type: external_exports.literal("zip"), localZipPath: filePath }),
15947
+ external_exports.strictObject({ type: external_exports.literal("localDir"), localDir: filePath })
15948
+ ]);
15949
+ var hostExtensionProvenanceSchema = external_exports.discriminatedUnion("type", [
15950
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
15951
+ hostExtensionGitHubSourceSchema,
15952
+ external_exports.strictObject({ type: external_exports.literal("zip") }),
15953
+ external_exports.strictObject({ type: external_exports.literal("localDir") })
15954
+ ]);
15955
+ var hostExtensionInstallationSchema = external_exports.strictObject({
15956
+ ...active,
15957
+ manifest: hostExtensionManifestV2Schema,
15958
+ installedAt: external_exports.iso.datetime(),
15959
+ source: hostExtensionProvenanceSchema.optional()
15960
+ });
15961
+ var rasterDataUrlSchema = (maxBytes) => external_exports.string().max("data:image/jpeg;base64,".length + 4 * Math.ceil(maxBytes / 3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u);
15962
+ var desktopConflict = { desktopConflictWith: hostExtensionIdSchema.optional() };
15963
+ var backendState = external_exports.enum(["none", "inactive", "starting", "running", "failed"]);
15964
+ var hostExtensionListItemSchema = external_exports.discriminatedUnion("state", [
15965
+ hostExtensionInstallationSchema.extend({
15966
+ state: external_exports.literal("valid"),
15967
+ enabled: external_exports.boolean(),
15968
+ ...desktopConflict,
15969
+ iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
15970
+ screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15971
+ backendState: backendState.optional(),
15972
+ backendError: external_exports.string().optional()
15973
+ }),
15974
+ external_exports.strictObject({
15975
+ state: external_exports.enum(["invalid", "incompatible"]),
15976
+ id: external_exports.string().min(1),
15977
+ enabled: external_exports.boolean(),
15978
+ error: external_exports.string()
15979
+ })
15980
+ ]);
15981
+ var hostExtensionsListResultSchema = external_exports.strictObject({
15982
+ revision: hostExtensionRevisionSchema,
15983
+ configuration: hostExtensionConfigurationSchema,
15984
+ diagnostics: external_exports.array(external_exports.string()),
15985
+ extensions: external_exports.array(hostExtensionListItemSchema)
15986
+ });
15987
+ var hostExtensionRuntimeEntrySchema = hostExtensionInstallationSchema.extend({
15988
+ ...desktopConflict,
15989
+ settingsRevision: hostExtensionRevisionSchema
15990
+ });
15991
+ var hostExtensionsSnapshotResultSchema = external_exports.strictObject({
15992
+ /** The Host publishes this revision in extensions-changed, independent of enabled.json's revision. */
15993
+ revision: hostExtensionRevisionSchema,
15994
+ // Enabled, valid activations only. A Desktop conflict does not hide other capabilities.
15995
+ extensions: external_exports.array(hostExtensionRuntimeEntrySchema).max(DESKTOP_EXTENSION_LIMIT)
15996
+ });
15997
+ var HOST_EXTENSIONS_RPC = {
15998
+ list: "codexhost/extensions/list",
15999
+ snapshot: "codexhost/extensions/snapshot",
16000
+ catalog: "codexhost/extensions/catalog",
16001
+ install: "codexhost/extensions/install",
16002
+ update: "codexhost/extensions/update",
16003
+ enable: "codexhost/extensions/enable",
16004
+ disable: "codexhost/extensions/disable",
16005
+ uninstall: "codexhost/extensions/uninstall",
16006
+ recover: "codexhost/extensions/recover",
16007
+ asset: "codexhost/extensions/asset",
16008
+ settingsGet: "codexhost/extensions/settings/get",
16009
+ settingsSet: "codexhost/extensions/settings/set",
16010
+ backendInvoke: "codexhost/extensions/backend/invoke"
16011
+ };
16012
+ var HOST_EXTENSION_MANAGEMENT_METHODS = Object.freeze(Object.values(HOST_EXTENSIONS_RPC));
16013
+ var methods = new Set(HOST_EXTENSION_MANAGEMENT_METHODS);
16014
+ var noParams = external_exports.strictObject({});
16015
+ var expectedRevision = { expectedRevision: hostExtensionRevisionSchema };
16016
+ var selection = external_exports.strictObject({ ...id, ...expectedRevision });
16017
+ var installationResult = hostExtensionInstallationSchema.extend({ replaced: external_exports.boolean() });
16018
+ var mutationResult = external_exports.discriminatedUnion("state", [
16019
+ external_exports.strictObject({ state: external_exports.literal("saved"), configuration: hostExtensionConfigurationSchema }),
16020
+ external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: hostExtensionRevisionSchema })
16021
+ ]);
16022
+ var hostExtensionsAssetParamsSchema = external_exports.strictObject({
16023
+ ...optionalActivation,
16024
+ digest: active.digest.optional(),
16025
+ path: hostExtensionResourcePathSchema
16026
+ });
16027
+ var hostExtensionsAssetResultSchema = external_exports.strictObject({
16028
+ mimeType: external_exports.string().min(1),
16029
+ base64: base643(DESKTOP_EXTENSION_ASSET_MAX_BYTES),
16030
+ digest: active.digest
16031
+ });
16032
+ var hostExtensionSettingsSchema = external_exports.strictObject({
16033
+ settingsRevision: hostExtensionRevisionSchema,
16034
+ values: jsonObjectSchema
16035
+ });
16036
+ var hostExtensionsRpcSchemas = {
16037
+ [HOST_EXTENSIONS_RPC.list]: { params: noParams, result: hostExtensionsListResultSchema },
16038
+ [HOST_EXTENSIONS_RPC.snapshot]: { params: noParams, result: hostExtensionsSnapshotResultSchema },
16039
+ [HOST_EXTENSIONS_RPC.catalog]: {
16040
+ params: external_exports.strictObject({ forceRefresh: external_exports.boolean().optional() }),
16041
+ result: hostExtensionsCatalogResultSchema
16042
+ },
16043
+ [HOST_EXTENSIONS_RPC.install]: {
16044
+ params: external_exports.strictObject({ source: hostExtensionInstallSourceSchema }),
16045
+ result: installationResult
16046
+ },
16047
+ [HOST_EXTENSIONS_RPC.update]: {
16048
+ params: external_exports.strictObject({
16049
+ ...id,
16050
+ expectedDigest: active.digest,
16051
+ expectedActivationId: active.activationId.optional(),
16052
+ source: hostExtensionInstallSourceSchema.optional()
16053
+ }),
16054
+ result: installationResult
16055
+ },
16056
+ [HOST_EXTENSIONS_RPC.enable]: { params: selection, result: mutationResult },
16057
+ [HOST_EXTENSIONS_RPC.disable]: { params: selection, result: mutationResult },
16058
+ [HOST_EXTENSIONS_RPC.uninstall]: {
16059
+ params: external_exports.strictObject({
16060
+ ...id,
16061
+ removeData: external_exports.boolean().optional(),
16062
+ expectedDigest: active.digest.optional()
16063
+ }),
16064
+ result: external_exports.strictObject({ ...id, removed: external_exports.boolean() })
16065
+ },
16066
+ [HOST_EXTENSIONS_RPC.recover]: {
16067
+ params: external_exports.strictObject({ expectedRevision: expectedRevision.expectedRevision.optional() }),
16068
+ result: mutationResult
16069
+ },
16070
+ [HOST_EXTENSIONS_RPC.asset]: {
16071
+ params: hostExtensionsAssetParamsSchema,
16072
+ result: hostExtensionsAssetResultSchema
16073
+ },
16074
+ [HOST_EXTENSIONS_RPC.settingsGet]: {
16075
+ params: external_exports.strictObject(optionalActivation),
16076
+ result: hostExtensionSettingsSchema
16077
+ },
16078
+ [HOST_EXTENSIONS_RPC.settingsSet]: {
16079
+ params: external_exports.strictObject({
16080
+ ...optionalActivation,
16081
+ expectedSettingsRevision: hostExtensionRevisionSchema,
16082
+ values: jsonObjectSchema
16083
+ }),
16084
+ result: hostExtensionSettingsSchema
16085
+ },
16086
+ [HOST_EXTENSIONS_RPC.backendInvoke]: {
16087
+ params: external_exports.strictObject({
16088
+ ...optionalActivation,
16089
+ method: hostExtensionBackendMethodSchema,
16090
+ params: jsonValueSchema.optional()
16091
+ }),
16092
+ result: external_exports.strictObject({ result: jsonValueSchema })
16093
+ }
16094
+ };
16095
+
15518
16096
  // ../../shared-contracts/dist/thread-archive-confirm.js
16097
+ var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
15519
16098
  var threadArchiveConfirmParamsSchema = external_exports.object({ threadId: hostThreadIdSchema }).strict();
15520
16099
  var threadArchiveConfirmResultSchema = external_exports.object({ confirmed: external_exports.boolean() }).strict();
15521
16100
 
15522
16101
  // ../../shared-contracts/dist/client-channel.js
15523
16102
  var CLIENT_CHANNEL_VERSION = 1;
15524
16103
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
16104
+ var CLIENT_CHANNEL_METHODS = [
16105
+ "codexhost/skills/list",
16106
+ "codexhost/voice/status",
16107
+ "codexhost/voice/transcribe",
16108
+ "codexhost/harness/display-settings/get",
16109
+ "codexhost/harness/display-settings/set",
16110
+ "codexhost/harness/display-settings/capabilities",
16111
+ "codexhost/harness/preferences/get",
16112
+ "codexhost/harness/preferences/patch",
16113
+ "thread/list",
16114
+ "codexhost/thread/catalog/read",
16115
+ "thread/read",
16116
+ "thread/resume",
16117
+ "thread/fork",
16118
+ "thread/turns/list",
16119
+ "thread/revert",
16120
+ "thread/items/list",
16121
+ "thread/start",
16122
+ "thread/name/set",
16123
+ "codexhost/thread/title/generate",
16124
+ "thread/archive",
16125
+ THREAD_ARCHIVE_CONFIRM_METHOD,
16126
+ "thread/unarchive",
16127
+ "turn/start",
16128
+ "turn/interrupt",
16129
+ "turn/steer",
16130
+ "thread/queue/list",
16131
+ "thread/queue/add",
16132
+ "thread/queue/update",
16133
+ "thread/queue/delete",
16134
+ "thread/queue/reorder",
16135
+ "thread/queue/start",
16136
+ "codexhost/thread/queue/send-now",
16137
+ "codexhost/workspace/read",
16138
+ "codexhost/thread/tree/read",
16139
+ "codexhost/thread/pins/list",
16140
+ "codexhost/thread/pins/set",
16141
+ "codexhost/harness/plugins/list",
16142
+ "codexhost/harness/inspect",
16143
+ "codexhost/thread/inspect",
16144
+ "codexhost/thread/usage/inspect",
16145
+ "codexhost/thread/ownership/list",
16146
+ "codexhost/thread/model/select",
16147
+ "codexhost/thread/thinking/select",
16148
+ "codexhost/thread/permission-mode/select",
16149
+ "codexhost/thread/commands/inspect",
16150
+ "codexhost/harness/commands/inspect",
16151
+ "codexhost/thread/command/execute",
16152
+ "codexhost/thread/fork",
16153
+ "codexhost/harness/session-import/sources",
16154
+ "codexhost/harness/session-import/list",
16155
+ "codexhost/harness/session-import/import",
16156
+ // Host settings shared across Desktop and Web.
16157
+ ...HOST_EXTENSION_MANAGEMENT_METHODS,
16158
+ "codexhost/harness/installation",
16159
+ "codexhost/harness/installation/start",
16160
+ "codexhost/harness/installation/status",
16161
+ "codexhost/harness/launch-settings/get",
16162
+ "codexhost/harness/launch-settings/set",
16163
+ "codexhost/harness/web-ui/open",
16164
+ "codexhost/harness/accounts/sources",
16165
+ "codexhost/harness/accounts/list",
16166
+ "codexhost/harness/accounts/inspect",
16167
+ "codexhost/harness/credential-imports",
16168
+ "codexhost/account/list",
16169
+ "codexhost/account/refresh",
16170
+ "codexhost/account/usage/inspect",
16171
+ "codexhost/usage/model-prices/get",
16172
+ "codexhost/usage/model-prices/set",
16173
+ "codexhost/usage/model-prices/default",
16174
+ "codexhost/usage/statistics/get",
16175
+ "codexhost/update/check",
16176
+ "codexhost/update/start",
16177
+ "codexhost/update/status",
16178
+ "codexhost/sessions/loaded/list"
16179
+ ];
15525
16180
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15526
16181
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15527
16182
  var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
@@ -15560,6 +16215,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15560
16215
  cursor: clientChannelCursorSchema,
15561
16216
  revision: external_exports.number().int().nonnegative()
15562
16217
  }),
16218
+ external_exports.object({
16219
+ type: external_exports.literal("extensions-changed"),
16220
+ cursor: clientChannelCursorSchema,
16221
+ revision: hostExtensionRevisionSchema
16222
+ }),
15563
16223
  external_exports.object({
15564
16224
  type: external_exports.literal("hello"),
15565
16225
  version: external_exports.literal(1),
@@ -15735,6 +16395,29 @@ var threadCatalogReadResultSchema = external_exports.object({
15735
16395
  officialCursor: external_exports.object({ live: external_exports.string().nullable(), archived: external_exports.string().nullable().optional() }).strict().optional()
15736
16396
  }).strict();
15737
16397
 
16398
+ // ../../shared-contracts/dist/thread-tree-watch.js
16399
+ var THREAD_TREE_MAX_NODES = 5e3;
16400
+ var threadTreeStatusSchema = external_exports.enum(["running", "waiting", "idle", "unknown"]);
16401
+ var threadTreeNodeSchema = external_exports.strictObject({
16402
+ harnessId: harnessIdSchema,
16403
+ title: external_exports.string().optional(),
16404
+ status: threadTreeStatusSchema,
16405
+ archived: external_exports.boolean()
16406
+ });
16407
+ var threadTreeSnapshotSchema = external_exports.strictObject({
16408
+ revision: external_exports.int().nonnegative(),
16409
+ parents: external_exports.record(hostThreadIdSchema, hostThreadIdSchema),
16410
+ nodes: external_exports.record(hostThreadIdSchema, threadTreeNodeSchema),
16411
+ truncated: external_exports.boolean()
16412
+ }).refine((snapshot) => Object.keys(snapshot.nodes).length <= THREAD_TREE_MAX_NODES, "Too many Thread tree nodes").refine(({ parents, nodes }) => Object.entries(parents).every(([child, parent]) => Object.hasOwn(nodes, child) && Object.hasOwn(nodes, parent)), "Missing Thread tree node");
16413
+ var subscriptionId = external_exports.string().min(1).max(128);
16414
+ var threadTreeWatchParamsSchema = external_exports.strictObject({});
16415
+ var threadTreeUnwatchParamsSchema = external_exports.strictObject({ subscriptionId });
16416
+ var threadTreeUnwatchResultSchema = external_exports.strictObject({});
16417
+ var threadTreeWatchResultSchema = threadTreeUnwatchParamsSchema.extend({
16418
+ snapshot: threadTreeSnapshotSchema
16419
+ });
16420
+
15738
16421
  // ../../shared-contracts/dist/voice.js
15739
16422
  var VOICE_AUDIO_MAX_BYTES = 10 * 1024 * 1024;
15740
16423
  var voiceAudioMimeTypeSchema = external_exports.string().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);
@@ -15973,7 +16656,7 @@ var DEFAULT_IDLE_RELEASE_SETTINGS = Object.freeze({
15973
16656
 
15974
16657
  // ../../shared-contracts/dist/harness-preferences.js
15975
16658
  var harnessPreferenceScopeSchema = external_exports.string().regex(/^external$/u);
15976
- var preferenceHarnessKey = harnessIdSchema.transform((id) => String(id));
16659
+ var preferenceHarnessKey = harnessIdSchema.transform((id2) => String(id2));
15977
16660
  var harnessDefaultConfigurationSchema = external_exports.strictObject({
15978
16661
  model: harnessModelRefSchema.optional(),
15979
16662
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -15983,11 +16666,19 @@ var newThreadDefaultsSchema = external_exports.strictObject({
15983
16666
  lastHarness: harnessIdSchema.optional(),
15984
16667
  byHarness: external_exports.record(preferenceHarnessKey, harnessDefaultConfigurationSchema)
15985
16668
  });
16669
+ var harnessDelegationDefaultSchema = external_exports.strictObject({
16670
+ model: harnessModelRefSchema.optional(),
16671
+ thinkingOptionId: harnessThinkingOptionIdSchema.optional()
16672
+ }).refine((value) => Boolean(value.model || value.thinkingOptionId), "A delegation default must contain a Model or Thinking option");
16673
+ var delegationDefaultsSchema = external_exports.strictObject({
16674
+ byHarness: external_exports.record(preferenceHarnessKey, harnessDelegationDefaultSchema)
16675
+ });
15986
16676
  var modelId = external_exports.string().min(1).max(1024);
15987
16677
  var harnessPreferenceValuesSchema = external_exports.strictObject({
15988
16678
  idleRelease: idleReleaseSettingsSchema.optional(),
15989
16679
  favorites: external_exports.record(preferenceHarnessKey, external_exports.array(modelId).max(2048)).default({}),
15990
- newThread: newThreadDefaultsSchema.optional()
16680
+ newThread: newThreadDefaultsSchema.optional(),
16681
+ delegation: delegationDefaultsSchema.optional()
15991
16682
  });
15992
16683
  var harnessPreferenceSnapshotSchema = external_exports.strictObject({
15993
16684
  scope: harnessPreferenceScopeSchema,
@@ -16015,6 +16706,11 @@ var harnessPreferenceOperationSchema = external_exports.discriminatedUnion("kind
16015
16706
  lastHarness: harnessIdSchema.optional(),
16016
16707
  harnessId: harnessIdSchema.optional(),
16017
16708
  configuration: harnessDefaultConfigurationSchema.optional()
16709
+ }),
16710
+ external_exports.strictObject({
16711
+ kind: external_exports.literal("delegation"),
16712
+ harnessId: harnessIdSchema,
16713
+ configuration: harnessDelegationDefaultSchema.nullable()
16018
16714
  })
16019
16715
  ]);
16020
16716
  var harnessPreferencePatchSchema = external_exports.strictObject({
@@ -16365,13 +17061,6 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
16365
17061
  });
16366
17062
 
16367
17063
  // ../../shared-contracts/dist/harness-accounts.js
16368
- var accountBalanceSnapshotSchema = external_exports.object({
16369
- amount: external_exports.number().finite().nonnegative(),
16370
- /** ISO 4217 code as reported by the Provider, for example `CNY`. */
16371
- currency: external_exports.string().trim().min(1).max(8),
16372
- /** Native label when the Harness exposes several Billing Sources. */
16373
- label: external_exports.string().trim().min(1).max(128).optional()
16374
- }).strict();
16375
17064
  var harnessAccountSnapshotObject = external_exports.object({
16376
17065
  email: external_exports.string().trim().min(1).max(320).optional(),
16377
17066
  label: external_exports.string().trim().min(1).max(256).optional(),
@@ -16405,76 +17094,6 @@ var harnessAccountListResultSchema = external_exports.object({
16405
17094
  accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
16406
17095
  }).strict();
16407
17096
 
16408
- // ../../shared-contracts/dist/harness-plugins.js
16409
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
16410
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
16411
- var HARNESS_PLUGIN_LIMIT = 128;
16412
- var installedHarnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).pipe(harnessIdSchema);
16413
- var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
16414
- var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
16415
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
16416
- var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
16417
- var harnessInstallationGuideSchema = external_exports.object({
16418
- commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
16419
- before: localizedTextSchema.optional(),
16420
- after: localizedTextSchema.optional(),
16421
- downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
16422
- }).strict();
16423
- var pluginPresentationShape = {
16424
- id: installedHarnessPluginIdSchema,
16425
- name: external_exports.string().trim().min(1).max(128),
16426
- version: external_exports.string().min(1).max(128),
16427
- /** Capability-only plugin; omitted for existing session-capable plugins. */
16428
- kind: external_exports.literal("usage").optional(),
16429
- /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
16430
- iconStyle: external_exports.object({
16431
- vector: external_exports.object({
16432
- viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
16433
- color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
16434
- paths: external_exports.array(external_exports.object({
16435
- d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
16436
- fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
16437
- fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
16438
- }).strict()).min(1).max(32)
16439
- }).strict().optional(),
16440
- background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
16441
- borderRadius: external_exports.number().min(0).max(50).optional(),
16442
- paddingRatio: external_exports.number().min(0).max(0.25).optional()
16443
- }).strict().optional(),
16444
- installation: harnessInstallationGuideSchema.optional(),
16445
- notice: localizedTextSchema.optional(),
16446
- /** The factory accepts a persisted local entrypoint through its construction context. */
16447
- launchCommand: external_exports.literal(true).optional(),
16448
- links: external_exports.object({
16449
- website: documentationUrlSchema.optional(),
16450
- documentation: documentationUrlSchema.optional(),
16451
- installation: documentationUrlSchema.optional()
16452
- }).strict().optional()
16453
- };
16454
- var harnessPluginManifestSchema = external_exports.object({
16455
- manifestVersion: external_exports.literal(1),
16456
- ...pluginPresentationShape,
16457
- adapterApiVersion: external_exports.number().int().positive(),
16458
- entry: relativeResourceSchema,
16459
- icon: relativeResourceSchema.optional()
16460
- }).strict();
16461
- var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
16462
- var harnessPluginDescriptorSchema = external_exports.object({
16463
- ...pluginPresentationShape,
16464
- icon: harnessPluginIconSchema.optional()
16465
- }).strict();
16466
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
16467
- var harnessPluginListResultSchema = external_exports.object({
16468
- plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
16469
- }).strict();
16470
- var harnessPluginConfigurationSchema = external_exports.object({
16471
- version: external_exports.literal(1),
16472
- enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
16473
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
16474
- message: "Enabled plugin IDs must be unique",
16475
- path: ["enabled"]
16476
- });
16477
-
16478
17097
  // ../../shared-contracts/dist/harness-route.js
16479
17098
  var harnessPluginRouteSchema = external_exports.object({
16480
17099
  harnessId: harnessPluginIdSchema,
@@ -16915,9 +17534,12 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16915
17534
  ...thread,
16916
17535
  epoch: identity,
16917
17536
  modelId: identity.optional(),
17537
+ serviceTier: harnessModelServiceTierSchema.optional(),
16918
17538
  thinkingOptionId: identity.optional(),
16919
17539
  permissionModeId: identity.optional()
16920
- }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17540
+ }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting").refine((value) => value.serviceTier === void 0 || value.modelId !== void 0, {
17541
+ message: "A service tier requires a Model ID"
17542
+ }),
16921
17543
  external_exports.strictObject({
16922
17544
  kind: external_exports.literal("prompt"),
16923
17545
  ...thread,
@@ -16967,7 +17589,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
16967
17589
  external_exports.strictObject({ action: external_exports.literal("catalog") }),
16968
17590
  external_exports.strictObject({
16969
17591
  action: external_exports.literal("read-thread"),
16970
- hostId: hostId.refine((id) => id !== "local"),
17592
+ hostId: hostId.refine((id2) => id2 !== "local"),
16971
17593
  input: delegationReadParamsSchema
16972
17594
  }),
16973
17595
  external_exports.strictObject({
@@ -16981,7 +17603,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
16981
17603
  external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
16982
17604
  external_exports.strictObject({
16983
17605
  action: external_exports.literal("update"),
16984
- hostId: hostId.refine((id) => id !== "local"),
17606
+ hostId: hostId.refine((id2) => id2 !== "local"),
16985
17607
  version: remoteUpdateParamsSchema.shape.version
16986
17608
  })
16987
17609
  ]);
@@ -17045,7 +17667,7 @@ function invalidRequest(message3) {
17045
17667
  return { code: "invalidRequest", message: message3, retryable: false };
17046
17668
  }
17047
17669
  function validateHostApprovalResponse(interaction, response) {
17048
- return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17670
+ return interaction.actions.some(({ id: id2 }) => id2 === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17049
17671
  }
17050
17672
 
17051
17673
  // ../../harness-adapter/dist/question.js
@@ -17053,7 +17675,7 @@ function invalidRequest2(message3) {
17053
17675
  return { code: "invalidRequest", message: message3, retryable: false };
17054
17676
  }
17055
17677
  function validateHostQuestionResponse(interaction, response) {
17056
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17678
+ const questionIds = new Set(interaction.questions.map(({ id: id2 }) => id2));
17057
17679
  if (response.cancelled) {
17058
17680
  return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17059
17681
  }
@@ -17168,7 +17790,8 @@ var tokenFields = [
17168
17790
  var safeIntegerFields = [
17169
17791
  "planFiveHourResetsAtUnix",
17170
17792
  "planSevenDayResetsAtUnix",
17171
- "timeToFirstOutputMs"
17793
+ "timeToFirstOutputMs",
17794
+ "latestRequestTimeToFirstOutputMs"
17172
17795
  ];
17173
17796
  var percentFields = [
17174
17797
  "cacheHitRatePercent",
@@ -17432,7 +18055,7 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17432
18055
  if (!live)
17433
18056
  return builtIns;
17434
18057
  const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17435
- const ids = new Set(builtIns.commands.map(({ id }) => id));
18058
+ const ids = new Set(builtIns.commands.map(({ id: id2 }) => id2));
17436
18059
  const dynamic = [];
17437
18060
  for (const command of live) {
17438
18061
  const name = command.name.trim().replace(/^\//u, "");
@@ -17441,12 +18064,12 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17441
18064
  if (isExcludedLiveCommand(name, exclusions))
17442
18065
  continue;
17443
18066
  const invocation = `/${name}`;
17444
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17445
- if (invocations.has(invocation) || ids.has(id))
18067
+ const id2 = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
18068
+ if (invocations.has(invocation) || ids.has(id2))
17446
18069
  continue;
17447
18070
  const description = command.description?.trim().slice(0, 512);
17448
18071
  const parsed = harnessCommandDescriptorSchema.safeParse({
17449
- id,
18072
+ id: id2,
17450
18073
  invocation,
17451
18074
  label: name.slice(0, 128),
17452
18075
  ...description ? { description } : {},
@@ -17455,7 +18078,7 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17455
18078
  if (!parsed.success)
17456
18079
  continue;
17457
18080
  invocations.add(invocation);
17458
- ids.add(id);
18081
+ ids.add(id2);
17459
18082
  dynamic.push(parsed.data);
17460
18083
  }
17461
18084
  return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
@@ -19328,8 +19951,8 @@ var RequestResponder = class {
19328
19951
  signal;
19329
19952
  finishRequest;
19330
19953
  didRespond = false;
19331
- constructor(id, sendResult, signal = new AbortController().signal, finishRequest) {
19332
- this.id = id;
19954
+ constructor(id2, sendResult, signal = new AbortController().signal, finishRequest) {
19955
+ this.id = id2;
19333
19956
  this.sendResult = sendResult;
19334
19957
  this.signal = signal;
19335
19958
  this.finishRequest = finishRequest;
@@ -19620,7 +20243,7 @@ var Connection = class {
19620
20243
  return this.sendWireMessage({ jsonrpc: "2.0", method, params });
19621
20244
  }
19622
20245
  prepareRequest(method, params, mapResponse, options = {}) {
19623
- const id = this.nextRequestId++;
20246
+ const id2 = this.nextRequestId++;
19624
20247
  let cancel = () => {
19625
20248
  };
19626
20249
  const response = new Promise((resolve, reject) => {
@@ -19640,7 +20263,7 @@ var Connection = class {
19640
20263
  }
19641
20264
  pendingResponse.cancellationSent = true;
19642
20265
  pendingResponse.cleanup?.();
19643
- void this.sendCancelRequest(id).catch(() => {
20266
+ void this.sendCancelRequest(id2).catch(() => {
19644
20267
  });
19645
20268
  };
19646
20269
  options.cancellationSignal?.addEventListener("abort", cancel, {
@@ -19649,12 +20272,12 @@ var Connection = class {
19649
20272
  pendingResponse.cleanup = () => {
19650
20273
  options.cancellationSignal?.removeEventListener("abort", cancel);
19651
20274
  };
19652
- this.pendingResponses.set(id, pendingResponse);
20275
+ this.pendingResponses.set(id2, pendingResponse);
19653
20276
  });
19654
20277
  response.catch(() => {
19655
20278
  });
19656
20279
  return {
19657
- message: { jsonrpc: "2.0", id, method, params },
20280
+ message: { jsonrpc: "2.0", id: id2, method, params },
19658
20281
  response,
19659
20282
  cancel: () => cancel()
19660
20283
  };
@@ -20291,7 +20914,7 @@ function memoryStreamPair() {
20291
20914
  }
20292
20915
  ];
20293
20916
  }
20294
- var methods = {
20917
+ var methods2 = {
20295
20918
  agent: {
20296
20919
  initialize: AGENT_METHODS.initialize,
20297
20920
  authenticate: AGENT_METHODS.authenticate,
@@ -21739,16 +22362,16 @@ var Diff = class {
21739
22362
  }
21740
22363
  }
21741
22364
  }
21742
- addToPath(path13, added, removed, oldPosInc, options) {
21743
- const last = path13.lastComponent;
22365
+ addToPath(path14, added, removed, oldPosInc, options) {
22366
+ const last = path14.lastComponent;
21744
22367
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
21745
22368
  return {
21746
- oldPos: path13.oldPos + oldPosInc,
22369
+ oldPos: path14.oldPos + oldPosInc,
21747
22370
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
21748
22371
  };
21749
22372
  } else {
21750
22373
  return {
21751
- oldPos: path13.oldPos + oldPosInc,
22374
+ oldPos: path14.oldPos + oldPosInc,
21752
22375
  lastComponent: { count: 1, added, removed, previousComponent: last }
21753
22376
  };
21754
22377
  }
@@ -22646,16 +23269,16 @@ var AntigravityToolTracker = class {
22646
23269
  const diff = record3(value);
22647
23270
  if (diff.type !== "diff")
22648
23271
  return [];
22649
- const path13 = displayPath(text(diff.path), this.options.cwd)?.path;
22650
- if (!path13)
23272
+ const path14 = displayPath(text(diff.path), this.options.cwd)?.path;
23273
+ if (!path14)
22651
23274
  return [];
22652
23275
  const oldText = text(diff.oldText);
22653
23276
  const newText = text(diff.newText);
22654
23277
  const kind = diff.oldText == null ? "add" : diff.newText == null ? "delete" : "update";
22655
- const patch = createTwoFilesPatch(kind === "add" ? "/dev/null" : path13, kind === "delete" ? "/dev/null" : path13, oldText, newText, void 0, void 0, { context: 3 });
23278
+ const patch = createTwoFilesPatch(kind === "add" ? "/dev/null" : path14, kind === "delete" ? "/dev/null" : path14, oldText, newText, void 0, void 0, { context: 3 });
22656
23279
  return [
22657
23280
  {
22658
- path: path13,
23281
+ path: path14,
22659
23282
  kind,
22660
23283
  unifiedDiff: patch.length > limit ? `${patch.slice(0, limit)}
22661
23284
  [diff truncated]
@@ -22724,41 +23347,46 @@ var AntigravityToolTracker = class {
22724
23347
  ]);
22725
23348
  }
22726
23349
  };
22727
- function projectReplayedEventsToTurns(params) {
22728
- const turns = [];
22729
- const usedTurnKeys = new Set(params.knownTurnRefs?.map(({ nativeTurnKey }) => nativeTurnKey));
22730
- let active;
22731
- let userRun = false;
22732
- let textItem;
22733
- let sequence = 0;
22734
- const begin = () => {
22735
- active?.tracker.finishPending({
23350
+ function compactionItemId(stepIndex) {
23351
+ return hostItemIdSchema.parse(`checkpoint-${stepIndex}`);
23352
+ }
23353
+ function compactionOutcome(event) {
23354
+ if (event.status === "succeeded")
23355
+ return succeeded;
23356
+ return {
23357
+ status: "failed",
23358
+ error: {
23359
+ code: "nativeFailure",
23360
+ message: event.error ?? "Antigravity context compaction failed",
23361
+ retryable: false
23362
+ }
23363
+ };
23364
+ }
23365
+ function projectReplayedEventsToTurns(params) {
23366
+ const turns = [];
23367
+ const sessionRef = {
23368
+ harnessId: "antigravity",
23369
+ nativeSessionId: params.nativeSessionId,
23370
+ formatVersion: 1
23371
+ };
23372
+ const turnRef = (nativeTurnKey) => nativeTurnRefSchema.parse({ ...sessionRef, nativeTurnKey });
23373
+ const checkpoint = (checkpointId) => nativeCheckpointRefSchema.parse({ ...sessionRef, checkpointId });
23374
+ let active2;
23375
+ let userRun = false;
23376
+ let textItem;
23377
+ let sequence = 0;
23378
+ let nativeTurnIndex;
23379
+ const begin = (boundary, wakeStep) => {
23380
+ active2?.tracker.finishPending({
22736
23381
  status: "cancelled",
22737
23382
  reason: "No terminal tool status in native history"
22738
23383
  });
22739
- const index = turns.length;
22740
- const turnId = hostTurnIdSchema.parse(`turn-${index}`);
22741
- let nativeTurnKey = params.knownTurnRefs?.[index]?.nativeTurnKey;
22742
- if (nativeTurnKey === void 0) {
22743
- let n = index;
22744
- nativeTurnKey = `turn-${n}`;
22745
- while (usedTurnKeys.has(nativeTurnKey))
22746
- nativeTurnKey = `turn-${++n}`;
22747
- usedTurnKeys.add(nativeTurnKey);
22748
- }
23384
+ const checkpointId = wakeStep !== void 0 ? `wake-${wakeStep}` : boundary === void 0 ? void 0 : `turn-${boundary}`;
23385
+ const nativeTurnKey = checkpointId ?? `replay-${turns.length}`;
23386
+ const turnId = hostTurnIdSchema.parse(nativeTurnKey);
22749
23387
  const turn = {
22750
- nativeTurnRef: nativeTurnRefSchema.parse({
22751
- harnessId: "antigravity",
22752
- nativeSessionId: params.nativeSessionId,
22753
- nativeTurnKey,
22754
- formatVersion: 1
22755
- }),
22756
- checkpoint: nativeCheckpointRefSchema.parse({
22757
- harnessId: "antigravity",
22758
- nativeSessionId: params.nativeSessionId,
22759
- checkpointId: `turn-${index}`,
22760
- formatVersion: 1
22761
- }),
23388
+ nativeTurnRef: turnRef(nativeTurnKey),
23389
+ ...checkpointId !== void 0 ? { checkpoint: checkpoint(checkpointId) } : {},
22762
23390
  input: [],
22763
23391
  items: [],
22764
23392
  outcome: { status: "unknown", reason: "Native history does not include prompt stop reasons" }
@@ -22782,12 +23410,22 @@ function projectReplayedEventsToTurns(params) {
22782
23410
  }
22783
23411
  });
22784
23412
  textItem = void 0;
22785
- active = { turn, tracker };
22786
- return active;
23413
+ nativeTurnIndex = boundary;
23414
+ active2 = { turnId, turn, tracker };
23415
+ return active2;
22787
23416
  };
22788
23417
  for (const event of params.events) {
22789
- if (event.type === "user.text") {
22790
- const { turn } = !active || !userRun ? begin() : active;
23418
+ if (event.type === "history.autonomous") {
23419
+ begin(void 0, event.stepIndex);
23420
+ userRun = false;
23421
+ } else if (event.type === "user.text") {
23422
+ const { turn } = !active2 || !userRun ? begin(event.nativeTurnIndex) : active2;
23423
+ if (event.nativeTurnIndex !== void 0 && event.nativeTurnIndex !== nativeTurnIndex) {
23424
+ nativeTurnIndex = event.nativeTurnIndex;
23425
+ const key = `turn-${nativeTurnIndex}`;
23426
+ turn.nativeTurnRef = turnRef(key);
23427
+ turn.checkpoint = checkpoint(key);
23428
+ }
22791
23429
  const previous = turn.input[0];
22792
23430
  if (previous)
22793
23431
  previous.text += event.text;
@@ -22796,7 +23434,7 @@ function projectReplayedEventsToTurns(params) {
22796
23434
  userRun = true;
22797
23435
  textItem = void 0;
22798
23436
  } else if (event.type === "agent.text" || event.type === "agent.thought") {
22799
- const { turn } = active ?? begin();
23437
+ const { turn, turnId } = active2 ?? begin();
22800
23438
  userRun = false;
22801
23439
  const type = event.type === "agent.text" ? "agentMessage" : "reasoning";
22802
23440
  if (textItem?.item.type === type)
@@ -22805,7 +23443,7 @@ function projectReplayedEventsToTurns(params) {
22805
23443
  textItem = {
22806
23444
  item: {
22807
23445
  type,
22808
- itemId: hostItemIdSchema.parse(`turn-${turns.length - 1}-item-${sequence++}`),
23446
+ itemId: hostItemIdSchema.parse(`${turnId}-item-${sequence++}`),
22809
23447
  text: event.text
22810
23448
  },
22811
23449
  outcome: succeeded
@@ -22813,13 +23451,21 @@ function projectReplayedEventsToTurns(params) {
22813
23451
  turn.items.push(textItem);
22814
23452
  }
22815
23453
  } else if (event.type === "tool.call" || event.type === "tool.update") {
22816
- const { tracker } = active ?? begin();
23454
+ const { tracker } = active2 ?? begin();
22817
23455
  userRun = false;
22818
23456
  textItem = void 0;
22819
23457
  tracker.handleToolEvent(event);
23458
+ } else if (event.type === "history.compaction") {
23459
+ const { turn } = active2 ?? begin();
23460
+ userRun = false;
23461
+ textItem = void 0;
23462
+ turn.items.push({
23463
+ item: { type: "contextCompaction", itemId: compactionItemId(event.stepIndex) },
23464
+ outcome: compactionOutcome(event)
23465
+ });
22820
23466
  }
22821
23467
  }
22822
- active?.tracker.finishPending({
23468
+ active2?.tracker.finishPending({
22823
23469
  status: "cancelled",
22824
23470
  reason: "No terminal tool status in native history"
22825
23471
  });
@@ -22894,7 +23540,9 @@ var AntigravityAcpTransport = class {
22894
23540
  #sessionId = null;
22895
23541
  #sessionHandler = null;
22896
23542
  #active = null;
23543
+ #promptRequestId;
22897
23544
  #callbacks = /* @__PURE__ */ new Set();
23545
+ #acceptedCallbacks = /* @__PURE__ */ new WeakSet();
22898
23546
  #acceptCallbacks = false;
22899
23547
  #promptInterrupted = null;
22900
23548
  #opening = null;
@@ -22954,7 +23602,18 @@ var AntigravityAcpTransport = class {
22954
23602
  strategy: { highWaterMark: Infinity }
22955
23603
  })
22956
23604
  );
23605
+ const writer = stream.writable.getWriter();
23606
+ stream.writable = new WritableStream({
23607
+ write: (message3) => {
23608
+ if ("method" in message3 && message3.method === "session/prompt" && "id" in message3)
23609
+ this.#promptRequestId = message3.id;
23610
+ return writer.write(message3);
23611
+ },
23612
+ close: () => writer.close(),
23613
+ abort: (reason) => writer.abort(reason)
23614
+ });
22957
23615
  const nativeMethods = /* @__PURE__ */ new Set(["session/request_permission", "elicitation/create"]);
23616
+ const extensionPrefix = "_antigravity/";
22958
23617
  stream.readable = stream.readable.pipeThrough(new TransformStream({
22959
23618
  transform: (message3, controller) => {
22960
23619
  if ("method" in message3 && message3.method === "session/update") {
@@ -22962,15 +23621,26 @@ var AntigravityAcpTransport = class {
22962
23621
  this.#update(params.sessionId, params.update);
22963
23622
  return;
22964
23623
  }
22965
- if ("method" in message3 && nativeMethods.has(message3.method))
22966
- message3.method = `_antigravity/${message3.method}`;
23624
+ if ("method" in message3 && typeof message3.method === "string") {
23625
+ const method = message3.method.startsWith(extensionPrefix) ? message3.method.slice(extensionPrefix.length) : message3.method;
23626
+ if (nativeMethods.has(method)) {
23627
+ message3.method = extensionPrefix + method;
23628
+ if (this.#acceptCallbacks && "id" in message3 && typeof message3.params === "object" && message3.params !== null)
23629
+ this.#acceptedCallbacks.add(message3.params);
23630
+ }
23631
+ }
23632
+ if (!("method" in message3) && "id" in message3 && message3.id === this.#promptRequestId && ("result" in message3 || "error" in message3)) {
23633
+ this.#promptRequestId = void 0;
23634
+ this.#acceptCallbacks = false;
23635
+ this.#active?.onResponse?.();
23636
+ }
22967
23637
  controller.enqueue(message3);
22968
23638
  }
22969
23639
  }));
22970
- const onElicitation = (request) => this.#callback("sessionId" in request ? request.sessionId : void 0, (handler) => handler.onElicitation(request), { action: "cancel" });
23640
+ const onElicitation = (request) => this.#callback(request, (handler) => handler.onElicitation(request), { action: "cancel" });
22971
23641
  const client2 = {
22972
23642
  sessionUpdate: ({ sessionId, update }) => this.#update(sessionId, update),
22973
- requestPermission: (request) => this.#callback(request.sessionId, (handler) => handler.onPermission(request), {
23643
+ requestPermission: (request) => this.#callback(request, (handler) => handler.onPermission(request), {
22974
23644
  outcome: { outcome: "cancelled" }
22975
23645
  }),
22976
23646
  unstable_createElicitation: onElicitation,
@@ -23067,6 +23737,7 @@ var AntigravityAcpTransport = class {
23067
23737
  this.#clearCallbacks();
23068
23738
  this.#acceptCallbacks = false;
23069
23739
  this.#active = null;
23740
+ this.#promptRequestId = void 0;
23070
23741
  this.#promptInterrupted = null;
23071
23742
  }
23072
23743
  }
@@ -23076,14 +23747,19 @@ var AntigravityAcpTransport = class {
23076
23747
  this.#clearCallbacks();
23077
23748
  await this.#request(connection.cancel({ sessionId }), "session/cancel");
23078
23749
  }
23079
- async closeSession() {
23750
+ #clearSessionState() {
23080
23751
  const sessionId = this.#sessionId;
23081
23752
  this.#sessionId = null;
23082
23753
  this.#acceptCallbacks = false;
23083
23754
  this.#promptInterrupted?.abort(new AntigravityTransportError("unavailable", "ACP session closed"));
23084
23755
  this.#active = null;
23756
+ this.#promptRequestId = void 0;
23085
23757
  this.#pendingEvents = [];
23086
23758
  this.#clearCallbacks();
23759
+ return sessionId;
23760
+ }
23761
+ async closeSession() {
23762
+ const sessionId = this.#clearSessionState();
23087
23763
  if (sessionId && this.#connection)
23088
23764
  await this.#request(this.#connection.closeSession({ sessionId }), "session/close", this.options.closeTimeoutMs ?? 2e3);
23089
23765
  }
@@ -23094,12 +23770,7 @@ var AntigravityAcpTransport = class {
23094
23770
  return this.#closing = this.#shutdown();
23095
23771
  }
23096
23772
  async #shutdown() {
23097
- try {
23098
- await this.closeSession();
23099
- } catch (error51) {
23100
- this.#stderrRaw = `${this.#stderrRaw}
23101
- ${this.#error(error51).message}`.slice(-32e3);
23102
- }
23773
+ this.#clearSessionState();
23103
23774
  this.#faultSignal.abort(new AntigravityTransportError("unavailable", "Antigravity ACP closed"));
23104
23775
  this.#opening = null;
23105
23776
  this.#sessionHandler = null;
@@ -23139,7 +23810,9 @@ ${this.#error(error51).message}`.slice(-32e3);
23139
23810
  this.#dispatch(event);
23140
23811
  }
23141
23812
  #dispatch(event) {
23142
- if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type)) {
23813
+ if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type) || // The wire request bounds foreground updates; the handler may still
23814
+ // be present to let the SDK finish processing earlier callbacks.
23815
+ this.#promptRequestId === void 0 && !this.#opening) {
23143
23816
  if (this.#sessionHandler)
23144
23817
  this.#sessionHandler(event);
23145
23818
  else
@@ -23147,9 +23820,9 @@ ${this.#error(error51).message}`.slice(-32e3);
23147
23820
  } else
23148
23821
  this.#active?.onEvent(event);
23149
23822
  }
23150
- async #callback(sessionId, invoke, cancelled) {
23151
- const active = this.#active;
23152
- if (!active || !this.#acceptCallbacks || sessionId !== this.#sessionId || this.#closed)
23823
+ async #callback(request, invoke, cancelled) {
23824
+ const active2 = this.#active;
23825
+ if (!active2 || !this.#acceptedCallbacks.delete(request) || !("sessionId" in request) || request.sessionId !== this.#sessionId || this.#closed)
23153
23826
  return cancelled;
23154
23827
  let cancel;
23155
23828
  const cancellation = new Promise((resolve) => {
@@ -23157,12 +23830,13 @@ ${this.#error(error51).message}`.slice(-32e3);
23157
23830
  });
23158
23831
  this.#callbacks.add(cancel);
23159
23832
  try {
23160
- return await Promise.race([invoke(active), cancellation]);
23833
+ return await Promise.race([invoke(active2), cancellation]);
23161
23834
  } finally {
23162
23835
  this.#callbacks.delete(cancel);
23163
23836
  }
23164
23837
  }
23165
23838
  #clearCallbacks() {
23839
+ this.#acceptedCallbacks = /* @__PURE__ */ new WeakSet();
23166
23840
  for (const cancel of this.#callbacks)
23167
23841
  cancel();
23168
23842
  this.#callbacks.clear();
@@ -23298,7 +23972,12 @@ function nanoseconds(fields) {
23298
23972
  const result = seconds * 1000000000n + nanos;
23299
23973
  return result / NANOSECONDS_PER_MS <= MAX_MS ? result : null;
23300
23974
  }
23301
- function stepIndices(fields) {
23975
+ function nativeStepCreatedAtMs(blob) {
23976
+ const fields = blob instanceof Uint8Array && readProtoFields(blob);
23977
+ const timestamp = fields ? nanoseconds(message(fields, 1)) : null;
23978
+ return timestamp === null ? void 0 : Number(timestamp / NANOSECONDS_PER_MS);
23979
+ }
23980
+ function generatorStepIndices(fields) {
23302
23981
  const result = [];
23303
23982
  for (const item of fields.filter((candidate) => candidate.number === 2)) {
23304
23983
  if (item.wire === 0 && typeof item.value === "bigint") {
@@ -23347,11 +24026,14 @@ function requestMetadata(metadata, generator, request) {
23347
24026
  const streamed = nanoseconds(message(chat, 12));
23348
24027
  if (created === null || started === null || completed === null || ttft === null || streamed === null || started < created || completed <= started || streamed <= 0n || !closeTo(started - created, ttft) || !closeTo(completed - started, streamed))
23349
24028
  return facts;
23350
- const startedAtMs = Number(started / NANOSECONDS_PER_MS);
23351
- const completedAtMs = Number(completed / NANOSECONDS_PER_MS);
23352
24029
  return {
23353
24030
  ...facts,
23354
- ...completedAtMs > startedAtMs ? { timing: { startedAtMs, completedAtMs } } : {}
24031
+ timing: {
24032
+ requestStartedAtMs: Number(created / NANOSECONDS_PER_MS),
24033
+ timeToFirstOutputMs: Number(ttft / NANOSECONDS_PER_MS),
24034
+ startedAtMs: Number(started / NANOSECONDS_PER_MS),
24035
+ completedAtMs: Number(completed / NANOSECONDS_PER_MS)
24036
+ }
23355
24037
  };
23356
24038
  }
23357
24039
  async function readAntigravityRequestMetadata(nativeSessionId, home, requests, neededSteps = new Set(requests.keys())) {
@@ -23386,7 +24068,7 @@ async function readAntigravityRequestMetadata(nativeSessionId, home, requests, n
23386
24068
  if (!(generated?.data instanceof Uint8Array))
23387
24069
  continue;
23388
24070
  const fields = readProtoFields(generated.data);
23389
- const indices = fields && stepIndices(fields);
24071
+ const indices = fields && generatorStepIndices(fields);
23390
24072
  if (!fields || !indices)
23391
24073
  continue;
23392
24074
  const plannerSteps = [...new Set(indices.filter((step) => requests.get(step)))];
@@ -23509,7 +24191,7 @@ var AntigravitySessionUsageTracker = class {
23509
24191
  #file;
23510
24192
  #nativeSessionId;
23511
24193
  #home;
23512
- #turnStartedAtMs = 0;
24194
+ #timingTurn = { startedAtMs: 0 };
23513
24195
  #consumed = /* @__PURE__ */ new Map();
23514
24196
  #requests = /* @__PURE__ */ new Map();
23515
24197
  #expectedInitialTurns;
@@ -23522,6 +24204,7 @@ var AntigravitySessionUsageTracker = class {
23522
24204
  #outputTokensPerSecond;
23523
24205
  #complete = true;
23524
24206
  #turnCollectionSteps = /* @__PURE__ */ new Set();
24207
+ #awaitingTiming = /* @__PURE__ */ new Map();
23525
24208
  constructor(options) {
23526
24209
  this.#nativeSessionId = options.nativeSessionId;
23527
24210
  this.#home = options.homedir;
@@ -23557,8 +24240,8 @@ var AntigravitySessionUsageTracker = class {
23557
24240
  }
23558
24241
  return this.currentUsage();
23559
24242
  }
23560
- beginTurn(startedAtMs = Date.now()) {
23561
- this.#turnStartedAtMs = startedAtMs;
24243
+ beginTurn(startedAtMs = Date.now(), turnId) {
24244
+ this.#timingTurn = { startedAtMs, ...turnId && { turnId } };
23562
24245
  this.#turnBase = this.#pending ? addUsage(this.#pending.base, this.#pending.usage) : requestUsage([...this.#requests.values()]);
23563
24246
  this.#turnCollectionSteps.clear();
23564
24247
  this.#turnActive = true;
@@ -23592,7 +24275,7 @@ var AntigravitySessionUsageTracker = class {
23592
24275
  }
23593
24276
  async replayHistoricalRequests(signal) {
23594
24277
  const transcript = await this.#read(signal);
23595
- const requests = this.#consume(transcript, true);
24278
+ const { requests } = this.#consume(transcript, true);
23596
24279
  this.#reconcile();
23597
24280
  return { requests, complete: this.#historyComplete(), usage: this.currentUsage() };
23598
24281
  }
@@ -23607,17 +24290,27 @@ var AntigravitySessionUsageTracker = class {
23607
24290
  const usage = promptUsage(input.promptUsage);
23608
24291
  const hadPending = this.#pending !== void 0;
23609
24292
  const cacheUsage = usage && this.#pending ? addUsage(this.#pending.usage, usage) : usage ?? this.#pending?.usage;
23610
- const requests = this.#consume(transcript, false, cacheUsage, input.completedAtMs !== void 0);
23611
- const single = requests[0];
23612
- const step = [...this.#turnCollectionSteps][0];
23613
- if (!hadPending && !input.hasToolCalls && transcript.metadata === null && single?.reasoningOutputTokens === 0 && usage?.inputTokens !== void 0 && usage.outputTokens !== void 0 && requests.length === 1 && single && step !== void 0 && !transcript.toolCallSteps.has(step) && this.#turnCollectionSteps.size === 1 && transcript.complete && !this.#invalidated && usageMatches(requestUsage([single]), usage, true)) {
23614
- const updated = parseHostUsageRequest({ ...single, ...timing(input) });
23615
- requests[0] = updated;
23616
- this.#requests.set(step, updated);
24293
+ const { requests, timings } = this.#consume(transcript, false, cacheUsage);
24294
+ const [step] = this.#turnCollectionSteps;
24295
+ if (step !== void 0 && this.#turnCollectionSteps.size === 1 && !hadPending && !input.hasToolCalls && !transcript.toolCallSteps.has(step) && transcript.metadata === null && transcript.complete && !this.#invalidated && usage?.inputTokens !== void 0 && usage.outputTokens !== void 0) {
24296
+ const single = this.#requests.get(step);
24297
+ const { startedAtMs, completedAtMs } = timing(input);
24298
+ if (single && single.startedAtMs === void 0 && (single.reasoningOutputTokens ?? usage.reasoningOutputTokens) === 0 && (usage.reasoningOutputTokens ?? 0) === 0 && usageMatches(requestUsage([single]), usage, true) && startedAtMs !== void 0 && completedAtMs !== void 0) {
24299
+ const updated = parseHostUsageRequest({ ...single, startedAtMs, completedAtMs });
24300
+ const index = requests.indexOf(single);
24301
+ if (index !== -1)
24302
+ requests[index] = updated;
24303
+ else if (completedAtMs > startedAtMs && single.outputTokens > 0)
24304
+ timings.push({
24305
+ ...this.#timingIdentity(single, this.#timingTurn),
24306
+ output: { startedAtMs, completedAtMs, outputTokens: single.outputTokens }
24307
+ });
24308
+ this.#requests.set(step, updated);
24309
+ }
23617
24310
  }
23618
24311
  this.#recordTurnOutputSpeed();
23619
24312
  this.#reconcile();
23620
- return { requests, complete: this.#historyComplete(), usage: this.currentUsage() };
24313
+ return { requests, timings, complete: this.#historyComplete(), usage: this.currentUsage() };
23621
24314
  }
23622
24315
  #recordTurnOutputSpeed() {
23623
24316
  let tokens = 0;
@@ -23632,9 +24325,10 @@ var AntigravitySessionUsageTracker = class {
23632
24325
  if (milliseconds > 0)
23633
24326
  this.#outputTokensPerSecond = tokens / (milliseconds / 1e3);
23634
24327
  }
23635
- #consume(transcript, historical, cacheUsage, finalizing = false) {
24328
+ #consume(transcript, historical, cacheUsage) {
23636
24329
  this.#complete = transcript.complete;
23637
24330
  const requests = [];
24331
+ const timings = [];
23638
24332
  const steps = /* @__PURE__ */ new Set([...this.#pending?.steps ?? [], ...this.#turnCollectionSteps]);
23639
24333
  for (const [step, request] of transcript.steps) {
23640
24334
  if (!request)
@@ -23649,8 +24343,14 @@ var AntigravitySessionUsageTracker = class {
23649
24343
  "cachedInputTokens",
23650
24344
  "cacheWriteInputTokens",
23651
24345
  "reasoningOutputTokens"
23652
- ].some((field3) => previous[field3] !== request[field3]))
24346
+ ].some((field3) => previous[field3] !== request[field3])) {
23653
24347
  this.#invalidated = true;
24348
+ this.#awaitingTiming.delete(step);
24349
+ }
24350
+ const recorded = this.#requests.get(step);
24351
+ const turn2 = this.#awaitingTiming.get(step);
24352
+ if (!historical && recorded && turn2)
24353
+ this.#requests.set(step, this.#applyTiming(transcript, step, recorded, timings, turn2, true));
23654
24354
  continue;
23655
24355
  }
23656
24356
  const write = cacheUsage?.cacheWriteInputTokens;
@@ -23673,26 +24373,46 @@ var AntigravitySessionUsageTracker = class {
23673
24373
  this.#complete = false;
23674
24374
  continue;
23675
24375
  }
23676
- const candidate = native?.timing;
23677
- const clock = parsed.reasoningOutputTokens !== void 0 && parsed.reasoningOutputTokens === native?.reasoningOutputTokens && // A thinking-only request has no output inside the visible window to time.
23678
- parsed.reasoningOutputTokens < parsed.outputTokens && !transcript.toolCallSteps.has(step) && candidate && (historical || candidate.startedAtMs >= this.#turnStartedAtMs) && candidate.completedAtMs <= Date.now() ? {
23679
- ...candidate,
23680
- timedOutputTokens: parsed.outputTokens - parsed.reasoningOutputTokens
23681
- } : void 0;
23682
- if (!historical && this.#turnActive && !finalizing && transcript.metadata !== null && !clock && !transcript.toolCallSteps.has(step))
23683
- continue;
23684
- parsed = parseHostUsageRequest({
23685
- ...parsed,
23686
- ...historical ? { historical: true } : {},
23687
- ...clock
23688
- });
24376
+ const turn = historical ? void 0 : this.#timingTurn;
24377
+ if (turn)
24378
+ this.#awaitingTiming.set(step, turn);
24379
+ else
24380
+ parsed.historical = true;
24381
+ const timed = this.#applyTiming(transcript, step, parsed, timings, turn);
23689
24382
  this.#consumed.set(step, request);
23690
- this.#requests.set(step, parsed);
23691
- requests.push(parsed);
23692
- }
23693
- return requests;
24383
+ this.#requests.set(step, timed);
24384
+ requests.push(historical || this.#turnActive ? timed : parsed);
24385
+ }
24386
+ return { requests, timings };
24387
+ }
24388
+ #timingIdentity(request, turn) {
24389
+ return { requestId: request.requestId, ...turn.turnId && { turnId: turn.turnId } };
24390
+ }
24391
+ #applyTiming(transcript, step, request, timings, turn, late = false) {
24392
+ const native = transcript.metadata?.get(step);
24393
+ if (!native?.timing || native.timing.completedAtMs > Date.now())
24394
+ return request;
24395
+ this.#awaitingTiming.delete(step);
24396
+ const { requestStartedAtMs, timeToFirstOutputMs, startedAtMs, completedAtMs } = native.timing;
24397
+ const thought = request.reasoningOutputTokens ?? native.reasoningOutputTokens;
24398
+ if (turn && requestStartedAtMs < turn.startedAtMs || thought !== native.reasoningOutputTokens)
24399
+ return request;
24400
+ const interval = request.startedAtMs === void 0 && thought < request.outputTokens && !transcript.toolCallSteps.has(step) && completedAtMs > startedAtMs ? { startedAtMs, completedAtMs, outputTokens: request.outputTokens - thought } : void 0;
24401
+ const separateOutput = late || !this.#turnActive;
24402
+ if (turn)
24403
+ timings.push({
24404
+ ...this.#timingIdentity(request, turn),
24405
+ requestStartedAtMs,
24406
+ timeToFirstOutputMs,
24407
+ ...separateOutput && interval ? { output: interval } : {}
24408
+ });
24409
+ return parseHostUsageRequest({
24410
+ ...request,
24411
+ reasoningOutputTokens: thought,
24412
+ ...interval ? { startedAtMs, completedAtMs, timedOutputTokens: interval.outputTokens } : {}
24413
+ });
23694
24414
  }
23695
- async #read(signal, withTimings = true) {
24415
+ async #read(signal) {
23696
24416
  signal?.throwIfAborted();
23697
24417
  const stream = createReadStream(this.#file, { encoding: "utf8", signal });
23698
24418
  const lines = createInterface({ input: stream, crlfDelay: Infinity });
@@ -23754,9 +24474,12 @@ var AntigravitySessionUsageTracker = class {
23754
24474
  stream.destroy();
23755
24475
  }
23756
24476
  result.complete &&= [...result.steps.values()].every((request) => request !== null) && [...this.#consumed.keys()].every((step) => result.steps.has(step));
23757
- const unseen = new Set([...result.steps.keys()].filter((step) => !this.#consumed.has(step)));
23758
- if (withTimings && unseen.size > 0)
23759
- result.metadata = await readAntigravityRequestMetadata(this.#nativeSessionId, this.#home, result.steps, unseen);
24477
+ const needed = new Set(this.#awaitingTiming.keys());
24478
+ for (const step of result.steps.keys())
24479
+ if (!this.#consumed.has(step))
24480
+ needed.add(step);
24481
+ if (needed.size > 0)
24482
+ result.metadata = await readAntigravityRequestMetadata(this.#nativeSessionId, this.#home, result.steps, needed);
23760
24483
  signal?.throwIfAborted();
23761
24484
  return result;
23762
24485
  }
@@ -23770,7 +24493,8 @@ var DELEGATION_ENVIRONMENT_KEYS = [
23770
24493
  "CODEXHOST_THREAD_ID"
23771
24494
  ];
23772
24495
  var ANTIGRAVITY_DELEGATION_INSTRUCTIONS = `This Antigravity Session runs inside codexhost.
23773
- When the user requests cross-Harness delegation, use the executable specified by the CODEXHOST_CLI_PATH environment variable through your native shell tool. Start with --help and harness list, then use delegate start and thread send/read/wait/cancel as documented. Use --format compact for results. Keep the inherited CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID environment variables for every call; they identify this Runtime and parent Thread. Never print their values, substitute another executable, or delegate without user authorization. Native Antigravity subagents are separate from cross-Harness delegation.`;
24496
+ When the user requests cross-Harness delegation, use the executable specified by the CODEXHOST_CLI_PATH environment variable through your native shell tool. Use delegate start and thread send/read/wait/cancel as documented. Use --help or harness list when you need to discover commands or targets. Use --format compact for results. Keep the inherited CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID environment variables for every call; they identify this Runtime and parent Thread. Never print their values, substitute another executable, or delegate without user authorization. Native Antigravity subagents are separate from cross-Harness delegation.
24497
+ For an explicit Model, Thinking level, or speed, read harness inspect --help and inspect the target. Pass the exact advertised Model Ref for the requested speed via --model and the Thinking option ID via --thinking. If a requested selection is unavailable, report it and ask before choosing a different one.`;
23774
24498
  function antigravityDelegationInstructions(environment) {
23775
24499
  return DELEGATION_ENVIRONMENT_KEYS.every((key) => environment[key]) ? ANTIGRAVITY_DELEGATION_INSTRUCTIONS : void 0;
23776
24500
  }
@@ -23778,8 +24502,8 @@ function antigravityDelegationInstructions(environment) {
23778
24502
  // dist/fork.js
23779
24503
  import { randomUUID } from "node:crypto";
23780
24504
  import { access as access2, cp, mkdir, open, rm as rm2 } from "node:fs/promises";
23781
- import os3 from "node:os";
23782
- import path9 from "node:path";
24505
+ import os4 from "node:os";
24506
+ import path10 from "node:path";
23783
24507
 
23784
24508
  // dist/native-trajectory-metadata.js
23785
24509
  var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
@@ -23878,19 +24602,83 @@ function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
23878
24602
 
23879
24603
  // dist/native-turn-boundaries.js
23880
24604
  import { access } from "node:fs/promises";
24605
+ import os2 from "node:os";
24606
+ import path8 from "node:path";
24607
+ import { setTimeout as delay } from "node:timers/promises";
24608
+ function nativeConversationDbPath(id2, home = os2.homedir()) {
24609
+ return path8.join(home, ".gemini", "antigravity-cli", "conversations", `${id2}.db`);
24610
+ }
23881
24611
  async function readNativeTurnCount(dbPath) {
24612
+ return withReadSnapshot(dbPath, countInputs);
24613
+ }
24614
+ function countInputs(db) {
24615
+ return Number(db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
24616
+ }
24617
+ function latestInputCreatedAtMs(db) {
24618
+ const columns = db.prepare("PRAGMA table_info(steps)").all();
24619
+ if (!columns.some((column) => column.name === "metadata"))
24620
+ return void 0;
24621
+ const row = db.prepare("SELECT metadata FROM steps WHERE step_type = 14 ORDER BY idx DESC LIMIT 1").get();
24622
+ return nativeStepCreatedAtMs(row?.metadata);
24623
+ }
24624
+ async function withReadSnapshot(dbPath, read) {
23882
24625
  await access(dbPath);
23883
24626
  const { DatabaseSync } = await import("node:sqlite");
23884
24627
  const db = new DatabaseSync(dbPath, { readOnly: true });
23885
24628
  try {
23886
- const row = db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get();
23887
- return Number(row?.n ?? 0);
24629
+ db.exec("BEGIN");
24630
+ return read(db);
23888
24631
  } finally {
23889
24632
  db.close();
23890
24633
  }
23891
24634
  }
24635
+ var COMMIT_BUDGET_MS = 250;
24636
+ var COMMIT_RECHECK_MS = [0, 25, 75, 175, COMMIT_BUDGET_MS];
24637
+ async function observeNativeTurnCount(dbPath, before, submittedAtMs, completedAtMs, retry, signal) {
24638
+ const started = performance.now();
24639
+ for (const at of retry ? COMMIT_RECHECK_MS : [0]) {
24640
+ if (at > 0) {
24641
+ const elapsed = performance.now() - started;
24642
+ if (elapsed >= COMMIT_BUDGET_MS && at < COMMIT_BUDGET_MS)
24643
+ continue;
24644
+ if (elapsed < at)
24645
+ await delay(Math.ceil(at - elapsed), void 0, { signal }).catch(() => void 0);
24646
+ if (signal.aborted)
24647
+ break;
24648
+ }
24649
+ try {
24650
+ const confirmed = await withReadSnapshot(dbPath, (db) => {
24651
+ const count4 = countInputs(db);
24652
+ if (count4 <= (before ?? 0))
24653
+ return null;
24654
+ const createdAtMs = latestInputCreatedAtMs(db);
24655
+ if (createdAtMs !== void 0) {
24656
+ return createdAtMs > submittedAtMs && createdAtMs <= completedAtMs ? count4 : null;
24657
+ }
24658
+ return before !== null && count4 === before + 1 ? count4 : null;
24659
+ });
24660
+ if (confirmed !== null)
24661
+ return confirmed;
24662
+ } catch (error51) {
24663
+ const { code } = nativeHistoryError(error51);
24664
+ if (code !== "sessionBusy" && code !== "sessionNotFound")
24665
+ break;
24666
+ }
24667
+ }
24668
+ return null;
24669
+ }
23892
24670
  function nativeHistoryError(error51) {
23893
- const missing = error51?.code === "ENOENT";
24671
+ const sqlite = error51;
24672
+ if (sqlite?.code === "ERR_SQLITE_ERROR" && sqlite.errcode !== void 0) {
24673
+ const primary = sqlite.errcode & 255;
24674
+ if (primary === 5 || primary === 6)
24675
+ return {
24676
+ code: "sessionBusy",
24677
+ message: "Antigravity native history database is locked; retry shortly",
24678
+ retryable: true
24679
+ };
24680
+ }
24681
+ const missing = sqlite?.code === "ENOENT";
23894
24682
  return {
23895
24683
  code: missing ? "sessionNotFound" : "nativeFailure",
23896
24684
  message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
@@ -23898,10 +24686,298 @@ function nativeHistoryError(error51) {
23898
24686
  };
23899
24687
  }
23900
24688
 
24689
+ // dist/native-replay.js
24690
+ var USER_INPUT = 14;
24691
+ var PLANNER_RESPONSE = 15;
24692
+ var ERROR_MESSAGE = 17;
24693
+ var CHECKPOINT = 23;
24694
+ var SYSTEM_MESSAGE = 101;
24695
+ var GENERIC_TOOL = 132;
24696
+ var DONE = 3;
24697
+ var ERROR = 7;
24698
+ var IN_FLIGHT = /* @__PURE__ */ new Set([1, 2, 8, 9, 11]);
24699
+ function message2(payload) {
24700
+ const fields = payload instanceof Uint8Array ? readProtoFields(payload) : null;
24701
+ if (!fields)
24702
+ throw new Error("Invalid Antigravity history protobuf");
24703
+ return fields;
24704
+ }
24705
+ function messageField(fields, number4) {
24706
+ const field3 = fields.find((entry) => entry.number === number4 && entry.wire === 2);
24707
+ return field3?.value instanceof Uint8Array ? field3.value : void 0;
24708
+ }
24709
+ function nested(fields, number4) {
24710
+ const payload = messageField(fields, number4);
24711
+ return payload ? message2(payload) : [];
24712
+ }
24713
+ function textField(fields, number4) {
24714
+ const bytes = messageField(fields, number4);
24715
+ return bytes ? Buffer.from(bytes).toString("utf8") : "";
24716
+ }
24717
+ function argsValue(raw) {
24718
+ if (!raw)
24719
+ return void 0;
24720
+ try {
24721
+ return JSON.parse(raw);
24722
+ } catch {
24723
+ return raw;
24724
+ }
24725
+ }
24726
+ async function readNativeHistory(sessionId, home) {
24727
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
24728
+ throw new Error("Invalid native Session ID");
24729
+ const { DatabaseSync } = await import("node:sqlite");
24730
+ const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
24731
+ try {
24732
+ db.exec("BEGIN");
24733
+ return decodeNativeHistory(db);
24734
+ } finally {
24735
+ db.close();
24736
+ }
24737
+ }
24738
+ async function readNativeStepWatermark(dbPath) {
24739
+ const { DatabaseSync } = await import("node:sqlite");
24740
+ let db;
24741
+ try {
24742
+ db = new DatabaseSync(dbPath, { readOnly: true });
24743
+ } catch {
24744
+ return -1;
24745
+ }
24746
+ try {
24747
+ db.exec("BEGIN");
24748
+ const row = db.prepare("SELECT MAX(idx) AS max_idx FROM steps").get();
24749
+ return row?.max_idx === null || row?.max_idx === void 0 ? -1 : Number(row.max_idx);
24750
+ } catch {
24751
+ return -1;
24752
+ } finally {
24753
+ db.close();
24754
+ }
24755
+ }
24756
+ function decodeCheckpointEvent(idx, status, step) {
24757
+ if (status !== DONE && status !== ERROR)
24758
+ return void 0;
24759
+ const error51 = status === ERROR ? nested(step, 31) : [];
24760
+ const errorText = textField(error51, 3) || textField(error51, 2) || textField(error51, 1);
24761
+ return {
24762
+ type: "history.compaction",
24763
+ stepIndex: idx,
24764
+ status: status === DONE ? "succeeded" : "failed",
24765
+ ...errorText ? { error: errorText } : {}
24766
+ };
24767
+ }
24768
+ async function readNativeTurnCompactions(dbPath, afterStepIndex) {
24769
+ const { DatabaseSync } = await import("node:sqlite");
24770
+ let db;
24771
+ try {
24772
+ db = new DatabaseSync(dbPath, { readOnly: true });
24773
+ } catch {
24774
+ return [];
24775
+ }
24776
+ try {
24777
+ db.exec("BEGIN");
24778
+ if (db.prepare("PRAGMA user_version").get()?.user_version !== 1)
24779
+ return [];
24780
+ const compactions = [];
24781
+ let turnRun;
24782
+ let seenUserInput = false;
24783
+ const wakeRuns = /* @__PURE__ */ new Set();
24784
+ for (const row of db.prepare(`SELECT idx, step_type, status, step_payload FROM steps
24785
+ WHERE idx > ? AND step_type IN (${USER_INPUT}, ${SYSTEM_MESSAGE}, ${CHECKPOINT})
24786
+ ORDER BY idx`).iterate(afterStepIndex)) {
24787
+ const idx = Number(row.idx);
24788
+ const step = message2(row.step_payload);
24789
+ const stepRun = textField(nested(step, 5), 12);
24790
+ if (row.step_type === USER_INPUT) {
24791
+ seenUserInput = true;
24792
+ turnRun = stepRun;
24793
+ continue;
24794
+ }
24795
+ if (row.step_type === SYSTEM_MESSAGE) {
24796
+ if (stepRun && stepRun !== turnRun)
24797
+ wakeRuns.add(stepRun);
24798
+ continue;
24799
+ }
24800
+ if (!seenUserInput)
24801
+ continue;
24802
+ if (stepRun && wakeRuns.has(stepRun))
24803
+ continue;
24804
+ if (stepRun && turnRun && stepRun !== turnRun)
24805
+ continue;
24806
+ const event = decodeCheckpointEvent(idx, row.status, step);
24807
+ if (event)
24808
+ compactions.push(event);
24809
+ }
24810
+ return compactions;
24811
+ } catch {
24812
+ return [];
24813
+ } finally {
24814
+ db.close();
24815
+ }
24816
+ }
24817
+ function decodeNativeHistory(db) {
24818
+ const events = [];
24819
+ let toolCalls = /* @__PURE__ */ new Map();
24820
+ let turnCount = 0;
24821
+ let run = "";
24822
+ let candidate;
24823
+ let wake;
24824
+ let finalPlanner = false;
24825
+ const endWake = () => {
24826
+ if (wake && !wake.settled)
24827
+ events.length = wake.eventIndex;
24828
+ wake = void 0;
24829
+ candidate = void 0;
24830
+ };
24831
+ const append = (type, text2) => {
24832
+ if (text2)
24833
+ events.push({ type, text: events.at(-1)?.type === type ? `
24834
+
24835
+ ${text2}` : text2 });
24836
+ };
24837
+ if (db.prepare("PRAGMA user_version").get()?.user_version !== 1)
24838
+ throw new Error("Unsupported Antigravity history database version");
24839
+ for (const row of db.prepare(`SELECT idx, step_type, status, step_payload FROM steps
24840
+ WHERE step_type IN (${USER_INPUT}, ${PLANNER_RESPONSE}, ${ERROR_MESSAGE}, ${CHECKPOINT}, ${SYSTEM_MESSAGE}, ${GENERIC_TOOL})
24841
+ ORDER BY idx`).iterate()) {
24842
+ const idx = Number(row.idx);
24843
+ const nativeTurnIndex = row.step_type === USER_INPUT ? turnCount++ : void 0;
24844
+ if (nativeTurnIndex !== void 0) {
24845
+ endWake();
24846
+ finalPlanner = false;
24847
+ }
24848
+ if (IN_FLIGHT.has(Number(row.status))) {
24849
+ if (wake && row.step_type === PLANNER_RESPONSE)
24850
+ wake.settled = false;
24851
+ continue;
24852
+ }
24853
+ const step = message2(row.step_payload);
24854
+ const metadata = nested(step, 5);
24855
+ const stepRun = textField(metadata, 12);
24856
+ if (row.step_type === SYSTEM_MESSAGE) {
24857
+ if (row.status === DONE && (stepRun ? stepRun !== run : finalPlanner)) {
24858
+ if (candidate?.run !== stepRun) {
24859
+ endWake();
24860
+ candidate = { stepIndex: idx, run: stepRun, events: [], calls: /* @__PURE__ */ new Map() };
24861
+ }
24862
+ }
24863
+ continue;
24864
+ }
24865
+ if (row.step_type === CHECKPOINT) {
24866
+ const event = decodeCheckpointEvent(idx, row.status, step);
24867
+ if (!event)
24868
+ continue;
24869
+ const pendingWake = candidate?.run === stepRun ? candidate : void 0;
24870
+ if (!pendingWake && (candidate || stepRun && run && stepRun !== run))
24871
+ continue;
24872
+ (pendingWake?.events ?? events).push(event);
24873
+ continue;
24874
+ }
24875
+ if (row.step_type === USER_INPUT)
24876
+ run = stepRun;
24877
+ const number4 = row.step_type === USER_INPUT ? 19 : row.step_type === PLANNER_RESPONSE ? 20 : 24;
24878
+ const body = row.step_type === GENERIC_TOOL ? nested(step, 140) : message2(messageField(step, number4));
24879
+ switch (row.step_type) {
24880
+ case USER_INPUT: {
24881
+ const items = body.flatMap((field3) => field3.number === 3 && field3.wire === 2 ? [textField(message2(field3.value), 1)] : []);
24882
+ const text2 = items.join("") || textField(body, 2) || textField(body, 1);
24883
+ toolCalls.clear();
24884
+ if (text2 && nativeTurnIndex !== void 0)
24885
+ events.push({ type: "user.text", text: text2, nativeTurnIndex });
24886
+ break;
24887
+ }
24888
+ case PLANNER_RESPONSE: {
24889
+ const thought = textField(body, 3);
24890
+ const text2 = textField(body, 1);
24891
+ const calls = body.filter((field3) => field3.number === 7 && field3.wire === 2);
24892
+ if (candidate && candidate.run === stepRun) {
24893
+ const { stepIndex, events: earlierTools, calls: earlierCalls } = candidate;
24894
+ endWake();
24895
+ wake = { eventIndex: events.length, settled: false };
24896
+ events.push({ type: "history.autonomous", stepIndex });
24897
+ for (const event of earlierTools)
24898
+ events.push(event);
24899
+ toolCalls = earlierCalls;
24900
+ }
24901
+ if (stepRun)
24902
+ run = stepRun;
24903
+ finalPlanner = row.status === DONE && !!text2.trim() && calls.length === 0;
24904
+ if (wake)
24905
+ wake.settled = finalPlanner;
24906
+ append("agent.thought", thought);
24907
+ append("agent.text", text2);
24908
+ for (const field3 of body) {
24909
+ if (field3.number !== 7 || field3.wire !== 2)
24910
+ continue;
24911
+ const call = message2(field3.value);
24912
+ const toolCallId = textField(call, 1);
24913
+ const name = textField(call, 2);
24914
+ if (!toolCallId || !name || toolCalls.get(toolCallId) === "settled")
24915
+ continue;
24916
+ toolCalls.set(toolCallId, "pending");
24917
+ events.push({
24918
+ type: "tool.call",
24919
+ toolCallId,
24920
+ name,
24921
+ args: argsValue(textField(call, 3))
24922
+ });
24923
+ }
24924
+ break;
24925
+ }
24926
+ case ERROR_MESSAGE: {
24927
+ if (candidate?.run === stepRun)
24928
+ break;
24929
+ const warning = textField(nested(body, 3), 2);
24930
+ if (warning)
24931
+ append("agent.text", `⚠ ${warning}`);
24932
+ break;
24933
+ }
24934
+ case GENERIC_TOOL: {
24935
+ const call = nested(metadata, 4);
24936
+ const toolCallId = textField(call, 1);
24937
+ if (!toolCallId)
24938
+ break;
24939
+ const pendingWake = candidate?.run === stepRun ? candidate : void 0;
24940
+ const calls = pendingWake?.calls ?? toolCalls;
24941
+ const target2 = pendingWake?.events ?? events;
24942
+ const state = calls.get(toolCallId);
24943
+ if (state === "settled")
24944
+ break;
24945
+ if (state === void 0) {
24946
+ const name = textField(call, 2);
24947
+ if (row.status !== DONE || !name)
24948
+ break;
24949
+ if (!pendingWake && (candidate || stepRun && run && stepRun !== run))
24950
+ break;
24951
+ target2.push({
24952
+ type: "tool.call",
24953
+ toolCallId,
24954
+ name,
24955
+ args: argsValue(textField(call, 3))
24956
+ });
24957
+ }
24958
+ calls.set(toolCallId, "settled");
24959
+ const error51 = nested(step, 31);
24960
+ const output = textField(nested(body, 2), 1) || textField(error51, 3) || textField(error51, 2) || textField(error51, 1);
24961
+ const status = row.status === DONE ? "completed" : row.status === ERROR ? "failed" : "cancelled";
24962
+ target2.push({
24963
+ type: "tool.update",
24964
+ toolCallId,
24965
+ status,
24966
+ ...output ? { rawOutput: output } : {}
24967
+ });
24968
+ break;
24969
+ }
24970
+ }
24971
+ }
24972
+ endWake();
24973
+ const wakeWatermark = events.findLast((event) => event.type === "history.autonomous")?.stepIndex ?? -1;
24974
+ return { events, turnCount, wakeWatermark };
24975
+ }
24976
+
23901
24977
  // dist/usage-statistics.js
23902
24978
  import { lstat, opendir } from "node:fs/promises";
23903
- import os2 from "node:os";
23904
- import path8 from "node:path";
24979
+ import os3 from "node:os";
24980
+ import path9 from "node:path";
23905
24981
 
23906
24982
  // ../../harness-adapter/dist/usage-statistics.js
23907
24983
  import { createReadStream as createReadStream2 } from "node:fs";
@@ -23980,10 +25056,10 @@ function count3(value) {
23980
25056
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
23981
25057
  }
23982
25058
  function antigravityHome(environment) {
23983
- return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
25059
+ return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os3.homedir();
23984
25060
  }
23985
25061
  function transcriptPath(brainRoot, conversationId) {
23986
- return path8.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
25062
+ return path9.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
23987
25063
  }
23988
25064
  function isMissing(error51) {
23989
25065
  const code = error51?.code;
@@ -23999,8 +25075,8 @@ async function lstatIfPresent(target2) {
23999
25075
  }
24000
25076
  }
24001
25077
  async function transcriptFingerprint(file2) {
24002
- const logs = path8.dirname(file2);
24003
- for (const directory of [path8.dirname(logs), logs]) {
25078
+ const logs = path9.dirname(file2);
25079
+ for (const directory of [path9.dirname(logs), logs]) {
24004
25080
  if (!(await lstatIfPresent(directory))?.isDirectory())
24005
25081
  return null;
24006
25082
  }
@@ -24029,7 +25105,7 @@ async function listTranscripts(brainRoot, signal) {
24029
25105
  return sources;
24030
25106
  }
24031
25107
  async function readAntigravityUsage(file2, signal) {
24032
- const sessionId = path8.basename(path8.resolve(file2, "..", "..", ".."));
25108
+ const sessionId = path9.basename(path9.resolve(file2, "..", "..", ".."));
24033
25109
  const requests = /* @__PURE__ */ new Map();
24034
25110
  for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
24035
25111
  if (record4.type !== "PLANNER_RESPONSE")
@@ -24062,21 +25138,21 @@ function createAntigravityUsageStatistics(environment) {
24062
25138
  return Object.freeze({
24063
25139
  async listSources(signal) {
24064
25140
  const sources = await listTranscripts(brainRoot, signal);
24065
- listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
25141
+ listed = new Map(sources.map(({ id: id2, fingerprint }) => [id2, fingerprint]));
24066
25142
  return sources;
24067
25143
  },
24068
- async readSource(id, signal) {
24069
- const expected = listed.get(id);
25144
+ async readSource(id2, signal) {
25145
+ const expected = listed.get(id2);
24070
25146
  let entries;
24071
25147
  try {
24072
- entries = await readAntigravityUsage(id, signal);
25148
+ entries = await readAntigravityUsage(id2, signal);
24073
25149
  } catch (error51) {
24074
25150
  if (expected !== void 0 && isMissing(error51)) {
24075
25151
  throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
24076
25152
  }
24077
25153
  throw error51;
24078
25154
  }
24079
- if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
25155
+ if (expected !== void 0 && await transcriptFingerprint(id2) !== expected) {
24080
25156
  throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
24081
25157
  }
24082
25158
  return entries;
@@ -24085,23 +25161,24 @@ function createAntigravityUsageStatistics(environment) {
24085
25161
  }
24086
25162
 
24087
25163
  // dist/fork.js
24088
- function nativeConversationDbPath(id, home = os3.homedir()) {
24089
- return path9.join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
24090
- }
24091
- function nativeConversationSummariesDbPath(home = os3.homedir()) {
24092
- return path9.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
25164
+ function nativeConversationSummariesDbPath(home = os4.homedir()) {
25165
+ return path10.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
24093
25166
  }
24094
- function nativeBrainRoot(home = os3.homedir()) {
24095
- return path9.join(home, ".gemini", "antigravity-cli", "brain");
25167
+ function nativeBrainRoot(home = os4.homedir()) {
25168
+ return path10.join(home, ".gemini", "antigravity-cli", "brain");
24096
25169
  }
24097
- function nativeBrainDirPath(id, home = os3.homedir()) {
24098
- return path9.join(nativeBrainRoot(home), id);
25170
+ function nativeBrainDirPath(id2, home = os4.homedir()) {
25171
+ return path10.join(nativeBrainRoot(home), id2);
24099
25172
  }
24100
25173
  function validNativeSessionRef(ref, harnessId2) {
24101
25174
  return nativeSessionRefSchema.safeParse(ref).success && ref.harnessId === harnessId2 && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(ref.nativeSessionId);
24102
25175
  }
24103
- async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os3.homedir()) {
24104
- if (![sourceId, derivedId].every((id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id)))
25176
+ var ForkBoundaryError = class extends Error {
25177
+ };
25178
+ var ActiveForkUnavailable = class extends Error {
25179
+ };
25180
+ async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os4.homedir(), fork) {
25181
+ if (![sourceId, derivedId].every((id2) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id2)))
24105
25182
  throw new Error("Invalid native conversation ID");
24106
25183
  const home = typeof retainedTurnsCountOrHome === "string" ? retainedTurnsCountOrHome : homeOption;
24107
25184
  const retained = typeof retainedTurnsCountOrHome === "number" ? retainedTurnsCountOrHome : void 0;
@@ -24109,18 +25186,44 @@ async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCount
24109
25186
  const targetPath2 = nativeConversationDbPath(derivedId, home);
24110
25187
  await access2(sourcePath);
24111
25188
  const { DatabaseSync, backup } = await import("node:sqlite");
24112
- const source = new DatabaseSync(sourcePath, { readOnly: true });
24113
25189
  let owned = false;
25190
+ let cutoff;
25191
+ const activeTurnIndex = fork?.activeTurnIndex;
24114
25192
  try {
24115
- source.exec("BEGIN");
24116
- const count4 = Number(source.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
24117
- if (retained !== void 0 && (!Number.isSafeInteger(retained) || retained < 0 || retained > count4))
24118
- throw new Error("Invalid retained native Turn count");
24119
- await mkdir(path9.dirname(targetPath2), { recursive: true });
24120
- const reservation = await open(targetPath2, "wx");
24121
- owned = true;
24122
- await reservation.close();
24123
- await backup(source, targetPath2);
25193
+ const source = new DatabaseSync(sourcePath, { readOnly: true });
25194
+ try {
25195
+ source.exec("BEGIN");
25196
+ if (activeTurnIndex !== void 0 && source.prepare("PRAGMA journal_mode").get()?.journal_mode !== "wal")
25197
+ throw new ActiveForkUnavailable("Running Antigravity Session has no WAL snapshot; retry when idle");
25198
+ const count4 = Number(source.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
25199
+ if (activeTurnIndex !== void 0 && count4 <= activeTurnIndex)
25200
+ throw new ActiveForkUnavailable("The running Antigravity Turn has no committed user input yet; retry shortly");
25201
+ if (retained !== void 0 && (!Number.isSafeInteger(retained) || retained < 0 || retained > count4)) {
25202
+ if (fork)
25203
+ throw new ForkBoundaryError();
25204
+ throw new Error("Invalid retained native Turn count");
25205
+ }
25206
+ if (typeof retainedTurnsCountOrHome === "object") {
25207
+ if ("checkpointId" in retainedTurnsCountOrHome) {
25208
+ const boundaries = derivationBoundaries(source);
25209
+ const index = boundaries.findIndex(({ checkpointId }) => checkpointId === retainedTurnsCountOrHome.checkpointId);
25210
+ if (index < 0)
25211
+ throw new ForkBoundaryError();
25212
+ cutoff = boundaries[index + 1]?.idx;
25213
+ } else
25214
+ cutoff = retainedTurnsCountOrHome.cutoff;
25215
+ } else if (retained !== void 0 && retained < count4) {
25216
+ const boundary = source.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
25217
+ cutoff = retained === 0 ? 0 : Number(boundary?.idx);
25218
+ }
25219
+ await mkdir(path10.dirname(targetPath2), { recursive: true });
25220
+ const reservation = await open(targetPath2, "wx");
25221
+ owned = true;
25222
+ await reservation.close();
25223
+ await backup(source, targetPath2);
25224
+ } finally {
25225
+ source.close();
25226
+ }
24124
25227
  const target2 = new DatabaseSync(targetPath2);
24125
25228
  try {
24126
25229
  target2.exec("BEGIN IMMEDIATE");
@@ -24130,35 +25233,72 @@ async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCount
24130
25233
  if (!blob)
24131
25234
  throw new Error("Invalid native trajectory metadata");
24132
25235
  target2.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(blob);
24133
- if (retained !== void 0 && retained < count4) {
24134
- const boundary = target2.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
24135
- const cutoff = retained === 0 ? 0 : Number(boundary?.idx);
24136
- target2.prepare("DELETE FROM steps WHERE idx >= ?").run(cutoff);
24137
- for (const table of [
24138
- "gen_metadata",
24139
- "executor_metadata",
24140
- "parent_references",
24141
- "battle_mode_infos"
24142
- ]) {
24143
- if (target2.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table))
24144
- target2.prepare(`DELETE FROM ${table} WHERE idx >= ?`).run(cutoff);
25236
+ if (cutoff !== void 0) {
25237
+ const cutoffIndex = cutoff;
25238
+ target2.prepare("DELETE FROM steps WHERE idx >= ?").run(cutoffIndex);
25239
+ for (const [table, stepFields] of Object.entries({
25240
+ gen_metadata: [],
25241
+ // CortexStepGeneratorMetadata.step_indices (repeated uint32)
25242
+ executor_metadata: [3],
25243
+ // ExecutorMetadata.last_step_idx
25244
+ parent_references: [2],
25245
+ // CortexTrajectoryReference.step_index in the inherited prefix
25246
+ battle_mode_infos: [3, 4]
25247
+ // BattleModeInfo.start_step_index / end_step_index
25248
+ })) {
25249
+ if (!target2.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table))
25250
+ continue;
25251
+ if (cutoffIndex === 0) {
25252
+ target2.exec(`DELETE FROM ${table}`);
25253
+ continue;
25254
+ }
25255
+ const rows = target2.prepare(`SELECT idx, data FROM ${table} ORDER BY idx`);
25256
+ if (table === "gen_metadata") {
25257
+ let last = -1;
25258
+ for (const { idx, data } of rows.iterate()) {
25259
+ const fields = data instanceof Uint8Array && readProtoFields(data);
25260
+ const indices = fields && generatorStepIndices(fields);
25261
+ if (!indices)
25262
+ throw new Error("Invalid native generator metadata");
25263
+ if (indices.some((step) => step >= cutoffIndex))
25264
+ break;
25265
+ if (indices.length > 0)
25266
+ last = Number(idx);
25267
+ }
25268
+ target2.prepare("DELETE FROM gen_metadata WHERE idx > ?").run(last);
25269
+ continue;
25270
+ }
25271
+ const remove = target2.prepare(`DELETE FROM ${table} WHERE idx = ?`);
25272
+ const move = target2.prepare(`UPDATE ${table} SET idx = ? WHERE idx = ?`);
25273
+ let next = 0;
25274
+ for (const { idx, data } of rows.all()) {
25275
+ const fields = data instanceof Uint8Array && readProtoFields(data);
25276
+ if (!fields)
25277
+ throw new Error(`Invalid native ${table}`);
25278
+ const outsidePrefix = fields.some((field3) => stepFields.includes(field3.number) && typeof field3.value === "bigint" && BigInt.asIntN(32, field3.value) >= BigInt(cutoffIndex));
25279
+ if (outsidePrefix)
25280
+ remove.run(Number(idx));
25281
+ else {
25282
+ if (idx !== next)
25283
+ move.run(next, Number(idx));
25284
+ next++;
25285
+ }
25286
+ }
24145
25287
  }
24146
25288
  }
24147
25289
  target2.exec("COMMIT");
24148
25290
  } finally {
24149
25291
  target2.close();
24150
25292
  }
24151
- await registerDerivedSummary(sourceId, derivedId, home);
25293
+ await registerDerivedSummary(sourceId, derivedId, home, activeTurnIndex !== void 0);
24152
25294
  return true;
24153
25295
  } catch (error51) {
24154
25296
  if (owned)
24155
25297
  await removeDerivedDb(derivedId, home);
24156
25298
  throw error51;
24157
- } finally {
24158
- source.close();
24159
25299
  }
24160
25300
  }
24161
- async function registerDerivedSummary(sourceId, derivedId, home) {
25301
+ async function registerDerivedSummary(sourceId, derivedId, home, liveFork) {
24162
25302
  const summaryPath = nativeConversationSummariesDbPath(home);
24163
25303
  try {
24164
25304
  await access2(summaryPath);
@@ -24173,17 +25313,24 @@ async function registerDerivedSummary(sourceId, derivedId, home) {
24173
25313
  const template = summaries.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?").get(sourceId);
24174
25314
  if (!template)
24175
25315
  return;
25316
+ if (liveFork && "parent_conversation_id" in template && summaries.prepare(`SELECT 1 FROM conversation_summaries
25317
+ WHERE parent_conversation_id = ? AND status IS NOT 'CASCADE_RUN_STATUS_IDLE' LIMIT 1`).get(sourceId))
25318
+ throw new ActiveForkUnavailable("A native Subagent is not idle; retry after it settles");
24176
25319
  const derived = new DatabaseSync(nativeConversationDbPath(derivedId, home), { readOnly: true });
24177
25320
  let row;
24178
25321
  try {
24179
25322
  const metadata = derived.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get()?.data;
24180
25323
  const trajectoryId = derived.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get()?.trajectory_id;
25324
+ const lastInput = derived.prepare(`SELECT idx${"last_user_input_time" in template ? ", metadata" : ""}
25325
+ FROM steps WHERE step_type = 14 ORDER BY idx DESC LIMIT 1`).get();
25326
+ const lastInputMs = nativeStepCreatedAtMs(lastInput?.metadata);
24181
25327
  row = {
24182
25328
  ...template,
24183
25329
  conversation_id: derivedId,
24184
25330
  status: "CASCADE_RUN_STATUS_IDLE",
24185
25331
  step_count: Number(derived.prepare("SELECT count(*) AS n FROM steps").get()?.n),
24186
- last_user_input_step_index: Number(derived.prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = 14").get()?.idx ?? -1),
25332
+ last_user_input_step_index: lastInput?.idx ?? -1,
25333
+ last_user_input_time: lastInputMs === void 0 ? "0001-01-01T00:00:00Z" : new Date(lastInputMs).toISOString(),
24187
25334
  not_fully_idle: 0,
24188
25335
  killed: 0,
24189
25336
  last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
@@ -24198,7 +25345,7 @@ async function registerDerivedSummary(sourceId, derivedId, home) {
24198
25345
  summaries.close();
24199
25346
  }
24200
25347
  }
24201
- async function removeDerivedSummary(id, home) {
25348
+ async function removeDerivedSummary(id2, home) {
24202
25349
  try {
24203
25350
  await access2(nativeConversationSummariesDbPath(home));
24204
25351
  } catch (error51) {
@@ -24209,16 +25356,16 @@ async function removeDerivedSummary(id, home) {
24209
25356
  const { DatabaseSync } = await import("node:sqlite");
24210
25357
  const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
24211
25358
  try {
24212
- db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
25359
+ db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id2);
24213
25360
  } finally {
24214
25361
  db.close();
24215
25362
  }
24216
25363
  }
24217
- async function removeDerivedDb(id, home) {
24218
- const file2 = nativeConversationDbPath(id, home);
25364
+ async function removeDerivedDb(id2, home) {
25365
+ const file2 = nativeConversationDbPath(id2, home);
24219
25366
  await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
24220
25367
  }
24221
- async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedir()) {
25368
+ async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os4.homedir()) {
24222
25369
  try {
24223
25370
  await access2(nativeBrainDirPath(sourceId, home));
24224
25371
  } catch (error51) {
@@ -24230,19 +25377,20 @@ async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedi
24230
25377
  recursive: true,
24231
25378
  errorOnExist: true,
24232
25379
  force: false,
24233
- filter: (source) => path9.basename(source) !== ".system_generated"
25380
+ filter: (source) => path10.basename(source) !== ".system_generated"
24234
25381
  });
24235
25382
  return true;
24236
25383
  }
24237
- async function openDerivedAntigravitySession(options, input, sourceRef, retained) {
25384
+ async function openDerivedAntigravitySession(options, input, sourceRef, retained, fork) {
24238
25385
  const environment = { ...options.adapterEnvironment, ...input.environment };
24239
25386
  const home = antigravityHome(environment);
24240
25387
  const derivedId = randomUUID();
24241
25388
  let cloned = false;
24242
25389
  try {
24243
- await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home);
25390
+ await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home, fork);
24244
25391
  cloned = true;
24245
- await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
25392
+ if (fork?.activeTurnIndex === void 0)
25393
+ await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
24246
25394
  const result = await options.openSession({
24247
25395
  ...input,
24248
25396
  environment,
@@ -24253,6 +25401,10 @@ async function openDerivedAntigravitySession(options, input, sourceRef, retained
24253
25401
  const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24254
25402
  return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
24255
25403
  } catch (error51) {
25404
+ if (error51 instanceof ForkBoundaryError)
25405
+ return checkpointError();
25406
+ if (error51 instanceof ActiveForkUnavailable)
25407
+ return activeForkError(error51.message);
24256
25408
  const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24257
25409
  return {
24258
25410
  ok: false,
@@ -24286,32 +25438,54 @@ async function forkAntigravitySession(options) {
24286
25438
  const checkpoint = nativeCheckpointRefSchema.safeParse(input.checkpoint);
24287
25439
  if (!checkpoint.success || checkpoint.data.harnessId !== harnessId2 || checkpoint.data.nativeSessionId !== input.sourceRef.nativeSessionId)
24288
25440
  return checkpointError();
24289
- if (options.sourceSession?.isActive)
24290
- return {
24291
- ok: false,
24292
- error: {
24293
- code: "sessionBusy",
24294
- message: "Source Session is busy",
24295
- retryable: true
24296
- }
24297
- };
24298
- const match = /^turn-(0|[1-9]\d*)$/u.exec(checkpoint.data.checkpointId);
25441
+ const checkpointId = checkpoint.data.checkpointId;
25442
+ const match = /^(turn|wake)-(0|[1-9]\d*)$/u.exec(checkpointId);
24299
25443
  if (!match)
24300
25444
  return checkpointError();
25445
+ const index = Number(match[2]);
25446
+ if (!Number.isSafeInteger(index + 1))
25447
+ return checkpointError();
25448
+ let activeTurnIndex;
25449
+ if (options.sourceSession?.isActive) {
25450
+ activeTurnIndex = options.sourceSession.activeForkTurnIndex?.(checkpointId, antigravityHome({ ...options.adapterEnvironment, ...input.environment }));
25451
+ if (match[1] !== "turn" || activeTurnIndex === void 0 || index >= activeTurnIndex)
25452
+ return activeForkError("Fork requires a confirmed completed Turn before the running Antigravity Turn and no active Subagents; retry when idle");
25453
+ }
25454
+ return openDerivedAntigravitySession(options, {
25455
+ kind: "resume",
25456
+ nativeRef: input.sourceRef,
25457
+ cwd: input.cwd,
25458
+ ...input.environment ? { environment: input.environment } : {}
25459
+ }, input.sourceRef, { checkpointId }, activeTurnIndex === void 0 ? {} : { activeTurnIndex });
25460
+ }
25461
+ function activeForkError(message3) {
25462
+ return { ok: false, error: { code: "sessionBusy", message: message3, retryable: true } };
25463
+ }
25464
+ async function readDerivationBoundaries(dbPath) {
25465
+ await access2(dbPath);
25466
+ const { DatabaseSync } = await import("node:sqlite");
25467
+ const db = new DatabaseSync(dbPath, { readOnly: true });
24301
25468
  try {
24302
- const count4 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
24303
- const index = Number(match[1]);
24304
- if (!Number.isSafeInteger(index) || index >= count4)
24305
- return checkpointError();
24306
- return openDerivedAntigravitySession(options, {
24307
- kind: "resume",
24308
- nativeRef: input.sourceRef,
24309
- cwd: input.cwd,
24310
- ...input.environment ? { environment: input.environment } : {}
24311
- }, input.sourceRef, index + 1);
24312
- } catch (error51) {
24313
- return { ok: false, error: nativeHistoryError(error51) };
25469
+ db.exec("BEGIN");
25470
+ return derivationBoundaries(db);
25471
+ } finally {
25472
+ db.close();
25473
+ }
25474
+ }
25475
+ function derivationBoundaries(db) {
25476
+ const users = db.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx").all();
25477
+ const boundaries = users.map((row, index) => ({
25478
+ idx: Number(row.idx),
25479
+ checkpointId: `turn-${index}`
25480
+ }));
25481
+ if (db.prepare("SELECT 1 FROM steps WHERE step_type = 101 LIMIT 1").get()) {
25482
+ for (const event of decodeNativeHistory(db).events) {
25483
+ if (event.type === "history.autonomous")
25484
+ boundaries.push({ idx: event.stepIndex, checkpointId: `wake-${event.stepIndex}` });
25485
+ }
25486
+ boundaries.sort((a, b) => a.idx - b.idx);
24314
25487
  }
25488
+ return boundaries;
24315
25489
  }
24316
25490
  function checkpointError() {
24317
25491
  return {
@@ -24337,16 +25511,16 @@ function listedModel(line) {
24337
25511
  const separator = line.indexOf(" ");
24338
25512
  if (separator <= 0)
24339
25513
  return null;
24340
- const id = line.slice(0, separator).trim();
25514
+ const id2 = line.slice(0, separator).trim();
24341
25515
  const label = line.slice(separator + 1).trim();
24342
- if (!id || !label)
25516
+ if (!id2 || !label)
24343
25517
  return null;
24344
- const match = EFFORT_SUFFIX_PATTERN.exec(id);
25518
+ const match = EFFORT_SUFFIX_PATTERN.exec(id2);
24345
25519
  if (!match?.groups) {
24346
- return { rawId: id, rawLabel: label, baseId: id, baseLabel: label, effort: null };
25520
+ return { rawId: id2, rawLabel: label, baseId: id2, baseLabel: label, effort: null };
24347
25521
  }
24348
25522
  return {
24349
- rawId: id,
25523
+ rawId: id2,
24350
25524
  rawLabel: label,
24351
25525
  baseId: match.groups.base,
24352
25526
  baseLabel: label.replace(EFFORT_LABEL_SUFFIX_PATTERN, "").trim() || label,
@@ -24377,7 +25551,7 @@ function parseAntigravityModels(output) {
24377
25551
  }
24378
25552
  const models = [];
24379
25553
  const thinkingOptions = /* @__PURE__ */ new Map();
24380
- for (const [id, { label, efforts, rows }] of grouped) {
25554
+ for (const [id2, { label, efforts, rows }] of grouped) {
24381
25555
  const soleRow = rows.length === 1 ? rows[0] : void 0;
24382
25556
  if (soleRow?.effort && harnessModelRefSchema.safeParse({ id: soleRow.rawId }).success) {
24383
25557
  models.push({
@@ -24395,7 +25569,7 @@ function parseAntigravityModels(output) {
24395
25569
  thinkingOptions.set(effort, { id: effort, label: EFFORT_LABELS.get(effort) });
24396
25570
  }
24397
25571
  models.push({
24398
- ref: harnessModelRefSchema.parse({ id }),
25572
+ ref: harnessModelRefSchema.parse({ id: id2 }),
24399
25573
  label,
24400
25574
  resolvedModelLabel: label,
24401
25575
  ...ordered.length > 0 ? { supportedThinkingOptionIds: ordered } : {}
@@ -24421,15 +25595,15 @@ function antigravityAvailableThinkingOptions(catalog, model2) {
24421
25595
  const supported = catalog.models.find(({ ref }) => ref.id === model2.id)?.supportedThinkingOptionIds;
24422
25596
  if (!supported)
24423
25597
  return void 0;
24424
- const options = supported.flatMap((id) => {
24425
- const option = catalog.thinkingOptions.find((candidate) => candidate.id === id);
25598
+ const options = supported.flatMap((id2) => {
25599
+ const option = catalog.thinkingOptions.find((candidate) => candidate.id === id2);
24426
25600
  return option ? [option] : [];
24427
25601
  });
24428
25602
  return options.length > 0 ? options : void 0;
24429
25603
  }
24430
25604
  function parseAntigravityAcpModelCatalog(availableModels, configOptions = []) {
24431
- const modelOption = configOptions.find(({ id }) => id === "model");
24432
- const thoughtOption = configOptions.find(({ id }) => id === "thought_level");
25605
+ const modelOption = configOptions.find(({ id: id2 }) => id2 === "model");
25606
+ const thoughtOption = configOptions.find(({ id: id2 }) => id2 === "thought_level");
24433
25607
  const thinkingOptions = (thoughtOption?.options ?? []).map(({ value, name }) => ({
24434
25608
  id: harnessThinkingOptionIdSchema.parse(value),
24435
25609
  label: name
@@ -24444,23 +25618,23 @@ function parseAntigravityAcpModelCatalog(availableModels, configOptions = []) {
24444
25618
  ref: { id: modelId2 },
24445
25619
  label: name,
24446
25620
  resolvedModelLabel: name,
24447
- ...modelId2 === currentModelId && thinkingOptions.length > 0 ? { supportedThinkingOptionIds: thinkingOptions.map(({ id }) => id) } : {}
25621
+ ...modelId2 === currentModelId && thinkingOptions.length > 0 ? { supportedThinkingOptionIds: thinkingOptions.map(({ id: id2 }) => id2) } : {}
24448
25622
  })),
24449
25623
  defaultModel: { id: currentModelId },
24450
25624
  thinkingOptions,
24451
- ...thoughtOption && thinkingOptions.some(({ id }) => id === thoughtOption.currentValue) ? { defaultThinkingOptionId: thoughtOption.currentValue } : {}
25625
+ ...thoughtOption && thinkingOptions.some(({ id: id2 }) => id2 === thoughtOption.currentValue) ? { defaultThinkingOptionId: thoughtOption.currentValue } : {}
24452
25626
  });
24453
25627
  }
24454
25628
  function readAcpEffectiveModelState(configOptions, catalog) {
24455
- const model2 = configOptions?.find(({ id }) => id === "model");
24456
- const thought = configOptions?.find(({ id }) => id === "thought_level");
25629
+ const model2 = configOptions?.find(({ id: id2 }) => id2 === "model");
25630
+ const thought = configOptions?.find(({ id: id2 }) => id2 === "thought_level");
24457
25631
  const effectiveModel = model2 ? harnessModelRefSchema.parse({ id: model2.currentValue }) : void 0;
24458
25632
  const resolvedModelLabel = model2?.options.find(({ value }) => value === model2.currentValue)?.name ?? catalog?.models.find(({ ref }) => ref.id === effectiveModel?.id)?.resolvedModelLabel;
24459
25633
  const availableThinkingOptions = thought ? thought.options.map(({ value, name }) => ({
24460
25634
  id: harnessThinkingOptionIdSchema.parse(value),
24461
25635
  label: name
24462
25636
  })) : configOptions !== void 0 ? [] : antigravityAvailableThinkingOptions(catalog, effectiveModel);
24463
- const effectiveThinkingOptionId = thought && availableThinkingOptions?.some(({ id }) => id === thought.currentValue) ? harnessThinkingOptionIdSchema.parse(thought.currentValue) : void 0;
25637
+ const effectiveThinkingOptionId = thought && availableThinkingOptions?.some(({ id: id2 }) => id2 === thought.currentValue) ? harnessThinkingOptionIdSchema.parse(thought.currentValue) : void 0;
24464
25638
  return {
24465
25639
  ...effectiveModel ? { effectiveModel } : {},
24466
25640
  ...resolvedModelLabel ? { resolvedModelLabel } : {},
@@ -24480,127 +25654,86 @@ function splitAntigravityModelAndEffort(rawModelId) {
24480
25654
  return { modelRef: harnessModelRefSchema.parse({ id: rawModelId.trim() }) };
24481
25655
  }
24482
25656
 
24483
- // dist/native-replay.js
24484
- var USER_INPUT = 14;
24485
- var PLANNER_RESPONSE = 15;
24486
- var ERROR_MESSAGE = 17;
24487
- var GENERIC_TOOL = 132;
24488
- var DONE = 3;
24489
- var ERROR = 7;
24490
- var IN_FLIGHT = /* @__PURE__ */ new Set([1, 2, 8, 9, 11]);
24491
- function message2(payload) {
24492
- const fields = payload instanceof Uint8Array ? readProtoFields(payload) : null;
24493
- if (!fields)
24494
- throw new Error("Invalid Antigravity history protobuf");
24495
- return fields;
24496
- }
24497
- function messageField(fields, number4) {
24498
- const field3 = fields.find((entry) => entry.number === number4 && entry.wire === 2);
24499
- return field3?.value instanceof Uint8Array ? field3.value : void 0;
24500
- }
24501
- function nested(fields, number4) {
24502
- const payload = messageField(fields, number4);
24503
- return payload ? message2(payload) : [];
24504
- }
24505
- function textField(fields, number4) {
24506
- const bytes = messageField(fields, number4);
24507
- return bytes ? Buffer.from(bytes).toString("utf8") : "";
24508
- }
24509
- function argsValue(raw) {
24510
- if (!raw)
24511
- return void 0;
24512
- try {
24513
- return JSON.parse(raw);
24514
- } catch {
24515
- return raw;
25657
+ // dist/wake-observer.js
25658
+ var COMMIT_POLL_MS = 100;
25659
+ var COMMIT_WAIT_MS = 1e4;
25660
+ var AntigravityWakeObserver = class {
25661
+ options;
25662
+ #cursor;
25663
+ #deadline = 0;
25664
+ #work;
25665
+ #timer;
25666
+ #closed = false;
25667
+ constructor(options) {
25668
+ this.options = options;
25669
+ this.#cursor = options.cursor;
24516
25670
  }
24517
- }
24518
- async function readNativeHistory(sessionId, home) {
24519
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
24520
- throw new Error("Invalid native Session ID");
24521
- const { DatabaseSync } = await import("node:sqlite");
24522
- const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
24523
- const events = [];
24524
- const pendingCalls = /* @__PURE__ */ new Set();
24525
- let turnCount = 0;
24526
- const append = (type, text2) => {
24527
- if (text2)
24528
- events.push({ type, text: events.at(-1)?.type === type ? `
24529
-
24530
- ${text2}` : text2 });
24531
- };
24532
- try {
24533
- db.exec("BEGIN");
24534
- if (db.prepare("PRAGMA user_version").get()?.user_version !== 1)
24535
- throw new Error("Unsupported Antigravity history database version");
24536
- for (const row of db.prepare(`SELECT step_type, status, step_payload FROM steps
24537
- WHERE step_type IN (${USER_INPUT}, ${PLANNER_RESPONSE}, ${ERROR_MESSAGE}, ${GENERIC_TOOL})
24538
- ORDER BY idx`).iterate()) {
24539
- if (row.step_type === USER_INPUT)
24540
- turnCount++;
24541
- if (IN_FLIGHT.has(Number(row.status)))
24542
- continue;
24543
- const step = message2(row.step_payload);
24544
- const number4 = row.step_type === USER_INPUT ? 19 : row.step_type === PLANNER_RESPONSE ? 20 : row.step_type === ERROR_MESSAGE ? 24 : 140;
24545
- const body = message2(messageField(step, number4));
24546
- switch (row.step_type) {
24547
- case USER_INPUT: {
24548
- const items = body.flatMap((field3) => field3.number === 3 && field3.wire === 2 ? [textField(message2(field3.value), 1)] : []);
24549
- const text2 = items.join("") || textField(body, 2) || textField(body, 1);
24550
- pendingCalls.clear();
24551
- if (text2)
24552
- events.push({ type: "user.text", text: text2 });
24553
- break;
24554
- }
24555
- case PLANNER_RESPONSE: {
24556
- append("agent.thought", textField(body, 3));
24557
- append("agent.text", textField(body, 1));
24558
- for (const field3 of body) {
24559
- if (field3.number !== 7 || field3.wire !== 2)
24560
- continue;
24561
- const call = message2(field3.value);
24562
- const toolCallId = textField(call, 1);
24563
- const name = textField(call, 2);
24564
- if (!toolCallId || !name)
24565
- continue;
24566
- pendingCalls.add(toolCallId);
24567
- events.push({
24568
- type: "tool.call",
24569
- toolCallId,
24570
- name,
24571
- args: argsValue(textField(call, 3))
24572
- });
24573
- }
24574
- break;
24575
- }
24576
- case ERROR_MESSAGE: {
24577
- const warning = textField(nested(body, 3), 2);
24578
- if (warning)
24579
- append("agent.text", `⚠ ${warning}`);
24580
- break;
24581
- }
24582
- case GENERIC_TOOL: {
24583
- const toolCallId = textField(nested(nested(step, 5), 4), 1);
24584
- if (!pendingCalls.delete(toolCallId))
24585
- break;
24586
- const error51 = nested(step, 31);
24587
- const output = textField(nested(body, 2), 1) || textField(error51, 3) || textField(error51, 2) || textField(error51, 1);
24588
- const status = row.status === DONE ? "completed" : row.status === ERROR ? "failed" : "cancelled";
24589
- events.push({
24590
- type: "tool.update",
24591
- toolCallId,
24592
- status,
24593
- ...output ? { rawOutput: output } : {}
24594
- });
24595
- break;
24596
- }
25671
+ get observing() {
25672
+ return this.#work !== void 0 || this.#timer !== void 0;
25673
+ }
25674
+ observe() {
25675
+ if (this.#closed)
25676
+ return;
25677
+ this.#deadline = Date.now() + COMMIT_WAIT_MS;
25678
+ if (!this.observing)
25679
+ void this.#startRead();
25680
+ }
25681
+ /** Probe once before submitting a successor, without waiting on a pending native wake. */
25682
+ async flush() {
25683
+ if (this.#closed || !this.observing)
25684
+ return;
25685
+ if (this.#work)
25686
+ return this.#work;
25687
+ clearTimeout(this.#timer);
25688
+ this.#timer = void 0;
25689
+ return this.#startRead();
25690
+ }
25691
+ #startRead() {
25692
+ return this.#work = this.#read().finally(() => {
25693
+ this.#work = void 0;
25694
+ });
25695
+ }
25696
+ async #read() {
25697
+ try {
25698
+ const { nativeSessionId, home, cwd, outputLimit } = this.options;
25699
+ const { events, wakeWatermark } = await readNativeHistory(nativeSessionId, home);
25700
+ if (this.#closed || !this.options.canPublish())
25701
+ return;
25702
+ if (wakeWatermark <= this.#cursor)
25703
+ return;
25704
+ const turns = projectReplayedEventsToTurns({
25705
+ nativeSessionId,
25706
+ cwd,
25707
+ events,
25708
+ ...outputLimit !== void 0 ? { outputLimit } : {}
25709
+ });
25710
+ for (const turn of turns) {
25711
+ const key = turn.nativeTurnRef.nativeTurnKey;
25712
+ if (!key.startsWith("wake-"))
25713
+ continue;
25714
+ const idx = Number(key.slice(5));
25715
+ if (idx <= this.#cursor)
25716
+ continue;
25717
+ this.options.publish(turn);
25718
+ this.#cursor = idx;
25719
+ }
25720
+ } catch {
25721
+ } finally {
25722
+ if (!this.#closed && Date.now() < this.#deadline) {
25723
+ this.#timer = setTimeout(() => {
25724
+ this.#timer = void 0;
25725
+ void this.#startRead();
25726
+ }, COMMIT_POLL_MS);
25727
+ this.#timer.unref();
24597
25728
  }
24598
25729
  }
24599
- return { events, turnCount };
24600
- } finally {
24601
- db.close();
24602
25730
  }
24603
- }
25731
+ close() {
25732
+ this.#closed = true;
25733
+ clearTimeout(this.#timer);
25734
+ this.#timer = void 0;
25735
+ }
25736
+ };
24604
25737
 
24605
25738
  // dist/permission-modes.js
24606
25739
  var ANTIGRAVITY_ACP_SESSION_MODES = ["default", "accept-edits", "auto", "plan"];
@@ -24877,8 +26010,9 @@ async function rollbackAntigravityLastTurn(options) {
24877
26010
  }
24878
26011
  };
24879
26012
  try {
24880
- const count4 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
24881
- if (count4 === 0)
26013
+ const boundaries = await readDerivationBoundaries(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
26014
+ const last = boundaries.at(-1);
26015
+ if (!last)
24882
26016
  return {
24883
26017
  ok: false,
24884
26018
  error: {
@@ -24895,7 +26029,7 @@ async function rollbackAntigravityLastTurn(options) {
24895
26029
  ...input.model ? { model: input.model } : {},
24896
26030
  ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {},
24897
26031
  ...input.permissionModeId ? { permissionModeId: input.permissionModeId } : {}
24898
- }, input.sourceRef, count4 - 1);
26032
+ }, input.sourceRef, { cutoff: boundaries.length === 1 ? 0 : last.idx });
24899
26033
  } catch (error51) {
24900
26034
  return { ok: false, error: nativeHistoryError(error51) };
24901
26035
  }
@@ -24904,7 +26038,7 @@ async function rollbackAntigravityLastTurn(options) {
24904
26038
  // dist/session-import.js
24905
26039
  import { constants, createReadStream as createReadStream3 } from "node:fs";
24906
26040
  import { access as access3, stat } from "node:fs/promises";
24907
- import path10 from "node:path";
26041
+ import path11 from "node:path";
24908
26042
  import { createInterface as createInterface3 } from "node:readline";
24909
26043
  import { fileURLToPath } from "node:url";
24910
26044
 
@@ -25044,9 +26178,9 @@ function workspacePaths(raw) {
25044
26178
  continue;
25045
26179
  cwd = fileURLToPath(url2);
25046
26180
  }
25047
- if (!path10.isAbsolute(cwd))
26181
+ if (!path11.isAbsolute(cwd))
25048
26182
  continue;
25049
- cwd = path10.resolve(cwd);
26183
+ cwd = path11.resolve(cwd);
25050
26184
  const normalized = `${cwd.replaceAll("\\", "/")}/`;
25051
26185
  if (normalized.includes("/.codexhost/antigravity-history/hooks/"))
25052
26186
  continue;
@@ -25139,11 +26273,11 @@ var AntigravitySessionImport = class {
25139
26273
  }
25140
26274
  async #source(row, signal) {
25141
26275
  signal.throwIfAborted();
25142
- const id = row.conversation_id;
25143
- if (typeof id !== "string" || !SESSION_ID.test(id) || typeof row.parent_conversation_id === "string" && row.parent_conversation_id.length > 0 || typeof row.step_count !== "number" || !Number.isSafeInteger(row.step_count) || row.step_count <= 0 || row.killed !== void 0 && row.killed !== null && row.killed !== 0) {
26276
+ const id2 = row.conversation_id;
26277
+ if (typeof id2 !== "string" || !SESSION_ID.test(id2) || typeof row.parent_conversation_id === "string" && row.parent_conversation_id.length > 0 || typeof row.step_count !== "number" || !Number.isSafeInteger(row.step_count) || row.step_count <= 0 || row.killed !== void 0 && row.killed !== null && row.killed !== 0) {
25144
26278
  return null;
25145
26279
  }
25146
- const file2 = nativeConversationDbPath(id, this.#home);
26280
+ const file2 = nativeConversationDbPath(id2, this.#home);
25147
26281
  try {
25148
26282
  return await readStableFiles([file2], async ([info]) => {
25149
26283
  if (!info?.isFile())
@@ -25158,10 +26292,10 @@ var AntigravitySessionImport = class {
25158
26292
  }
25159
26293
  if (!cwd)
25160
26294
  return null;
25161
- const title = sessionImportTitle(row.title) ?? sessionImportTitle(row.preview) ?? await firstUserTitle(path10.join(nativeBrainDirPath(id, this.#home), ".system_generated", "logs", "transcript.jsonl"), signal);
26295
+ const title = sessionImportTitle(row.title) ?? sessionImportTitle(row.preview) ?? await firstUserTitle(path11.join(nativeBrainDirPath(id2, this.#home), ".system_generated", "logs", "transcript.jsonl"), signal);
25162
26296
  signal.throwIfAborted();
25163
26297
  const candidate = sessionImportCandidate({
25164
- nativeSessionId: id,
26298
+ nativeSessionId: id2,
25165
26299
  cwd,
25166
26300
  title,
25167
26301
  updatedAt: row.last_modified_time,
@@ -25171,7 +26305,7 @@ var AntigravitySessionImport = class {
25171
26305
  candidate,
25172
26306
  nativeRef: nativeSessionRefSchema.parse({
25173
26307
  harnessId: "antigravity",
25174
- nativeSessionId: id,
26308
+ nativeSessionId: id2,
25175
26309
  formatVersion: 1
25176
26310
  })
25177
26311
  } : null;
@@ -25187,7 +26321,7 @@ var AntigravitySessionImport = class {
25187
26321
 
25188
26322
  // dist/subagent-transcript.js
25189
26323
  import { open as open2, realpath } from "node:fs/promises";
25190
- import path11 from "node:path";
26324
+ import path12 from "node:path";
25191
26325
  var nativeSubagentIdSchema = external_exports.uuid();
25192
26326
  var MAX_TRANSCRIPT_BYTES = 8 * 1024 * 1024;
25193
26327
  var transcriptStepSchema = external_exports.object({
@@ -25318,10 +26452,10 @@ async function readSubagentTranscript(input) {
25318
26452
  };
25319
26453
  }
25320
26454
  try {
25321
- const file2 = path11.join(nativeBrainDirPath(input.childId, input.home), ".system_generated", "logs", "transcript.jsonl");
25322
- const brainRoot = await realpath(path11.dirname(nativeBrainDirPath(input.childId, input.home)));
26455
+ const file2 = path12.join(nativeBrainDirPath(input.childId, input.home), ".system_generated", "logs", "transcript.jsonl");
26456
+ const brainRoot = await realpath(path12.dirname(nativeBrainDirPath(input.childId, input.home)));
25323
26457
  const resolved = await realpath(file2);
25324
- const expected = path11.join(brainRoot, input.childId, ".system_generated", "logs", "transcript.jsonl");
26458
+ const expected = path12.join(brainRoot, input.childId, ".system_generated", "logs", "transcript.jsonl");
25325
26459
  const normalize = (value) => process.platform === "win32" ? value.toLowerCase() : value;
25326
26460
  if (normalize(resolved) !== normalize(expected))
25327
26461
  throw new Error("Subagent log redirects outside its native location");
@@ -25392,24 +26526,24 @@ var AntigravitySubagents = class {
25392
26526
  get running() {
25393
26527
  return [...this.#states.values()].some((state) => state.status === "running" || state.status === "pending");
25394
26528
  }
25395
- state(id) {
25396
- return this.#states.get(id);
26529
+ state(id2) {
26530
+ return this.#states.get(id2);
25397
26531
  }
25398
- track(id, snapshot) {
25399
- if (this.#stopped || !nativeSubagentIdSchema.safeParse(id).success)
26532
+ track(id2, snapshot) {
26533
+ if (this.#stopped || !nativeSubagentIdSchema.safeParse(id2).success)
25400
26534
  return;
25401
26535
  const item = snapshot.item;
25402
- const child = item.type === "subagentDelegation" ? item.subagents.find((state) => state.nativeSubagentId === id) : void 0;
25403
- this.#states.set(id, {
25404
- subagentId: id,
25405
- nativeSubagentId: id,
26536
+ const child = item.type === "subagentDelegation" ? item.subagents.find((state) => state.nativeSubagentId === id2) : void 0;
26537
+ this.#states.set(id2, {
26538
+ subagentId: id2,
26539
+ nativeSubagentId: id2,
25406
26540
  description: "Antigravity Subagent",
25407
26541
  background: true,
25408
- ...this.#states.get(id),
26542
+ ...this.#states.get(id2),
25409
26543
  ...child,
25410
26544
  status: "running"
25411
26545
  });
25412
- this.#unavailableSince.delete(id);
26546
+ this.#unavailableSince.delete(id2);
25413
26547
  if (!this.#timer) {
25414
26548
  this.#timer = setInterval(() => {
25415
26549
  void this.refresh();
@@ -25429,21 +26563,21 @@ var AntigravitySubagents = class {
25429
26563
  }
25430
26564
  });
25431
26565
  }
25432
- #publish(id, state) {
25433
- this.#states.set(id, state);
26566
+ #publish(id2, state) {
26567
+ this.#states.set(id2, state);
25434
26568
  this.options.emit({
25435
26569
  type: "subagent.state.changed",
25436
- nativeSubagentId: id,
26570
+ nativeSubagentId: id2,
25437
26571
  status: state.status,
25438
26572
  ...state.resultSummary ? { resultSummary: state.resultSummary } : {}
25439
26573
  });
25440
26574
  }
25441
- #expireUnavailable(id, previous) {
25442
- const since = this.#unavailableSince.get(id) ?? Date.now();
25443
- this.#unavailableSince.set(id, since);
26575
+ #expireUnavailable(id2, previous) {
26576
+ const since = this.#unavailableSince.get(id2) ?? Date.now();
26577
+ this.#unavailableSince.set(id2, since);
25444
26578
  if (Date.now() - since < (this.options.observationTimeoutMs ?? 3e4))
25445
26579
  return false;
25446
- this.#publish(id, {
26580
+ this.#publish(id2, {
25447
26581
  ...previous,
25448
26582
  status: "interrupted",
25449
26583
  resultSummary: "Native Subagent status could not be confirmed"
@@ -25452,24 +26586,24 @@ var AntigravitySubagents = class {
25452
26586
  }
25453
26587
  async #read() {
25454
26588
  const parentId = this.options.parentId();
25455
- for (const [id, previous] of this.#states) {
26589
+ for (const [id2, previous] of this.#states) {
25456
26590
  if (this.#stopped)
25457
26591
  return;
25458
26592
  if (previous.status !== "running" && previous.status !== "pending")
25459
26593
  continue;
25460
- const observed = parentId ? await readNativeSubagentState(this.options.home, parentId, id) : { ownership: "unavailable" };
26594
+ const observed = parentId ? await readNativeSubagentState(this.options.home, parentId, id2) : { ownership: "unavailable" };
25461
26595
  if (this.#stopped)
25462
26596
  return;
25463
- if (this.#states.get(id) !== previous)
26597
+ if (this.#states.get(id2) !== previous)
25464
26598
  continue;
25465
26599
  if (observed.ownership === "foreign") {
25466
26600
  const state = { ...previous, status: "interrupted" };
25467
26601
  delete state.resultSummary;
25468
- this.#publish(id, state);
26602
+ this.#publish(id2, state);
25469
26603
  continue;
25470
26604
  }
25471
26605
  if (observed.ownership !== "matched" || observed.status === null) {
25472
- const expired = this.#expireUnavailable(id, previous);
26606
+ const expired = this.#expireUnavailable(id2, previous);
25473
26607
  if (observed.ownership !== "matched" || expired)
25474
26608
  continue;
25475
26609
  }
@@ -25477,7 +26611,7 @@ var AntigravitySubagents = class {
25477
26611
  continue;
25478
26612
  const transcript = await readSubagentTranscript({
25479
26613
  parentId,
25480
- childId: id,
26614
+ childId: id2,
25481
26615
  status: observed.status ?? previous.status,
25482
26616
  cwd: this.options.cwd,
25483
26617
  outputLimit: this.options.outputLimit,
@@ -25485,26 +26619,26 @@ var AntigravitySubagents = class {
25485
26619
  });
25486
26620
  if (this.#stopped)
25487
26621
  return;
25488
- if (this.#states.get(id) !== previous)
26622
+ if (this.#states.get(id2) !== previous)
25489
26623
  continue;
25490
26624
  if (observed.status === "running")
25491
- this.#unavailableSince.delete(id);
25492
- else if (!transcript.ok && this.#expireUnavailable(id, previous))
26625
+ this.#unavailableSince.delete(id2);
26626
+ else if (!transcript.ok && this.#expireUnavailable(id2, previous))
25493
26627
  continue;
25494
26628
  if (transcript.ok && observed.status !== null)
25495
- this.#unavailableSince.delete(id);
26629
+ this.#unavailableSince.delete(id2);
25496
26630
  let status = transcript.ok ? observed.status ?? previous.status : previous.status;
25497
26631
  if (status === "completed" && transcript.ok && transcript.value.turns.at(-1)?.outcome.status === "failed")
25498
26632
  status = "failed";
25499
26633
  const last = transcript.ok ? transcript.value.turns.at(-1)?.items.findLast(({ item }) => item.type === "agentMessage")?.item : void 0;
25500
26634
  const resultSummary = last?.type === "agentMessage" ? last.text.slice(0, 2e3) : previous.resultSummary;
25501
26635
  if (status !== previous.status || resultSummary !== previous.resultSummary)
25502
- this.#publish(id, { ...previous, status, ...resultSummary ? { resultSummary } : {} });
26636
+ this.#publish(id2, { ...previous, status, ...resultSummary ? { resultSummary } : {} });
25503
26637
  if (transcript.ok) {
25504
26638
  const content = JSON.stringify(transcript.value);
25505
- if (content !== this.#transcripts.get(id)) {
25506
- this.#transcripts.set(id, content);
25507
- this.options.emit({ type: "subagent.transcript.changed", nativeSubagentId: id });
26639
+ if (content !== this.#transcripts.get(id2)) {
26640
+ this.#transcripts.set(id2, content);
26641
+ this.options.emit({ type: "subagent.transcript.changed", nativeSubagentId: id2 });
25508
26642
  }
25509
26643
  }
25510
26644
  }
@@ -25532,7 +26666,7 @@ var antigravitySessionCapabilities = {
25532
26666
  },
25533
26667
  history: { fork: true, forkAcrossCwd: true, rollbackLastTurn: true },
25534
26668
  subagents: { observe: true, readTranscript: true },
25535
- autonomousTurns: { observe: false }
26669
+ autonomousTurns: { observe: true }
25536
26670
  };
25537
26671
  function ok(value) {
25538
26672
  return { ok: true, value };
@@ -25654,16 +26788,23 @@ var AntigravitySession = class {
25654
26788
  #configOptions = [];
25655
26789
  #catalog;
25656
26790
  #commands = ANTIGRAVITY_COMMAND_CATALOG;
25657
- #turnCount = 0;
26791
+ // Null means a raw count increase alone cannot identify the next prompt.
26792
+ #confirmedCount = null;
26793
+ #confirmedCheckpoints = /* @__PURE__ */ new Set();
25658
26794
  #active;
26795
+ #wakes;
26796
+ #postPromptWake = false;
25659
26797
  #pending = /* @__PURE__ */ new Map();
25660
26798
  #usage;
25661
- #usageWork = Promise.resolve();
26799
+ #usageWork;
26800
+ #usageDirty = false;
26801
+ #usageRetry;
26802
+ #usageTurnId;
25662
26803
  #abort = new AbortController();
25663
26804
  #closed = false;
25664
26805
  #faulted = false;
25665
26806
  #closing;
25666
- #configuring = false;
26807
+ #configurationQueue;
25667
26808
  #historyOperation = false;
25668
26809
  constructor(options) {
25669
26810
  this.#options = options;
@@ -25693,13 +26834,17 @@ var AntigravitySession = class {
25693
26834
  return this.#state.nativeRef;
25694
26835
  }
25695
26836
  get isActive() {
25696
- return !!this.#active || !!this.#opening || this.#configuring || this.#subagents.running;
26837
+ return !!this.#active || !!this.#opening || !!this.#configurationQueue || this.#subagents.running;
25697
26838
  }
25698
26839
  hasBackgroundWork() {
25699
- return this.#subagents.running;
26840
+ return this.#subagents.running || !!this.#wakes?.observing;
26841
+ }
26842
+ activeForkTurnIndex(checkpointId, home) {
26843
+ if (this.#active?.promptPhase === "submitted" && this.#confirmedCount !== null && !this.#opening && !this.#configurationQueue && !this.#subagents.running && !this.#historyOperation && !this.#closed && !this.#faulted && home === antigravityHome(this.#options.environment) && this.#confirmedCheckpoints.has(checkpointId))
26844
+ return this.#confirmedCount;
25700
26845
  }
25701
26846
  reserveHistoryOperation() {
25702
- if (this.isActive || this.#historyOperation || this.#closed || this.#faulted)
26847
+ if (this.isActive || this.#wakes?.observing || this.#historyOperation || this.#closed || this.#faulted)
25703
26848
  return null;
25704
26849
  this.#historyOperation = true;
25705
26850
  return () => {
@@ -25768,8 +26913,25 @@ var AntigravitySession = class {
25768
26913
  if (!validNativeSessionRef({ harnessId, nativeSessionId: opened.sessionId, formatVersion: 1 }, harnessId))
25769
26914
  throw new AntigravityTransportError("protocolError", "Antigravity returned an invalid native Session ID");
25770
26915
  this.#applyOpened(opened, skip);
25771
- this.#turnCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment))).catch(() => this.#turnCount);
26916
+ if (!this.#wakes) {
26917
+ this.#confirmedCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment))).catch((error51) => !ref && error51.code === "ENOENT" ? 0 : null);
26918
+ }
25772
26919
  this.#initializeUsage(opened.sessionId);
26920
+ if (!this.#wakes) {
26921
+ const home = antigravityHome(this.#options.environment);
26922
+ const cursor = ref ? await readNativeHistory(opened.sessionId, home).then((value) => value.wakeWatermark, () => -1) : -1;
26923
+ if (this.#closed || this.#faulted)
26924
+ return;
26925
+ this.#wakes = new AntigravityWakeObserver({
26926
+ nativeSessionId: opened.sessionId,
26927
+ cwd: this.#options.cwd,
26928
+ home,
26929
+ cursor,
26930
+ outputLimit: this.#options.adapter.toolOutputLimit,
26931
+ canPublish: () => this.#active?.promptPhase !== "returned",
26932
+ publish: (snapshot) => this.#emit({ type: "turn.autonomous.completed", snapshot })
26933
+ });
26934
+ }
25773
26935
  transport.setSessionEventHandler((event) => {
25774
26936
  if (this.#transport === transport && !this.#closed && !this.#faulted)
25775
26937
  this.#sessionEvent(event);
@@ -25777,13 +26939,12 @@ var AntigravitySession = class {
25777
26939
  if (this.#requested.model) {
25778
26940
  const applied = await this.#setModelConfig(this.#requested.model.id, this.#requested.thinkingOptionId);
25779
26941
  if (!applied.bakedInThinking) {
25780
- if (this.#requested.thinkingOptionId) {
25781
- await this.#setConfig("thinking", this.#requested.thinkingOptionId);
25782
- } else if (applied.impliedThinking && this.#hasConfigChoice("thinking", applied.impliedThinking)) {
25783
- await this.#setConfig("thinking", applied.impliedThinking);
26942
+ const desiredThinking = this.#resolveThinkingChoice(this.#requested.thinkingOptionId ?? applied.impliedThinking);
26943
+ if (desiredThinking) {
26944
+ await this.#setConfig("thinking", desiredThinking);
25784
26945
  }
25785
26946
  }
25786
- } else if (this.#requested.thinkingOptionId) {
26947
+ } else if (this.#requested.thinkingOptionId && this.#hasConfigChoice("thinking", this.#requested.thinkingOptionId)) {
25787
26948
  await this.#setConfig("thinking", this.#requested.thinkingOptionId);
25788
26949
  }
25789
26950
  if (!skip && this.#requested.permissionModeId) {
@@ -25791,7 +26952,8 @@ var AntigravitySession = class {
25791
26952
  this.#state.effectivePermissionModeId = this.#requested.permissionModeId;
25792
26953
  this.#setLocatorPermissionMode(this.#requested.permissionModeId);
25793
26954
  }
25794
- this.#publishState();
26955
+ if (!this.#configurationQueue)
26956
+ this.#publishState();
25795
26957
  } catch (error51) {
25796
26958
  await transport.close().catch(() => void 0);
25797
26959
  if (this.#transport === transport)
@@ -25805,9 +26967,9 @@ var AntigravitySession = class {
25805
26967
  this.#usage = new AntigravitySessionUsageTracker({
25806
26968
  nativeSessionId,
25807
26969
  homedir: antigravityHome(this.#options.environment),
25808
- expectedInitialTurns: this.#turnCount
26970
+ expectedInitialTurns: this.#confirmedCount ?? 0
25809
26971
  });
25810
- this.#usageWork = this.#replayUsage();
26972
+ this.#trackUsageWork(this.#replayUsage());
25811
26973
  }
25812
26974
  #setLocatorPermissionMode(permissionModeId) {
25813
26975
  const ref = this.#state.nativeRef;
@@ -25856,7 +27018,6 @@ var AntigravitySession = class {
25856
27018
  ...effectivePermissionModeId ? { effectivePermissionModeId } : {},
25857
27019
  ...readAcpEffectiveModelState(config2, this.#catalog)
25858
27020
  };
25859
- this.#publishState();
25860
27021
  }
25861
27022
  #findConfigOption(category) {
25862
27023
  return this.#configOptions.find((entry) => entry.category === category || entry.id === category || category === "thinking" && entry.id === "thought_level");
@@ -25865,6 +27026,14 @@ var AntigravitySession = class {
25865
27026
  const option = this.#findConfigOption(category);
25866
27027
  return !!option?.options.some((choice) => choice.value === value);
25867
27028
  }
27029
+ #resolveThinkingChoice(preferred) {
27030
+ if (preferred && this.#hasConfigChoice("thinking", preferred))
27031
+ return preferred;
27032
+ if (!this.#state.effectiveThinkingOptionId) {
27033
+ return this.#findConfigOption("thinking")?.options.at(-1)?.value;
27034
+ }
27035
+ return void 0;
27036
+ }
25868
27037
  async #setModelConfig(requestedModelId, requestedThinking) {
25869
27038
  const option = this.#findConfigOption("model");
25870
27039
  if (!option) {
@@ -25908,15 +27077,28 @@ var AntigravitySession = class {
25908
27077
  this.#applyConfig(confirmed);
25909
27078
  }
25910
27079
  #sessionEvent(event) {
27080
+ if ((event.type === "agent.text" || event.type === "agent.thought") && event.text.trim() || event.type === "tool.call" || event.type === "tool.update") {
27081
+ if (this.#opening || this.#historyOperation || this.#active?.cancelled)
27082
+ return;
27083
+ if (this.#active?.promptPhase === "returned")
27084
+ this.#postPromptWake = true;
27085
+ else if (this.#active?.promptPhase !== "submitted")
27086
+ this.#wakes?.observe();
27087
+ return;
27088
+ }
25911
27089
  switch (event.type) {
25912
27090
  case "config.update":
25913
- this.#applyConfig(event.configOptions);
27091
+ if (!this.#opening && !this.#configurationQueue) {
27092
+ this.#applyConfig(event.configOptions);
27093
+ this.#publishState();
27094
+ }
25914
27095
  break;
25915
27096
  case "mode.update":
25916
27097
  if (!this.#transport?.skipPermissions) {
25917
27098
  this.#state.effectivePermissionModeId = harnessPermissionModeIdSchema.parse(event.currentModeId);
25918
27099
  this.#setLocatorPermissionMode(event.currentModeId);
25919
- this.#publishState();
27100
+ if (!this.#opening && !this.#configurationQueue)
27101
+ this.#publishState();
25920
27102
  }
25921
27103
  break;
25922
27104
  case "commands.update":
@@ -25926,8 +27108,11 @@ var AntigravitySession = class {
25926
27108
  const usage = this.#usage?.recordContextWindow(event.used, event.size);
25927
27109
  if (usage)
25928
27110
  this.#emit({ type: "session.usage.changed", usage });
25929
- if (this.#active?.promptSubmitted)
27111
+ if (this.#active?.promptPhase === "submitted") {
25930
27112
  void this.refreshUsage();
27113
+ void this.#syncTurnCompactions(this.#active);
27114
+ this.#scheduleUsageRetry();
27115
+ }
25931
27116
  break;
25932
27117
  }
25933
27118
  }
@@ -25950,24 +27135,75 @@ var AntigravitySession = class {
25950
27135
  }
25951
27136
  }
25952
27137
  async refreshUsage() {
27138
+ if (this.#usageWork) {
27139
+ this.#usageDirty = true;
27140
+ await this.#usageWork;
27141
+ } else
27142
+ await this.#trackUsageWork(this.#collectUsage());
27143
+ }
27144
+ #trackUsageWork(work) {
27145
+ const drain = async () => {
27146
+ try {
27147
+ await work;
27148
+ while (this.#usageWork === tracked && this.#usageDirty) {
27149
+ this.#usageDirty = false;
27150
+ await this.#collectUsage();
27151
+ }
27152
+ } finally {
27153
+ if (this.#usageWork === tracked)
27154
+ this.#usageWork = void 0;
27155
+ }
27156
+ };
27157
+ const tracked = drain();
27158
+ this.#usageWork = tracked;
27159
+ return tracked;
27160
+ }
27161
+ #scheduleUsageRetry(remaining = 2) {
27162
+ if (this.#usageRetry || this.#abort.signal.aborted)
27163
+ return;
27164
+ this.#usageRetry = setTimeout(() => {
27165
+ this.#usageRetry = void 0;
27166
+ void this.refreshUsage().then(() => {
27167
+ if (remaining > 1)
27168
+ this.#scheduleUsageRetry(remaining - 1);
27169
+ });
27170
+ }, 150);
27171
+ this.#usageRetry.unref();
27172
+ }
27173
+ async #collectUsage(final) {
25953
27174
  const tracker = this.#usage;
25954
27175
  if (!tracker || this.#closed || this.#faulted)
25955
27176
  return;
25956
- this.#usageWork = this.#usageWork.then(async () => {
27177
+ if (final && !this.#isCurrent(final.turn))
27178
+ return;
27179
+ try {
25957
27180
  const update = await tracker.collectNewTranscriptRequests({
25958
- signal: this.#abort.signal
27181
+ signal: this.#abort.signal,
27182
+ ...final && {
27183
+ completedAtMs: final.completedAtMs,
27184
+ ...final.turn.firstOutputAtMs === void 0 ? {} : { firstOutputAtMs: final.turn.firstOutputAtMs },
27185
+ ...final.turn.hasToolCalls && { hasToolCalls: true },
27186
+ ...final.usage && { promptUsage: final.usage }
27187
+ }
25959
27188
  });
27189
+ const recorded = final ? tracker.recordTurnPromptUsage(final) : update;
25960
27190
  if (this.#closed || this.#faulted)
25961
27191
  return;
25962
27192
  for (const request of update.requests)
25963
27193
  this.#emit({ type: "usage.request", request });
25964
- this.#emit({ type: "usage.history", complete: update.complete });
25965
- this.#emit({ type: "session.usage.changed", usage: update.usage });
25966
- }).catch(() => {
27194
+ this.#emit({ type: "usage.history", complete: recorded.complete });
27195
+ this.#emit({
27196
+ type: "session.usage.changed",
27197
+ usage: recorded.usage,
27198
+ ...this.#usageTurnId && { observedForTurnId: this.#usageTurnId }
27199
+ });
27200
+ for (const { turnId, ...timing2 } of update.timings)
27201
+ if (turnId)
27202
+ this.#emit({ type: "usage.request.timing", turnId, timing: timing2 });
27203
+ } catch {
25967
27204
  if (!this.#closed && !this.#faulted)
25968
27205
  this.#emit({ type: "usage.history", complete: false });
25969
- });
25970
- await this.#usageWork;
27206
+ }
25971
27207
  }
25972
27208
  get commands() {
25973
27209
  return {
@@ -25986,11 +27222,11 @@ var AntigravitySession = class {
25986
27222
  return err("invalidRequest", "Command accepts only a text argument");
25987
27223
  prompt = `${descriptor.invocation}${typeof args.text === "string" && args.text.trim() ? ` ${args.text.trim()}` : ""}`;
25988
27224
  }
25989
- return this.execute({
27225
+ return this.#startTurn({
25990
27226
  type: "turn.start",
25991
27227
  turnId: invocation.turnId,
25992
27228
  input: [{ type: "text", text: prompt }]
25993
- });
27229
+ }, true);
25994
27230
  }
25995
27231
  };
25996
27232
  }
@@ -26009,11 +27245,10 @@ var AntigravitySession = class {
26009
27245
  nativeSessionId,
26010
27246
  cwd: this.#options.cwd,
26011
27247
  events,
26012
- ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {},
26013
27248
  ...this.#options.adapter.toolOutputLimit !== void 0 ? { outputLimit: this.#options.adapter.toolOutputLimit } : {}
26014
27249
  });
26015
- if (!this.#transport) {
26016
- this.#turnCount = turnCount;
27250
+ if (!this.#transport && !this.#wakes) {
27251
+ this.#confirmedCount = turnCount;
26017
27252
  this.#initializeUsage(nativeSessionId);
26018
27253
  }
26019
27254
  return ok({ turns, ...this.#transport ? { state: { ...this.#state } } : {} });
@@ -26024,32 +27259,24 @@ var AntigravitySession = class {
26024
27259
  }
26025
27260
  }
26026
27261
  async execute(command) {
27262
+ if (command.type === "turn.start")
27263
+ return this.#startTurn(command, false);
26027
27264
  if (this.#closed || this.#faulted)
26028
27265
  return err("invalidState", "Session is closed");
26029
27266
  try {
26030
27267
  switch (command.type) {
26031
27268
  case "turn.steer":
26032
27269
  return unsupportedSteer("Antigravity ACP");
26033
- case "turn.start": {
26034
- if (this.#active || this.#configuring || this.#historyOperation)
26035
- return err("sessionBusy", "Session is busy", true);
26036
- if (!command.turnId || !command.input.length || !command.input.some((part) => typeof part.text === "string" && part.text.trim()))
26037
- return err("invalidRequest", "Prompt and Turn ID must not be empty");
26038
- const turn = { turnId: command.turnId, cancelled: false, ended: false };
26039
- this.#active = turn;
26040
- this.#emit({ type: "turn.started", turnId: turn.turnId });
26041
- void this.#runTurn(turn, command);
26042
- return ok({ turnId: command.turnId });
26043
- }
26044
27270
  case "turn.cancel": {
26045
27271
  const turn = this.#active;
26046
27272
  if (!turn || turn.turnId !== command.turnId)
26047
27273
  return err("invalidRequest", "Turn is not active");
26048
27274
  if (!turn.cancelled) {
26049
27275
  turn.cancelled = true;
27276
+ turn.accounting.abort();
26050
27277
  this.#closeInteractions("cancelled");
26051
27278
  try {
26052
- if (turn.promptSubmitted)
27279
+ if (turn.promptPhase === "submitted")
26053
27280
  await this.#transport?.cancel();
26054
27281
  } catch (error51) {
26055
27282
  this.handleTransportFault(new AntigravityTransportError("unavailable", "Native cancellation could not be confirmed", { cause: error51 }));
@@ -26067,8 +27294,55 @@ var AntigravitySession = class {
26067
27294
  return { ok: false, error: normalizeAntigravityError(error51) };
26068
27295
  }
26069
27296
  }
27297
+ async #enqueueConfiguration(run) {
27298
+ const previous = this.#configurationQueue;
27299
+ let release;
27300
+ const current = new Promise((resolve) => {
27301
+ release = resolve;
27302
+ });
27303
+ const tail = previous ? previous.then(() => current) : current;
27304
+ this.#configurationQueue = tail;
27305
+ if (previous)
27306
+ await previous;
27307
+ const before = this.#state;
27308
+ try {
27309
+ return await run();
27310
+ } finally {
27311
+ if (this.#transport && !this.#closed && !this.#faulted && this.#state !== before) {
27312
+ this.#publishState();
27313
+ }
27314
+ if (this.#configurationQueue === tail)
27315
+ this.#configurationQueue = void 0;
27316
+ release();
27317
+ }
27318
+ }
27319
+ #startTurn(command, catalogCommand) {
27320
+ if (this.#closed || this.#faulted)
27321
+ return err("invalidState", "Session is closed");
27322
+ if (this.#active || this.#configurationQueue || this.#historyOperation)
27323
+ return err("sessionBusy", "Session is busy", true);
27324
+ if (!command.turnId || !command.input.length || !command.input.some((part) => typeof part.text === "string" && part.text.trim()))
27325
+ return err("invalidRequest", "Prompt and Turn ID must not be empty");
27326
+ try {
27327
+ this.#postPromptWake = false;
27328
+ const turn = {
27329
+ turnId: command.turnId,
27330
+ cancelled: false,
27331
+ ended: false,
27332
+ promptPhase: "notSubmitted",
27333
+ accounting: new AbortController(),
27334
+ emittedCompactions: /* @__PURE__ */ new Set()
27335
+ };
27336
+ this.#active = turn;
27337
+ this.#emit({ type: "turn.started", turnId: turn.turnId });
27338
+ void this.#runTurn(turn, command, catalogCommand);
27339
+ return ok({ turnId: command.turnId });
27340
+ } catch (error51) {
27341
+ return { ok: false, error: normalizeAntigravityError(error51) };
27342
+ }
27343
+ }
26070
27344
  async #select(command) {
26071
- if (this.#configuring || this.#historyOperation)
27345
+ if (this.#historyOperation)
26072
27346
  return err("sessionBusy", "Configuration or history is changing", true);
26073
27347
  if (command.type === "permissionMode.select") {
26074
27348
  try {
@@ -26079,17 +27353,44 @@ var AntigravitySession = class {
26079
27353
  if (this.#options.unattended && command.permissionModeId !== SKIP)
26080
27354
  return err("invalidRequest", "Unattended execution requires Skip permissions");
26081
27355
  }
26082
- this.#configuring = true;
26083
- try {
27356
+ return this.#enqueueConfiguration(async () => {
27357
+ if (this.#closed || this.#faulted)
27358
+ return err("invalidState", "Session is closed");
27359
+ if (this.#historyOperation)
27360
+ return err("sessionBusy", "Configuration or history is changing", true);
27361
+ if (this.#opening) {
27362
+ try {
27363
+ await this.#opening;
27364
+ } catch (error51) {
27365
+ if (!(command.type === "model.select" && error51 instanceof AntigravityTransportError && error51.kind === "unsupported"))
27366
+ throw error51;
27367
+ }
27368
+ if (this.#closed || this.#faulted)
27369
+ return err("invalidState", "Session is closed");
27370
+ }
26084
27371
  const openingFromCold = !this.#transport;
27372
+ const previousModel = this.#requested.model;
27373
+ const previousThinkingOptionId = this.#requested.thinkingOptionId;
26085
27374
  const previousPermissionMode = this.#requested.permissionModeId;
26086
- if (openingFromCold && command.type === "permissionMode.select") {
27375
+ if (openingFromCold && command.type === "model.select") {
27376
+ this.#requested.model = command.model;
27377
+ if (command.model.id !== previousModel?.id) {
27378
+ this.#requested.thinkingOptionId = void 0;
27379
+ }
27380
+ } else if (openingFromCold && command.type === "thinking.select") {
27381
+ this.#requested.thinkingOptionId = void 0;
27382
+ } else if (openingFromCold && command.type === "permissionMode.select") {
26087
27383
  this.#requested.permissionModeId = command.permissionModeId;
26088
27384
  }
26089
27385
  try {
26090
27386
  await this.initialize();
26091
27387
  } catch (error51) {
26092
- if (openingFromCold && command.type === "permissionMode.select") {
27388
+ if (openingFromCold && command.type === "model.select") {
27389
+ this.#requested.model = previousModel;
27390
+ this.#requested.thinkingOptionId = previousThinkingOptionId;
27391
+ } else if (openingFromCold && command.type === "thinking.select") {
27392
+ this.#requested.thinkingOptionId = previousThinkingOptionId;
27393
+ } else if (openingFromCold && command.type === "permissionMode.select") {
26093
27394
  this.#requested.permissionModeId = previousPermissionMode;
26094
27395
  }
26095
27396
  throw error51;
@@ -26097,16 +27398,26 @@ var AntigravitySession = class {
26097
27398
  const transport = this.#transport;
26098
27399
  if (!transport || this.#closed || this.#faulted)
26099
27400
  return err("invalidState", "Native Session is not connected");
26100
- if (openingFromCold && command.type === "permissionMode.select") {
27401
+ if (openingFromCold && (command.type === "model.select" || command.type === "permissionMode.select")) {
27402
+ if (command.type === "model.select") {
27403
+ this.#requested.model = this.#state.effectiveModel;
27404
+ this.#requested.thinkingOptionId = this.#state.effectiveThinkingOptionId;
27405
+ }
26101
27406
  return ok({ completed: true });
26102
27407
  }
26103
27408
  if (command.type === "model.select") {
26104
27409
  const applied = await this.#setModelConfig(command.model.id);
26105
- if (!applied.bakedInThinking && applied.impliedThinking && this.#hasConfigChoice("thinking", applied.impliedThinking)) {
26106
- await this.#setConfig("thinking", applied.impliedThinking);
27410
+ try {
27411
+ if (!applied.bakedInThinking) {
27412
+ const desiredThinking = this.#resolveThinkingChoice(applied.impliedThinking);
27413
+ if (desiredThinking) {
27414
+ await this.#setConfig("thinking", desiredThinking);
27415
+ }
27416
+ }
27417
+ } finally {
27418
+ this.#requested.model = this.#state.effectiveModel;
27419
+ this.#requested.thinkingOptionId = this.#state.effectiveThinkingOptionId;
26107
27420
  }
26108
- this.#requested.model = this.#state.effectiveModel;
26109
- this.#requested.thinkingOptionId = this.#state.effectiveThinkingOptionId;
26110
27421
  } else if (command.type === "thinking.select") {
26111
27422
  await this.#setConfig("thinking", command.thinkingOptionId);
26112
27423
  this.#requested.thinkingOptionId = this.#state.effectiveThinkingOptionId;
@@ -26141,26 +27452,46 @@ var AntigravitySession = class {
26141
27452
  this.#state.effectivePermissionModeId = command.permissionModeId;
26142
27453
  this.#setLocatorPermissionMode(command.permissionModeId);
26143
27454
  this.#requested.permissionModeId = command.permissionModeId;
26144
- this.#publishState();
26145
27455
  }
26146
27456
  }
26147
27457
  return ok({ completed: true });
26148
- } finally {
26149
- this.#configuring = false;
26150
- }
27458
+ });
26151
27459
  }
26152
- async #runTurn(turn, command) {
27460
+ async #runTurn(turn, command, catalogCommand) {
26153
27461
  let outcome;
26154
27462
  let nativeTurnRef;
27463
+ let confirmedCheckpoint;
27464
+ let mayWriteInput = true;
26155
27465
  try {
26156
27466
  await this.initialize();
26157
27467
  await this.#usageWork;
27468
+ await this.#wakes?.flush();
27469
+ if (!this.#isCurrent(turn))
27470
+ return;
27471
+ if (turn.cancelled) {
27472
+ this.#finish(turn, { status: "cancelled" });
27473
+ return;
27474
+ }
27475
+ const ref = this.nativeRef;
27476
+ if (!ref)
27477
+ throw new AntigravityTransportError("unavailable", "Native Session is not connected");
27478
+ const home = antigravityHome(this.#options.environment);
27479
+ const file2 = nativeConversationDbPath(ref.nativeSessionId, home);
27480
+ const parts = promptParts(command);
27481
+ const part = parts[0];
27482
+ mayWriteInput = !catalogCommand || part?.type !== "text" || !/^\/(?:compact|help)(?:\s|$)/u.test(part.text);
27483
+ while (this.#configurationQueue && !turn.cancelled && this.#isCurrent(turn)) {
27484
+ await this.#configurationQueue;
27485
+ }
26158
27486
  if (!this.#isCurrent(turn))
26159
27487
  return;
26160
27488
  if (turn.cancelled) {
26161
27489
  this.#finish(turn, { status: "cancelled" });
26162
27490
  return;
26163
27491
  }
27492
+ const transport = this.#transport;
27493
+ if (!transport)
27494
+ throw new AntigravityTransportError("unavailable", "Native Session is not connected");
26164
27495
  turn.tracker = new AntigravityToolTracker({
26165
27496
  turnId: turn.turnId,
26166
27497
  cwd: this.#options.cwd,
@@ -26173,15 +27504,21 @@ var AntigravitySession = class {
26173
27504
  if (this.#isCurrent(turn))
26174
27505
  this.#emit(event);
26175
27506
  },
26176
- onSubagentSpawned: (id, item) => this.#subagents.track(id, item)
27507
+ onSubagentSpawned: (id2, item) => this.#subagents.track(id2, item)
26177
27508
  });
26178
- const transport = this.#transport;
26179
- const ref = this.nativeRef;
26180
- if (!transport || !ref)
26181
- throw new AntigravityTransportError("unavailable", "Native Session is not connected");
26182
- this.#usage?.beginTurn();
26183
- turn.promptSubmitted = true;
26184
- const result = await transport.prompt(promptParts(command), {
27509
+ const before = this.#confirmedCount;
27510
+ turn.dbPath = file2;
27511
+ turn.compactionAfterStep = await readNativeStepWatermark(file2);
27512
+ if (!this.#isCurrent(turn))
27513
+ return;
27514
+ const submittedAtMs = Date.now();
27515
+ this.#usage?.beginTurn(submittedAtMs, turn.turnId);
27516
+ this.#usageTurnId = turn.turnId;
27517
+ turn.promptPhase = "submitted";
27518
+ const result = await transport.prompt(parts, {
27519
+ onResponse: () => {
27520
+ turn.promptPhase = "returned";
27521
+ },
26185
27522
  onEvent: (event) => {
26186
27523
  if (!this.#isCurrent(turn) || turn.cancelled)
26187
27524
  return;
@@ -26205,7 +27542,7 @@ var AntigravitySession = class {
26205
27542
  return this.#question(turn, request);
26206
27543
  }
26207
27544
  });
26208
- turn.promptSubmitted = false;
27545
+ turn.promptPhase = "returned";
26209
27546
  const completedAtMs = Date.now();
26210
27547
  if (!this.#isCurrent(turn))
26211
27548
  return;
@@ -26217,15 +27554,11 @@ var AntigravitySession = class {
26217
27554
  retryable: false
26218
27555
  }
26219
27556
  } : { status: "succeeded" };
26220
- const before = this.#turnCount;
26221
- let count4;
26222
- try {
26223
- count4 = await readNativeTurnCount(nativeConversationDbPath(ref.nativeSessionId, antigravityHome(this.#options.environment)));
26224
- } catch {
26225
- count4 = outcome.status === "succeeded" ? before + 1 : before;
26226
- }
26227
- if (count4 > before) {
26228
- const key = `turn-${count4 - 1}`;
27557
+ const confirmedCount = mayWriteInput ? await observeNativeTurnCount(file2, before, submittedAtMs, completedAtMs, outcome.status === "succeeded", AbortSignal.any([turn.accounting.signal, this.#abort.signal])) : null;
27558
+ if (!this.#isCurrent(turn))
27559
+ return;
27560
+ if (confirmedCount !== null) {
27561
+ const key = `turn-${confirmedCount - 1}`;
26229
27562
  nativeTurnRef = {
26230
27563
  harnessId,
26231
27564
  nativeSessionId: ref.nativeSessionId,
@@ -26233,40 +27566,12 @@ var AntigravitySession = class {
26233
27566
  nativeTurnKey: key
26234
27567
  };
26235
27568
  outcome = { ...outcome, checkpoint: { ...ref, checkpointId: key } };
26236
- this.#turnCount = count4;
26237
- }
26238
- await this.#usageWork;
26239
- if (this.#usage && this.#isCurrent(turn)) {
26240
- try {
26241
- const timing2 = {
26242
- ...turn.firstOutputAtMs !== void 0 ? { firstOutputAtMs: turn.firstOutputAtMs } : {},
26243
- completedAtMs
26244
- };
26245
- const update = await this.#usage.collectNewTranscriptRequests({
26246
- ...timing2,
26247
- ...turn.hasToolCalls ? { hasToolCalls: true } : {},
26248
- ...result.usage ? { promptUsage: result.usage } : {},
26249
- signal: this.#abort.signal
26250
- });
26251
- const recorded = this.#usage.recordTurnPromptUsage({
26252
- ...result.usage ? { usage: result.usage } : {},
26253
- ...timing2
26254
- });
26255
- if (!this.#isCurrent(turn))
26256
- return;
26257
- for (const request of update.requests)
26258
- this.#emit({ type: "usage.request", request });
26259
- this.#emit({ type: "usage.history", complete: recorded.complete });
26260
- this.#emit({
26261
- type: "session.usage.changed",
26262
- usage: recorded.usage,
26263
- observedForTurnId: turn.turnId
26264
- });
26265
- } catch {
26266
- if (this.#isCurrent(turn))
26267
- this.#emit({ type: "usage.history", complete: false });
26268
- }
27569
+ this.#confirmedCount = confirmedCount;
27570
+ confirmedCheckpoint = key;
26269
27571
  }
27572
+ await this.#trackUsageWork(Promise.resolve(this.#usageWork).then(() => this.#collectUsage({ turn, completedAtMs, ...result.usage && { usage: result.usage } })));
27573
+ await this.#syncTurnCompactions(turn);
27574
+ this.#scheduleUsageRetry();
26270
27575
  } catch (error51) {
26271
27576
  if (error51 instanceof AntigravityTransportError && (error51.kind === "processExited" || error51.kind === "protocolError" || this.#transport?.isClosed)) {
26272
27577
  this.handleTransportFault(error51);
@@ -26275,8 +27580,18 @@ var AntigravitySession = class {
26275
27580
  } finally {
26276
27581
  this.#usage?.endTurn();
26277
27582
  }
26278
- if (this.#isCurrent(turn))
27583
+ if (this.#isCurrent(turn)) {
27584
+ if (mayWriteInput && turn.promptPhase !== "notSubmitted" && !nativeTurnRef)
27585
+ this.#confirmedCount = null;
27586
+ if (turn.cancelled)
27587
+ outcome = {
27588
+ status: "cancelled",
27589
+ ...outcome.checkpoint && { checkpoint: outcome.checkpoint }
27590
+ };
27591
+ if (confirmedCheckpoint && outcome.checkpoint)
27592
+ this.#confirmedCheckpoints.add(confirmedCheckpoint);
26279
27593
  this.#finish(turn, outcome, nativeTurnRef);
27594
+ }
26280
27595
  }
26281
27596
  #isCurrent(turn) {
26282
27597
  return this.#active === turn && !turn.ended;
@@ -26308,6 +27623,29 @@ var AntigravitySession = class {
26308
27623
  });
26309
27624
  turn.textItem = void 0;
26310
27625
  }
27626
+ async #syncTurnCompactions(turn) {
27627
+ if (!this.#isCurrent(turn) || turn.cancelled || turn.dbPath === void 0 || turn.compactionAfterStep === void 0)
27628
+ return;
27629
+ const compactions = await readNativeTurnCompactions(turn.dbPath, turn.compactionAfterStep);
27630
+ if (!this.#isCurrent(turn) || turn.cancelled)
27631
+ return;
27632
+ for (const compaction of compactions) {
27633
+ if (turn.emittedCompactions.has(compaction.stepIndex))
27634
+ continue;
27635
+ turn.emittedCompactions.add(compaction.stepIndex);
27636
+ this.#completeText(turn, { status: "succeeded" });
27637
+ const item = {
27638
+ type: "contextCompaction",
27639
+ itemId: compactionItemId(compaction.stepIndex)
27640
+ };
27641
+ this.#emit({ type: "item.started", turnId: turn.turnId, item });
27642
+ this.#emit({
27643
+ type: "item.completed",
27644
+ turnId: turn.turnId,
27645
+ snapshot: { item, outcome: compactionOutcome(compaction) }
27646
+ });
27647
+ }
27648
+ }
26311
27649
  #finish(turn, outcome, nativeTurnRef) {
26312
27650
  if (!this.#isCurrent(turn))
26313
27651
  return;
@@ -26322,6 +27660,9 @@ var AntigravitySession = class {
26322
27660
  ...nativeTurnRef ? { nativeTurnRef } : outcome.status === "succeeded" ? { ephemeral: true } : {},
26323
27661
  outcome
26324
27662
  });
27663
+ if (this.#postPromptWake && !this.#closed && !this.#faulted)
27664
+ this.#wakes?.observe();
27665
+ this.#postPromptWake = false;
26325
27666
  }
26326
27667
  #permission(turn, request) {
26327
27668
  const ref = this.nativeRef;
@@ -26412,11 +27753,11 @@ var AntigravitySession = class {
26412
27753
  return ok({ accepted: true });
26413
27754
  }
26414
27755
  #closeInteractions(reason) {
26415
- for (const [id, pending] of this.#pending) {
27756
+ for (const [id2, pending] of this.#pending) {
26416
27757
  pending.resolve(pending.cancelValue);
26417
27758
  this.#emit({
26418
27759
  type: "interaction.closed",
26419
- interactionId: hostInteractionIdSchema.parse(id),
27760
+ interactionId: hostInteractionIdSchema.parse(id2),
26420
27761
  turnId: pending.interaction.turnId,
26421
27762
  reason
26422
27763
  });
@@ -26427,7 +27768,10 @@ var AntigravitySession = class {
26427
27768
  if (this.#closed || this.#faulted)
26428
27769
  return;
26429
27770
  this.#faulted = true;
27771
+ clearTimeout(this.#usageRetry);
26430
27772
  this.#abort.abort();
27773
+ this.#wakes?.close();
27774
+ this.#postPromptWake = false;
26431
27775
  this.#closeInteractions("cancelled");
26432
27776
  if (this.#active)
26433
27777
  this.#finish(this.#active, { status: "failed", error: normalizeAntigravityError(error51) });
@@ -26444,14 +27788,17 @@ var AntigravitySession = class {
26444
27788
  }
26445
27789
  async #close() {
26446
27790
  this.#closed = true;
27791
+ clearTimeout(this.#usageRetry);
26447
27792
  this.#abort.abort();
27793
+ this.#wakes?.close();
27794
+ this.#postPromptWake = false;
26448
27795
  this.#closeInteractions("cancelled");
26449
- const active = this.#active;
26450
- if (active)
26451
- this.#finish(active, { status: "cancelled", reason: "Session closed" });
27796
+ const active2 = this.#active;
27797
+ if (active2)
27798
+ this.#finish(active2, { status: "cancelled", reason: "Session closed" });
26452
27799
  this.#channel.end();
26453
27800
  this.#transport?.setSessionEventHandler(null);
26454
- if (active)
27801
+ if (active2?.promptPhase === "submitted")
26455
27802
  await this.#transport?.cancel().catch(() => void 0);
26456
27803
  await Promise.all([this.#transport?.close(), this.#subagents.close()]);
26457
27804
  this.#options.onClosed(this);
@@ -26497,7 +27844,7 @@ var AntigravityAdapter = class {
26497
27844
  status: "unavailable",
26498
27845
  error: { code: "invalidState", message: "Adapter is closed", retryable: false }
26499
27846
  };
26500
- const cwd = path12.resolve(input.cwd ?? process.cwd());
27847
+ const cwd = path13.resolve(input.cwd ?? process.cwd());
26501
27848
  const key = `${cwd}\0${input.purpose ?? "catalog"}`;
26502
27849
  const cached2 = this.#cache.get(key);
26503
27850
  const inFlight = this.#inflight.get(key);
@@ -26506,8 +27853,8 @@ var AntigravityAdapter = class {
26506
27853
  if (!input.refresh && inFlight)
26507
27854
  return inFlight;
26508
27855
  if (input.refresh) {
26509
- this.#cache.delete(`${cwd}\0catalog`);
26510
- this.#cache.delete(`${cwd}\0availability`);
27856
+ this.#cache.clear();
27857
+ this.#inflight.clear();
26511
27858
  }
26512
27859
  const pending = this.#inspect(cwd, input.purpose).then((result) => {
26513
27860
  if (!this.#closed && this.#inflight.get(key) === pending && result.status === "ready")
@@ -26567,7 +27914,7 @@ var AntigravityAdapter = class {
26567
27914
  async open(input) {
26568
27915
  if (this.#closed)
26569
27916
  return err("invalidState", "Adapter is closed");
26570
- if (!input.cwd || !path12.isAbsolute(input.cwd))
27917
+ if (!input.cwd || !path13.isAbsolute(input.cwd))
26571
27918
  return err("invalidRequest", "cwd must be an absolute directory");
26572
27919
  try {
26573
27920
  if (!(await stat2(input.cwd)).isDirectory())
@@ -26577,9 +27924,10 @@ var AntigravityAdapter = class {
26577
27924
  }
26578
27925
  if (input.kind === "fork" || input.kind === "rollbackLastTurn") {
26579
27926
  const source = [...this.#sessions].find((session2) => session2.nativeRef?.nativeSessionId === input.sourceRef.nativeSessionId);
26580
- const release = source?.reserveHistoryOperation();
26581
- if (source && !release)
26582
- return err("sessionBusy", "Source Session is busy", true);
27927
+ const liveSource = input.kind === "fork" && source?.isActive ? source : void 0;
27928
+ const release = liveSource ? void 0 : source?.reserveHistoryOperation();
27929
+ if (source && !liveSource && !release)
27930
+ return err("sessionBusy", "Source Session is busy; retry when idle", true);
26583
27931
  const common = {
26584
27932
  harnessId,
26585
27933
  adapterEnvironment: this.#environment,
@@ -26601,7 +27949,11 @@ var AntigravityAdapter = class {
26601
27949
  }
26602
27950
  };
26603
27951
  try {
26604
- return await (input.kind === "fork" ? forkAntigravitySession({ ...common, input }) : rollbackAntigravityLastTurn({ ...common, input }));
27952
+ return await (input.kind === "fork" ? forkAntigravitySession({
27953
+ ...common,
27954
+ input,
27955
+ ...liveSource ? { sourceSession: liveSource } : {}
27956
+ }) : rollbackAntigravityLastTurn({ ...common, input }));
26605
27957
  } finally {
26606
27958
  release?.();
26607
27959
  }
@@ -26625,7 +27977,7 @@ var AntigravityAdapter = class {
26625
27977
  model: input.model,
26626
27978
  thinkingOptionId: input.thinkingOptionId,
26627
27979
  permissionModeId: unattended || !input.permissionModeId && locator && typeof locator === "object" && !Array.isArray(locator) && locator.permissionModeId === SKIP ? harnessPermissionModeIdSchema.parse(SKIP) : input.permissionModeId,
26628
- ...input.kind === "resume" ? { nativeRef: input.nativeRef, knownTurnRefs: input.knownTurnRefs } : {},
27980
+ ...input.kind === "resume" ? { nativeRef: input.nativeRef } : {},
26629
27981
  unattended,
26630
27982
  adapter: this.options,
26631
27983
  onClosed: (closed) => this.#sessions.delete(closed)